tron@2186: /* $Id$ */ tron@2186: truelight@0: #include "stdafx.h" Darkvater@1891: #include "openttd.h" hackykid@1922: #include "debug.h" tron@2163: #include "functions.h" tron@2561: #include "gui.h" tron@507: #include "table/strings.h" tron@679: #include "map.h" tron@1209: #include "tile.h" truelight@0: #include "vehicle.h" truelight@0: #include "command.h" truelight@0: #include "pathfind.h" matthijs@1247: #include "npf.h" truelight@0: #include "station.h" truelight@0: #include "table/train_cmd.h" truelight@0: #include "news.h" truelight@0: #include "engine.h" truelight@0: #include "player.h" tron@337: #include "sound.h" truelight@1313: #include "depot.h" truelight@1542: #include "waypoint.h" matthijs@1752: #include "vehicle_gui.h" bjarni@2676: #include "train.h" truelight@0: truelight@742: static bool TrainCheckIfLineEnds(Vehicle *v); hackykid@1922: static void TrainController(Vehicle *v); truelight@0: truelight@0: static const byte _vehicle_initial_x_fract[4] = {10,8,4,8}; truelight@0: static const byte _vehicle_initial_y_fract[4] = {8,4,8,10}; truelight@0: static const byte _state_dir_table[4] = { 0x20, 8, 0x10, 4 }; truelight@0: hackykid@1905: /** hackykid@1905: * Recalculates the cached weight of a train and its vehicles. Should be called each time the cargo on hackykid@1905: * the consist changes. hackykid@1905: * @param v First vehicle of the consist. hackykid@1905: */ tron@2752: static void TrainCargoChanged(Vehicle* v) tron@2639: { hackykid@1905: Vehicle *u; hackykid@1905: uint16 weight = 0; hackykid@1905: hackykid@1905: for (u = v; u != NULL; u = u->next) { hackykid@1905: const RailVehicleInfo *rvi = RailVehInfo(u->engine_type); hackykid@1905: uint16 vweight = 0; hackykid@1905: hackykid@1905: vweight += (_cargoc.weights[u->cargo_type] * u->cargo_count) / 16; peter1138@2602: peter1138@2602: // Vehicle weight is not added for articulated parts. bjarni@2676: if (!IsArticulatedPart(u)) { peter1138@2602: // vehicle weight is the sum of the weight of the vehicle and the weight of its cargo peter1138@2602: vweight += rvi->weight; peter1138@2602: peter1138@2602: // powered wagons have extra weight added peter1138@2602: if (HASBIT(u->u.rail.flags, VRF_POWEREDWAGON)) peter1138@2602: vweight += RailVehInfo(v->engine_type)->pow_wag_weight; peter1138@2602: } hackykid@1905: hackykid@1905: // consist weight is the sum of the weight of all vehicles in the consist hackykid@1905: weight += vweight; hackykid@1905: hackykid@1905: // store vehicle weight in cache hackykid@1905: u->u.rail.cached_veh_weight = vweight; hackykid@1905: }; hackykid@1905: hackykid@1905: // store consist weight in cache hackykid@1905: v->u.rail.cached_weight = weight; hackykid@1905: } hackykid@1905: hackykid@1905: /** hackykid@1917: * Recalculates the cached stuff of a train. Should be called each time a vehicle is added hackykid@1917: * to/removed from the chain, and when the game is loaded. hackykid@1917: * Note: this needs to be called too for 'wagon chains' (in the depot, without an engine) hackykid@1917: * @param v First vehicle of the chain. hackykid@1905: */ tron@2639: void TrainConsistChanged(Vehicle* v) tron@2639: { hackykid@1917: const RailVehicleInfo *rvi_v; hackykid@1905: Vehicle *u; hackykid@1905: uint16 max_speed = 0xFFFF; hackykid@1905: uint32 power = 0; hackykid@1917: EngineID first_engine; hackykid@1917: hackykid@1917: assert(v->type == VEH_Train); hackykid@1917: bjarni@2676: assert(IsFrontEngine(v) || IsFreeWagon(v)); hackykid@1917: hackykid@1917: rvi_v = RailVehInfo(v->engine_type); bjarni@2676: first_engine = IsFrontEngine(v) ? v->engine_type : INVALID_VEHICLE; peter1138@2587: v->u.rail.cached_total_length = 0; hackykid@1905: hackykid@1905: for (u = v; u != NULL; u = u->next) { hackykid@1908: const RailVehicleInfo *rvi_u = RailVehInfo(u->engine_type); hackykid@1922: uint16 veh_len; hackykid@1908: Darkvater@9924: // Update the v->first cache. This is faster than having to brute force it later. Darkvater@9924: if (u->first == NULL) u->first = v; Darkvater@9924: hackykid@1917: // update the 'first engine' hackykid@1917: u->u.rail.first_engine = (v == u) ? INVALID_VEHICLE : first_engine; hackykid@1917: peter1138@2595: if (rvi_u->visual_effect != 0) { peter1138@2595: u->u.rail.cached_vis_effect = rvi_u->visual_effect; peter1138@2595: } else { bjarni@2676: if (IsTrainWagon(u) || IsArticulatedPart(u)) { peter1138@2602: // Wagons and articulated parts have no effect by default peter1138@2595: u->u.rail.cached_vis_effect = 0x40; peter1138@2595: } else if (rvi_u->engclass == 0) { peter1138@2595: // Steam is offset by -4 units peter1138@2595: u->u.rail.cached_vis_effect = 4; peter1138@2595: } else { peter1138@2595: // Diesel fumes and sparks come from the centre peter1138@2595: u->u.rail.cached_vis_effect = 8; peter1138@2595: } peter1138@2595: } peter1138@2595: bjarni@2676: if (!IsArticulatedPart(u)) { peter1138@2602: // power is the sum of the powers of all engines and powered wagons in the consist peter1138@2602: power += rvi_u->power; peter1138@2602: peter1138@2602: // check if its a powered wagon peter1138@2602: CLRBIT(u->u.rail.flags, VRF_POWEREDWAGON); peter1138@2602: if ((rvi_v->pow_wag_power != 0) && (rvi_u->flags & RVI_WAGON) && UsesWagonOverride(u)) { peter1138@2602: if (HASBIT(rvi_u->callbackmask, CBM_WAGON_POWER)) { peter1138@2602: uint16 callback = GetCallBackResult(CBID_WAGON_POWER, u->engine_type, u); peter1138@2602: peter1138@2602: if (callback != CALLBACK_FAILED) peter1138@2602: u->u.rail.cached_vis_effect = callback; peter1138@2602: } peter1138@2602: peter1138@2602: if (u->u.rail.cached_vis_effect < 0x40) { peter1138@2602: /* wagon is powered */ peter1138@2602: SETBIT(u->u.rail.flags, VRF_POWEREDWAGON); // cache 'powered' status peter1138@2602: power += rvi_v->pow_wag_power; peter1138@2602: } peter1138@2595: } peter1138@2595: peter1138@2602: // max speed is the minimum of the speed limits of all vehicles in the consist peter1138@2602: if (!(rvi_u->flags & RVI_WAGON) || _patches.wagon_speed_limits) peter1138@2602: if (rvi_u->max_speed != 0 && !UsesWagonOverride(u)) peter1138@2602: max_speed = min(rvi_u->max_speed, max_speed); hackykid@1908: } hackykid@1908: hackykid@1922: // check the vehicle length (callback) hackykid@1922: veh_len = CALLBACK_FAILED; hackykid@1922: if (HASBIT(rvi_u->callbackmask, CBM_VEH_LENGTH)) hackykid@1922: veh_len = GetCallBackResult(CBID_VEH_LENGTH, u->engine_type, u); hackykid@1922: if (veh_len == CALLBACK_FAILED) hackykid@1922: veh_len = rvi_u->shorten_factor; hackykid@1934: veh_len = clamp(veh_len, 0, u->next == NULL ? 7 : 5); // the clamp on vehicles not the last in chain is stricter, as too short wagons can break the 'follow next vehicle' code hackykid@1922: u->u.rail.cached_veh_length = 8 - veh_len; peter1138@2587: v->u.rail.cached_total_length += u->u.rail.cached_veh_length; hackykid@1922: hackykid@1905: }; hackykid@1905: hackykid@1905: // store consist weight/max speed in cache hackykid@1905: v->u.rail.cached_max_speed = max_speed; hackykid@1905: v->u.rail.cached_power = power; hackykid@1908: hackykid@1908: // recalculate cached weights too (we do this *after* the rest, so it is known which wagons are powered and need extra weight added) hackykid@1908: TrainCargoChanged(v); hackykid@1905: } matthijs@1247: matthijs@1247: /* These two arrays are used for realistic acceleration. XXX: How should they matthijs@1247: * be interpreted? */ celestar@1179: static const byte _curve_neighbours45[8][2] = { celestar@1179: {7, 1}, celestar@1179: {0, 2}, celestar@1179: {1, 3}, celestar@1179: {2, 4}, celestar@1179: {3, 5}, celestar@1179: {4, 6}, celestar@1179: {5, 7}, celestar@1179: {6, 0}, celestar@1179: }; celestar@1179: celestar@1179: static const byte _curve_neighbours90[8][2] = { celestar@1179: {6, 2}, celestar@1179: {7, 3}, celestar@1179: {0, 4}, celestar@1179: {1, 5}, celestar@1179: {2, 6}, celestar@1179: {3, 7}, celestar@1179: {4, 0}, celestar@1179: {5, 1}, celestar@1179: }; celestar@1179: celestar@1179: enum AccelType { celestar@1179: AM_ACCEL, celestar@1179: AM_BRAKE celestar@1179: }; celestar@1179: tron@2630: static bool TrainShouldStop(const Vehicle* v, TileIndex tile) celestar@1236: { tron@2630: const Order* o = &v->current_order; tron@2630: celestar@1236: assert(v->type == VEH_Train); celestar@1236: assert(IsTileType(v->tile, MP_STATION)); celestar@1236: //When does a train drive through a station celestar@1236: //first we deal with the "new nonstop handling" tron@1472: if (_patches.new_nonstop && o->flags & OF_NON_STOP && tron@2049: _m[tile].m2 == o->station ) celestar@1236: return false; celestar@1236: tron@2049: if (v->last_station_visited == _m[tile].m2) celestar@1236: return false; celestar@1236: tron@2049: if (_m[tile].m2 != o->station && tron@1472: (o->flags & OF_NON_STOP || _patches.new_nonstop)) celestar@1236: return false; celestar@1236: celestar@1236: return true; celestar@1236: } celestar@1236: celestar@1179: //new acceleration celestar@1179: static int GetTrainAcceleration(Vehicle *v, bool mode) celestar@1179: { tron@1531: const Vehicle *u; celestar@1179: int num = 0; //number of vehicles, change this into the number of axles later celestar@1179: int power = 0; celestar@1179: int mass = 0; celestar@1179: int max_speed = 2000; celestar@1179: int area = 120; celestar@1179: int friction = 35; //[1e-3] celestar@1179: int drag_coeff = 20; //[1e-4] celestar@1179: int incl = 0; celestar@1179: int resistance; celestar@1179: int speed = v->cur_speed; //[mph] celestar@1179: int force = 0x3FFFFFFF; celestar@1179: int pos = 0; celestar@1179: int lastpos = -1; celestar@1179: int curvecount[2] = {0, 0}; celestar@1179: int sum = 0; celestar@1179: int numcurve = 0; celestar@1179: celestar@1179: speed *= 10; celestar@1179: speed /= 16; celestar@1179: celestar@1179: //first find the curve speed limit tron@1531: for (u = v; u->next != NULL; u = u->next, pos++) { celestar@1179: int dir = u->direction; celestar@1179: int ndir = u->next->direction; tron@1531: int i; celestar@1179: celestar@1179: for (i = 0; i < 2; i++) { celestar@1179: if ( _curve_neighbours45[dir][i] == ndir) { celestar@1179: curvecount[i]++; celestar@1179: if (lastpos != -1) { tron@1531: numcurve++; tron@1531: sum += pos - lastpos; celestar@1179: if (pos - lastpos == 1) { celestar@1179: max_speed = 88; celestar@1179: } celestar@1179: } celestar@1179: lastpos = pos; celestar@1179: } celestar@1179: } celestar@1179: celestar@1179: //if we have a 90 degree turn, fix the speed limit to 60 tron@1472: if (_curve_neighbours90[dir][0] == ndir || tron@1472: _curve_neighbours90[dir][1] == ndir) { celestar@1179: max_speed = 61; celestar@1179: } celestar@1179: } celestar@1179: tron@1472: if (numcurve > 0) sum /= numcurve; tron@1472: tron@1472: if ((curvecount[0] != 0 || curvecount[1] != 0) && max_speed > 88) { celestar@1179: int total = curvecount[0] + curvecount[1]; tron@1472: celestar@1179: if (curvecount[0] == 1 && curvecount[1] == 1) { celestar@1179: max_speed = 0xFFFF; celestar@1179: } else if (total > 1) { celestar@1179: max_speed = 232 - (13 - clamp(sum, 1, 12)) * (13 - clamp(sum, 1, 12)); celestar@1179: } celestar@1179: } celestar@1179: celestar@1179: max_speed += (max_speed / 2) * v->u.rail.railtype; celestar@1179: bjarni@2676: if (IsTileType(v->tile, MP_STATION) && IsFrontEngine(v)) { celestar@1236: if (TrainShouldStop(v, v->tile)) { celestar@1179: int station_length = 0; celestar@1179: TileIndex tile = v->tile; celestar@1179: int delta_v; celestar@1179: celestar@1179: max_speed = 120; celestar@1179: do { celestar@1179: station_length++; tron@1531: tile = TILE_ADD(tile, TileOffsByDir(v->direction / 2)); tron@1685: } while (IsCompatibleTrainStationTile(tile, v->tile)); celestar@1179: celestar@1179: delta_v = v->cur_speed / (station_length + 1); celestar@1179: if (v->max_speed > (v->cur_speed - delta_v)) celestar@1179: max_speed = v->cur_speed - (delta_v / 10); celestar@1179: celestar@1179: max_speed = max(max_speed, 25 * station_length); celestar@1179: } celestar@1179: } celestar@1179: hackykid@1905: mass = v->u.rail.cached_weight; hackykid@1905: power = v->u.rail.cached_power * 746; hackykid@1905: max_speed = min(max_speed, v->u.rail.cached_max_speed); hackykid@1905: celestar@1179: for (u = v; u != NULL; u = u->next) { celestar@1179: num++; celestar@1179: drag_coeff += 3; celestar@1179: celestar@1179: if (u->u.rail.track == 0x80) hackykid@1882: max_speed = min(61, max_speed); celestar@1179: tron@1683: if (HASBIT(u->u.rail.flags, VRF_GOINGUP)) { hackykid@1905: incl += u->u.rail.cached_veh_weight * 60; //3% slope, quite a bit actually tron@1683: } else if (HASBIT(u->u.rail.flags, VRF_GOINGDOWN)) { hackykid@1905: incl -= u->u.rail.cached_veh_weight * 60; celestar@1179: } celestar@1179: } celestar@1179: celestar@1179: v->max_speed = max_speed; celestar@1179: tron@2519: if (v->u.rail.railtype != RAILTYPE_MAGLEV) { celestar@1179: resistance = 13 * mass / 10; celestar@1179: resistance += 60 * num; celestar@1179: resistance += friction * mass * speed / 1000; celestar@1179: resistance += (area * drag_coeff * speed * speed) / 10000; celestar@1179: } else celestar@1179: resistance = (area * (drag_coeff / 2) * speed * speed) / 10000; celestar@1179: resistance += incl; celestar@1179: resistance *= 4; //[N] celestar@1179: celestar@1179: if (speed > 0) { celestar@1179: switch (v->u.rail.railtype) { tron@2519: case RAILTYPE_RAIL: tron@2519: case RAILTYPE_MONO: celestar@1179: force = power / speed; //[N] celestar@1179: force *= 22; celestar@1179: force /= 10; tron@1472: break; tron@1472: tron@2519: case RAILTYPE_MAGLEV: celestar@1179: force = power / 25; tron@1472: break; celestar@1179: } tron@1472: } else { celestar@1179: //"kickoff" acceleration celestar@1969: force = (mass * 8) + resistance; tron@1472: } celestar@1179: celestar@1179: if (force <= 0) force = 10000; celestar@1179: tron@2519: if (v->u.rail.railtype != RAILTYPE_MAGLEV) force = min(force, mass * 10 * 200); celestar@1179: celestar@1179: if (mode == AM_ACCEL) { tron@1684: return (force - resistance) / (mass * 4); celestar@1179: } else { tron@1472: return min((-force - resistance) / (mass * 4), 10000 / (mass * 4)); celestar@1179: } celestar@1179: } celestar@1179: tron@2817: static void UpdateTrainAcceleration(Vehicle* v) truelight@0: { tron@1472: uint power = 0; tron@1472: uint weight = 0; truelight@0: bjarni@2676: assert(IsFrontEngine(v)); truelight@0: hackykid@1905: weight = v->u.rail.cached_weight; hackykid@1905: power = v->u.rail.cached_power; hackykid@1905: v->max_speed = v->u.rail.cached_max_speed; truelight@0: truelight@0: assert(weight != 0); truelight@0: tron@1472: v->acceleration = clamp(power / weight * 4, 1, 255); truelight@0: } truelight@0: tron@1475: int GetTrainImage(const Vehicle *v, byte direction) truelight@0: { truelight@0: int img = v->spritenum; truelight@0: int base; truelight@0: truelight@0: if (is_custom_sprite(img)) { Darkvater@1766: base = GetCustomVehicleSprite(v, direction + 4 * IS_CUSTOM_SECONDHEAD_SPRITE(img)); tron@1472: if (base != 0) return base; peter1138@2464: img = orig_rail_vehicle_info[v->engine_type].image_index; truelight@0: } truelight@193: truelight@0: base = _engine_sprite_base[img] + ((direction + _engine_sprite_add[img]) & _engine_sprite_and[img]); truelight@0: tron@2639: if (v->cargo_count >= v->cargo_cap / 2) base += _wagon_full_adder[img]; truelight@0: return base; truelight@0: } truelight@0: peter1138@2570: extern int _traininfo_vehicle_pitch; peter1138@2570: tron@2477: void DrawTrainEngine(int x, int y, EngineID engine, uint32 image_ormod) truelight@0: { tron@540: const RailVehicleInfo *rvi = RailVehInfo(engine); truelight@193: truelight@0: int img = rvi->image_index; truelight@0: uint32 image = 0; truelight@0: truelight@0: if (is_custom_sprite(img)) { darkvater@358: image = GetCustomVehicleIcon(engine, 6); peter1138@2570: if (image == 0) { peter1138@2570: img = orig_rail_vehicle_info[engine].image_index; peter1138@2570: } else { peter1138@2570: y += _traininfo_vehicle_pitch; peter1138@2570: } truelight@0: } tron@1472: if (image == 0) { truelight@0: image = (6 & _engine_sprite_and[img]) + _engine_sprite_base[img]; truelight@0: } truelight@0: truelight@0: if (rvi->flags & RVI_MULTIHEAD) { tron@1472: DrawSprite(image | image_ormod, x - 14, y); truelight@0: x += 15; truelight@0: image = 0; truelight@0: if (is_custom_sprite(img)) { darkvater@358: image = GetCustomVehicleIcon(engine, 2); peter1138@2464: if (image == 0) img = orig_rail_vehicle_info[engine].image_index; truelight@0: } tron@1472: if (image == 0) { tron@1472: image = tron@1472: ((6 + _engine_sprite_add[img + 1]) & _engine_sprite_and[img + 1]) + tron@1472: _engine_sprite_base[img + 1]; truelight@0: } truelight@0: } truelight@0: DrawSprite(image | image_ormod, x, y); truelight@0: } truelight@0: peter1138@2602: static uint CountArticulatedParts(const RailVehicleInfo *rvi, EngineID engine_type) peter1138@2602: { peter1138@2602: uint16 callback; peter1138@2602: uint i; peter1138@2602: tron@2639: if (!HASBIT(rvi->callbackmask, CBM_ARTIC_ENGINE)) return 0; peter1138@2602: peter1138@2602: for (i = 1; i < 10; i++) { peter1138@2602: callback = GetCallBackResult(CBID_ARTIC_ENGINE + (i << 8), engine_type, NULL); tron@2639: if (callback == CALLBACK_FAILED || callback == 0xFF) break; peter1138@2602: } peter1138@2602: peter1138@2608: return i - 1; peter1138@2602: } peter1138@2602: peter1138@2602: static void AddArticulatedParts(const RailVehicleInfo *rvi, Vehicle **vl) peter1138@2602: { peter1138@2602: const RailVehicleInfo *rvi_artic; peter1138@2602: EngineID engine_type; peter1138@2602: Vehicle *v = vl[0]; peter1138@2602: Vehicle *u = v; peter1138@2602: uint16 callback; peter1138@2602: bool flip_image; peter1138@2602: uint i; peter1138@2602: peter1138@2602: if (!HASBIT(rvi->callbackmask, CBM_ARTIC_ENGINE)) peter1138@2602: return; peter1138@2602: peter1138@2602: for (i = 1; i < 10; i++) { peter1138@2602: callback = GetCallBackResult(CBID_ARTIC_ENGINE + (i << 8), v->engine_type, NULL); peter1138@2602: if (callback == CALLBACK_FAILED || callback == 0xFF) peter1138@2602: return; peter1138@2602: peter1138@2602: u->next = vl[i]; peter1138@2602: u = u->next; peter1138@2602: peter1138@2608: engine_type = GB(callback, 0, 7); peter1138@2602: flip_image = HASBIT(callback, 7); peter1138@2602: rvi_artic = RailVehInfo(engine_type); peter1138@2602: peter1138@2602: // get common values from first engine peter1138@2602: u->direction = v->direction; peter1138@2602: u->owner = v->owner; peter1138@2602: u->tile = v->tile; peter1138@2602: u->x_pos = v->x_pos; peter1138@2602: u->y_pos = v->y_pos; peter1138@2602: u->z_pos = v->z_pos; peter1138@2602: u->z_height = v->z_height; peter1138@2602: u->u.rail.track = v->u.rail.track; peter1138@2602: u->u.rail.railtype = v->u.rail.railtype; peter1138@2602: u->build_year = v->build_year; peter1138@2602: u->vehstatus = v->vehstatus & ~VS_STOPPED; peter1138@2602: u->u.rail.first_engine = v->engine_type; peter1138@2602: peter1138@2602: // get more settings from rail vehicle info peter1138@2602: u->spritenum = rvi_artic->image_index; peter1138@2602: if (flip_image) u->spritenum++; peter1138@2602: u->cargo_type = rvi_artic->cargo_type; peter1138@2602: u->cargo_cap = rvi_artic->capacity; peter1138@2602: u->max_speed = 0; peter1138@2602: u->max_age = 0; peter1138@2602: u->engine_type = engine_type; peter1138@2602: u->value = 0; peter1138@2602: u->type = VEH_Train; bjarni@2676: u->subtype = 0; bjarni@2676: SetArticulatedPart(u); peter1138@2602: u->cur_image = 0xAC2; peter1138@2804: u->random_bits = VehicleRandomBits(); peter1138@2602: peter1138@2602: VehiclePositionChanged(u); peter1138@2602: } peter1138@2602: } truelight@0: tron@2477: static int32 CmdBuildRailWagon(EngineID engine, TileIndex tile, uint32 flags) truelight@0: { truelight@0: int32 value; truelight@0: const RailVehicleInfo *rvi; peter1138@2602: uint num_vehicles; truelight@0: darkvater@889: SET_EXPENSES_TYPE(EXPENSES_NEW_VEHICLES); darkvater@889: tron@540: rvi = RailVehInfo(engine); truelight@0: value = (rvi->base_cost * _price.build_railwagon) >> 8; truelight@0: peter1138@2602: num_vehicles = 1 + CountArticulatedParts(rvi, engine); peter1138@2602: truelight@0: if (!(flags & DC_QUERY_COST)) { peter1138@2609: Vehicle *vl[11]; // Allow for wagon and upto 10 artic parts. tron@2639: Vehicle* v; tron@2639: int x; tron@2639: int y; peter1138@2602: peter1138@2602: if (!AllocateVehicles(vl, num_vehicles)) peter1138@2602: return_cmd_error(STR_00E1_TOO_MANY_VEHICLES_IN_GAME); truelight@0: truelight@0: if (flags & DC_EXEC) { truelight@919: Vehicle *u, *w; tron@2150: uint dir; truelight@0: peter1138@2602: v = vl[0]; tron@2639: v->spritenum = rvi->image_index; truelight@0: truelight@919: u = NULL; truelight@919: truelight@919: FOR_ALL_VEHICLES(w) { tron@1986: if (w->type == VEH_Train && w->tile == tile && bjarni@2676: IsFreeWagon(w) && w->engine_type == engine) { truelight@919: u = GetLastVehicleInChain(w); truelight@0: break; truelight@0: } truelight@0: } truelight@0: truelight@0: v->engine_type = engine; truelight@0: tron@2150: dir = GB(_m[tile].m5, 0, 2); tron@2150: tron@2150: v->direction = dir * 2 + 1; tron@1986: v->tile = tile; truelight@193: matthijs@1942: x = TileX(tile) * TILE_SIZE | _vehicle_initial_x_fract[dir]; matthijs@1942: y = TileY(tile) * TILE_SIZE | _vehicle_initial_y_fract[dir]; truelight@0: truelight@0: v->x_pos = x; truelight@0: v->y_pos = y; truelight@0: v->z_pos = GetSlopeZ(x,y); truelight@0: v->owner = _current_player; truelight@0: v->z_height = 6; truelight@0: v->u.rail.track = 0x80; truelight@0: v->vehstatus = VS_HIDDEN | VS_DEFPAL; truelight@0: bjarni@2676: v->subtype = 0; bjarni@2676: SetTrainWagon(v); truelight@0: if (u != NULL) { truelight@0: u->next = v; bjarni@2676: } else { bjarni@2676: SetFreeWagon(v); truelight@0: } truelight@0: truelight@0: v->cargo_type = rvi->cargo_type; truelight@0: v->cargo_cap = rvi->capacity; truelight@0: v->value = value; truelight@0: // v->day_counter = 0; truelight@0: tron@2639: v->u.rail.railtype = GetEngine(engine)->railtype; truelight@193: truelight@0: v->build_year = _cur_year; truelight@0: v->type = VEH_Train; truelight@0: v->cur_image = 0xAC2; peter1138@2804: v->random_bits = VehicleRandomBits(); truelight@193: peter1138@2602: AddArticulatedParts(rvi, vl); peter1138@2602: truelight@0: _new_wagon_id = v->index; bjarni@2564: _new_vehicle_id = v->index; truelight@0: truelight@0: VehiclePositionChanged(v); hackykid@1917: TrainConsistChanged(GetFirstVehicleInChain(v)); truelight@0: truelight@0: InvalidateWindow(WC_VEHICLE_DEPOT, v->tile); truelight@0: } truelight@0: } truelight@0: truelight@0: return value; truelight@0: } truelight@0: truelight@0: // Move all free vehicles in the depot to the train tron@2630: static void NormalizeTrainVehInDepot(const Vehicle* u) truelight@0: { tron@2630: const Vehicle* v; tron@1472: truelight@0: FOR_ALL_VEHICLES(v) { bjarni@2676: if (v->type == VEH_Train && IsFreeWagon(v) && truelight@0: v->tile == u->tile && truelight@0: v->u.rail.track == 0x80) { bjarni@2676: if (CmdFailed(DoCommandByTile(0, v->index | (u->index << 16), 1, DC_EXEC, bjarni@2676: CMD_MOVE_RAIL_VEHICLE))) truelight@0: break; truelight@0: } truelight@0: } truelight@0: } truelight@0: truelight@0: static const byte _railveh_score[] = { truelight@0: 1, 4, 7, 19, 20, 30, 31, 19, truelight@0: 20, 21, 22, 10, 11, 30, 31, 32, truelight@0: 33, 34, 35, 29, 45, 32, 50, 40, truelight@0: 41, 51, 52, 0, 0, 0, 0, 0, truelight@0: 0, 0, 0, 0, 0, 0, 0, 0, truelight@0: 0, 0, 0, 0, 0, 0, 0, 0, truelight@0: 0, 0, 0, 0, 0, 0, 60, 62, truelight@0: 63, 0, 0, 0, 0, 0, 0, 0, truelight@0: 0, 0, 0, 0, 0, 0, 0, 0, truelight@0: 0, 0, 0, 0, 0, 0, 0, 0, truelight@0: 0, 0, 0, 0, 70, 71, 72, 73, truelight@0: 74, 0, 0, 0, 0, 0, 0, 0, truelight@0: 0, 0, 0, 0, 0, 0, 0, 0, truelight@0: 0, 0, 0, 0, 0, 0, 0, 0, truelight@0: 0, 0, 0, 0, truelight@0: }; truelight@0: truelight@0: tron@2630: static int32 EstimateTrainCost(const RailVehicleInfo* rvi) truelight@0: { truelight@0: return (rvi->base_cost * (_price.build_railvehicle >> 3)) >> 5; truelight@0: } truelight@0: tron@2817: static void AddRearEngineToMultiheadedTrain(Vehicle* v, Vehicle* u, bool building) bjarni@1060: { bjarni@1060: u->direction = v->direction; bjarni@1060: u->owner = v->owner; bjarni@1060: u->tile = v->tile; bjarni@1060: u->x_pos = v->x_pos; bjarni@1060: u->y_pos = v->y_pos; bjarni@1060: u->z_pos = v->z_pos; bjarni@1060: u->z_height = 6; bjarni@1060: u->u.rail.track = 0x80; bjarni@1060: u->vehstatus = v->vehstatus & ~VS_STOPPED; bjarni@2676: u->subtype = 0; bjarni@2676: SetMultiheaded(u); bjarni@1060: u->spritenum = v->spritenum + 1; bjarni@1060: u->cargo_type = v->cargo_type; bjarni@1060: u->cargo_cap = v->cargo_cap; bjarni@1060: u->u.rail.railtype = v->u.rail.railtype; bjarni@1060: if (building) v->next = u; bjarni@1060: u->engine_type = v->engine_type; bjarni@1060: u->build_year = v->build_year; tron@1472: if (building) v->value >>= 1; tron@1472: u->value = v->value; bjarni@1060: u->type = VEH_Train; bjarni@1060: u->cur_image = 0xAC2; peter1138@2804: u->random_bits = VehicleRandomBits(); bjarni@1060: VehiclePositionChanged(u); bjarni@1060: } bjarni@1060: Darkvater@1784: /** Build a railroad vehicle. Darkvater@1784: * @param x,y tile coordinates (depot) where rail-vehicle is built Darkvater@1784: * @param p1 engine type id bjarni@2677: * @param p2 bit 0 prevents any free cars from being added to the train truelight@0: */ truelight@0: int32 CmdBuildRailVehicle(int x, int y, uint32 flags, uint32 p1, uint32 p2) truelight@0: { truelight@0: const RailVehicleInfo *rvi; tron@2150: int value; peter1138@2602: Vehicle *v; truelight@1282: UnitID unit_num; truelight@0: Engine *e; tron@1980: TileIndex tile = TileVirtXY(x, y); peter1138@2602: uint num_vehicles; truelight@0: Darkvater@1784: /* Check if the engine-type is valid (for the player) */ bjarni@2854: if (!IsEngineBuildable(p1, VEH_Train)) return_cmd_error(STR_ENGINE_NOT_BUILDABLE); bjarni@1196: Darkvater@1784: /* Check if the train is actually being built in a depot belonging Darkvater@1784: * to the player. Doesn't matter if only the cost is queried */ pasky@1443: if (!(flags & DC_QUERY_COST)) { pasky@1443: if (!IsTileDepotType(tile, TRANSPORT_RAIL)) return CMD_ERROR; tron@1901: if (!IsTileOwner(tile, _current_player)) return CMD_ERROR; pasky@1443: } bjarni@1221: truelight@0: SET_EXPENSES_TYPE(EXPENSES_NEW_VEHICLES); truelight@0: tron@540: rvi = RailVehInfo(p1); bjarni@2244: e = GetEngine(p1); bjarni@2244: bjarni@2244: /* Check if depot and new engine uses the same kind of tracks */ bjarni@2244: if (!IsCompatibleRail(e->railtype, GetRailType(tile))) return CMD_ERROR; truelight@193: Darkvater@1784: if (rvi->flags & RVI_WAGON) return CmdBuildRailWagon(p1, tile, flags); truelight@0: truelight@0: value = EstimateTrainCost(rvi); ludde@2261: bjarni@2677: num_vehicles = (rvi->flags & RVI_MULTIHEAD) ? 2 : 1; peter1138@2602: num_vehicles += CountArticulatedParts(rvi, p1); truelight@0: truelight@0: if (!(flags & DC_QUERY_COST)) { peter1138@2609: Vehicle *vl[12]; // Allow for upto 10 artic parts and dual-heads peter1138@2602: if (!AllocateVehicles(vl, num_vehicles) || IsOrderPoolFull()) truelight@0: return_cmd_error(STR_00E1_TOO_MANY_VEHICLES_IN_GAME); truelight@0: peter1138@2602: v = vl[0]; peter1138@2602: truelight@0: unit_num = GetFreeUnitNumber(VEH_Train); truelight@0: if (unit_num > _patches.max_trains) truelight@0: return_cmd_error(STR_00E1_TOO_MANY_VEHICLES_IN_GAME); truelight@0: truelight@0: if (flags & DC_EXEC) { tron@2150: uint dir; tron@2150: truelight@0: v->unitnumber = unit_num; truelight@0: tron@2150: dir = GB(_m[tile].m5, 0, 2); tron@2150: tron@2150: v->direction = dir * 2 + 1; tron@1986: v->tile = tile; truelight@0: v->owner = _current_player; truelight@0: v->x_pos = (x |= _vehicle_initial_x_fract[dir]); truelight@0: v->y_pos = (y |= _vehicle_initial_y_fract[dir]); truelight@0: v->z_pos = GetSlopeZ(x,y); truelight@0: v->z_height = 6; truelight@0: v->u.rail.track = 0x80; truelight@0: v->vehstatus = VS_HIDDEN | VS_STOPPED | VS_DEFPAL; truelight@0: v->spritenum = rvi->image_index; truelight@0: v->cargo_type = rvi->cargo_type; truelight@0: v->cargo_cap = rvi->capacity; truelight@0: v->max_speed = rvi->max_speed; truelight@0: v->value = value; truelight@1266: v->last_station_visited = INVALID_STATION; truelight@0: v->dest_tile = 0; truelight@193: tron@2477: v->engine_type = p1; truelight@0: truelight@0: v->reliability = e->reliability; truelight@0: v->reliability_spd_dec = e->reliability_spd_dec; truelight@0: v->max_age = e->lifelength * 366; truelight@193: truelight@0: v->string_id = STR_SV_TRAIN_NAME; truelight@0: v->u.rail.railtype = e->railtype; truelight@0: _new_train_id = v->index; bjarni@2564: _new_vehicle_id = v->index; truelight@193: truelight@0: v->service_interval = _patches.servint_trains; truelight@0: v->date_of_last_service = _date; truelight@0: v->build_year = _cur_year; truelight@0: v->type = VEH_Train; truelight@0: v->cur_image = 0xAC2; peter1138@2804: v->random_bits = VehicleRandomBits(); truelight@0: bjarni@2676: v->subtype = 0; bjarni@2676: SetFrontEngine(v); bjarni@2676: SetTrainEngine(v); bjarni@2676: truelight@0: VehiclePositionChanged(v); truelight@0: bjarni@2677: if (rvi->flags & RVI_MULTIHEAD) { bjarni@2676: SetMultiheaded(v); peter1138@2602: AddRearEngineToMultiheadedTrain(vl[0], vl[1], true); bjarni@2676: /* Now we need to link the front and rear engines together bjarni@2676: * other_multiheaded_part is the pointer that links to the other half of the engine bjarni@2676: * vl[0] is the front and vl[1] is the rear bjarni@2676: */ bjarni@2676: vl[0]->u.rail.other_multiheaded_part = vl[1]; bjarni@2676: vl[1]->u.rail.other_multiheaded_part = vl[0]; peter1138@2602: } else { peter1138@2602: AddArticulatedParts(rvi, vl); bjarni@2244: } truelight@0: hackykid@1905: TrainConsistChanged(v); truelight@0: UpdateTrainAcceleration(v); bjarni@2244: bjarni@2677: if (!HASBIT(p2, 0)) { // check if the cars should be added to the new vehicle bjarni@2244: NormalizeTrainVehInDepot(v); bjarni@2244: } truelight@0: truelight@0: InvalidateWindow(WC_VEHICLE_DEPOT, tile); tron@588: RebuildVehicleLists(); truelight@0: InvalidateWindow(WC_COMPANY, v->owner); bjarni@2618: if (IsLocalPlayer()) { bjarni@2618: InvalidateWindow(WC_REPLACE_VEHICLE, VEH_Train); // updates the replace Train window bjarni@2618: } truelight@0: } truelight@0: } truelight@0: _cmd_build_rail_veh_score = _railveh_score[p1]; bjarni@1128: truelight@193: return value; truelight@0: } truelight@0: truelight@0: matthijs@1942: /* Check if all the wagons of the given train are in a depot, returns the matthijs@1942: * number of cars (including loco) then. If not, sets the error message to matthijs@1942: * STR_881A_TRAINS_CAN_ONLY_BE_ALTERED and returns -1 */ tron@1472: int CheckTrainStoppedInDepot(const Vehicle *v) truelight@0: { truelight@0: int count; truelight@0: TileIndex tile = v->tile; truelight@193: truelight@0: /* check if stopped in a depot */ matthijs@1330: if (!IsTileDepotType(tile, TRANSPORT_RAIL) || v->cur_speed != 0) { truelight@0: _error_message = STR_881A_TRAINS_CAN_ONLY_BE_ALTERED; truelight@0: return -1; truelight@0: } truelight@0: truelight@0: count = 0; tron@1472: for (; v != NULL; v = v->next) { peter1138@2844: /* This count is used by the depot code to determine the number of engines peter1138@2844: * in the consist. Exclude articulated parts so that autoreplacing to peter1138@2844: * engines with more articulated parts that before works correctly. */ peter1138@2844: if (!IsArticulatedPart(v)) count++; tron@1472: if (v->u.rail.track != 0x80 || v->tile != tile || bjarni@2676: (IsFrontEngine(v) && !(v->vehstatus & VS_STOPPED))) { tron@1472: _error_message = STR_881A_TRAINS_CAN_ONLY_BE_ALTERED; tron@1472: return -1; tron@1472: } tron@1472: } truelight@0: truelight@0: return count; truelight@0: } truelight@0: peter1138@2602: /** peter1138@2602: * Unlink a rail wagon from the consist. peter1138@2602: * @param v Vehicle to remove. peter1138@2602: * @param first The first vehicle of the consist. peter1138@2602: * @return The first vehicle of the consist. peter1138@2602: */ truelight@0: static Vehicle *UnlinkWagon(Vehicle *v, Vehicle *first) truelight@0: { Darkvater@1766: Vehicle *u; Darkvater@1766: truelight@0: // unlinking the first vehicle of the chain? truelight@0: if (v == first) { peter1138@2602: v = GetNextVehicle(v); tron@1472: if (v == NULL) return NULL; Darkvater@1766: bjarni@2676: if (IsTrainWagon(v)) SetFreeWagon(v); bjarni@2676: truelight@0: return v; truelight@0: } Darkvater@1766: peter1138@2602: for (u = first; GetNextVehicle(u) != v; u = GetNextVehicle(u)) {} peter1138@2602: GetLastEnginePart(u)->next = GetNextVehicle(v); Darkvater@1766: return first; truelight@0: } truelight@0: tron@1472: static Vehicle *FindGoodVehiclePos(const Vehicle *src) truelight@0: { truelight@0: Vehicle *dst; tron@2477: EngineID eng = src->engine_type; truelight@0: TileIndex tile = src->tile; truelight@0: truelight@0: FOR_ALL_VEHICLES(dst) { bjarni@2676: if (dst->type == VEH_Train && IsFreeWagon(dst) && tron@1472: dst->tile == tile) { truelight@0: // check so all vehicles in the line have the same engine. truelight@0: Vehicle *v = dst; tron@1472: truelight@0: while (v->engine_type == eng) { tron@1472: v = v->next; tron@1472: if (v == NULL) return dst; truelight@0: } truelight@0: } truelight@0: } truelight@0: truelight@0: return NULL; truelight@0: } truelight@0: bjarni@2676: /* bjarni@2676: * add a vehicle v behind vehicle dest bjarni@2676: * use this function since it sets flags as needed bjarni@2676: */ bjarni@2676: static void AddWagonToConsist(Vehicle *v, Vehicle *dest) bjarni@2676: { bjarni@2676: UnlinkWagon(v, GetFirstVehicleInChain(v)); bjarni@2676: if (dest == NULL) return; bjarni@2676: bjarni@2676: v->next = dest->next; bjarni@2676: dest->next = v; bjarni@2676: ClearFreeWagon(v); bjarni@2676: ClearFrontEngine(v); bjarni@2676: } bjarni@2676: bjarni@2676: /* bjarni@2676: * move around on the train so rear engines are placed correctly according to the other engines bjarni@2676: * always call with the front engine bjarni@2676: */ bjarni@2676: static void NormaliseTrainConsist(Vehicle *v) bjarni@2676: { bjarni@2676: Vehicle *u; bjarni@2676: bjarni@2676: if (IsFreeWagon(v)) return; bjarni@2676: bjarni@2676: assert(IsFrontEngine(v)); bjarni@2676: bjarni@2676: for(; v != NULL; v = GetNextVehicle(v)) { bjarni@2676: if (!IsMultiheaded(v) || !IsTrainEngine(v)) continue; bjarni@2676: bjarni@2676: /* make sure that there are no free cars before next engine */ bjarni@2676: for(u = v; u->next != NULL && !IsTrainEngine(u->next); u = u->next); bjarni@2676: bjarni@2676: if (u == v->u.rail.other_multiheaded_part) continue; bjarni@2676: AddWagonToConsist(v->u.rail.other_multiheaded_part, u); bjarni@2676: bjarni@2676: } bjarni@2676: } bjarni@2676: Darkvater@1784: /** Move a rail vehicle around inside the depot. Darkvater@1784: * @param x,y unused Darkvater@1784: * @param p1 various bitstuffed elements tron@2639: * - p1 (bit 0 - 15) source vehicle index tron@2639: * - p1 (bit 16 - 31) what wagon to put the source wagon AFTER, XXX - INVALID_VEHICLE to make a new line Darkvater@1784: * @param p2 (bit 0) move all vehicles following the source vehicle truelight@0: */ truelight@0: int32 CmdMoveRailVehicle(int x, int y, uint32 flags, uint32 p1, uint32 p2) truelight@0: { tron@2484: VehicleID s = GB(p1, 0, 16); tron@2484: VehicleID d = GB(p1, 16, 16); truelight@0: Vehicle *src, *dst, *src_head, *dst_head; truelight@0: tron@2484: if (!IsVehicleIndex(s)) return CMD_ERROR; tron@2484: tron@2484: src = GetVehicle(s); bjarni@1237: truelight@0: if (src->type != VEH_Train) return CMD_ERROR; truelight@0: truelight@0: // if nothing is selected as destination, try and find a matching vehicle to drag to. tron@2484: if (d == INVALID_VEHICLE) { truelight@0: dst = NULL; bjarni@2676: if (!IsTrainEngine(src)) dst = FindGoodVehiclePos(src); truelight@0: } else { tron@2484: dst = GetVehicle(d); truelight@0: } truelight@0: peter1138@2602: // if an articulated part is being handled, deal with its parent vehicle bjarni@2676: while (IsArticulatedPart(src)) src = GetPrevVehicleInChain(src); peter1138@2602: if (dst != NULL) { bjarni@2676: while (IsArticulatedPart(dst)) dst = GetPrevVehicleInChain(dst); peter1138@2602: } peter1138@2602: truelight@0: // don't move the same vehicle.. Darkvater@1784: if (src == dst) return 0; truelight@193: truelight@0: /* the player must be the owner */ tron@2639: if (!CheckOwnership(src->owner) || (dst != NULL && !CheckOwnership(dst->owner))) truelight@0: return CMD_ERROR; truelight@0: truelight@0: /* locate the head of the two chains */ truelight@0: src_head = GetFirstVehicleInChain(src); truelight@0: dst_head = NULL; peter1138@2602: if (dst != NULL) { peter1138@2602: dst_head = GetFirstVehicleInChain(dst); peter1138@2602: // Now deal with articulated part of destination wagon peter1138@2602: dst = GetLastEnginePart(dst); peter1138@2602: } truelight@193: bjarni@2676: if (dst != NULL && IsMultiheaded(dst) && !IsTrainEngine(dst) && IsTrainWagon(src)) { bjarni@2676: /* We are moving a wagon to the rear part of a multiheaded engine */ bjarni@2676: if (dst->next == NULL) { bjarni@2676: /* It's the last one, so we will add the wagon just before the rear engine */ bjarni@2676: dst = GetPrevVehicleInChain(dst); truelight@2825: /* Now if the vehicle we want to link to is the vehicle itself, drop out */ truelight@2825: if (dst == src) return CMD_ERROR; bjarni@2676: // if dst is NULL, it means that dst got a rear multiheaded engine as first engine. We can't use that bjarni@2676: if (dst == NULL) return CMD_ERROR; bjarni@2676: } else { bjarni@2676: /* there are more units on this train, so we will add the wagon after the next one*/ bjarni@2676: dst = dst->next; bjarni@2676: } celestar@1601: } celestar@1601: bjarni@2676: if (IsTrainEngine(src) && dst_head != NULL) { bjarni@2676: /* we need to make sure that we didn't place it between a pair of multiheaded engines */ bjarni@2676: Vehicle *u, *engine = NULL; bjarni@2676: bjarni@2676: for(u = dst_head; u != NULL; u = u->next) { bjarni@2676: if (IsTrainEngine(u) && IsMultiheaded(u) && u->u.rail.other_multiheaded_part != NULL) { bjarni@2676: engine = u; bjarni@2676: } bjarni@2676: if (engine != NULL && engine->u.rail.other_multiheaded_part == u) { bjarni@2676: engine = NULL; bjarni@2676: } bjarni@2676: if (u == dst) { bjarni@2676: if (engine != NULL) { bjarni@2676: dst = engine->u.rail.other_multiheaded_part; bjarni@2676: } bjarni@2676: break; bjarni@2676: } bjarni@2676: bjarni@2676: } bjarni@2676: } bjarni@2676: bjarni@2676: if (IsMultiheaded(src) && !IsTrainEngine(src)) return_cmd_error(STR_REAR_ENGINE_FOLLOW_FRONT_ERROR); bjarni@2676: truelight@0: // when moving all wagons, we can't have the same src_head and dst_head Darkvater@1784: if (HASBIT(p2, 0) && src_head == dst_head) return 0; truelight@0: peter1138@2883: { peter1138@2883: int src_len = 0; peter1138@2883: int max_len = _patches.mammoth_trains ? 100 : 9; peter1138@2883: peter1138@2883: // check if all vehicles in the source train are stopped inside a depot. peter1138@2883: src_len = CheckTrainStoppedInDepot(src_head); peter1138@2883: if (src_len < 0) return CMD_ERROR; peter1138@2883: peter1138@2883: // check the destination row if the source and destination aren't the same. peter1138@2883: if (src_head != dst_head) { peter1138@2883: int dst_len = 0; peter1138@2883: peter1138@2883: if (dst_head != NULL) { peter1138@2883: // check if all vehicles in the dest train are stopped. peter1138@2883: dst_len = CheckTrainStoppedInDepot(dst_head); peter1138@2883: if (dst_len < 0) return CMD_ERROR; peter1138@2883: peter1138@2883: assert(dst_head->tile == src_head->tile); peter1138@2883: } peter1138@2883: peter1138@2883: // We are moving between rows, so only count the wagons from the source peter1138@2883: // row that are being moved. peter1138@2883: if (HASBIT(p2, 0)) { peter1138@2883: const Vehicle *u; peter1138@2883: for (u = src_head; u != src && u != NULL; u = GetNextVehicle(u)) peter1138@2883: src_len--; peter1138@2883: } else { peter1138@2883: // If moving only one vehicle, just count that. peter1138@2883: src_len = 1; peter1138@2883: } peter1138@2883: peter1138@2883: if (src_len + dst_len > max_len) { peter1138@2883: // Abort if we're adding too many wagons to a train. peter1138@2883: if (dst_head != NULL && IsFrontEngine(dst_head)) return_cmd_error(STR_8819_TRAIN_TOO_LONG); peter1138@2883: // Abort if we're making a train on a new row. peter1138@2883: if (dst_head == NULL && IsTrainEngine(src)) return_cmd_error(STR_8819_TRAIN_TOO_LONG); peter1138@2883: } peter1138@2883: } else { peter1138@2883: // Abort if we're creating a new train on an existing row. peter1138@2883: if (src_len > max_len && src == src_head && IsTrainEngine(GetNextVehicle(src_head))) peter1138@2883: return_cmd_error(STR_8819_TRAIN_TOO_LONG); peter1138@2883: } peter1138@2883: } peter1138@2883: truelight@0: // moving a loco to a new line?, then we need to assign a unitnumber. bjarni@2676: if (dst == NULL && !IsFrontEngine(src) && IsTrainEngine(src)) { truelight@1282: UnitID unit_num = GetFreeUnitNumber(VEH_Train); truelight@0: if (unit_num > _patches.max_trains) truelight@0: return_cmd_error(STR_00E1_TOO_MANY_VEHICLES_IN_GAME); truelight@0: truelight@0: if (flags & DC_EXEC) truelight@0: src->unitnumber = unit_num; truelight@0: } truelight@0: truelight@0: truelight@0: /* do it? */ truelight@0: if (flags & DC_EXEC) { bjarni@2676: /* clear the ->first cache */ bjarni@2676: { bjarni@2676: Vehicle *u; bjarni@2676: bjarni@2676: for (u = src_head; u != NULL; u = u->next) u->first = NULL; bjarni@2676: for (u = dst_head; u != NULL; u = u->next) u->first = NULL; bjarni@2676: } bjarni@2607: Darkvater@1784: if (HASBIT(p2, 0)) { truelight@0: // unlink ALL wagons truelight@0: if (src != src_head) { truelight@0: Vehicle *v = src_head; peter1138@2602: while (GetNextVehicle(v) != src) v = GetNextVehicle(v); peter1138@2602: GetLastEnginePart(v)->next = NULL; hackykid@1917: } else { hackykid@1917: src_head = NULL; truelight@0: } truelight@0: } else { hackykid@1921: // if moving within the same chain, dont use dst_head as it may get invalidated hackykid@1921: if (src_head == dst_head) hackykid@1921: dst_head = NULL; truelight@0: // unlink single wagon from linked list hackykid@1917: src_head = UnlinkWagon(src, src_head); peter1138@2602: GetLastEnginePart(src)->next = NULL; truelight@0: } truelight@0: truelight@0: if (dst == NULL) { bjarni@2676: // move the train to an empty line. for locomotives, we set the type to TS_Front. for wagons, 4. bjarni@2676: if (IsTrainEngine(src)) { bjarni@2676: if (!IsFrontEngine(src)) { truelight@1024: // setting the type to 0 also involves setting up the orders field. bjarni@2676: SetFrontEngine(src); truelight@1024: assert(src->orders == NULL); truelight@0: src->num_orders = 0; truelight@0: } truelight@0: } else { bjarni@2676: SetFreeWagon(src); truelight@0: } hackykid@1917: dst_head = src; truelight@0: } else { bjarni@2676: if (IsFrontEngine(src)) { truelight@1024: // the vehicle was previously a loco. need to free the order list and delete vehicle windows etc. truelight@0: DeleteWindowById(WC_VEHICLE_VIEW, src->index); truelight@1024: DeleteVehicleOrders(src); truelight@0: } truelight@193: bjarni@2676: ClearFrontEngine(src); bjarni@2676: ClearFreeWagon(src); truelight@0: src->unitnumber = 0; // doesn't occupy a unitnumber anymore. truelight@0: truelight@0: // link in the wagon(s) in the chain. truelight@0: { tron@1472: Vehicle *v; tron@1472: peter1138@2602: for (v = src; GetNextVehicle(v) != NULL; v = GetNextVehicle(v)); peter1138@2602: GetLastEnginePart(v)->next = dst->next; truelight@0: } truelight@0: dst->next = src; truelight@0: } bjarni@2676: if (src->u.rail.other_multiheaded_part != NULL) { bjarni@2676: if (src->u.rail.other_multiheaded_part == src_head) { bjarni@2676: src_head = src_head->next; bjarni@2676: } bjarni@2676: AddWagonToConsist(src->u.rail.other_multiheaded_part, src); bjarni@2676: } bjarni@2676: bjarni@2676: if (HASBIT(p2, 0) && src_head != NULL && src_head != src) { bjarni@2676: /* if we stole a rear multiheaded engine, we better give it back to the front end */ bjarni@2676: Vehicle *engine = NULL, *u; bjarni@2676: for (u = src_head; u != NULL; u = u->next) { bjarni@2676: if (IsMultiheaded(u)) { bjarni@2676: if (IsTrainEngine(u)) { bjarni@2676: engine = u; bjarni@2676: continue; bjarni@2676: } bjarni@2676: /* we got the rear engine to match with the front one */ bjarni@2676: engine = NULL; bjarni@2676: } bjarni@2676: } bjarni@2676: if (engine != NULL && engine->u.rail.other_multiheaded_part != NULL) { bjarni@2676: AddWagonToConsist(engine->u.rail.other_multiheaded_part, engine); bjarni@2676: // previous line set the front engine to the old front. We need to clear that bjarni@2676: engine->u.rail.other_multiheaded_part->first = NULL; bjarni@2676: } bjarni@2676: } truelight@0: bjarni@2607: /* If there is an engine behind first_engine we moved away, it should become new first_engine bjarni@2607: * To do this, CmdMoveRailVehicle must be called once more bjarni@2676: * we can't loop forever here because next time we reach this line we will have a front engine */ bjarni@2676: if (src_head != NULL && !IsFrontEngine(src_head) && IsTrainEngine(src_head)) { bjarni@2676: CmdMoveRailVehicle(x, y, flags, src_head->index | (INVALID_VEHICLE << 16), 1); bjarni@2676: src_head = NULL; // don't do anything more to this train since the new call will do it bjarni@2607: } bjarni@2607: hackykid@1917: if (src_head) { bjarni@2676: NormaliseTrainConsist(src_head); hackykid@1905: TrainConsistChanged(src_head); bjarni@2676: if (IsFrontEngine(src_head)) { hackykid@1917: UpdateTrainAcceleration(src_head); hackykid@1917: InvalidateWindow(WC_VEHICLE_DETAILS, src_head->index); hackykid@1917: /* Update the refit button and window */ hackykid@1917: InvalidateWindow(WC_VEHICLE_REFIT, src_head->index); hackykid@1917: InvalidateWindowWidget(WC_VEHICLE_VIEW, src_head->index, 12); hackykid@1917: } hackykid@1917: /* Update the depot window */ hackykid@1917: InvalidateWindow(WC_VEHICLE_DEPOT, src_head->tile); hackykid@1917: }; truelight@0: truelight@0: if (dst_head) { bjarni@2676: NormaliseTrainConsist(dst_head); hackykid@1917: TrainConsistChanged(dst_head); bjarni@2676: if (IsFrontEngine(dst_head)) { truelight@0: UpdateTrainAcceleration(dst_head); hackykid@1917: InvalidateWindow(WC_VEHICLE_DETAILS, dst_head->index); hackykid@1917: /* Update the refit button and window */ hackykid@1917: InvalidateWindowWidget(WC_VEHICLE_VIEW, dst_head->index, 12); hackykid@1917: InvalidateWindow(WC_VEHICLE_REFIT, dst_head->index); hackykid@1905: } hackykid@1917: /* Update the depot window */ hackykid@1917: InvalidateWindow(WC_VEHICLE_DEPOT, dst_head->tile); truelight@0: } truelight@0: tron@737: RebuildVehicleLists(); truelight@0: } truelight@0: truelight@0: return 0; truelight@0: } truelight@0: Darkvater@1784: /** Start/Stop a train. Darkvater@1784: * @param x,y unused Darkvater@1784: * @param p1 train to start/stop Darkvater@1784: * @param p2 unused Darkvater@1784: */ truelight@0: int32 CmdStartStopTrain(int x, int y, uint32 flags, uint32 p1, uint32 p2) truelight@0: { truelight@0: Vehicle *v; truelight@0: bjarni@1237: if (!IsVehicleIndex(p1)) return CMD_ERROR; bjarni@1237: truelight@919: v = GetVehicle(p1); truelight@0: Darkvater@1784: if (v->type != VEH_Train || !CheckOwnership(v->owner)) return CMD_ERROR; truelight@0: truelight@0: if (flags & DC_EXEC) { truelight@0: v->u.rail.days_since_order_progr = 0; truelight@0: v->vehstatus ^= VS_STOPPED; darkvater@755: InvalidateWindowWidget(WC_VEHICLE_VIEW, v->index, STATUS_BAR); truelight@0: InvalidateWindow(WC_VEHICLE_DEPOT, v->tile); truelight@0: } truelight@0: return 0; truelight@0: } truelight@0: Darkvater@1784: /** Sell a (single) train wagon/engine. Darkvater@1784: * @param x,y unused Darkvater@1766: * @param p1 the wagon/engine index Darkvater@1766: * @param p2 the selling mode Darkvater@1784: * - p2 = 0: only sell the single dragged wagon/engine (and any belonging rear-engines) Darkvater@1784: * - p2 = 1: sell the vehicle and all vehicles following it in the chain Darkvater@1784: if the wagon is dragged, don't delete the possibly belonging rear-engine to some front Darkvater@1784: * - p2 = 2: when selling attached locos, rearrange all vehicles after it to separate lines; Darkvater@1784: * all wagons of the same type will go on the same line. Used by the AI currently Darkvater@1766: */ truelight@0: int32 CmdSellRailWagon(int x, int y, uint32 flags, uint32 p1, uint32 p2) truelight@0: { Darkvater@1766: Vehicle *v, *tmp, *first; bjarni@2676: Vehicle *new_f = NULL; Darkvater@1766: int32 cost = 0; Darkvater@1766: Darkvater@1766: if (!IsVehicleIndex(p1) || p2 > 2) return CMD_ERROR; truelight@0: truelight@919: v = GetVehicle(p1); truelight@0: Darkvater@1784: if (v->type != VEH_Train || !CheckOwnership(v->owner)) return CMD_ERROR; truelight@0: bjarni@1237: SET_EXPENSES_TYPE(EXPENSES_NEW_VEHICLES); bjarni@1237: bjarni@2676: while (IsArticulatedPart(v)) v = GetPrevVehicleInChain(v); Darkvater@1766: first = GetFirstVehicleInChain(v); truelight@193: truelight@0: // make sure the vehicle is stopped in the depot Darkvater@1784: if (CheckTrainStoppedInDepot(first) < 0) return CMD_ERROR; truelight@0: bjarni@2676: if (IsMultiheaded(v) && !IsTrainEngine(v)) return_cmd_error(STR_REAR_ENGINE_FOLLOW_FRONT_ERROR); bjarni@2676: Darkvater@1842: if (flags & DC_EXEC) { bjarni@2676: if (v == first && IsFrontEngine(first)) { Darkvater@1842: DeleteWindowById(WC_VEHICLE_VIEW, first->index); bjarni@2618: } bjarni@2618: if (IsLocalPlayer() && (p1 == 1 || !(RailVehInfo(v->engine_type)->flags & RVI_WAGON))) { Darkvater@1842: InvalidateWindow(WC_REPLACE_VEHICLE, VEH_Train); Darkvater@1842: } truelight@0: InvalidateWindow(WC_VEHICLE_DEPOT, first->tile); Darkvater@1779: RebuildVehicleLists(); Darkvater@1766: } Darkvater@1766: Darkvater@1766: switch (p2) { Darkvater@1766: case 0: case 2: { /* Delete given wagon */ Darkvater@1766: bool switch_engine = false; // update second wagon to engine? Darkvater@1766: byte ori_subtype = v->subtype; // backup subtype of deleted wagon in case DeleteVehicle() changes Darkvater@1766: Darkvater@1766: /* 1. Delete the engine, if it is dualheaded also delete the matching bjarni@2676: * rear engine of the loco (from the point of deletion onwards) */ bjarni@2676: Vehicle *rear = (IsMultiheaded(v) && bjarni@2676: IsTrainEngine(v)) ? v->u.rail.other_multiheaded_part : NULL; bjarni@2676: Darkvater@1766: if (rear != NULL) { bjarni@2676: cost -= rear->value; Darkvater@1766: if (flags & DC_EXEC) { bjarni@2676: UnlinkWagon(rear, first); Darkvater@1766: DeleteVehicle(rear); truelight@0: } truelight@0: } Darkvater@1766: Darkvater@1766: /* 2. We are selling the first engine, some special action might be required bjarni@2676: * here, so take attention */ Darkvater@1770: if ((flags & DC_EXEC) && v == first) { bjarni@2676: new_f = GetNextVehicle(first); Darkvater@1766: Darkvater@1766: /* 2.1 If the first wagon is sold, update the first-> pointers to NULL */ Darkvater@1766: for (tmp = first; tmp != NULL; tmp = tmp->next) tmp->first = NULL; Darkvater@1766: Darkvater@1766: /* 2.2 If there are wagons present after the deleted front engine, check Darkvater@1766: * if the second wagon (which will be first) is an engine. If it is one, Darkvater@1766: * promote it as a new train, retaining the unitnumber, orders */ Darkvater@1766: if (new_f != NULL) { bjarni@2676: if (IsTrainEngine(new_f)) { Darkvater@1766: switch_engine = true; Darkvater@1766: /* Copy important data from the front engine */ Darkvater@1766: new_f->unitnumber = first->unitnumber; Darkvater@1766: new_f->current_order = first->current_order; Darkvater@1766: new_f->cur_order_index = first->cur_order_index; Darkvater@1766: new_f->orders = first->orders; Darkvater@1766: new_f->num_orders = first->num_orders; Darkvater@1766: first->orders = NULL; // XXX - to not to delete the orders */ Darkvater@2425: if (IsLocalPlayer()) ShowTrainViewWindow(new_f); Darkvater@1766: } Darkvater@1766: } Darkvater@1766: } Darkvater@1766: Darkvater@1766: /* 3. Delete the requested wagon */ tron@1472: cost -= v->value; Darkvater@1766: if (flags & DC_EXEC) { Darkvater@1766: first = UnlinkWagon(v, first); Darkvater@1766: DeleteVehicle(v); Darkvater@1766: Darkvater@1766: /* 4 If the second wagon was an engine, update it to front_engine Darkvater@1766: * which UnlinkWagon() has changed to TS_Free_Car */ bjarni@2676: if (switch_engine) SetFrontEngine(first); Darkvater@1766: Darkvater@1766: /* 5. If the train still exists, update its acceleration, window, etc. */ hackykid@1917: if (first != NULL) { bjarni@2676: NormaliseTrainConsist(first); hackykid@1905: TrainConsistChanged(first); bjarni@2676: if (IsFrontEngine(first)) { hackykid@1917: InvalidateWindow(WC_VEHICLE_DETAILS, first->index); hackykid@1917: InvalidateWindow(WC_VEHICLE_REFIT, first->index); hackykid@1917: UpdateTrainAcceleration(first); hackykid@1917: } Darkvater@1766: } Darkvater@1766: Darkvater@1766: Darkvater@1766: /* (6.) Borked AI. If it sells an engine it expects all wagons lined bjarni@2676: * up on a new line to be added to the newly built loco. Replace it is. bjarni@2676: * Totally braindead cause building a new engine adds all loco-less bjarni@2676: * engines to its train anyways */ bjarni@2676: if (p2 == 2 && HASBIT(ori_subtype, Train_Front)) { Darkvater@1766: for (v = first; v != NULL; v = tmp) { peter1138@2602: tmp = GetNextVehicle(v); Darkvater@1766: DoCommandByTile(v->tile, v->index | INVALID_VEHICLE << 16, 0, DC_EXEC, CMD_MOVE_RAIL_VEHICLE); Darkvater@1766: } Darkvater@1766: } Darkvater@1766: } Darkvater@1766: } break; Darkvater@1766: case 1: { /* Delete wagon and all wagons after it given certain criteria */ bjarni@2676: /* Start deleting every vehicle after the selected one bjarni@2676: * If we encounter a matching rear-engine to a front-engine bjarni@2676: * earlier in the chain (before deletion), leave it alone */ Darkvater@1766: for (; v != NULL; v = tmp) { peter1138@2602: tmp = GetNextVehicle(v); Darkvater@1766: bjarni@2676: if (IsMultiheaded(v)) { bjarni@2676: if (IsTrainEngine(v)) { bjarni@2676: /* We got a front engine of a multiheaded set. Now we will sell the rear end too */ bjarni@2676: Vehicle *rear = v->u.rail.other_multiheaded_part; bjarni@2676: bjarni@2676: if (rear != NULL) { bjarni@2676: cost -= rear->value; bjarni@2676: if (flags & DC_EXEC) { bjarni@2676: first = UnlinkWagon(rear, first); bjarni@2676: DeleteVehicle(rear); bjarni@2676: } bjarni@2676: } bjarni@2676: } else if (v->u.rail.other_multiheaded_part != NULL) { bjarni@2676: /* The front to this engine is earlier in this train. Do nothing */ tron@2549: continue; tron@2549: } Darkvater@1766: } Darkvater@1766: Darkvater@1766: cost -= v->value; Darkvater@1766: if (flags & DC_EXEC) { Darkvater@1766: first = UnlinkWagon(v, first); Darkvater@1766: DeleteVehicle(v); Darkvater@1766: } Darkvater@1766: } Darkvater@1766: hackykid@1905: /* 3. If it is still a valid train after selling, update its acceleration and cached values */ hackykid@1917: if ((flags & DC_EXEC) && first != NULL) { bjarni@2676: NormaliseTrainConsist(first); hackykid@1905: TrainConsistChanged(first); bjarni@2676: if (IsFrontEngine(first)) hackykid@1917: UpdateTrainAcceleration(first); bjarni@2676: InvalidateWindow(WC_VEHICLE_DETAILS, first->index); bjarni@2676: InvalidateWindow(WC_VEHICLE_REFIT, first->index); hackykid@1905: } Darkvater@1766: } break; truelight@0: } truelight@0: return cost; truelight@0: } truelight@0: truelight@0: static void UpdateTrainDeltaXY(Vehicle *v, int direction) truelight@0: { truelight@0: #define MKIT(a,b,c,d) ((a&0xFF)<<24) | ((b&0xFF)<<16) | ((c&0xFF)<<8) | ((d&0xFF)<<0) truelight@0: static const uint32 _delta_xy_table[8] = { truelight@0: MKIT(3, 3, -1, -1), truelight@0: MKIT(3, 7, -1, -3), truelight@0: MKIT(3, 3, -1, -1), truelight@0: MKIT(7, 3, -3, -1), truelight@0: MKIT(3, 3, -1, -1), truelight@0: MKIT(3, 7, -1, -3), truelight@0: MKIT(3, 3, -1, -1), truelight@0: MKIT(7, 3, -3, -1), truelight@0: }; truelight@0: #undef MKIT truelight@0: truelight@0: uint32 x = _delta_xy_table[direction]; truelight@0: tron@2150: v->x_offs = GB(x, 0, 8); tron@2150: v->y_offs = GB(x, 8, 8); tron@2150: v->sprite_width = GB(x, 16, 8); tron@2150: v->sprite_height = GB(x, 24, 8); truelight@0: } truelight@0: truelight@0: static void UpdateVarsAfterSwap(Vehicle *v) truelight@0: { truelight@0: UpdateTrainDeltaXY(v, v->direction); truelight@0: v->cur_image = GetTrainImage(v, v->direction); truelight@0: BeginVehicleMove(v); truelight@0: VehiclePositionChanged(v); truelight@0: EndVehicleMove(v); truelight@0: } truelight@0: tron@2639: static void SetLastSpeed(Vehicle* v, int spd) tron@2639: { truelight@0: int old = v->u.rail.last_speed; truelight@0: if (spd != old) { truelight@0: v->u.rail.last_speed = spd; truelight@0: if (_patches.vehicle_speed || !old != !spd) darkvater@755: InvalidateWindowWidget(WC_VEHICLE_VIEW, v->index, STATUS_BAR); truelight@0: } truelight@0: } truelight@0: truelight@954: static void SwapTrainFlags(byte *swap_flag1, byte *swap_flag2) truelight@954: { truelight@954: byte flag1, flag2; truelight@954: truelight@954: flag1 = *swap_flag1; truelight@954: flag2 = *swap_flag2; truelight@954: truelight@954: /* Clear the flags */ truelight@954: CLRBIT(*swap_flag1, VRF_GOINGUP); truelight@954: CLRBIT(*swap_flag1, VRF_GOINGDOWN); truelight@954: CLRBIT(*swap_flag2, VRF_GOINGUP); truelight@954: CLRBIT(*swap_flag2, VRF_GOINGDOWN); truelight@954: truelight@954: /* Reverse the rail-flags (if needed) */ truelight@954: if (HASBIT(flag1, VRF_GOINGUP)) { truelight@954: SETBIT(*swap_flag2, VRF_GOINGDOWN); truelight@954: } else if (HASBIT(flag1, VRF_GOINGDOWN)) { truelight@954: SETBIT(*swap_flag2, VRF_GOINGUP); truelight@954: } truelight@954: if (HASBIT(flag2, VRF_GOINGUP)) { truelight@954: SETBIT(*swap_flag1, VRF_GOINGDOWN); truelight@954: } else if (HASBIT(flag2, VRF_GOINGDOWN)) { truelight@954: SETBIT(*swap_flag1, VRF_GOINGUP); truelight@954: } truelight@954: } truelight@954: truelight@0: static void ReverseTrainSwapVeh(Vehicle *v, int l, int r) truelight@0: { truelight@0: Vehicle *a, *b; truelight@0: truelight@0: /* locate vehicles to swap */ tron@2549: for (a = v; l != 0; l--) a = a->next; tron@2549: for (b = v; r != 0; r--) b = b->next; truelight@0: truelight@0: if (a != b) { truelight@0: /* swap the hidden bits */ truelight@0: { truelight@0: uint16 tmp = (a->vehstatus & ~VS_HIDDEN) | (b->vehstatus&VS_HIDDEN); truelight@0: b->vehstatus = (b->vehstatus & ~VS_HIDDEN) | (a->vehstatus&VS_HIDDEN); truelight@0: a->vehstatus = tmp; truelight@0: } truelight@193: truelight@0: /* swap variables */ truelight@0: swap_byte(&a->u.rail.track, &b->u.rail.track); truelight@0: swap_byte(&a->direction, &b->direction); truelight@0: truelight@0: /* toggle direction */ truelight@0: if (!(a->u.rail.track & 0x80)) a->direction ^= 4; truelight@0: if (!(b->u.rail.track & 0x80)) b->direction ^= 4; truelight@193: truelight@0: /* swap more variables */ tron@1174: swap_int32(&a->x_pos, &b->x_pos); tron@1174: swap_int32(&a->y_pos, &b->y_pos); truelight@0: swap_tile(&a->tile, &b->tile); truelight@0: swap_byte(&a->z_pos, &b->z_pos); truelight@0: truelight@954: SwapTrainFlags(&a->u.rail.flags, &b->u.rail.flags); truelight@954: truelight@0: /* update other vars */ truelight@0: UpdateVarsAfterSwap(a); truelight@0: UpdateVarsAfterSwap(b); truelight@1554: truelight@1554: VehicleEnterTile(a, a->tile, a->x_pos, a->y_pos); truelight@1554: VehicleEnterTile(b, b->tile, b->x_pos, b->y_pos); truelight@0: } else { truelight@0: if (!(a->u.rail.track & 0x80)) a->direction ^= 4; truelight@193: UpdateVarsAfterSwap(a); truelight@1554: truelight@1554: VehicleEnterTile(a, a->tile, a->x_pos, a->y_pos); truelight@0: } truelight@0: } truelight@0: truelight@744: /* Check if the vehicle is a train and is on the tile we are testing */ truelight@744: static void *TestTrainOnCrossing(Vehicle *v, void *data) truelight@744: { tron@2639: if (v->tile != *(const TileIndex*)data || v->type != VEH_Train) return NULL; truelight@744: return v; truelight@744: } truelight@744: dominik@1103: static void DisableTrainCrossing(TileIndex tile) dominik@1103: { tron@2639: if (IsTileType(tile, MP_STREET) && tron@2639: IsLevelCrossing(tile) && tron@2639: VehicleFromPos(tile, &tile, TestTrainOnCrossing) == NULL && // empty? tron@2639: GB(_m[tile].m5, 2, 1) != 0) { // Lights on? tron@2639: SB(_m[tile].m5, 2, 1, 0); // Switch lights off tron@2639: MarkTileDirtyByTile(tile); dominik@1103: } dominik@1103: } dominik@1103: hackykid@1922: /** hackykid@1922: * Advances wagons for train reversing, needed for variable length wagons. hackykid@1922: * Needs to be called once before the train is reversed, and once after it. hackykid@1922: * @param v First vehicle in chain hackykid@1922: * @param before Set to true for the call before reversing, false otherwise hackykid@1922: */ hackykid@1922: static void AdvanceWagons(Vehicle *v, bool before) hackykid@1922: { tron@2639: Vehicle* base; tron@2639: Vehicle* first; tron@2639: int length; hackykid@1922: hackykid@1922: base = v; hackykid@1922: first = base->next; hackykid@1922: length = CountVehiclesInChain(v); hackykid@1922: hackykid@1922: while (length > 2) { tron@2639: Vehicle* last; tron@2639: int differential; tron@2639: int i; tron@2639: hackykid@1922: // find pairwise matching wagon hackykid@1922: // start<>end, start+1<>end-1, ... */ hackykid@1922: last = first; tron@2639: for (i = length - 3; i > 0; i--) last = last->next; hackykid@1922: hackykid@1922: differential = last->u.rail.cached_veh_length - base->u.rail.cached_veh_length; tron@2639: if (before) differential *= -1; hackykid@1922: hackykid@1922: if (differential > 0) { tron@2639: Vehicle* tempnext; tron@2639: hackykid@1922: // disconnect last car to make sure only this subset moves hackykid@1922: tempnext = last->next; hackykid@1922: last->next = NULL; hackykid@1922: tron@2639: for (i = 0; i < differential; i++) TrainController(first); hackykid@1922: hackykid@1922: last->next = tempnext; hackykid@1922: } hackykid@1922: hackykid@1922: base = first; hackykid@1922: first = first->next; hackykid@1922: length -= 2; hackykid@1922: } hackykid@1922: } hackykid@1922: truelight@0: static void ReverseTrainDirection(Vehicle *v) truelight@0: { truelight@0: int l = 0, r = -1; truelight@0: Vehicle *u; truelight@0: matthijs@1330: if (IsTileDepotType(v->tile, TRANSPORT_RAIL)) truelight@0: InvalidateWindow(WC_VEHICLE_DEPOT, v->tile); truelight@0: hackykid@2008: truelight@743: /* Check if we were approaching a rail/road-crossing */ truelight@743: { truelight@743: TileIndex tile = v->tile; truelight@743: int t; matthijs@1459: /* Determine the diagonal direction in which we will exit this tile */ truelight@743: t = v->direction >> 1; truelight@743: if (!(v->direction & 1) && v->u.rail.track != _state_dir_table[t]) { truelight@743: t = (t - 1) & 3; truelight@743: } truelight@743: /* Calculate next tile */ tron@900: tile += TileOffsByDir(t); dominik@1103: dominik@1103: /* Check if the train left a rail/road-crossing */ dominik@1103: DisableTrainCrossing(tile); truelight@743: } truelight@743: truelight@0: // count number of vehicles truelight@0: u = v; truelight@0: do r++; while ( (u = u->next) != NULL ); truelight@0: hackykid@1922: AdvanceWagons(v, true); hackykid@1922: truelight@0: /* swap start<>end, start+1<>end-1, ... */ truelight@0: do { truelight@0: ReverseTrainSwapVeh(v, l++, r--); truelight@0: } while (l <= r); truelight@0: hackykid@1922: AdvanceWagons(v, false); hackykid@1922: matthijs@1330: if (IsTileDepotType(v->tile, TRANSPORT_RAIL)) truelight@0: InvalidateWindow(WC_VEHICLE_DEPOT, v->tile); truelight@0: truelight@954: CLRBIT(v->u.rail.flags, VRF_REVERSING); truelight@0: } truelight@0: Darkvater@1784: /** Reverse train. Darkvater@1784: * @param x,y unused Darkvater@1784: * @param p1 train to reverse Darkvater@1784: * @param p2 unused Darkvater@1784: */ Darkvater@1784: int32 CmdReverseTrainDirection(int x, int y, uint32 flags, uint32 p1, uint32 p2) truelight@0: { truelight@0: Vehicle *v; truelight@0: bjarni@1237: if (!IsVehicleIndex(p1)) return CMD_ERROR; bjarni@1237: truelight@919: v = GetVehicle(p1); truelight@0: Darkvater@1784: if (v->type != VEH_Train || !CheckOwnership(v->owner)) return CMD_ERROR; truelight@0: truelight@0: _error_message = STR_EMPTY; truelight@0: matthijs@1330: // if (v->u.rail.track & 0x80 || IsTileDepotType(v->tile, TRANSPORT_RAIL)) truelight@0: // return CMD_ERROR; truelight@0: Darkvater@1784: if (v->u.rail.crash_anim_pos != 0 || v->breakdown_ctr != 0) return CMD_ERROR; truelight@0: truelight@0: if (flags & DC_EXEC) { truelight@0: if (_patches.realistic_acceleration && v->cur_speed != 0) { truelight@954: TOGGLEBIT(v->u.rail.flags, VRF_REVERSING); truelight@0: } else { truelight@0: v->cur_speed = 0; truelight@0: SetLastSpeed(v, 0); truelight@0: ReverseTrainDirection(v); truelight@0: } truelight@0: } truelight@0: return 0; truelight@0: } truelight@0: Darkvater@1784: /** Force a train through a red signal Darkvater@1784: * @param x,y unused Darkvater@1784: * @param p1 train to ignore the red signal Darkvater@1784: * @param p2 unused Darkvater@1784: */ truelight@0: int32 CmdForceTrainProceed(int x, int y, uint32 flags, uint32 p1, uint32 p2) truelight@0: { truelight@0: Vehicle *v; truelight@0: bjarni@1237: if (!IsVehicleIndex(p1)) return CMD_ERROR; bjarni@1237: truelight@919: v = GetVehicle(p1); truelight@0: Darkvater@1784: if (v->type != VEH_Train || !CheckOwnership(v->owner)) return CMD_ERROR; truelight@0: tron@2639: if (flags & DC_EXEC) v->u.rail.force_proceed = 0x50; truelight@193: truelight@0: return 0; truelight@0: } truelight@0: Darkvater@1802: /** Refits a train to the specified cargo type. Darkvater@1802: * @param x,y unused Darkvater@1802: * @param p1 vehicle ID of the train to refit bjarni@2244: * @param p2 the new cargo type to refit to (p2 & 0xFF) Darkvater@1802: */ truelight@0: int32 CmdRefitRailVehicle(int x, int y, uint32 flags, uint32 p1, uint32 p2) truelight@0: { tron@2635: CargoID new_cid = GB(p2, 0, 8); truelight@0: Vehicle *v; truelight@0: int32 cost; truelight@0: uint num; bjarni@842: bjarni@1237: if (!IsVehicleIndex(p1)) return CMD_ERROR; tron@915: truelight@919: v = GetVehicle(p1); bjarni@1237: Darkvater@1802: if (v->type != VEH_Train || !CheckOwnership(v->owner)) return CMD_ERROR; bjarni@2244: if (CheckTrainStoppedInDepot(v) < 0) return_cmd_error(STR_TRAIN_MUST_BE_STOPPED); Darkvater@1802: Darkvater@1802: /* Check cargo */ Darkvater@1802: if (new_cid > NUM_CARGO) return CMD_ERROR; truelight@0: bjarni@1237: SET_EXPENSES_TYPE(EXPENSES_TRAIN_RUN); bjarni@1237: truelight@0: cost = 0; truelight@0: num = 0; tron@915: truelight@0: do { pasky@491: /* XXX: We also refit all the attached wagons en-masse if they pasky@491: * can be refitted. This is how TTDPatch does it. TODO: Have pasky@491: * some nice [Refit] button near each wagon. --pasky */ peter1138@2704: if (!CanRefitTo(v->engine_type, new_cid)) continue; Darkvater@1802: hackykid@1859: if (v->cargo_cap != 0) { peter1138@2463: const RailVehicleInfo *rvi = RailVehInfo(v->engine_type); hackykid@1895: uint16 amount = CALLBACK_FAILED; hackykid@1895: hackykid@1895: if (HASBIT(rvi->callbackmask, CBM_REFIT_CAP)) { hackykid@1895: /* Check the 'refit capacity' callback */ hackykid@1895: CargoID temp_cid = v->cargo_type; hackykid@1895: v->cargo_type = new_cid; hackykid@1895: amount = GetCallBackResult(CBID_REFIT_CAP, v->engine_type, v); hackykid@1895: v->cargo_type = temp_cid; hackykid@1895: } hackykid@1895: hackykid@1895: if (amount == CALLBACK_FAILED) { // callback failed or not used, use default hackykid@1883: CargoID old_cid = rvi->cargo_type; hackykid@1883: /* normally, the capacity depends on the cargo type, a rail vehicle hackykid@1883: * can carry twice as much mail/goods as normal cargo, hackykid@1883: * and four times as much passengers */ hackykid@1883: amount = rvi->capacity; hackykid@1883: (old_cid == CT_PASSENGERS) || hackykid@1883: (amount <<= 1, old_cid == CT_MAIL || old_cid == CT_GOODS) || hackykid@1883: (amount <<= 1, true); hackykid@1883: (new_cid == CT_PASSENGERS) || hackykid@1883: (amount >>= 1, new_cid == CT_MAIL || new_cid == CT_GOODS) || hackykid@1883: (amount >>= 1, true); hackykid@1883: }; hackykid@1883: hackykid@1883: if (amount != 0) { tron@2639: if (new_cid != v->cargo_type) cost += _price.build_railvehicle >> 8; hackykid@1883: num += amount; hackykid@1883: if (flags & DC_EXEC) { bjarni@2244: v->cargo_count = 0; hackykid@1883: v->cargo_type = new_cid; hackykid@1883: v->cargo_cap = amount; hackykid@1883: InvalidateWindow(WC_VEHICLE_DETAILS, v->index); hackykid@1883: InvalidateWindow(WC_VEHICLE_DEPOT, v->tile); hackykid@1883: } truelight@0: } truelight@193: } bjarni@2244: } while ( (v=v->next) != NULL ); truelight@0: truelight@0: _returned_refit_amount = num; truelight@0: truelight@0: return cost; truelight@0: } truelight@0: truelight@0: typedef struct TrainFindDepotData { truelight@0: uint best_length; tron@1977: TileIndex tile; tron@2475: PlayerID owner; matthijs@1777: /** tron@2639: * true if reversing is necessary for the train to get to this depot tron@2639: * This value is unused when new depot finding and NPF are both disabled matthijs@1777: */ matthijs@1777: bool reverse; truelight@0: } TrainFindDepotData; truelight@0: ludde@2125: static bool NtpCallbFindDepot(TileIndex tile, TrainFindDepotData *tfdd, int track, uint length) truelight@0: { tron@1901: if (IsTileType(tile, MP_RAILWAY) && IsTileOwner(tile, tfdd->owner)) { tron@2049: if ((_m[tile].m5 & ~0x3) == 0xC0) { ludde@2125: tfdd->best_length = length; ludde@2125: tfdd->tile = tile; truelight@0: return true; truelight@0: } truelight@0: } truelight@0: ludde@2125: return false; truelight@0: } truelight@0: matthijs@1758: // returns the tile of a depot to goto to. The given vehicle must not be matthijs@1758: // crashed! darkvater@308: static TrainFindDepotData FindClosestTrainDepot(Vehicle *v) truelight@0: { truelight@0: int i; truelight@0: TrainFindDepotData tfdd; tron@1977: TileIndex tile = v->tile; truelight@0: matthijs@1758: assert(!(v->vehstatus & VS_CRASHED)); matthijs@1758: darkvater@308: tfdd.owner = v->owner; darkvater@308: tfdd.best_length = (uint)-1; matthijs@1777: tfdd.reverse = false; darkvater@308: matthijs@1330: if (IsTileDepotType(tile, TRANSPORT_RAIL)){ darkvater@308: tfdd.tile = tile; darkvater@308: tfdd.best_length = 0; darkvater@308: return tfdd; darkvater@308: } truelight@0: tron@2549: if (v->u.rail.track == 0x40) tile = GetVehicleOutOfTunnelTile(v); truelight@193: matthijs@1247: if (_patches.new_pathfinding_all) { matthijs@1247: NPFFoundTargetData ftd; matthijs@1777: Vehicle* last = GetLastVehicleInChain(v); matthijs@1942: Trackdir trackdir = GetVehicleTrackdir(v); matthijs@1942: Trackdir trackdir_rev = ReverseTrackdir(GetVehicleTrackdir(last)); matthijs@1942: matthijs@1942: assert (trackdir != INVALID_TRACKDIR); matthijs@2006: ftd = NPFRouteToDepotBreadthFirstTwoWay(v->tile, trackdir, last->tile, trackdir_rev, TRANSPORT_RAIL, v->owner, v->u.rail.railtype, NPF_INFINITE_PENALTY); matthijs@1247: if (ftd.best_bird_dist == 0) { matthijs@1247: /* Found target */ matthijs@1247: tfdd.tile = ftd.node.tile; matthijs@1675: /* Our caller expects a number of tiles, so we just approximate that matthijs@1675: * number by this. It might not be completely what we want, but it will matthijs@1675: * work for now :-) We can possibly change this when the old pathfinder matthijs@1675: * is removed. */ matthijs@1777: tfdd.best_length = ftd.best_path_dist / NPF_TILE_LENGTH; matthijs@1777: if (NPFGetFlag(&ftd.node, NPF_FLAG_REVERSE)) matthijs@1777: tfdd.reverse = true; matthijs@1247: } truelight@0: } else { truelight@0: // search in the forward direction first. truelight@0: i = v->direction >> 1; tron@2639: if (!(v->direction & 1) && v->u.rail.track != _state_dir_table[i]) i = (i - 1) & 3; ludde@2125: NewTrainPathfind(tile, 0, i, (NTPEnumProc*)NtpCallbFindDepot, &tfdd); darkvater@308: if (tfdd.best_length == (uint)-1){ matthijs@1777: tfdd.reverse = true; darkvater@308: // search in backwards direction darkvater@308: i = (v->direction^4) >> 1; tron@2639: if (!(v->direction & 1) && v->u.rail.track != _state_dir_table[i]) i = (i - 1) & 3; ludde@2125: NewTrainPathfind(tile, 0, i, (NTPEnumProc*)NtpCallbFindDepot, &tfdd); darkvater@308: } truelight@0: } truelight@193: darkvater@308: return tfdd; truelight@0: } truelight@0: Darkvater@1784: /** Send a train to a depot Darkvater@1784: * @param x,y unused Darkvater@1784: * @param p1 train to send to the depot Darkvater@1784: * @param p2 unused Darkvater@1784: */ Darkvater@1794: int32 CmdSendTrainToDepot(int x, int y, uint32 flags, uint32 p1, uint32 p2) truelight@0: { bjarni@1237: Vehicle *v; darkvater@308: TrainFindDepotData tfdd; truelight@0: bjarni@1237: if (!IsVehicleIndex(p1)) return CMD_ERROR; bjarni@1237: bjarni@1237: v = GetVehicle(p1); bjarni@1237: Darkvater@1784: if (v->type != VEH_Train || !CheckOwnership(v->owner)) return CMD_ERROR; Darkvater@1784: Darkvater@1784: if (v->vehstatus & VS_CRASHED) return CMD_ERROR; matthijs@1757: tron@555: if (v->current_order.type == OT_GOTO_DEPOT) { truelight@0: if (flags & DC_EXEC) { pasky@1615: if (HASBIT(v->current_order.flags, OFB_PART_OF_ORDERS)) { truelight@0: v->u.rail.days_since_order_progr = 0; truelight@0: v->cur_order_index++; truelight@0: } truelight@193: tron@555: v->current_order.type = OT_DUMMY; tron@555: v->current_order.flags = 0; darkvater@755: InvalidateWindowWidget(WC_VEHICLE_VIEW, v->index, STATUS_BAR); truelight@0: } truelight@0: return 0; truelight@0: } truelight@0: darkvater@308: tfdd = FindClosestTrainDepot(v); darkvater@308: if (tfdd.best_length == (uint)-1) truelight@0: return_cmd_error(STR_883A_UNABLE_TO_FIND_ROUTE_TO); truelight@0: truelight@0: if (flags & DC_EXEC) { darkvater@308: v->dest_tile = tfdd.tile; tron@555: v->current_order.type = OT_GOTO_DEPOT; bjarni@1520: v->current_order.flags = OF_NON_STOP | OF_FULL_LOAD; truelight@1313: v->current_order.station = GetDepotByTile(tfdd.tile)->index; darkvater@755: InvalidateWindowWidget(WC_VEHICLE_VIEW, v->index, STATUS_BAR); matthijs@1777: /* If there is no depot in front, reverse automatically */ matthijs@1777: if (tfdd.reverse) matthijs@1777: DoCommandByTile(v->tile, v->index, 0, DC_EXEC, CMD_REVERSE_TRAIN_DIRECTION); truelight@0: } truelight@193: truelight@0: return 0; truelight@0: } truelight@0: truelight@0: tron@1093: void OnTick_Train(void) truelight@0: { truelight@0: _age_cargo_skip_counter = (_age_cargo_skip_counter == 0) ? 184 : (_age_cargo_skip_counter - 1); truelight@0: } truelight@0: peter1138@2595: static const int8 _vehicle_smoke_pos[8] = { peter1138@2595: 1, 1, 1, 0, -1, -1, -1, 0 truelight@0: }; truelight@0: tron@2630: static void HandleLocomotiveSmokeCloud(const Vehicle* v) truelight@0: { tron@2630: const Vehicle* u; truelight@0: truelight@0: if (v->vehstatus & VS_TRAIN_SLOWING || v->load_unload_time_rem != 0 || v->cur_speed < 2) truelight@0: return; truelight@0: truelight@0: u = v; truelight@0: truelight@0: do { tron@2477: EngineID engtype = v->engine_type; peter1138@2595: int effect_offset = GB(v->u.rail.cached_vis_effect, 0, 4) - 8; peter1138@2595: byte effect_type = GB(v->u.rail.cached_vis_effect, 4, 2); peter1138@2595: bool disable_effect = HASBIT(v->u.rail.cached_vis_effect, 6); peter1138@2595: int x, y; truelight@0: truelight@0: // no smoke? peter1138@2595: if ((RailVehInfo(engtype)->flags & RVI_WAGON && effect_type == 0) || peter1138@2595: disable_effect || tron@2519: GetEngine(engtype)->railtype > RAILTYPE_RAIL || tron@2639: v->vehstatus & VS_HIDDEN || tron@2639: v->u.rail.track & 0xC0) { truelight@0: continue; tron@2639: } truelight@0: peter1138@2612: // No smoke in depots or tunnels peter1138@2612: if (IsTileDepotType(v->tile, TRANSPORT_RAIL) || IsTunnelTile(v->tile)) peter1138@2612: continue; peter1138@2612: peter1138@2595: if (effect_type == 0) { peter1138@2595: // Use default effect type for engine class. peter1138@2595: effect_type = RailVehInfo(engtype)->engclass; peter1138@2595: } else { peter1138@2595: effect_type--; peter1138@2595: } peter1138@2595: peter1138@2595: x = _vehicle_smoke_pos[v->direction] * effect_offset; peter1138@2595: y = _vehicle_smoke_pos[(v->direction + 2) % 8] * effect_offset; peter1138@2595: peter1138@2595: switch (effect_type) { truelight@0: case 0: truelight@0: // steam smoke. peter1138@2612: if (GB(v->tick_counter, 0, 4) == 0) { peter1138@2595: CreateEffectVehicleRel(v, x, y, 10, EV_STEAM_SMOKE); truelight@0: } truelight@0: break; truelight@0: truelight@0: case 1: truelight@0: // diesel smoke tron@2637: if (u->cur_speed <= 40 && CHANCE16(15, 128)) { tron@1359: CreateEffectVehicleRel(v, 0, 0, 10, EV_DIESEL_SMOKE); truelight@0: } truelight@0: break; truelight@0: truelight@0: case 2: truelight@0: // blue spark tron@2637: if (GB(v->tick_counter, 0, 2) == 0 && CHANCE16(1, 45)) { tron@1359: CreateEffectVehicleRel(v, 0, 0, 10, EV_ELECTRIC_SPARK); truelight@0: } truelight@0: break; truelight@0: } tron@2637: } while ((v = v->next) != NULL); truelight@0: } truelight@0: tron@2549: static void TrainPlayLeaveStationSound(const Vehicle* v) truelight@0: { tron@541: static const SoundFx sfx[] = { tron@541: SND_04_TRAIN, tron@541: SND_0A_TRAIN_HORN, tron@541: SND_0A_TRAIN_HORN tron@541: }; tron@541: tron@2477: EngineID engtype = v->engine_type; truelight@0: tron@1926: switch (GetEngine(engtype)->railtype) { tron@2519: case RAILTYPE_RAIL: tron@540: SndPlayVehicleFx(sfx[RailVehInfo(engtype)->engclass], v); tron@337: break; tron@2519: tron@2519: case RAILTYPE_MONO: tron@337: SndPlayVehicleFx(SND_47_MAGLEV_2, v); tron@337: break; tron@2519: tron@2519: case RAILTYPE_MAGLEV: tron@337: SndPlayVehicleFx(SND_41_MAGLEV, v); tron@337: break; truelight@0: } truelight@0: } truelight@0: truelight@0: static bool CheckTrainStayInDepot(Vehicle *v) truelight@0: { truelight@0: Vehicle *u; tron@495: tron@495: // bail out if not all wagons are in the same depot or not in a depot at all tron@2639: for (u = v; u != NULL; u = u->next) { tron@2639: if (u->u.rail.track != 0x80 || u->tile != v->tile) return false; tron@2639: } truelight@0: truelight@0: if (v->u.rail.force_proceed == 0) { bjarni@1151: if (++v->load_unload_time_rem < 37) { bjarni@1151: InvalidateWindowClasses(WC_TRAINS_LIST); truelight@0: return true; bjarni@1151: } bjarni@1151: truelight@0: v->load_unload_time_rem = 0; truelight@0: bjarni@1151: if (UpdateSignalsOnSegment(v->tile, v->direction)) { bjarni@1151: InvalidateWindowClasses(WC_TRAINS_LIST); truelight@0: return true; bjarni@1151: } truelight@0: } Darkvater@2916: bjarni@578: VehicleServiceInDepot(v); bjarni@1151: InvalidateWindowClasses(WC_TRAINS_LIST); truelight@0: TrainPlayLeaveStationSound(v); truelight@193: truelight@0: v->u.rail.track = 1; tron@2639: if (v->direction & 2) v->u.rail.track = 2; truelight@193: truelight@0: v->vehstatus &= ~VS_HIDDEN; truelight@0: v->cur_speed = 0; truelight@193: truelight@0: UpdateTrainDeltaXY(v, v->direction); truelight@0: v->cur_image = GetTrainImage(v, v->direction); truelight@0: VehiclePositionChanged(v); truelight@0: UpdateSignalsOnSegment(v->tile, v->direction); truelight@0: UpdateTrainAcceleration(v); truelight@0: InvalidateWindow(WC_VEHICLE_DEPOT, v->tile); truelight@0: truelight@0: return false; truelight@0: } truelight@0: matthijs@1247: /* Check for station tiles */ truelight@0: typedef struct TrainTrackFollowerData { truelight@0: TileIndex dest_coords; celestar@1551: StationID station_index; // station index we're heading for truelight@0: uint best_bird_dist; truelight@0: uint best_track_dist; truelight@0: byte best_track; truelight@0: } TrainTrackFollowerData; truelight@0: ludde@2125: static bool NtpCallbFindStation(TileIndex tile, TrainTrackFollowerData *ttfd, int track, uint length) tron@1977: { truelight@0: // heading for nowhere? truelight@0: if (ttfd->dest_coords == 0) truelight@0: return false; truelight@0: truelight@0: // did we reach the final station? ludde@2044: if ((ttfd->station_index == INVALID_STATION && tile == ttfd->dest_coords) || tron@2049: (IsTileType(tile, MP_STATION) && IS_BYTE_INSIDE(_m[tile].m5, 0, 8) && _m[tile].m2 == ttfd->station_index)) { ludde@2044: /* We do not check for dest_coords if we have a station_index, ludde@2044: * because in that case the dest_coords are just an ludde@2044: * approximation of where the station is */ truelight@0: // found station ludde@2125: ttfd->best_track = track; truelight@0: return true; truelight@0: } else { truelight@0: uint dist; truelight@0: ludde@2125: // didn't find station, keep track of the best path so far. tron@1245: dist = DistanceManhattan(tile, ttfd->dest_coords); truelight@0: if (dist < ttfd->best_bird_dist) { truelight@0: ttfd->best_bird_dist = dist; ludde@2125: ttfd->best_track = track; truelight@0: } truelight@0: return false; truelight@0: } truelight@0: } truelight@0: tron@2630: static void FillWithStationData(TrainTrackFollowerData* fd, const Vehicle* v) truelight@0: { tron@2639: fd->dest_coords = v->dest_tile; tron@2639: if (v->current_order.type == OT_GOTO_STATION) { tron@2639: fd->station_index = v->current_order.station; tron@2639: } else { tron@2639: fd->station_index = INVALID_STATION; tron@2639: } truelight@0: } truelight@0: truelight@0: static const byte _initial_tile_subcoord[6][4][3] = { truelight@0: {{ 15, 8, 1 },{ 0, 0, 0 },{ 0, 8, 5 },{ 0, 0, 0 }}, truelight@0: {{ 0, 0, 0 },{ 8, 0, 3 },{ 0, 0, 0 },{ 8,15, 7 }}, truelight@0: {{ 0, 0, 0 },{ 7, 0, 2 },{ 0, 7, 6 },{ 0, 0, 0 }}, truelight@0: {{ 15, 8, 2 },{ 0, 0, 0 },{ 0, 0, 0 },{ 8,15, 6 }}, truelight@0: {{ 15, 7, 0 },{ 8, 0, 4 },{ 0, 0, 0 },{ 0, 0, 0 }}, truelight@0: {{ 0, 0, 0 },{ 0, 0, 0 },{ 0, 8, 4 },{ 7,15, 0 }}, truelight@0: }; truelight@0: truelight@0: static const uint32 _reachable_tracks[4] = { truelight@0: 0x10091009, truelight@0: 0x00160016, truelight@0: 0x05200520, truelight@0: 0x2A002A00, truelight@0: }; truelight@0: truelight@0: static const byte _search_directions[6][4] = { truelight@0: { 0, 9, 2, 9 }, // track 1 truelight@0: { 9, 1, 9, 3 }, // track 2 truelight@0: { 9, 0, 3, 9 }, // track upper truelight@0: { 1, 9, 9, 2 }, // track lower truelight@0: { 3, 2, 9, 9 }, // track left truelight@0: { 9, 9, 1, 0 }, // track right truelight@0: }; truelight@0: truelight@0: static const byte _pick_track_table[6] = {1, 3, 2, 2, 0, 0}; peter1138@2758: #ifdef PF_BENCHMARK ludde@2044: #if !defined(_MSC_VER) Darkvater@2482: unsigned int _rdtsc() matthijs@1247: { tron@2639: unsigned int high, low; tron@2639: tron@2639: __asm__ __volatile__ ("rdtsc" : "=a" (low), "=d" (high)); tron@2639: return low; matthijs@1247: } ludde@2044: #else Darkvater@2482: #ifndef _M_AMD64 Darkvater@2482: static unsigned int _declspec(naked) _rdtsc(void) ludde@2044: { ludde@2044: _asm { ludde@2044: rdtsc ludde@2044: ret ludde@2044: } ludde@2044: } matthijs@1247: #endif ludde@2044: #endif Darkvater@2482: #endif ludde@2044: matthijs@1247: truelight@0: truelight@0: /* choose a track */ tron@1977: static byte ChooseTrainTrack(Vehicle *v, TileIndex tile, int enterdir, TrackdirBits trackdirbits) truelight@193: { truelight@0: TrainTrackFollowerData fd; truelight@0: uint best_track; peter1138@2758: #ifdef PF_BENCHMARK Darkvater@2482: int time = _rdtsc(); truelight@0: static float f; truelight@0: #endif truelight@0: matthijs@1942: assert( (trackdirbits & ~0x3F) == 0); truelight@0: matthijs@1247: /* quick return in case only one possible track is available */ matthijs@1942: if (KILL_FIRST_BIT(trackdirbits) == 0) matthijs@1942: return FIND_FIRST_BIT(trackdirbits); truelight@0: matthijs@1247: if (_patches.new_pathfinding_all) { /* Use a new pathfinding for everything */ matthijs@1247: NPFFindStationOrTileData fstd; matthijs@1247: NPFFoundTargetData ftd; matthijs@1942: Trackdir trackdir; matthijs@1247: matthijs@1247: NPFFillWithOrderData(&fstd, v); matthijs@1247: /* The enterdir for the new tile, is the exitdir for the old tile */ matthijs@1752: trackdir = GetVehicleTrackdir(v); matthijs@1247: assert(trackdir != 0xff); matthijs@1247: Darkvater@2916: ftd = NPFRouteToStationOrTile(tile - TileOffsByDir(enterdir), trackdir, &fstd, TRANSPORT_RAIL, v->owner, v->u.rail.railtype); matthijs@1698: matthijs@1698: if (ftd.best_trackdir == 0xff) { matthijs@1698: /* We are already at our target. Just do something */ matthijs@1247: //TODO: maybe display error? matthijs@1247: //TODO: go straight ahead if possible? matthijs@1942: best_track = FIND_FIRST_BIT(trackdirbits); truelight@0: } else { matthijs@1698: /* If ftd.best_bird_dist is 0, we found our target and ftd.best_trackdir contains matthijs@1698: the direction we need to take to get there, if ftd.best_bird_dist is not 0, matthijs@1698: we did not find our target, but ftd.best_trackdir contains the direction leading matthijs@1698: to the tile closest to our target. */ matthijs@1247: /* Discard enterdir information, making it a normal track */ hackykid@2008: best_track = TrackdirToTrack(ftd.best_trackdir); truelight@0: } truelight@0: } else { matthijs@1247: FillWithStationData(&fd, v); matthijs@1247: ludde@2044: /* New train pathfinding */ ludde@2044: fd.best_bird_dist = (uint)-1; ludde@2044: fd.best_track_dist = (uint)-1; ludde@2044: fd.best_track = 0xFF; ludde@2044: ludde@2125: NewTrainPathfind(tile - TileOffsByDir(enterdir), v->dest_tile, ludde@2125: enterdir, (NTPEnumProc*)NtpCallbFindStation, &fd); ludde@2044: ludde@2044: if (fd.best_track == 0xff) { ludde@2044: // blaha ludde@2044: best_track = FIND_FIRST_BIT(trackdirbits); matthijs@1247: } else { ludde@2044: best_track = fd.best_track & 7; matthijs@1247: } truelight@0: } truelight@0: peter1138@2758: #ifdef PF_BENCHMARK Darkvater@2482: time = _rdtsc() - time; truelight@0: f = f * 0.99 + 0.01 * time; truelight@0: printf("PF time = %d %f\n", time, f); truelight@0: #endif truelight@0: truelight@0: return best_track; truelight@0: } truelight@0: truelight@0: truelight@0: static bool CheckReverseTrain(Vehicle *v) truelight@0: { truelight@0: TrainTrackFollowerData fd; truelight@0: int i, r; truelight@0: int best_track; truelight@0: uint best_bird_dist = 0; truelight@0: uint best_track_dist = 0; truelight@0: uint reverse, reverse_best; truelight@0: truelight@0: if (_opt.diff.line_reverse_mode != 0 || truelight@0: v->u.rail.track & 0xC0 || truelight@0: !(v->direction & 1)) truelight@0: return false; truelight@0: truelight@0: FillWithStationData(&fd, v); truelight@0: truelight@0: best_track = -1; truelight@0: reverse_best = reverse = 0; truelight@0: truelight@0: assert(v->u.rail.track); truelight@0: truelight@0: i = _search_directions[FIND_FIRST_BIT(v->u.rail.track)][v->direction>>1]; truelight@0: matthijs@1247: if (_patches.new_pathfinding_all) { /* Use a new pathfinding for everything */ matthijs@1247: NPFFindStationOrTileData fstd; matthijs@1247: NPFFoundTargetData ftd; matthijs@1247: byte trackdir, trackdir_rev; matthijs@1247: Vehicle* last = GetLastVehicleInChain(v); matthijs@1247: matthijs@1247: NPFFillWithOrderData(&fstd, v); matthijs@1247: matthijs@1752: trackdir = GetVehicleTrackdir(v); matthijs@1942: trackdir_rev = ReverseTrackdir(GetVehicleTrackdir(last)); matthijs@1247: assert(trackdir != 0xff); matthijs@1247: assert(trackdir_rev != 0xff); matthijs@1247: Darkvater@2916: ftd = NPFRouteToStationOrTileTwoWay(v->tile, trackdir, last->tile, trackdir_rev, &fstd, TRANSPORT_RAIL, v->owner, v->u.rail.railtype); matthijs@1247: if (ftd.best_bird_dist != 0) { matthijs@1247: /* We didn't find anything, just keep on going straight ahead */ matthijs@1247: reverse_best = false; matthijs@1247: } else { matthijs@1461: if (NPFGetFlag(&ftd.node, NPF_FLAG_REVERSE)) matthijs@1247: reverse_best = true; matthijs@1247: else matthijs@1247: reverse_best = false; matthijs@1247: } matthijs@1247: } else { matthijs@1247: while(true) { matthijs@1247: fd.best_bird_dist = (uint)-1; matthijs@1247: fd.best_track_dist = (uint)-1; matthijs@1247: ludde@2125: NewTrainPathfind(v->tile, v->dest_tile, reverse ^ i, (NTPEnumProc*)NtpCallbFindStation, &fd); matthijs@1247: matthijs@1247: if (best_track != -1) { matthijs@1247: if (best_bird_dist != 0) { matthijs@1247: if (fd.best_bird_dist != 0) { matthijs@1247: /* neither reached the destination, pick the one with the smallest bird dist */ matthijs@1247: if (fd.best_bird_dist > best_bird_dist) goto bad; matthijs@1247: if (fd.best_bird_dist < best_bird_dist) goto good; matthijs@1247: } else { matthijs@1247: /* we found the destination for the first time */ matthijs@1247: goto good; matthijs@1247: } truelight@0: } else { matthijs@1247: if (fd.best_bird_dist != 0) { matthijs@1247: /* didn't find destination, but we've found the destination previously */ matthijs@1247: goto bad; matthijs@1247: } else { matthijs@1247: /* both old & new reached the destination, compare track length */ matthijs@1247: if (fd.best_track_dist > best_track_dist) goto bad; matthijs@1247: if (fd.best_track_dist < best_track_dist) goto good; matthijs@1247: } truelight@0: } matthijs@1247: matthijs@1247: /* if we reach this position, there's two paths of equal value so far. matthijs@1247: * pick one randomly. */ tron@2150: r = GB(Random(), 0, 8); matthijs@1247: if (_pick_track_table[i] == (v->direction & 3)) r += 80; matthijs@1247: if (_pick_track_table[best_track] == (v->direction & 3)) r -= 80; matthijs@1247: if (r <= 127) goto bad; truelight@0: } matthijs@1247: good:; matthijs@1247: best_track = i; matthijs@1247: best_bird_dist = fd.best_bird_dist; matthijs@1247: best_track_dist = fd.best_track_dist; matthijs@1247: reverse_best = reverse; matthijs@1247: bad:; matthijs@1247: if (reverse != 0) matthijs@1247: break; matthijs@1247: reverse = 2; truelight@0: } truelight@0: } truelight@0: truelight@0: return reverse_best != 0; truelight@0: } truelight@0: truelight@0: static bool ProcessTrainOrder(Vehicle *v) truelight@0: { truelight@1024: const Order *order; truelight@0: bool result; truelight@0: truelight@0: // These are un-interruptible tron@555: if (v->current_order.type >= OT_GOTO_DEPOT && tron@555: v->current_order.type <= OT_LEAVESTATION) { truelight@1024: // Let a depot order in the orderlist interrupt. tron@555: if (v->current_order.type != OT_GOTO_DEPOT || tron@555: !(v->current_order.flags & OF_UNLOAD)) truelight@0: return false; truelight@0: } truelight@0: tron@555: if (v->current_order.type == OT_GOTO_DEPOT && celestar@2214: (v->current_order.flags & (OF_PART_OF_ORDERS | OF_SERVICE_IF_NEEDED)) == (OF_PART_OF_ORDERS | OF_SERVICE_IF_NEEDED) && bjarni@1520: !VehicleNeedsService(v)) { truelight@0: v->cur_order_index++; truelight@0: } truelight@0: darkvater@395: // check if we've reached the waypoint? tron@555: if (v->current_order.type == OT_GOTO_WAYPOINT && v->tile == v->dest_tile) { truelight@0: v->cur_order_index++; truelight@0: } truelight@0: truelight@193: // check if we've reached a non-stop station while TTDPatch nonstop is enabled.. tron@2549: if (_patches.new_nonstop && tron@2549: v->current_order.flags & OF_NON_STOP && tron@2549: IsTileType(v->tile, MP_STATION) && tron@2549: v->current_order.station == _m[v->tile].m2) { truelight@193: v->cur_order_index++; truelight@0: } truelight@0: truelight@0: // Get the current order tron@2639: if (v->cur_order_index >= v->num_orders) v->cur_order_index = 0; truelight@1024: truelight@1024: order = GetVehicleOrder(v, v->cur_order_index); truelight@0: truelight@0: // If no order, do nothing. truelight@1024: if (order == NULL) { tron@555: v->current_order.type = OT_NOTHING; tron@555: v->current_order.flags = 0; truelight@0: v->dest_tile = 0; truelight@0: return false; truelight@0: } truelight@0: truelight@0: // If it is unchanged, keep it. truelight@1024: if (order->type == v->current_order.type && truelight@1024: order->flags == v->current_order.flags && truelight@1024: order->station == v->current_order.station) truelight@0: return false; truelight@0: truelight@0: // Otherwise set it, and determine the destination tile. truelight@1024: v->current_order = *order; truelight@0: truelight@0: v->dest_tile = 0; truelight@0: truelight@0: result = false; truelight@1024: switch (order->type) { truelight@1024: case OT_GOTO_STATION: truelight@1024: if (order->station == v->last_station_visited) truelight@1266: v->last_station_visited = INVALID_STATION; truelight@1024: v->dest_tile = GetStation(order->station)->xy; truelight@1024: result = CheckReverseTrain(v); truelight@1024: break; truelight@1024: truelight@1024: case OT_GOTO_DEPOT: truelight@1313: v->dest_tile = GetDepot(order->station)->xy; truelight@1024: result = CheckReverseTrain(v); truelight@1024: break; truelight@1024: truelight@1024: case OT_GOTO_WAYPOINT: truelight@1542: v->dest_tile = GetWaypoint(order->station)->xy; truelight@1024: result = CheckReverseTrain(v); truelight@1024: break; truelight@0: } truelight@0: truelight@1024: InvalidateVehicleOrder(v); truelight@0: truelight@0: return result; truelight@0: } truelight@0: truelight@0: static void MarkTrainDirty(Vehicle *v) truelight@0: { truelight@0: do { truelight@0: v->cur_image = GetTrainImage(v, v->direction); truelight@0: MarkAllViewportsDirty(v->left_coord, v->top_coord, v->right_coord + 1, v->bottom_coord + 1); tron@2639: } while ((v = v->next) != NULL); truelight@0: } truelight@0: truelight@0: static void HandleTrainLoading(Vehicle *v, bool mode) truelight@0: { tron@2639: if (v->current_order.type == OT_NOTHING) return; truelight@193: tron@555: if (v->current_order.type != OT_DUMMY) { tron@2639: if (v->current_order.type != OT_LOADING) return; tron@2639: if (mode) return; truelight@0: truelight@0: // don't mark the train as lost if we're loading on the final station. tron@555: if (v->current_order.flags & OF_NON_STOP) truelight@0: v->u.rail.days_since_order_progr = 0; truelight@0: tron@2639: if (--v->load_unload_time_rem) return; truelight@0: tron@555: if (v->current_order.flags & OF_FULL_LOAD && CanFillVehicle(v)) { matthijs@882: v->u.rail.days_since_order_progr = 0; /* Prevent a train lost message for full loading trains */ truelight@0: SET_EXPENSES_TYPE(EXPENSES_TRAIN_INC); truelight@0: if (LoadUnloadVehicle(v)) { truelight@0: InvalidateWindow(WC_TRAINS_LIST, v->owner); truelight@0: MarkTrainDirty(v); truelight@193: hackykid@1905: // need to update acceleration and cached values since the goods on the train changed. hackykid@1905: TrainCargoChanged(v); truelight@0: UpdateTrainAcceleration(v); truelight@0: } truelight@0: return; truelight@0: } truelight@193: truelight@0: TrainPlayLeaveStationSound(v); truelight@193: truelight@0: { tron@555: Order b = v->current_order; tron@555: v->current_order.type = OT_LEAVESTATION; tron@555: v->current_order.flags = 0; truelight@193: truelight@0: // If this was not the final order, don't remove it from the list. tron@2639: if (!(b.flags & OF_NON_STOP)) return; truelight@0: } truelight@0: } truelight@0: truelight@0: v->u.rail.days_since_order_progr = 0; truelight@0: v->cur_order_index++; truelight@1024: InvalidateVehicleOrder(v); truelight@0: } truelight@0: truelight@0: static int UpdateTrainSpeed(Vehicle *v) truelight@0: { truelight@0: uint spd; truelight@0: uint accel; truelight@0: truelight@954: if (v->vehstatus & VS_STOPPED || HASBIT(v->u.rail.flags, VRF_REVERSING)) { tron@2639: if (_patches.realistic_acceleration) { celestar@1179: accel = GetTrainAcceleration(v, AM_BRAKE) * 2; tron@2639: } else { celestar@1179: accel = v->acceleration * -2; tron@2639: } truelight@0: } else { tron@2639: if (_patches.realistic_acceleration) { celestar@1179: accel = GetTrainAcceleration(v, AM_ACCEL); tron@2639: } else { celestar@1179: accel = v->acceleration; tron@2639: } truelight@0: } truelight@0: truelight@0: spd = v->subspeed + accel * 2; truelight@0: v->subspeed = (byte)spd; celestar@1179: { celestar@1179: int tempmax = v->max_speed; celestar@1179: if (v->cur_speed > v->max_speed) celestar@1179: tempmax = v->cur_speed - (v->cur_speed / 10) - 1; celestar@1179: v->cur_speed = spd = clamp(v->cur_speed + ((int)spd >> 8), 0, tempmax); celestar@1179: } truelight@0: truelight@0: if (!(v->direction & 1)) spd = spd * 3 >> 2; truelight@0: truelight@0: spd += v->progress; truelight@0: v->progress = (byte)spd; truelight@0: return (spd >> 8); truelight@0: } truelight@0: celestar@1551: static void TrainEnterStation(Vehicle *v, StationID station) truelight@0: { truelight@0: Station *st; truelight@0: uint32 flags; truelight@0: truelight@0: v->last_station_visited = station; truelight@0: truelight@0: /* check if a train ever visited this station before */ truelight@919: st = GetStation(station); truelight@0: if (!(st->had_vehicle_of_type & HVOT_TRAIN)) { truelight@0: st->had_vehicle_of_type |= HVOT_TRAIN; tron@534: SetDParam(0, st->index); truelight@0: flags = (v->owner == _local_player) ? NEWS_FLAGS(NM_THIN, NF_VIEWPORT|NF_VEHICLE, NT_ARRIVAL_PLAYER, 0) : NEWS_FLAGS(NM_THIN, NF_VIEWPORT|NF_VEHICLE, NT_ARRIVAL_OTHER, 0); truelight@0: AddNewsItem( truelight@0: STR_8801_CITIZENS_CELEBRATE_FIRST, truelight@0: flags, truelight@0: v->index, truelight@0: 0); truelight@0: } truelight@0: truelight@0: // Did we reach the final destination? tron@555: if (v->current_order.type == OT_GOTO_STATION && celestar@1552: v->current_order.station == station) { truelight@0: // Yeah, keep the load/unload flags truelight@0: // Non Stop now means if the order should be increased. tron@555: v->current_order.type = OT_LOADING; celestar@1935: v->current_order.flags &= OF_FULL_LOAD | OF_UNLOAD | OF_TRANSFER; tron@555: v->current_order.flags |= OF_NON_STOP; truelight@0: } else { truelight@0: // No, just do a simple load tron@555: v->current_order.type = OT_LOADING; tron@555: v->current_order.flags = 0; truelight@0: } tron@555: v->current_order.station = 0; truelight@0: truelight@0: SET_EXPENSES_TYPE(EXPENSES_TRAIN_INC); truelight@0: if (LoadUnloadVehicle(v) != 0) { truelight@0: InvalidateWindow(WC_TRAINS_LIST, v->owner); hackykid@1905: TrainCargoChanged(v); truelight@0: UpdateTrainAcceleration(v); truelight@0: } peter1138@2830: MarkTrainDirty(v); darkvater@755: InvalidateWindowWidget(WC_VEHICLE_VIEW, v->index, STATUS_BAR); truelight@0: } truelight@0: truelight@954: static byte AfterSetTrainPos(Vehicle *v, bool new_tile) truelight@0: { truelight@0: byte new_z, old_z; truelight@193: truelight@0: // need this hint so it returns the right z coordinate on bridges. truelight@0: _get_z_hint = v->z_pos; truelight@0: new_z = GetSlopeZ(v->x_pos, v->y_pos); truelight@0: _get_z_hint = 0; truelight@0: truelight@0: old_z = v->z_pos; truelight@0: v->z_pos = new_z; truelight@0: truelight@954: if (new_tile) { truelight@954: CLRBIT(v->u.rail.flags, VRF_GOINGUP); truelight@954: CLRBIT(v->u.rail.flags, VRF_GOINGDOWN); truelight@954: truelight@954: if (new_z != old_z) { tron@1980: TileIndex tile = TileVirtXY(v->x_pos, v->y_pos); tron@1683: tron@1683: // XXX workaround, whole UP/DOWN detection needs overhaul tron@2049: if (!IsTileType(tile, MP_TUNNELBRIDGE) || (_m[tile].m5 & 0x80) != 0) tron@1683: SETBIT(v->u.rail.flags, (new_z > old_z) ? VRF_GOINGUP : VRF_GOINGDOWN); truelight@954: } truelight@0: } truelight@0: truelight@0: VehiclePositionChanged(v); truelight@0: EndVehicleMove(v); truelight@0: return old_z; truelight@0: } truelight@0: truelight@0: static const byte _new_vehicle_direction_table[11] = { truelight@0: 0, 7, 6, 0, truelight@0: 1, 0, 5, 0, truelight@0: 2, 3, 4, truelight@0: }; truelight@0: tron@1977: static int GetNewVehicleDirectionByTile(TileIndex new_tile, TileIndex old_tile) truelight@0: { tron@926: uint offs = (TileY(new_tile) - TileY(old_tile) + 1) * 4 + tron@926: TileX(new_tile) - TileX(old_tile) + 1; truelight@0: assert(offs < 11); truelight@0: return _new_vehicle_direction_table[offs]; truelight@0: } truelight@0: Darkvater@2436: static int GetNewVehicleDirection(const Vehicle *v, int x, int y) truelight@0: { truelight@0: uint offs = (y - v->y_pos + 1) * 4 + (x - v->x_pos + 1); truelight@0: assert(offs < 11); truelight@0: return _new_vehicle_direction_table[offs]; truelight@0: } truelight@0: Darkvater@2436: static int GetDirectionToVehicle(const Vehicle *v, int x, int y) truelight@0: { truelight@0: byte offs; truelight@0: truelight@0: x -= v->x_pos; truelight@0: if (x >= 0) { truelight@0: offs = (x > 2) ? 0 : 1; truelight@0: } else { truelight@0: offs = (x < -2) ? 2 : 1; truelight@0: } truelight@0: truelight@0: y -= v->y_pos; truelight@0: if (y >= 0) { truelight@0: offs += ((y > 2) ? 0 : 1) * 4; truelight@0: } else { truelight@0: offs += ((y < -2) ? 2 : 1) * 4; truelight@0: } truelight@0: truelight@0: assert(offs < 11); truelight@0: return _new_vehicle_direction_table[offs]; truelight@0: } truelight@0: truelight@0: /* Check if the vehicle is compatible with the specified tile */ tron@1048: static bool CheckCompatibleRail(const Vehicle *v, TileIndex tile) truelight@0: { tron@1214: switch (GetTileType(tile)) { tron@1048: case MP_RAILWAY: tron@1048: case MP_STATION: tron@1048: // normal tracks, jump to owner check tron@1048: break; tron@1048: tron@1048: case MP_TUNNELBRIDGE: tron@2049: if ((_m[tile].m5 & 0xC0) == 0xC0) { // is bridge middle part? tron@1192: uint height; tron@1192: uint tileh = GetTileSlope(tile, &height); tron@1048: tron@1048: // correct Z position of a train going under a bridge on slopes tron@1394: if (CorrectZ(tileh)) height += 8; tron@1192: tron@1192: if (v->z_pos != height) return true; // train is going over bridge tron@1048: } tron@1048: break; tron@1048: tron@1048: case MP_STREET: tron@2360: // tracks over roads, do owner check of tracks tron@1048: return tron@2510: IsTileOwner(tile, v->owner) && ( bjarni@2676: !IsFrontEngine(v) || tron@2510: IsCompatibleRail(v->u.rail.railtype, GB(_m[tile].m4, 0, 4)) tron@2510: ); tron@1048: tron@1048: default: tron@1048: return true; tron@1048: } tron@1048: tron@1048: return tron@2549: IsTileOwner(tile, v->owner) && ( bjarni@2676: !IsFrontEngine(v) || tron@2549: IsCompatibleRail(v->u.rail.railtype, GetRailType(tile)) tron@2549: ); truelight@0: } truelight@0: truelight@0: typedef struct { truelight@0: byte small_turn, large_turn; truelight@0: byte z_up; // fraction to remove when moving up truelight@0: byte z_down; // fraction to remove when moving down truelight@0: } RailtypeSlowdownParams; truelight@0: truelight@0: static const RailtypeSlowdownParams _railtype_slowdown[3] = { truelight@0: // normal accel truelight@0: {256/4, 256/2, 256/4, 2}, // normal truelight@0: {256/4, 256/2, 256/4, 2}, // monorail truelight@0: {0, 256/2, 256/4, 2}, // maglev truelight@0: }; truelight@0: truelight@0: /* Modify the speed of the vehicle due to a turn */ truelight@0: static void AffectSpeedByDirChange(Vehicle *v, byte new_dir) truelight@0: { truelight@0: byte diff; truelight@0: const RailtypeSlowdownParams *rsp; truelight@0: truelight@0: if (_patches.realistic_acceleration || (diff = (v->direction - new_dir) & 7) == 0) truelight@0: return; truelight@0: truelight@0: rsp = &_railtype_slowdown[v->u.rail.railtype]; truelight@0: v->cur_speed -= ((diff == 1 || diff == 7) ? rsp->small_turn : rsp->large_turn) * v->cur_speed >> 8; truelight@0: } truelight@0: truelight@0: /* Modify the speed of the vehicle due to a change in altitude */ truelight@0: static void AffectSpeedByZChange(Vehicle *v, byte old_z) truelight@0: { truelight@0: const RailtypeSlowdownParams *rsp; tron@2639: if (old_z == v->z_pos || _patches.realistic_acceleration) return; truelight@0: truelight@0: rsp = &_railtype_slowdown[v->u.rail.railtype]; truelight@0: truelight@0: if (old_z < v->z_pos) { truelight@0: v->cur_speed -= (v->cur_speed * rsp->z_up >> 8); truelight@0: } else { truelight@0: uint16 spd = v->cur_speed + rsp->z_down; tron@2639: if (spd <= v->max_speed) v->cur_speed = spd; truelight@0: } truelight@0: } truelight@0: truelight@0: static const byte _otherside_signal_directions[14] = { truelight@0: 1, 3, 1, 3, 5, 3, 0, 0, truelight@0: 5, 7, 7, 5, 7, 1, truelight@0: }; truelight@0: tron@1977: static void TrainMovedChangeSignals(TileIndex tile, int dir) truelight@0: { tron@2049: if (IsTileType(tile, MP_RAILWAY) && (_m[tile].m5 & 0xC0) == 0x40) { tron@2639: uint i = FindFirstBit2x64((_m[tile].m5 + (_m[tile].m5 << 8)) & _reachable_tracks[dir]); truelight@0: UpdateSignalsOnSegment(tile, _otherside_signal_directions[i]); truelight@0: } truelight@0: } truelight@0: truelight@0: truelight@0: typedef struct TrainCollideChecker { tron@1434: const Vehicle *v; tron@1434: const Vehicle *v_skip; truelight@0: } TrainCollideChecker; truelight@0: tron@1434: static void *FindTrainCollideEnum(Vehicle *v, void *data) truelight@0: { tron@1434: const TrainCollideChecker* tcc = data; tron@1434: tron@1434: if (v != tcc->v && tron@1434: v != tcc->v_skip && tron@1434: v->type == VEH_Train && tron@1434: v->u.rail.track != 0x80 && tron@1434: myabs(v->z_pos - tcc->v->z_pos) <= 6 && tron@1434: myabs(v->x_pos - tcc->v->x_pos) < 6 && tron@1434: myabs(v->y_pos - tcc->v->y_pos) < 6) { tron@1434: return v; tron@1434: } else { tron@1434: return NULL; tron@1434: } truelight@0: } truelight@0: truelight@0: static void SetVehicleCrashed(Vehicle *v) truelight@0: { truelight@0: Vehicle *u; truelight@0: truelight@0: if (v->u.rail.crash_anim_pos != 0) truelight@0: return; truelight@0: truelight@0: v->u.rail.crash_anim_pos++; truelight@193: truelight@0: u = v; truelight@0: BEGIN_ENUM_WAGONS(v) truelight@0: v->vehstatus |= VS_CRASHED; truelight@0: END_ENUM_WAGONS(v) truelight@0: darkvater@755: InvalidateWindowWidget(WC_VEHICLE_VIEW, u->index, STATUS_BAR); truelight@0: } truelight@0: tron@2549: static uint CountPassengersInTrain(const Vehicle* v) truelight@0: { tron@2549: uint num = 0; truelight@0: BEGIN_ENUM_WAGONS(v) bjarni@1067: if (v->cargo_type == CT_PASSENGERS) num += v->cargo_count; truelight@0: END_ENUM_WAGONS(v) truelight@0: return num; truelight@0: } truelight@0: darkvater@22: /* tron@1434: * Checks whether the specified train has a collision with another vehicle. If bjarni@2676: * so, destroys this vehicle, and the other vehicle if its subtype has TS_Front. darkvater@22: * Reports the incident in a flashy news item, modifies station ratings and darkvater@22: * plays a sound. darkvater@22: */ truelight@0: static void CheckTrainCollision(Vehicle *v) truelight@0: { truelight@0: TrainCollideChecker tcc; tron@1434: Vehicle *coll; tron@1434: Vehicle *realcoll; tron@2639: uint num; truelight@0: truelight@0: /* can't collide in depot */ tron@2639: if (v->u.rail.track == 0x80) return; truelight@193: tron@1980: assert(v->u.rail.track == 0x40 || TileVirtXY(v->x_pos, v->y_pos) == v->tile); truelight@0: truelight@0: tcc.v = v; truelight@0: tcc.v_skip = v->next; truelight@0: truelight@0: /* find colliding vehicle */ tron@1980: realcoll = VehicleFromPos(TileVirtXY(v->x_pos, v->y_pos), &tcc, FindTrainCollideEnum); tron@2639: if (realcoll == NULL) return; truelight@193: tron@1434: coll = GetFirstVehicleInChain(realcoll); truelight@193: truelight@0: /* it can't collide with its own wagons */ tron@1434: if (v == coll || tron@1434: (v->u.rail.track & 0x40 && (v->direction & 2) != (realcoll->direction & 2))) truelight@0: return; truelight@0: truelight@193: //two drivers + passangers killed in train v truelight@0: num = 2 + CountPassengersInTrain(v); tron@1434: if (!(coll->vehstatus & VS_CRASHED)) truelight@0: //two drivers + passangers killed in train coll (if it was not crashed already) truelight@0: num += 2 + CountPassengersInTrain(coll); truelight@0: truelight@0: SetVehicleCrashed(v); bjarni@2676: if (IsFrontEngine(coll)) SetVehicleCrashed(coll); truelight@193: tron@534: SetDParam(0, num); truelight@0: AddNewsItem(STR_8868_TRAIN_CRASH_DIE_IN_FIREBALL, tron@1434: NEWS_FLAGS(NM_THIN, NF_VIEWPORT | NF_VEHICLE, NT_ACCIDENT, 0), truelight@0: v->index, tron@1434: 0 tron@1434: ); truelight@0: truelight@0: ModifyStationRatingAround(v->tile, v->owner, -160, 30); tron@541: SndPlayVehicleFx(SND_13_BIG_CRASH, v); truelight@0: } truelight@0: tron@1432: typedef struct VehicleAtSignalData { tron@1432: TileIndex tile; tron@1432: byte direction; tron@1432: } VehicleAtSignalData; tron@1432: truelight@0: static void *CheckVehicleAtSignal(Vehicle *v, void *data) truelight@0: { tron@1432: const VehicleAtSignalData* vasd = data; tron@1432: bjarni@2676: if (v->type == VEH_Train && IsFrontEngine(v) && tron@1432: v->tile == vasd->tile) { tron@1432: byte diff = (v->direction - vasd->direction + 2) & 7; tron@1432: truelight@0: if (diff == 2 || (v->cur_speed <= 5 && diff <= 4)) tron@1432: return v; truelight@0: } tron@1432: return NULL; truelight@0: } truelight@0: truelight@0: static void TrainController(Vehicle *v) truelight@0: { hackykid@1961: Vehicle *prev; truelight@0: GetNewVehiclePosResult gp; truelight@0: uint32 r, tracks,ts; matthijs@1247: int i, enterdir, newdir, dir; truelight@0: byte chosen_dir; truelight@0: byte chosen_track; truelight@0: byte old_z; truelight@0: darkvater@22: /* For every vehicle after and including the given vehicle */ hackykid@1961: for (prev = GetPrevVehicleInChain(v); v != NULL; prev = v, v = v->next) { truelight@0: BeginVehicleMove(v); truelight@193: truelight@0: if (v->u.rail.track != 0x40) { darkvater@22: /* Not inside tunnel */ truelight@0: if (GetNewVehiclePos(v, &gp)) { darkvater@22: /* Staying in the old tile */ truelight@0: if (v->u.rail.track == 0x80) { truelight@0: /* inside depot */ truelight@0: gp.x = v->x_pos; truelight@0: gp.y = v->y_pos; truelight@0: } else { darkvater@22: /* is not inside depot */ truelight@742: Darkvater@2916: if (!TrainCheckIfLineEnds(v)) truelight@742: return; truelight@742: truelight@0: r = VehicleEnterTile(v, gp.new_tile, gp.x, gp.y); matthijs@1247: if (r & 0x8) { matthijs@1247: //debug("%x & 0x8", r); truelight@0: goto invalid_rail; matthijs@1247: } truelight@0: if (r & 0x2) { truelight@0: TrainEnterStation(v, r >> 8); truelight@0: return; truelight@0: } truelight@0: tron@555: if (v->current_order.type == OT_LEAVESTATION) { tron@555: v->current_order.type = OT_NOTHING; tron@555: v->current_order.flags = 0; darkvater@755: InvalidateWindowWidget(WC_VEHICLE_VIEW, v->index, STATUS_BAR); truelight@0: } truelight@0: } truelight@0: } else { truelight@0: /* A new tile is about to be entered. */ truelight@0: matthijs@1247: byte bits; truelight@0: /* Determine what direction we're entering the new tile from */ truelight@0: dir = GetNewVehicleDirectionByTile(gp.new_tile, gp.old_tile); matthijs@1247: enterdir = dir >> 1; matthijs@1247: assert(enterdir==0 || enterdir==1 || enterdir==2 || enterdir==3); truelight@193: truelight@0: /* Get the status of the tracks in the new tile and mask truelight@0: * away the bits that aren't reachable. */ matthijs@1247: ts = GetTileTrackStatus(gp.new_tile, TRANSPORT_RAIL) & _reachable_tracks[enterdir]; truelight@0: truelight@0: /* Combine the from & to directions. truelight@0: * Now, the lower byte contains the track status, and the byte at bit 16 contains truelight@0: * the signal status. */ truelight@0: tracks = ts|(ts >> 8); matthijs@1247: bits = tracks & 0xFF; matthijs@1247: if (_patches.new_pathfinding_all && _patches.forbid_90_deg && prev == NULL) matthijs@1247: /* We allow wagons to make 90 deg turns, because forbid_90_deg matthijs@1247: * can be switched on halfway a turn */ matthijs@1942: bits &= ~TrackCrossesTracks(FIND_FIRST_BIT(v->u.rail.track)); matthijs@1247: matthijs@1247: if ( bits == 0) { matthijs@1247: //debug("%x == 0", bits); truelight@0: goto invalid_rail; matthijs@1247: } truelight@0: truelight@0: /* Check if the new tile contrains tracks that are compatible truelight@0: * with the current train, if not, bail out. */ matthijs@1247: if (!CheckCompatibleRail(v, gp.new_tile)) { matthijs@1247: //debug("!CheckCompatibleRail(%p, %x)", v, gp.new_tile); truelight@0: goto invalid_rail; matthijs@1247: } truelight@0: truelight@0: if (prev == NULL) { truelight@0: /* Currently the locomotive is active. Determine which one of the truelight@0: * available tracks to choose */ matthijs@1247: chosen_track = 1 << ChooseTrainTrack(v, gp.new_tile, enterdir, bits); matthijs@1247: assert(chosen_track & tracks); truelight@0: truelight@0: /* Check if it's a red signal and that force proceed is not clicked. */ truelight@0: if ( (tracks>>16)&chosen_track && v->u.rail.force_proceed == 0) goto red_light; truelight@0: } else { truelight@0: static byte _matching_tracks[8] = {0x30, 1, 0xC, 2, 0x30, 1, 0xC, 2}; truelight@193: truelight@0: /* The wagon is active, simply follow the prev vehicle. */ matthijs@1247: chosen_track = (byte)(_matching_tracks[GetDirectionToVehicle(prev, gp.x, gp.y)] & bits); truelight@0: } truelight@0: truelight@0: /* make sure chosen track is a valid track */ truelight@0: assert(chosen_track==1 || chosen_track==2 || chosen_track==4 || chosen_track==8 || chosen_track==16 || chosen_track==32); truelight@0: truelight@0: /* Update XY to reflect the entrance to the new tile, and select the direction to use */ truelight@0: { matthijs@1247: const byte *b = _initial_tile_subcoord[FIND_FIRST_BIT(chosen_track)][enterdir]; truelight@0: gp.x = (gp.x & ~0xF) | b[0]; truelight@0: gp.y = (gp.y & ~0xF) | b[1]; truelight@0: chosen_dir = b[2]; truelight@0: } truelight@193: truelight@0: /* Call the landscape function and tell it that the vehicle entered the tile */ truelight@0: r = VehicleEnterTile(v, gp.new_tile, gp.x, gp.y); matthijs@1247: if (r&0x8){ matthijs@1247: //debug("%x & 0x8", r); truelight@0: goto invalid_rail; matthijs@1247: } truelight@0: bjarni@2676: if (IsFrontEngine(v)) v->load_unload_time_rem = 0; truelight@0: truelight@0: if (!(r&0x4)) { truelight@0: v->tile = gp.new_tile; truelight@0: v->u.rail.track = chosen_track; matthijs@1330: assert(v->u.rail.track); truelight@0: } truelight@0: bjarni@2676: if (IsFrontEngine(v)) Darkvater@2916: TrainMovedChangeSignals(gp.new_tile, enterdir); truelight@0: darkvater@22: /* Signals can only change when the first darkvater@22: * (above) or the last vehicle moves. */ truelight@0: if (v->next == NULL) Darkvater@2916: TrainMovedChangeSignals(gp.old_tile, (enterdir) ^ 2); truelight@193: truelight@0: if (prev == NULL) { truelight@0: AffectSpeedByDirChange(v, chosen_dir); truelight@0: } truelight@0: truelight@0: v->direction = chosen_dir; truelight@0: } truelight@0: } else { truelight@0: /* in tunnel */ truelight@0: GetNewVehiclePos(v, &gp); truelight@193: ludde@2125: // Check if to exit the tunnel... ludde@2125: if (!IsTunnelTile(gp.new_tile) || ludde@2125: !(VehicleEnterTile(v, gp.new_tile, gp.x, gp.y)&0x4) ) { ludde@2125: v->x_pos = gp.x; ludde@2125: v->y_pos = gp.y; ludde@2125: VehiclePositionChanged(v); ludde@2125: continue; truelight@0: } truelight@0: } truelight@0: truelight@0: /* update image of train, as well as delta XY */ matthijs@1247: newdir = GetNewVehicleDirection(v, gp.x, gp.y); matthijs@1247: UpdateTrainDeltaXY(v, newdir); matthijs@1247: v->cur_image = GetTrainImage(v, newdir); truelight@0: truelight@0: v->x_pos = gp.x; truelight@0: v->y_pos = gp.y; truelight@0: truelight@0: /* update the Z position of the vehicle */ truelight@954: old_z = AfterSetTrainPos(v, (gp.new_tile != gp.old_tile)); truelight@193: truelight@0: if (prev == NULL) { darkvater@22: /* This is the first vehicle in the train */ truelight@0: AffectSpeedByZChange(v, old_z); truelight@0: } truelight@0: } tron@1438: return; truelight@0: truelight@0: invalid_rail: darkvater@22: /* We've reached end of line?? */ tron@2639: if (prev != NULL) error("!Disconnecting train"); truelight@0: goto reverse_train_direction; truelight@0: truelight@0: red_light: { darkvater@22: /* We're in front of a red signal ?? */ truelight@0: /* find the first set bit in ts. need to do it in 2 steps, since truelight@0: * FIND_FIRST_BIT only handles 6 bits at a time. */ truelight@0: i = FindFirstBit2x64(ts); truelight@193: tron@2049: if (!(_m[gp.new_tile].m3 & SignalAgainstTrackdir(i))) { truelight@0: v->cur_speed = 0; truelight@0: v->subspeed = 0; truelight@0: v->progress = 255-100; truelight@0: if (++v->load_unload_time_rem < _patches.wait_oneway_signal * 20) truelight@0: return; tron@2049: } else if (_m[gp.new_tile].m3 & SignalAlongTrackdir(i)){ truelight@0: v->cur_speed = 0; truelight@0: v->subspeed = 0; truelight@0: v->progress = 255-10; truelight@0: if (++v->load_unload_time_rem < _patches.wait_twoway_signal * 73) { tron@1432: TileIndex o_tile = gp.new_tile + TileOffsByDir(enterdir); darkvater@1507: VehicleAtSignalData vasd; darkvater@1507: vasd.tile = o_tile; darkvater@1507: vasd.direction = dir ^ 4; tron@1432: truelight@0: /* check if a train is waiting on the other side */ tron@1432: if (VehicleFromPos(o_tile, &vasd, CheckVehicleAtSignal) == NULL) truelight@0: return; truelight@0: } truelight@0: } truelight@0: } truelight@193: truelight@0: reverse_train_direction: truelight@0: v->load_unload_time_rem = 0; truelight@0: v->cur_speed = 0; truelight@0: v->subspeed = 0; truelight@0: ReverseTrainDirection(v); truelight@0: } truelight@0: tron@1430: extern TileIndex CheckTunnelBusy(TileIndex tile, uint *length); dominik@98: Darkvater@1418: /** Darkvater@1418: * Deletes/Clears the last wagon of a crashed train. It takes the engine of the Darkvater@1418: * train, then goes to the last wagon and deletes that. Each call to this function Darkvater@1418: * will remove the last wagon of a crashed train. If this wagon was on a crossing, Darkvater@1418: * or inside a tunnel, recalculate the signals as they might need updating Darkvater@1418: * @param v the @Vehicle of which last wagon is to be removed Darkvater@1418: */ truelight@0: static void DeleteLastWagon(Vehicle *v) truelight@0: { truelight@0: Vehicle *u = v; Darkvater@1418: Darkvater@1418: /* Go to the last wagon and delete the link pointing there Darkvater@1418: * *u is then the one-before-last wagon, and *v the last Darkvater@1418: * one which will physicially be removed */ tron@1434: for (; v->next != NULL; v = v->next) u = v; truelight@0: u->next = NULL; truelight@0: truelight@0: InvalidateWindow(WC_VEHICLE_DETAILS, v->index); truelight@0: DeleteWindowById(WC_VEHICLE_VIEW, v->index); tron@588: RebuildVehicleLists(); truelight@0: InvalidateWindow(WC_COMPANY, v->owner); truelight@0: truelight@0: BeginVehicleMove(v); truelight@0: EndVehicleMove(v); truelight@0: DeleteVehicle(v); truelight@0: Darkvater@1418: if (!(v->u.rail.track & 0xC0)) Darkvater@1418: SetSignalsOnBothDir(v->tile, FIND_FIRST_BIT(v->u.rail.track)); truelight@193: tron@1434: /* Check if the wagon was on a road/rail-crossing and disable it if no tron@1434: * others are on it */ dominik@1103: DisableTrainCrossing(v->tile); dominik@1103: Darkvater@1418: if (v->u.rail.track == 0x40) { // inside a tunnel tron@1430: TileIndex endtile = CheckTunnelBusy(v->tile, NULL); tron@1430: tron@1430: if (endtile == INVALID_TILE) // tunnel is busy (error returned) Darkvater@1418: return; Darkvater@1418: tron@1431: switch (v->direction) { tron@1431: case 1: tron@1431: case 5: tron@1431: SetSignalsOnBothDir(v->tile, 0); tron@1431: SetSignalsOnBothDir(endtile, 0); tron@1431: break; tron@1431: tron@1431: case 3: tron@1431: case 7: tron@1431: SetSignalsOnBothDir(v->tile, 1); tron@1431: SetSignalsOnBothDir(endtile, 1); tron@1431: break; tron@1431: tron@1431: default: tron@1431: break; tron@1431: } dominik@98: } truelight@0: } truelight@0: truelight@0: static void ChangeTrainDirRandomly(Vehicle *v) truelight@0: { truelight@0: static int8 _random_dir_change[4] = { -1, 0, 0, 1}; truelight@193: truelight@0: do { dominik@98: //I need to buffer the train direction darkvater@288: if (!(v->u.rail.track & 0x40)) tron@2635: v->direction = (v->direction + _random_dir_change[GB(Random(), 0, 2)]) & 7; truelight@0: if (!(v->vehstatus & VS_HIDDEN)) { truelight@0: BeginVehicleMove(v); truelight@0: UpdateTrainDeltaXY(v, v->direction); truelight@0: v->cur_image = GetTrainImage(v, v->direction); truelight@954: AfterSetTrainPos(v, false); truelight@0: } truelight@0: } while ( (v=v->next) != NULL); truelight@0: } truelight@0: truelight@0: static void HandleCrashedTrain(Vehicle *v) truelight@0: { truelight@0: int state = ++v->u.rail.crash_anim_pos, index; truelight@0: uint32 r; truelight@0: Vehicle *u; truelight@193: tron@2639: if (state == 4 && v->u.rail.track != 0x40) { tron@1359: CreateEffectVehicleRel(v, 4, 4, 8, EV_EXPLOSION_LARGE); truelight@0: } truelight@0: tron@2637: if (state <= 200 && CHANCE16R(1, 7, r)) { truelight@0: index = (r * 10 >> 16); truelight@0: truelight@0: u = v; truelight@0: do { truelight@0: if (--index < 0) { celestar@1137: r = Random(); truelight@0: truelight@0: CreateEffectVehicleRel(u, tron@2140: GB(r, 8, 3) + 2, tron@2140: GB(r, 16, 3) + 2, tron@2140: GB(r, 0, 3) + 5, tron@1359: EV_EXPLOSION_SMALL); truelight@0: break; truelight@0: } truelight@0: } while ( (u=u->next) != NULL); truelight@0: } truelight@0: truelight@0: if (state <= 240 && !(v->tick_counter&3)) { truelight@0: ChangeTrainDirRandomly(v); truelight@0: } truelight@0: bjarni@1128: if (state >= 4440 && !(v->tick_counter&0x1F)) { truelight@0: DeleteLastWagon(v); bjarni@1128: InvalidateWindow(WC_REPLACE_VEHICLE, VEH_Train); bjarni@1128: } truelight@0: } truelight@0: truelight@0: static void HandleBrokenTrain(Vehicle *v) truelight@0: { truelight@0: if (v->breakdown_ctr != 1) { truelight@0: v->breakdown_ctr = 1; truelight@0: v->cur_speed = 0; truelight@0: truelight@0: if (v->breakdowns_since_last_service != 255) truelight@0: v->breakdowns_since_last_service++; truelight@193: truelight@0: InvalidateWindow(WC_VEHICLE_VIEW, v->index); truelight@0: InvalidateWindow(WC_VEHICLE_DETAILS, v->index); truelight@193: tron@541: SndPlayVehicleFx((_opt.landscape != LT_CANDY) ? tron@541: SND_10_TRAIN_BREAKDOWN : SND_3A_COMEDY_BREAKDOWN_2, v); truelight@0: truelight@0: if (!(v->vehstatus & VS_HIDDEN)) { truelight@0: Vehicle *u = CreateEffectVehicleRel(v, 4, 4, 5, EV_BREAKDOWN_SMOKE); tron@2549: if (u != NULL) u->u.special.unk0 = v->breakdown_delay * 2; truelight@0: } truelight@0: } truelight@0: truelight@0: if (!(v->tick_counter & 3)) { truelight@0: if (!--v->breakdown_delay) { truelight@0: v->breakdown_ctr = 0; truelight@0: InvalidateWindow(WC_VEHICLE_VIEW, v->index); truelight@0: } truelight@0: } truelight@0: } truelight@0: truelight@0: static const byte _breakdown_speeds[16] = { truelight@0: 225, 210, 195, 180, 165, 150, 135, 120, 105, 90, 75, 60, 45, 30, 15, 15 truelight@0: }; truelight@0: truelight@742: static bool TrainCheckIfLineEnds(Vehicle *v) truelight@0: { tron@1977: TileIndex tile; truelight@0: uint x,y; tron@2484: uint16 break_speed; peter1138@2874: DiagDirection t; truelight@0: uint32 ts; truelight@0: tron@2484: t = v->breakdown_ctr; tron@2484: if (t > 1) { truelight@0: v->vehstatus |= VS_TRAIN_SLOWING; truelight@193: tron@2484: break_speed = _breakdown_speeds[GB(~t, 4, 4)]; tron@2484: if (break_speed < v->cur_speed) v->cur_speed = break_speed; truelight@0: } else { truelight@0: v->vehstatus &= ~VS_TRAIN_SLOWING; truelight@0: } truelight@0: tron@2639: if (v->u.rail.track & 0x40) return true; // exit if inside a tunnel tron@2639: if (v->u.rail.track & 0x80) return true; // exit if inside a depot hackykid@2008: truelight@0: tile = v->tile; truelight@0: truelight@0: // tunnel entrance? tron@2150: if (IsTunnelTile(tile) && GB(_m[tile].m5, 0, 2) * 2 + 1 == v->direction) tron@2150: return true; truelight@193: truelight@0: // depot? truelight@742: /* XXX -- When enabled, this makes it possible to crash trains of others truelight@742: (by building a depot right against a station) */ tron@2049: /* if (IsTileType(tile, MP_RAILWAY) && (_m[tile].m5 & 0xFC) == 0xC0) truelight@742: return true;*/ truelight@0: darkvater@22: /* Determine the non-diagonal direction in which we will exit this tile */ truelight@0: t = v->direction >> 1; truelight@0: if (!(v->direction & 1) && v->u.rail.track != _state_dir_table[t]) { truelight@0: t = (t - 1) & 3; truelight@0: } darkvater@22: /* Calculate next tile */ tron@900: tile += TileOffsByDir(t); darkvater@22: // determine the track status on the next tile. bjarni@1151: ts = GetTileTrackStatus(tile, TRANSPORT_RAIL) & _reachable_tracks[t]; truelight@193: darkvater@22: /* Calc position within the current tile ?? */ truelight@0: x = v->x_pos & 0xF; truelight@0: y = v->y_pos & 0xF; truelight@193: tron@2639: switch (v->direction) { truelight@0: case 0: truelight@0: x = (~x) + (~y) + 24; truelight@0: break; truelight@0: case 7: truelight@0: x = y; truelight@0: /* fall through */ truelight@0: case 1: truelight@0: x = (~x) + 16; truelight@0: break; truelight@0: case 2: truelight@0: x = (~x) + y + 8; truelight@0: break; truelight@0: case 3: truelight@0: x = y; truelight@0: break; truelight@0: case 4: truelight@0: x = x + y - 8; truelight@0: break; truelight@0: case 6: truelight@0: x = (~y) + x + 8; truelight@0: break; truelight@0: } truelight@0: tron@2484: if (GB(ts, 0, 16) != 0) { peter1138@2874: /* If we approach a rail-piece which we can't enter, or the back of a depot, don't enter it! */ peter1138@2874: if (x + 4 > 15 && peter1138@2874: (!CheckCompatibleRail(v, tile) || peter1138@2874: (IsTileDepotType(tile, TRANSPORT_RAIL) && peter1138@2874: GetDepotDirection(tile, TRANSPORT_RAIL) == t))) { truelight@742: v->cur_speed = 0; truelight@742: ReverseTrainDirection(v); truelight@742: return false; truelight@742: } truelight@0: if ((ts &= (ts >> 16)) == 0) { truelight@0: // make a rail/road crossing red Darkvater@1927: if (IsTileType(tile, MP_STREET) && IsLevelCrossing(tile)) { tron@2493: if (GB(_m[tile].m5, 2, 1) == 0) { tron@2493: SB(_m[tile].m5, 2, 1, 1); tron@541: SndPlayVehicleFx(SND_0E_LEVEL_CROSSING, v); truelight@0: MarkTileDirtyByTile(tile); truelight@0: } truelight@0: } truelight@742: return true; truelight@0: } truelight@0: } else if (x + 4 > 15) { truelight@0: v->cur_speed = 0; truelight@0: ReverseTrainDirection(v); truelight@742: return false; truelight@0: } truelight@0: truelight@0: // slow down truelight@0: v->vehstatus |= VS_TRAIN_SLOWING; tron@2484: break_speed = _breakdown_speeds[x & 0xF]; tron@2484: if (!(v->direction&1)) break_speed >>= 1; tron@2484: if (break_speed < v->cur_speed) v->cur_speed = break_speed; truelight@742: truelight@742: return true; truelight@0: } truelight@0: truelight@0: static void TrainLocoHandler(Vehicle *v, bool mode) truelight@0: { truelight@0: int j; truelight@0: truelight@0: /* train has crashed? */ truelight@0: if (v->u.rail.crash_anim_pos != 0) { truelight@0: if (!mode) HandleCrashedTrain(v); truelight@0: return; truelight@0: } truelight@0: truelight@0: if (v->u.rail.force_proceed != 0) truelight@0: v->u.rail.force_proceed--; truelight@0: truelight@0: /* train is broken down? */ truelight@0: if (v->breakdown_ctr != 0) { truelight@0: if (v->breakdown_ctr <= 2) { truelight@0: HandleBrokenTrain(v); truelight@0: return; truelight@0: } truelight@0: v->breakdown_ctr--; truelight@0: } truelight@0: truelight@954: if (HASBIT(v->u.rail.flags, VRF_REVERSING) && v->cur_speed == 0) { truelight@0: ReverseTrainDirection(v); truelight@0: } truelight@0: truelight@0: /* exit if train is stopped */ truelight@0: if (v->vehstatus & VS_STOPPED && v->cur_speed == 0) truelight@0: return; truelight@0: truelight@0: truelight@0: if (ProcessTrainOrder(v)) { truelight@0: v->load_unload_time_rem = 0; truelight@0: v->cur_speed = 0; truelight@0: v->subspeed = 0; truelight@0: ReverseTrainDirection(v); truelight@0: return; truelight@0: } truelight@0: truelight@0: HandleTrainLoading(v, mode); truelight@0: tron@555: if (v->current_order.type == OT_LOADING) truelight@0: return; truelight@0: truelight@0: if (CheckTrainStayInDepot(v)) truelight@0: return; truelight@0: truelight@0: if (!mode) HandleLocomotiveSmokeCloud(v); truelight@0: truelight@0: j = UpdateTrainSpeed(v); truelight@0: if (j == 0) { truelight@0: // if the vehicle has speed 0, update the last_speed field. truelight@0: if (v->cur_speed != 0) truelight@0: return; truelight@0: } else { truelight@0: TrainCheckIfLineEnds(v); truelight@0: truelight@0: do { truelight@0: TrainController(v); hackykid@1922: CheckTrainCollision(v); truelight@0: if (v->cur_speed <= 0x100) truelight@0: break; truelight@0: } while (--j != 0); truelight@0: } truelight@0: truelight@0: SetLastSpeed(v, v->cur_speed); truelight@0: } truelight@0: truelight@0: truelight@0: void Train_Tick(Vehicle *v) truelight@0: { truelight@0: if (_age_cargo_skip_counter == 0 && v->cargo_days != 0xff) truelight@0: v->cargo_days++; truelight@0: truelight@0: v->tick_counter++; truelight@0: bjarni@2676: if (IsFrontEngine(v)) { truelight@0: TrainLocoHandler(v, false); truelight@193: truelight@0: // make sure vehicle wasn't deleted. bjarni@2676: if (v->type == VEH_Train && IsFrontEngine(v)) truelight@0: TrainLocoHandler(v, true); bjarni@2676: } else if (IsFreeWagon(v) && HASBITS(v->vehstatus, VS_CRASHED)) { darkvater@1132: // Delete flooded standalone wagon darkvater@1132: if (++v->u.rail.crash_anim_pos >= 4400) darkvater@1132: DeleteVehicle(v); truelight@0: } truelight@0: } truelight@0: truelight@0: truelight@0: static const byte _depot_track_ind[4] = {0,1,0,1}; truelight@0: dominik@715: // Validation for the news item "Train is waiting in depot" tron@1095: static bool ValidateTrainInDepot( uint data_a, uint data_b ) dominik@715: { truelight@919: Vehicle *v = GetVehicle(data_a); celestar@1064: return (v->u.rail.track == 0x80 && (v->vehstatus | VS_STOPPED)); dominik@715: } dominik@715: tron@1977: void TrainEnterDepot(Vehicle *v, TileIndex tile) truelight@0: { tron@2493: SetSignalsOnBothDir(tile, _depot_track_ind[GB(_m[tile].m5, 0, 2)]); truelight@0: bjarni@2676: if (!IsFrontEngine(v)) v = GetFirstVehicleInChain(v); truelight@0: bjarni@578: VehicleServiceInDepot(v); bjarni@578: truelight@0: InvalidateWindow(WC_VEHICLE_DETAILS, v->index); truelight@0: truelight@0: v->load_unload_time_rem = 0; truelight@0: v->cur_speed = 0; truelight@0: tron@445: TriggerVehicle(v, VEHICLE_TRIGGER_DEPOT); tron@445: tron@555: if (v->current_order.type == OT_GOTO_DEPOT) { tron@555: Order t; tron@555: truelight@0: InvalidateWindow(WC_VEHICLE_VIEW, v->index); truelight@193: tron@555: t = v->current_order; tron@555: v->current_order.type = OT_DUMMY; tron@555: v->current_order.flags = 0; tron@555: celestar@1530: if (HASBIT(t.flags, OFB_PART_OF_ORDERS)) { // Part of the orderlist? tron@555: v->u.rail.days_since_order_progr = 0; tron@555: v->cur_order_index++; celestar@1530: } else if (HASBIT(t.flags, OFB_HALT_IN_DEPOT)) { // User initiated? truelight@0: v->vehstatus |= VS_STOPPED; truelight@0: if (v->owner == _local_player) { tron@534: SetDParam(0, v->unitnumber); dominik@715: AddValidatedNewsItem( truelight@0: STR_8814_TRAIN_IS_WAITING_IN_DEPOT, truelight@0: NEWS_FLAGS(NM_SMALL, NF_VIEWPORT|NF_VEHICLE, NT_ADVICE, 0), truelight@0: v->index, dominik@715: 0, dominik@715: ValidateTrainInDepot); truelight@0: } truelight@0: } truelight@0: } bjarni@1151: InvalidateWindowClasses(WC_TRAINS_LIST); truelight@0: } truelight@0: truelight@0: static void CheckIfTrainNeedsService(Vehicle *v) truelight@0: { tron@2630: const Depot* depot; darkvater@308: TrainFindDepotData tfdd; truelight@0: tron@2639: if (_patches.servint_trains == 0) return; tron@2639: if (!VehicleNeedsService(v)) return; tron@2639: if (v->vehstatus & VS_STOPPED) return; tron@2639: if (_patches.gotodepot && VehicleHasDepotOrders(v)) return; truelight@193: truelight@0: // Don't interfere with a depot visit scheduled by the user, or a truelight@0: // depot visit by the order list. tron@555: if (v->current_order.type == OT_GOTO_DEPOT && celestar@1530: (v->current_order.flags & (OF_HALT_IN_DEPOT | OF_PART_OF_ORDERS)) != 0) truelight@0: return; truelight@0: darkvater@308: tfdd = FindClosestTrainDepot(v); darkvater@308: /* Only go to the depot if it is not too far out of our way. */ darkvater@308: if (tfdd.best_length == (uint)-1 || tfdd.best_length > 16 ) { tron@555: if (v->current_order.type == OT_GOTO_DEPOT) { darkvater@308: /* If we were already heading for a depot but it has darkvater@308: * suddenly moved farther away, we continue our normal darkvater@308: * schedule? */ tron@555: v->current_order.type = OT_DUMMY; tron@555: v->current_order.flags = 0; darkvater@755: InvalidateWindowWidget(WC_VEHICLE_VIEW, v->index, STATUS_BAR); truelight@0: } truelight@0: return; truelight@0: } truelight@0: darkvater@308: depot = GetDepotByTile(tfdd.tile); truelight@0: tron@555: if (v->current_order.type == OT_GOTO_DEPOT && truelight@1313: v->current_order.station != depot->index && tron@555: !CHANCE16(3,16)) truelight@0: return; truelight@0: tron@555: v->current_order.type = OT_GOTO_DEPOT; tron@555: v->current_order.flags = OF_NON_STOP; truelight@1313: v->current_order.station = depot->index; darkvater@308: v->dest_tile = tfdd.tile; darkvater@755: InvalidateWindowWidget(WC_VEHICLE_VIEW, v->index, STATUS_BAR); truelight@0: } truelight@0: Darkvater@1790: int32 GetTrainRunningCost(const Vehicle *v) truelight@0: { truelight@0: int32 cost = 0; truelight@0: truelight@0: do { tron@540: const RailVehicleInfo *rvi = RailVehInfo(v->engine_type); peter1138@2840: if (rvi->running_cost_base > 0) peter1138@2840: cost += rvi->running_cost_base * _price.running_rail[rvi->running_cost_class]; peter1138@2840: } while ((v = v->next) != NULL); truelight@0: truelight@0: return cost; truelight@0: } truelight@0: truelight@0: void OnNewDay_Train(Vehicle *v) truelight@0: { truelight@0: TileIndex tile; truelight@0: truelight@0: if ((++v->day_counter & 7) == 0) truelight@0: DecreaseVehicleValue(v); truelight@0: bjarni@2676: if (IsFrontEngine(v)) { truelight@0: CheckVehicleBreakdown(v); truelight@0: AgeVehicle(v); truelight@193: truelight@0: CheckIfTrainNeedsService(v); truelight@193: truelight@0: // check if train hasn't advanced in its order list for a set number of days Celestar@1057: if (_patches.lost_train_days && v->num_orders && !(v->vehstatus & (VS_STOPPED | VS_CRASHED) ) && ++v->u.rail.days_since_order_progr >= _patches.lost_train_days && v->owner == _local_player) { truelight@0: v->u.rail.days_since_order_progr = 0; tron@534: SetDParam(0, v->unitnumber); truelight@0: AddNewsItem( truelight@0: STR_TRAIN_IS_LOST, truelight@0: NEWS_FLAGS(NM_SMALL, NF_VIEWPORT|NF_VEHICLE, NT_ADVICE, 0), truelight@0: v->index, truelight@0: 0); truelight@0: } truelight@0: celestar@1053: CheckOrders(v->index, OC_INIT); truelight@193: truelight@0: /* update destination */ tron@555: if (v->current_order.type == OT_GOTO_STATION && tron@2639: (tile = GetStation(v->current_order.station)->train_tile) != 0) { tron@2639: v->dest_tile = tile; tron@2639: } truelight@0: truelight@0: if ((v->vehstatus & VS_STOPPED) == 0) { truelight@0: /* running costs */ truelight@0: int32 cost = GetTrainRunningCost(v) / 364; truelight@0: truelight@0: v->profit_this_year -= cost >> 8; truelight@0: truelight@0: SET_EXPENSES_TYPE(EXPENSES_TRAIN_RUN); truelight@0: SubtractMoneyFromPlayerFract(v->owner, cost); truelight@0: truelight@0: InvalidateWindow(WC_VEHICLE_DETAILS, v->index); bjarni@1151: InvalidateWindowClasses(WC_TRAINS_LIST); truelight@0: } truelight@0: } truelight@0: } truelight@0: tron@1093: void TrainsYearlyLoop(void) truelight@0: { truelight@0: Vehicle *v; truelight@0: truelight@0: FOR_ALL_VEHICLES(v) { bjarni@2676: if (v->type == VEH_Train && IsFrontEngine(v)) { truelight@193: truelight@0: // show warning if train is not generating enough income last 2 years (corresponds to a red icon in the vehicle list) truelight@0: if (_patches.train_income_warn && v->owner == _local_player && v->age >= 730 && v->profit_this_year < 0) { tron@534: SetDParam(1, v->profit_this_year); tron@534: SetDParam(0, v->unitnumber); truelight@0: AddNewsItem( truelight@0: STR_TRAIN_IS_UNPROFITABLE, truelight@0: NEWS_FLAGS(NM_SMALL, NF_VIEWPORT|NF_VEHICLE, NT_ADVICE, 0), truelight@0: v->index, truelight@0: 0); truelight@0: } truelight@0: truelight@0: v->profit_last_year = v->profit_this_year; truelight@0: v->profit_this_year = 0; truelight@0: InvalidateWindow(WC_VEHICLE_DETAILS, v->index); truelight@0: } truelight@0: } truelight@0: } truelight@0: truelight@0: tron@1093: void InitializeTrains(void) truelight@0: { truelight@0: _age_cargo_skip_counter = 1; truelight@0: } bjarni@2855: bjarni@2855: /* bjarni@2855: * Link front and rear multiheaded engines to each other bjarni@2855: * This is done when loading a savegame bjarni@2855: */ bjarni@2855: void ConnectMultiheadedTrains(void) bjarni@2855: { bjarni@2855: Vehicle *v; bjarni@2855: bjarni@2855: FOR_ALL_VEHICLES(v) { bjarni@2855: if (v->type == VEH_Train) { bjarni@2855: v->u.rail.other_multiheaded_part = NULL; bjarni@2855: } bjarni@2855: } bjarni@2855: bjarni@2855: FOR_ALL_VEHICLES(v) { bjarni@2855: if (v->type == VEH_Train && IsFrontEngine(v)) { bjarni@2855: Vehicle *u = v; bjarni@2855: bjarni@2855: BEGIN_ENUM_WAGONS(u) { bjarni@2855: if (u->u.rail.other_multiheaded_part != NULL) continue; // we already linked this one bjarni@2855: bjarni@2855: if (IsMultiheaded(u)) { bjarni@2855: if (!IsTrainEngine(u)) { bjarni@2855: /* we got a rear car without a front car. We will convert it to a front one */ bjarni@2855: SetTrainEngine(u); bjarni@2855: u->spritenum--; bjarni@2855: } bjarni@2855: bjarni@2855: { bjarni@2855: Vehicle *w; bjarni@2855: bjarni@2855: for(w = u->next; w != NULL && (w->engine_type != u->engine_type || w->u.rail.other_multiheaded_part != NULL); w = GetNextVehicle(w)); bjarni@2855: if (w != NULL) { bjarni@2855: /* we found a car to partner with this engine. Now we will make sure it face the right way */ bjarni@2855: if (IsTrainEngine(w)) { bjarni@2855: ClearTrainEngine(w); bjarni@2855: w->spritenum++; bjarni@2855: } bjarni@2855: } bjarni@2855: bjarni@2855: if (w != NULL) { bjarni@2855: w->u.rail.other_multiheaded_part = u; bjarni@2855: u->u.rail.other_multiheaded_part = w; bjarni@2855: } else { bjarni@2855: /* we got a front car and no rear cars. We will fake this one for forget that it should have been multiheaded */ bjarni@2855: ClearMultiheaded(u); bjarni@2855: } bjarni@2855: } bjarni@2855: } bjarni@2855: } END_ENUM_WAGONS(u) bjarni@2855: } bjarni@2855: } bjarni@2855: } bjarni@2855: bjarni@2855: /* bjarni@2855: * Converts all trains to the new subtype format introduced in savegame 16.2 bjarni@2855: * It also links multiheaded engines or make them forget they are multiheaded if no suitable partner is found bjarni@2855: */ bjarni@2855: void ConvertOldMultiheadToNew(void) bjarni@2855: { bjarni@2855: Vehicle *v; bjarni@2855: FOR_ALL_VEHICLES(v) { bjarni@2855: if (v->type == VEH_Train) { bjarni@2855: SETBIT(v->subtype, 7); // indicates that it's the old format and needs to be converted in the next loop bjarni@2855: } bjarni@2855: } bjarni@2855: bjarni@2855: FOR_ALL_VEHICLES(v) { bjarni@2855: if (v->type == VEH_Train) { bjarni@2855: if (HASBIT(v->subtype, 7) && ((v->subtype & ~0x80) == 0 || (v->subtype & ~0x80) == 4)) { bjarni@2855: Vehicle *u = v; bjarni@2855: bjarni@2855: BEGIN_ENUM_WAGONS(u) bjarni@2855: const RailVehicleInfo *rvi = RailVehInfo(u->engine_type); bjarni@2855: CLRBIT(u->subtype, 7); bjarni@2855: switch (u->subtype) { bjarni@2855: case 0: /* TS_Front_Engine */ bjarni@2855: if (rvi->flags & RVI_MULTIHEAD) { bjarni@2855: SetMultiheaded(u); bjarni@2855: } bjarni@2855: SetFrontEngine(u); bjarni@2855: SetTrainEngine(u); bjarni@2855: break; bjarni@2855: case 1: /* TS_Artic_Part */ bjarni@2855: u->subtype = 0; bjarni@2855: SetArticulatedPart(u); bjarni@2855: break; bjarni@2855: case 2: /* TS_Not_First */ bjarni@2855: u->subtype = 0; bjarni@2855: if (rvi->flags & RVI_WAGON) { bjarni@2855: // normal wagon bjarni@2855: SetTrainWagon(u); bjarni@2855: break; bjarni@2855: } bjarni@2855: if (rvi->flags & RVI_MULTIHEAD && rvi->image_index == u->spritenum - 1) { bjarni@2855: // rear end of a multiheaded engine bjarni@2855: SetMultiheaded(u); bjarni@2855: break; bjarni@2855: } bjarni@2855: if (rvi->flags & RVI_MULTIHEAD) { bjarni@2855: SetMultiheaded(u); bjarni@2855: } bjarni@2855: SetTrainEngine(u); bjarni@2855: break; bjarni@2855: case 4: /* TS_Free_Car */ bjarni@2855: u->subtype = 0; bjarni@2855: SetTrainWagon(u); bjarni@2855: SetFreeWagon(u); bjarni@2855: break; bjarni@2855: default: NOT_REACHED(); break; bjarni@2855: } bjarni@2855: END_ENUM_WAGONS(u) bjarni@2855: } bjarni@2855: } bjarni@2855: } bjarni@2855: }