# newgrf_engine.cpp

Go to the documentation of this file.

    00001 /* $Id: newgrf_engine.cpp 15765 2009-03-18 19:50:34Z rubidium $ */
    00002
    00005 #include "stdafx.h"
    00006 #include "debug.h"
    00007 #include "train.h"
    00008 #include "company_func.h"
    00009 #include "newgrf_engine.h"
    00010 #include "newgrf_spritegroup.h"
    00011 #include "date_func.h"
    00012 #include "vehicle_func.h"
    00013 #include "core/random_func.hpp"
    00014 #include "aircraft.h"
    00015 #include "core/smallmap_type.hpp"
    00016 #include "settings_type.h"
    00017
    00018 int _traininfo_vehicle_pitch = 0;
    00019 int _traininfo_vehicle_width = 29;
    00020
    00021 struct WagonOverride {
    00022   EngineID *train_id;
    00023   uint trains;
    00024   CargoID cargo;
    00025   const SpriteGroup *group;
    00026 };
    00027
    00028 void SetWagonOverrideSprites(EngineID engine, CargoID cargo, const SpriteGroup *group, EngineID *train_id, uint trains)
    00029 {
    00030   Engine *e = GetEngine(engine);
    00031   WagonOverride *wo;
    00032
    00033   assert(cargo < NUM_CARGO + 2); // Include CT_DEFAULT and CT_PURCHASE pseudo cargos.
    00034
    00035   e->overrides_count++;
    00036   e->overrides = ReallocT(e->overrides, e->overrides_count);
    00037
    00038   wo = &e->overrides[e->overrides_count - 1];
    00039   wo->group = group;
    00040   wo->cargo = cargo;
    00041   wo->trains = trains;
    00042   wo->train_id = MallocT<EngineID>(trains);
    00043   memcpy(wo->train_id, train_id, trains * sizeof *train_id);
    00044 }
    00045
    00046 const SpriteGroup *GetWagonOverrideSpriteSet(EngineID engine, CargoID cargo, EngineID overriding_engine)
    00047 {
    00048   const Engine *e = GetEngine(engine);
    00049
    00050   /* XXX: This could turn out to be a timesink on profiles. We could
    00051    * always just dedicate 65535 bytes for an [engine][train] trampoline
    00052    * for O(1). Or O(logMlogN) and searching binary tree or smt. like
    00053    * that. --pasky */
    00054
    00055   for (uint i = 0; i < e->overrides_count; i++) {
    00056     const WagonOverride *wo = &e->overrides[i];
    00057
    00058     if (wo->cargo != cargo && wo->cargo != CT_DEFAULT) continue;
    00059
    00060     for (uint j = 0; j < wo->trains; j++) {
    00061       if (wo->train_id[j] == overriding_engine) return wo->group;
    00062     }
    00063   }
    00064   return NULL;
    00065 }
    00066
    00070 void UnloadWagonOverrides(Engine *e)
    00071 {
    00072   for (uint i = 0; i < e->overrides_count; i++) {
    00073     WagonOverride *wo = &e->overrides[i];
    00074     free(wo->train_id);
    00075   }
    00076   free(e->overrides);
    00077   e->overrides_count = 0;
    00078   e->overrides = NULL;
    00079 }
    00080
    00081
    00082 void SetCustomEngineSprites(EngineID engine, byte cargo, const SpriteGroup *group)
    00083 {
    00084   Engine *e = GetEngine(engine);
    00085   assert(cargo < lengthof(e->group));
    00086
    00087   if (e->group[cargo] != NULL) {
    00088     grfmsg(6, "SetCustomEngineSprites: engine %d cargo %d already has group -- replacing", engine, cargo);
    00089   }
    00090   e->group[cargo] = group;
    00091 }
    00092
    00093
    00100 void SetEngineGRF(EngineID engine, const GRFFile *file)
    00101 {
    00102   Engine *e = GetEngine(engine);
    00103   e->grffile = file;
    00104 }
    00105
    00106
    00112 const GRFFile *GetEngineGRF(EngineID engine)
    00113 {
    00114   return GetEngine(engine)->grffile;
    00115 }
    00116
    00117
    00123 uint32 GetEngineGRFID(EngineID engine)
    00124 {
    00125   const GRFFile *file = GetEngineGRF(engine);
    00126   return file == NULL ? 0 : file->grfid;
    00127 }
    00128
    00129
    00130 static int MapOldSubType(const Vehicle *v)
    00131 {
    00132   if (v->type != VEH_TRAIN) return v->subtype;
    00133   if (IsTrainEngine(v)) return 0;
    00134   if (IsFreeWagon(v)) return 4;
    00135   return 2;
    00136 }
    00137
    00138
    00139 /* TTDP style aircraft movement states for GRF Action 2 Var 0xE2 */
    00140 enum {
    00141   AMS_TTDP_HANGAR,
    00142   AMS_TTDP_TO_HANGAR,
    00143   AMS_TTDP_TO_PAD1,
    00144   AMS_TTDP_TO_PAD2,
    00145   AMS_TTDP_TO_PAD3,
    00146   AMS_TTDP_TO_ENTRY_2_AND_3,
    00147   AMS_TTDP_TO_ENTRY_2_AND_3_AND_H,
    00148   AMS_TTDP_TO_JUNCTION,
    00149   AMS_TTDP_LEAVE_RUNWAY,
    00150   AMS_TTDP_TO_INWAY,
    00151   AMS_TTDP_TO_RUNWAY,
    00152   AMS_TTDP_TO_OUTWAY,
    00153   AMS_TTDP_WAITING,
    00154   AMS_TTDP_TAKEOFF,
    00155   AMS_TTDP_TO_TAKEOFF,
    00156   AMS_TTDP_CLIMBING,
    00157   AMS_TTDP_FLIGHT_APPROACH,
    00158   AMS_TTDP_UNUSED_0x11,
    00159   AMS_TTDP_FLIGHT_TO_TOWER,
    00160   AMS_TTDP_UNUSED_0x13,
    00161   AMS_TTDP_FLIGHT_FINAL,
    00162   AMS_TTDP_FLIGHT_DESCENT,
    00163   AMS_TTDP_BRAKING,
    00164   AMS_TTDP_HELI_TAKEOFF_AIRPORT,
    00165   AMS_TTDP_HELI_TO_TAKEOFF_AIRPORT,
    00166   AMS_TTDP_HELI_LAND_AIRPORT,
    00167   AMS_TTDP_HELI_TAKEOFF_HELIPORT,
    00168   AMS_TTDP_HELI_TO_TAKEOFF_HELIPORT,
    00169   AMS_TTDP_HELI_LAND_HELIPORT,
    00170 };
    00171
    00172
    00177 static byte MapAircraftMovementState(const Vehicle *v)
    00178 {
    00179   const Station *st = GetTargetAirportIfValid(v);
    00180   if (st == NULL) return AMS_TTDP_FLIGHT_TO_TOWER;
    00181
    00182   const AirportFTAClass *afc = st->Airport();
    00183   uint16 amdflag = afc->MovingData(v->u.air.pos)->flag;
    00184
    00185   switch (v->u.air.state) {
    00186     case HANGAR:
    00187       /* The international airport is a special case as helicopters can land in
    00188        * front of the hanger. Helicopters also change their air.state to
    00189        * AMED_HELI_LOWER some time before actually descending. */
    00190
    00191       /* This condition only occurs for helicopters, during descent,
    00192        * to a landing by the hanger of an international airport. */
    00193       if (amdflag & AMED_HELI_LOWER) return AMS_TTDP_HELI_LAND_AIRPORT;
    00194
    00195       /* This condition only occurs for helicopters, before starting descent,
    00196        * to a landing by the hanger of an international airport. */
    00197       if (amdflag & AMED_SLOWTURN) return AMS_TTDP_FLIGHT_TO_TOWER;
    00198
    00199       /* The final two conditions apply to helicopters or aircraft.
    00200        * Has reached hanger? */
    00201       if (amdflag & AMED_EXACTPOS) return AMS_TTDP_HANGAR;
    00202
    00203       /* Still moving towards hanger. */
    00204       return AMS_TTDP_TO_HANGAR;
    00205
    00206     case TERM1:
    00207       if (amdflag & AMED_EXACTPOS) return AMS_TTDP_TO_PAD1;
    00208       return AMS_TTDP_TO_JUNCTION;
    00209
    00210     case TERM2:
    00211       if (amdflag & AMED_EXACTPOS) return AMS_TTDP_TO_PAD2;
    00212       return AMS_TTDP_TO_ENTRY_2_AND_3_AND_H;
    00213
    00214     case TERM3:
    00215     case TERM4:
    00216     case TERM5:
    00217     case TERM6:
    00218     case TERM7:
    00219     case TERM8:
    00220       /* TTDPatch only has 3 terminals, so treat these states the same */
    00221       if (amdflag & AMED_EXACTPOS) return AMS_TTDP_TO_PAD3;
    00222       return AMS_TTDP_TO_ENTRY_2_AND_3_AND_H;
    00223
    00224     case HELIPAD1:
    00225     case HELIPAD2:
    00226     case HELIPAD3:
    00227     case HELIPAD4: // Will only occur for helicopters.
    00228       if (amdflag & AMED_HELI_LOWER) return AMS_TTDP_HELI_LAND_AIRPORT; // Descending.
    00229       if (amdflag & AMED_SLOWTURN)   return AMS_TTDP_FLIGHT_TO_TOWER;   // Still hasn't started descent.
    00230       return AMS_TTDP_TO_JUNCTION; // On the ground.
    00231
    00232     case TAKEOFF: // Moving to takeoff position.
    00233       return AMS_TTDP_TO_OUTWAY;
    00234
    00235     case STARTTAKEOFF: // Accelerating down runway.
    00236       return AMS_TTDP_TAKEOFF;
    00237
    00238     case ENDTAKEOFF: // Ascent
    00239       return AMS_TTDP_CLIMBING;
    00240
    00241     case HELITAKEOFF: // Helicopter is moving to take off position.
    00242       if (afc->delta_z == 0) {
    00243         return amdflag & AMED_HELI_RAISE ?
    00244           AMS_TTDP_HELI_TAKEOFF_AIRPORT : AMS_TTDP_TO_JUNCTION;
    00245       } else {
    00246         return AMS_TTDP_HELI_TAKEOFF_HELIPORT;
    00247       }
    00248
    00249     case FLYING:
    00250       return amdflag & AMED_HOLD ? AMS_TTDP_FLIGHT_APPROACH : AMS_TTDP_FLIGHT_TO_TOWER;
    00251
    00252     case LANDING: // Descent
    00253       return AMS_TTDP_FLIGHT_DESCENT;
    00254
    00255     case ENDLANDING: // On the runway braking
    00256       if (amdflag & AMED_BRAKE) return AMS_TTDP_BRAKING;
    00257       /* Landed - moving off runway */
    00258       return AMS_TTDP_TO_INWAY;
    00259
    00260     case HELILANDING:
    00261     case HELIENDLANDING: // Helicoptor is decending.
    00262       if (amdflag & AMED_HELI_LOWER) {
    00263         return afc->delta_z == 0 ?
    00264           AMS_TTDP_HELI_LAND_AIRPORT : AMS_TTDP_HELI_LAND_HELIPORT;
    00265       } else {
    00266         return AMS_TTDP_FLIGHT_TO_TOWER;
    00267       }
    00268
    00269     default:
    00270       return AMS_TTDP_HANGAR;
    00271   }
    00272 }
    00273
    00274
    00275 /* TTDP style aircraft movement action for GRF Action 2 Var 0xE6 */
    00276 enum {
    00277   AMA_TTDP_IN_HANGAR,
    00278   AMA_TTDP_ON_PAD1,
    00279   AMA_TTDP_ON_PAD2,
    00280   AMA_TTDP_ON_PAD3,
    00281   AMA_TTDP_HANGAR_TO_PAD1,
    00282   AMA_TTDP_HANGAR_TO_PAD2,
    00283   AMA_TTDP_HANGAR_TO_PAD3,
    00284   AMA_TTDP_LANDING_TO_PAD1,
    00285   AMA_TTDP_LANDING_TO_PAD2,
    00286   AMA_TTDP_LANDING_TO_PAD3,
    00287   AMA_TTDP_PAD1_TO_HANGAR,
    00288   AMA_TTDP_PAD2_TO_HANGAR,
    00289   AMA_TTDP_PAD3_TO_HANGAR,
    00290   AMA_TTDP_PAD1_TO_TAKEOFF,
    00291   AMA_TTDP_PAD2_TO_TAKEOFF,
    00292   AMA_TTDP_PAD3_TO_TAKEOFF,
    00293   AMA_TTDP_HANGAR_TO_TAKOFF,
    00294   AMA_TTDP_LANDING_TO_HANGAR,
    00295   AMA_TTDP_IN_FLIGHT,
    00296 };
    00297
    00298
    00304 static byte MapAircraftMovementAction(const Vehicle *v)
    00305 {
    00306   switch (v->u.air.state) {
    00307     case HANGAR:
    00308       return (v->cur_speed > 0) ? AMA_TTDP_LANDING_TO_HANGAR : AMA_TTDP_IN_HANGAR;
    00309
    00310     case TERM1:
    00311     case HELIPAD1:
    00312       return (v->current_order.IsType(OT_LOADING)) ? AMA_TTDP_ON_PAD1 : AMA_TTDP_LANDING_TO_PAD1;
    00313
    00314     case TERM2:
    00315     case HELIPAD2:
    00316       return (v->current_order.IsType(OT_LOADING)) ? AMA_TTDP_ON_PAD2 : AMA_TTDP_LANDING_TO_PAD2;
    00317
    00318     case TERM3:
    00319     case TERM4:
    00320     case TERM5:
    00321     case TERM6:
    00322     case TERM7:
    00323     case TERM8:
    00324     case HELIPAD3:
    00325     case HELIPAD4:
    00326       return (v->current_order.IsType(OT_LOADING)) ? AMA_TTDP_ON_PAD3 : AMA_TTDP_LANDING_TO_PAD3;
    00327
    00328     case TAKEOFF:      // Moving to takeoff position
    00329     case STARTTAKEOFF: // Accelerating down runway
    00330     case ENDTAKEOFF:   // Ascent
    00331     case HELITAKEOFF:
    00332       /* @todo Need to find which terminal (or hanger) we've come from. How? */
    00333       return AMA_TTDP_PAD1_TO_TAKEOFF;
    00334
    00335     case FLYING:
    00336       return AMA_TTDP_IN_FLIGHT;
    00337
    00338     case LANDING:    // Descent
    00339     case ENDLANDING: // On the runway braking
    00340     case HELILANDING:
    00341     case HELIENDLANDING:
    00342       /* @todo Need to check terminal we're landing to. Is it known yet? */
    00343       return (v->current_order.IsType(OT_GOTO_DEPOT)) ?
    00344         AMA_TTDP_LANDING_TO_HANGAR : AMA_TTDP_LANDING_TO_PAD1;
    00345
    00346     default:
    00347       return AMA_TTDP_IN_HANGAR;
    00348   }
    00349 }
    00350
    00351
    00352 /* TTDP airport types. Used to map our types to TTDPatch's */
    00353 enum {
    00354   ATP_TTDP_SMALL,
    00355   ATP_TTDP_LARGE,
    00356   ATP_TTDP_HELIPORT,
    00357   ATP_TTDP_OILRIG,
    00358 };
    00359
    00360
    00361 /* Vehicle Resolver Functions */
    00362 static inline const Vehicle *GRV(const ResolverObject *object)
    00363 {
    00364   switch (object->scope) {
    00365     default: NOT_REACHED();
    00366     case VSG_SCOPE_SELF: return object->u.vehicle.self;
    00367     case VSG_SCOPE_PARENT: return object->u.vehicle.parent;
    00368     case VSG_SCOPE_RELATIVE: {
    00369       const Vehicle *v = NULL;
    00370       switch (GB(object->count, 6, 2)) {
    00371         default: NOT_REACHED();
    00372         case 0x00: // count back (away from the engine), starting at this vehicle
    00373         case 0x01: // count forward (toward the engine), starting at this vehicle
    00374           v = object->u.vehicle.self;
    00375           break;
    00376         case 0x02: // count back, starting at the engine
    00377           v = object->u.vehicle.parent;
    00378           break;
    00379         case 0x03: { // count back, starting at the first vehicle in this chain of vehicles with the same ID, as for vehicle variable 41
    00380           const Vehicle *self = object->u.vehicle.self;
    00381           for (const Vehicle *u = self->First(); u != self; u = u->Next()) {
    00382             if (u->engine_type != self->engine_type) {
    00383               v = NULL;
    00384             } else {
    00385               if (v == NULL) v = u;
    00386             }
    00387           }
    00388           if (v == NULL) v = self;
    00389         } break;
    00390       }
    00391       uint32 count = GB(object->count, 0, 4);
    00392       if (count == 0) count = GetRegister(0x100);
    00393       while (v != NULL && count-- != 0) v = (GB(object->count, 6, 2) == 0x01) ? v->Previous() : v->Next();
    00394       return v;
    00395     }
    00396   }
    00397 }
    00398
    00399
    00400 static uint32 VehicleGetRandomBits(const ResolverObject *object)
    00401 {
    00402   return GRV(object) == NULL ? 0 : GRV(object)->random_bits;
    00403 }
    00404
    00405
    00406 static uint32 VehicleGetTriggers(const ResolverObject *object)
    00407 {
    00408   return GRV(object) == NULL ? 0 : GRV(object)->waiting_triggers;
    00409 }
    00410
    00411
    00412 static void VehicleSetTriggers(const ResolverObject *object, int triggers)
    00413 {
    00414   /* Evil cast to get around const-ness. This used to be achieved by an
    00415    * innocent looking function pointer cast... Currently I cannot see a
    00416    * way of avoiding this without removing consts deep within gui code.
    00417    */
    00418   Vehicle *v = (Vehicle*)GRV(object);
    00419
    00420   /* This function must only be called when processing triggers -- any
    00421    * other time is an error. */
    00422   assert(object->trigger != 0);
    00423
    00424   if (v != NULL) v->waiting_triggers = triggers;
    00425 }
    00426
    00427
    00428 static uint8 LiveryHelper(EngineID engine, const Vehicle *v)
    00429 {
    00430   const Livery *l;
    00431
    00432   if (v == NULL) {
    00433     if (!IsValidCompanyID(_current_company)) return 0;
    00434     l = GetEngineLivery(engine, _current_company, INVALID_ENGINE, NULL);
    00435   } else if (v->type == VEH_TRAIN) {
    00436     l = GetEngineLivery(v->engine_type, v->owner, v->u.rail.first_engine, v);
    00437   } else if (v->type == VEH_ROAD) {
    00438     l = GetEngineLivery(v->engine_type, v->owner, v->u.road.first_engine, v);
    00439   } else {
    00440     l = GetEngineLivery(v->engine_type, v->owner, INVALID_ENGINE, v);
    00441   }
    00442
    00443   return l->colour1 + l->colour2 * 16;
    00444 }
    00445
    00453 static uint32 PositionHelper(const Vehicle *v, bool consecutive)
    00454 {
    00455   const Vehicle *u;
    00456   byte chain_before = 0;
    00457   byte chain_after  = 0;
    00458
    00459   for (u = v->First(); u != v; u = u->Next()) {
    00460     chain_before++;
    00461     if (consecutive && u->engine_type != v->engine_type) chain_before = 0;
    00462   }
    00463
    00464   while (u->Next() != NULL && (!consecutive || u->Next()->engine_type == v->engine_type)) {
    00465     chain_after++;
    00466     u = u->Next();
    00467   }
    00468
    00469   return chain_before | chain_after << 8 | (chain_before + chain_after + consecutive) << 16;
    00470 }
    00471
    00472 static uint32 VehicleGetVariable(const ResolverObject *object, byte variable, byte parameter, bool *available)
    00473 {
    00474   Vehicle *v = const_cast<Vehicle*>(GRV(object));
    00475
    00476   if (v == NULL) {
    00477     /* Vehicle does not exist, so we're in a purchase list */
    00478     switch (variable) {
    00479       case 0x43: return _current_company | (LiveryHelper(object->u.vehicle.self_type, NULL) << 24); // Owner information
    00480       case 0x46: return 0;               // Motion counter
    00481       case 0x47: { // Vehicle cargo info
    00482         const Engine *e = GetEngine(object->u.vehicle.self_type);
    00483         CargoID cargo_type = e->GetDefaultCargoType();
    00484         if (cargo_type != CT_INVALID) {
    00485           const CargoSpec *cs = GetCargo(cargo_type);
    00486           return (cs->classes << 16) | (cs->weight << 8) | GetEngineGRF(e->index)->cargo_map[cargo_type];
    00487         } else {
    00488           return 0x000000FF;
    00489         }
    00490       }
    00491       case 0x48: return GetEngine(object->u.vehicle.self_type)->flags; // Vehicle Type Info
    00492       case 0x49: return _cur_year; // 'Long' format build year
    00493       case 0xC4: return Clamp(_cur_year, ORIGINAL_BASE_YEAR, ORIGINAL_MAX_YEAR) - ORIGINAL_BASE_YEAR; // Build year
    00494       case 0xDA: return INVALID_VEHICLE; // Next vehicle
    00495       case 0xF2: return 0; // Cargo subtype
    00496     }
    00497
    00498     *available = false;
    00499     return UINT_MAX;
    00500   }
    00501
    00502   /* Calculated vehicle parameters */
    00503   switch (variable) {
    00504     case 0x25: // Get engine GRF ID
    00505       return GetEngineGRFID(v->engine_type);
    00506
    00507     case 0x40: // Get length of consist
    00508       if (!HasBit(v->cache_valid, 0)) {
    00509         v->cached_var40 = PositionHelper(v, false);
    00510         SetBit(v->cache_valid, 0);
    00511       }
    00512       return v->cached_var40;
    00513
    00514     case 0x41: // Get length of same consecutive wagons
    00515       if (!HasBit(v->cache_valid, 1)) {
    00516         v->cached_var41 = PositionHelper(v, true);
    00517         SetBit(v->cache_valid, 1);
    00518       }
    00519       return v->cached_var41;
    00520
    00521     case 0x42: // Consist cargo information
    00522       if (!HasBit(v->cache_valid, 2)) {
    00523         const Vehicle *u;
    00524         byte cargo_classes = 0;
    00525         CargoID common_cargo_best = CT_INVALID;
    00526         uint8 common_cargos[NUM_CARGO];
    00527         uint8 common_subtype_best = 0xFF; // Return 0xFF if nothing is carried
    00528         uint8 common_subtypes[256];
    00529         byte user_def_data = 0;
    00530         CargoID common_cargo_type = CT_PASSENGERS;
    00531         uint8 common_subtype = 0;
    00532
    00533         /* Reset our arrays */
    00534         memset(common_cargos, 0, sizeof(common_cargos));
    00535         memset(common_subtypes, 0, sizeof(common_subtypes));
    00536
    00537         for (u = v; u != NULL; u = u->Next()) {
    00538           if (v->type == VEH_TRAIN) user_def_data |= u->u.rail.user_def_data;
    00539
    00540           /* Skip empty engines */
    00541           if (u->cargo_cap == 0) continue;
    00542
    00543           cargo_classes |= GetCargo(u->cargo_type)->classes;
    00544           common_cargos[u->cargo_type]++;
    00545         }
    00546
    00547         /* Pick the most common cargo type */
    00548         for (CargoID cargo = 0; cargo < NUM_CARGO; cargo++) {
    00549           if (common_cargos[cargo] > common_cargo_best) {
    00550             common_cargo_best = common_cargos[cargo];
    00551             common_cargo_type = cargo;
    00552           }
    00553         }
    00554
    00555         /* Count subcargo types of common_cargo_type */
    00556         for (u = v; u != NULL; u = u->Next()) {
    00557           /* Skip empty engines and engines not carrying common_cargo_type */
    00558           if (u->cargo_cap == 0 || u->cargo_type != common_cargo_type) continue;
    00559
    00560           common_subtypes[u->cargo_subtype]++;
    00561         }
    00562
    00563         /* Pick the most common subcargo type*/
    00564         for (uint i = 0; i < lengthof(common_subtypes); i++) {
    00565           if (common_subtypes[i] > common_subtype_best) {
    00566             common_subtype_best = common_subtypes[i];
    00567             common_subtype = i;
    00568           }
    00569         }
    00570
    00571         uint8 common_bitnum = (common_cargo_type == CT_INVALID ? 0xFF : GetCargo(common_cargo_type)->bitnum);
    00572         v->cached_var42 = cargo_classes | (common_bitnum << 8) | (common_subtype << 16) | (user_def_data << 24);
    00573         SetBit(v->cache_valid, 2);
    00574       }
    00575       return v->cached_var42;
    00576
    00577     case 0x43: // Company information
    00578       if (!HasBit(v->cache_valid, 3)) {
    00579         v->cached_var43 = v->owner | (GetCompany(v->owner)->is_ai ? 0x10000 : 0) | (LiveryHelper(v->engine_type, v) << 24);
    00580         SetBit(v->cache_valid, 3);
    00581       }
    00582       return v->cached_var43;
    00583
    00584     case 0x44: // Aircraft information
    00585       if (v->type != VEH_AIRCRAFT) return UINT_MAX;
    00586
    00587       {
    00588         const Vehicle *w = v->Next();
    00589         uint16 altitude = v->z_pos - w->z_pos; // Aircraft height - shadow height
    00590         byte airporttype = ATP_TTDP_LARGE;
    00591
    00592         const Station *st = GetTargetAirportIfValid(v);
    00593
    00594         if (st != NULL) {
    00595           switch (st->airport_type) {
    00596             /* Note, Helidepot and Helistation are treated as small airports
    00597              * as they are at ground level. */
    00598             case AT_HELIDEPOT:
    00599             case AT_HELISTATION:
    00600             case AT_COMMUTER:
    00601             case AT_SMALL:         airporttype = ATP_TTDP_SMALL; break;
    00602             case AT_METROPOLITAN:
    00603             case AT_INTERNATIONAL:
    00604             case AT_INTERCON:
    00605             case AT_LARGE:         airporttype = ATP_TTDP_LARGE; break;
    00606             case AT_HELIPORT:      airporttype = ATP_TTDP_HELIPORT; break;
    00607             case AT_OILRIG:        airporttype = ATP_TTDP_OILRIG; break;
    00608             default:               airporttype = ATP_TTDP_LARGE; break;
    00609           }
    00610         }
    00611
    00612         return (altitude << 8) | airporttype;
    00613       }
    00614
    00615     case 0x45: { // Curvature info
    00616       /* Format: xxxTxBxF
    00617        * F - previous wagon to current wagon, 0 if vehicle is first
    00618        * B - current wagon to next wagon, 0 if wagon is last
    00619        * T - previous wagon to next wagon, 0 in an S-bend
    00620        */
    00621       if (v->type != VEH_TRAIN && v->type != VEH_ROAD) return 0;
    00622
    00623       const Vehicle *u_p = v->Previous();
    00624       const Vehicle *u_n = v->Next();
    00625       DirDiff f = (u_p == NULL) ?  DIRDIFF_SAME : DirDifference(u_p->direction, v->direction);
    00626       DirDiff b = (u_n == NULL) ?  DIRDIFF_SAME : DirDifference(v->direction, u_n->direction);
    00627       DirDiff t = ChangeDirDiff(f, b);
    00628
    00629       return ((t > DIRDIFF_REVERSE ? t | 8 : t) << 16) |
    00630              ((b > DIRDIFF_REVERSE ? b | 8 : b) <<  8) |
    00631              ( f > DIRDIFF_REVERSE ? f | 8 : f);
    00632     }
    00633
    00634     case 0x46: // Motion counter
    00635       return v->motion_counter;
    00636
    00637     case 0x47: { // Vehicle cargo info
    00638       /* Format: ccccwwtt
    00639        * tt - the cargo type transported by the vehicle,
    00640        *     translated if a translation table has been installed.
    00641        * ww - cargo unit weight in 1/16 tons, same as cargo prop. 0F.
    00642        * cccc - the cargo class value of the cargo transported by the vehicle.
    00643        */
    00644       const CargoSpec *cs = GetCargo(v->cargo_type);
    00645
    00646       return (cs->classes << 16) | (cs->weight << 8) | GetEngineGRF(v->engine_type)->cargo_map[v->cargo_type];
    00647     }
    00648
    00649     case 0x48: return GetEngine(v->engine_type)->flags; // Vehicle Type Info
    00650     case 0x49: return v->build_year;
    00651
    00652     /* Variables which use the parameter */
    00653     case 0x60: // Count consist's engine ID occurance
    00654       //EngineID engine = GetNewEngineID(GetEngineGRF(v->engine_type), v->type, parameter);
    00655       if (v->type != VEH_TRAIN) return GetEngine(v->engine_type)->internal_id == parameter;
    00656
    00657       {
    00658         uint count = 0;
    00659         for (; v != NULL; v = v->Next()) {
    00660           if (GetEngine(v->engine_type)->internal_id == parameter) count++;
    00661         }
    00662         return count;
    00663       }
    00664
    00665     case 0xFE:
    00666     case 0xFF: {
    00667       uint16 modflags = 0;
    00668
    00669       if (v->type == VEH_TRAIN) {
    00670         const Vehicle *u = IsTrainWagon(v) && HasBit(v->vehicle_flags, VRF_POWEREDWAGON) ? v->First() : v;
    00671         RailType railtype = GetRailType(v->tile);
    00672         bool powered = IsTrainEngine(v) || (IsTrainWagon(v) && HasBit(v->vehicle_flags, VRF_POWEREDWAGON));
    00673         bool has_power = powered && HasPowerOnRail(u->u.rail.railtype, railtype);
    00674         bool is_electric = powered && u->u.rail.railtype == RAILTYPE_ELECTRIC;
    00675
    00676         if (has_power) SetBit(modflags, 5);
    00677         if (is_electric && !has_power) SetBit(modflags, 6);
    00678         if (HasBit(v->u.rail.flags, VRF_TOGGLE_REVERSE)) SetBit(modflags, 8);
    00679       }
    00680       if (HasBit(v->vehicle_flags, VF_BUILT_AS_PROTOTYPE)) SetBit(modflags, 10);
    00681
    00682       return variable == 0xFE ? modflags : GB(modflags, 8, 8);
    00683     }
    00684   }
    00685
    00686   /* General vehicle properties */
    00687   switch (variable - 0x80) {
    00688     case 0x00: return v->type;
    00689     case 0x01: return MapOldSubType(v);
    00690     case 0x04: return v->index;
    00691     case 0x05: return GB(v->index, 8, 8);
    00692     case 0x0A: return v->current_order.Pack();
    00693     case 0x0B: return GB(v->current_order.Pack(), 8, 8);
    00694     case 0x0C: return v->GetNumOrders();
    00695     case 0x0D: return v->cur_order_index;
    00696     case 0x10: return v->load_unload_time_rem;
    00697     case 0x11: return GB(v->load_unload_time_rem, 8, 8);
    00698     case 0x12: return max(v->date_of_last_service - DAYS_TILL_ORIGINAL_BASE_YEAR, 0);
    00699     case 0x13: return GB(max(v->date_of_last_service - DAYS_TILL_ORIGINAL_BASE_YEAR, 0), 8, 8);
    00700     case 0x14: return v->service_interval;
    00701     case 0x15: return GB(v->service_interval, 8, 8);
    00702     case 0x16: return v->last_station_visited;
    00703     case 0x17: return v->tick_counter;
    00704     case 0x18: return v->max_speed;
    00705     case 0x19: return GB(v->max_speed, 8, 8);
    00706     case 0x1A: return v->x_pos;
    00707     case 0x1B: return GB(v->x_pos, 8, 8);
    00708     case 0x1C: return v->y_pos;
    00709     case 0x1D: return GB(v->y_pos, 8, 8);
    00710     case 0x1E: return v->z_pos;
    00711     case 0x1F: return object->info_view ? DIR_W : v->direction;
    00712     case 0x28: return v->cur_image;
    00713     case 0x29: return GB(v->cur_image, 8, 8);
    00714     case 0x32: return v->vehstatus;
    00715     case 0x33: return 0; // non-existent high byte of vehstatus
    00716     case 0x34: return v->cur_speed;
    00717     case 0x35: return GB(v->cur_speed, 8, 8);
    00718     case 0x36: return v->subspeed;
    00719     case 0x37: return v->acceleration;
    00720     case 0x39: return v->cargo_type;
    00721     case 0x3A: return v->cargo_cap;
    00722     case 0x3B: return GB(v->cargo_cap, 8, 8);
    00723     case 0x3C: return v->cargo.Count();
    00724     case 0x3D: return GB(v->cargo.Count(), 8, 8);
    00725     case 0x3E: return v->cargo.Source();
    00726     case 0x3F: return v->cargo.DaysInTransit();
    00727     case 0x40: return v->age;
    00728     case 0x41: return GB(v->age, 8, 8);
    00729     case 0x42: return v->max_age;
    00730     case 0x43: return GB(v->max_age, 8, 8);
    00731     case 0x44: return Clamp(v->build_year, ORIGINAL_BASE_YEAR, ORIGINAL_MAX_YEAR) - ORIGINAL_BASE_YEAR;
    00732     case 0x45: return v->unitnumber;
    00733     case 0x46: return GetEngine(v->engine_type)->internal_id;
    00734     case 0x47: return GB(GetEngine(v->engine_type)->internal_id, 8, 8);
    00735     case 0x48:
    00736       if (v->type != VEH_TRAIN || v->spritenum != 0xFD) return v->spritenum;
    00737       return HasBit(v->u.rail.flags, VRF_REVERSE_DIRECTION) ? 0xFE : 0xFD;
    00738
    00739     case 0x49: return v->day_counter;
    00740     case 0x4A: return v->breakdowns_since_last_service;
    00741     case 0x4B: return v->breakdown_ctr;
    00742     case 0x4C: return v->breakdown_delay;
    00743     case 0x4D: return v->breakdown_chance;
    00744     case 0x4E: return v->reliability;
    00745     case 0x4F: return GB(v->reliability, 8, 8);
    00746     case 0x50: return v->reliability_spd_dec;
    00747     case 0x51: return GB(v->reliability_spd_dec, 8, 8);
    00748     case 0x52: return ClampToI32(v->GetDisplayProfitThisYear());
    00749     case 0x53: return GB(ClampToI32(v->GetDisplayProfitThisYear()),  8, 24);
    00750     case 0x54: return GB(ClampToI32(v->GetDisplayProfitThisYear()), 16, 16);
    00751     case 0x55: return GB(ClampToI32(v->GetDisplayProfitThisYear()), 24,  8);
    00752     case 0x56: return ClampToI32(v->GetDisplayProfitLastYear());
    00753     case 0x57: return GB(ClampToI32(v->GetDisplayProfitLastYear()),  8, 24);
    00754     case 0x58: return GB(ClampToI32(v->GetDisplayProfitLastYear()), 16, 16);
    00755     case 0x59: return GB(ClampToI32(v->GetDisplayProfitLastYear()), 24,  8);
    00756     case 0x5A: return v->Next() == NULL ? INVALID_VEHICLE : v->Next()->index;
    00757     case 0x5C: return ClampToI32(v->value);
    00758     case 0x5D: return GB(ClampToI32(v->value),  8, 24);
    00759     case 0x5E: return GB(ClampToI32(v->value), 16, 16);
    00760     case 0x5F: return GB(ClampToI32(v->value), 24,  8);
    00761     case 0x72: return v->cargo_subtype;
    00762     case 0x7A: return v->random_bits;
    00763     case 0x7B: return v->waiting_triggers;
    00764   }
    00765
    00766   /* Vehicle specific properties */
    00767   switch (v->type) {
    00768     case VEH_TRAIN:
    00769       switch (variable - 0x80) {
    00770         case 0x62: return v->u.rail.track;
    00771         case 0x66: return v->u.rail.railtype;
    00772         case 0x73: return v->u.rail.cached_veh_length;
    00773         case 0x74: return v->u.rail.cached_power;
    00774         case 0x75: return GB(v->u.rail.cached_power,  8, 24);
    00775         case 0x76: return GB(v->u.rail.cached_power, 16, 16);
    00776         case 0x77: return GB(v->u.rail.cached_power, 24,  8);
    00777         case 0x7C: return v->First()->index;
    00778         case 0x7D: return GB(v->First()->index, 8, 8);
    00779         case 0x7F: return 0; // Used for vehicle reversing hack in TTDP
    00780       }
    00781       break;
    00782
    00783     case VEH_ROAD:
    00784       switch (variable - 0x80) {
    00785         case 0x62: return v->u.road.state;
    00786         case 0x64: return v->u.road.blocked_ctr;
    00787         case 0x65: return GB(v->u.road.blocked_ctr, 8, 8);
    00788         case 0x66: return v->u.road.overtaking;
    00789         case 0x67: return v->u.road.overtaking_ctr;
    00790         case 0x68: return v->u.road.crashed_ctr;
    00791         case 0x69: return GB(v->u.road.crashed_ctr, 8, 8);
    00792       }
    00793       break;
    00794
    00795     case VEH_AIRCRAFT:
    00796       switch (variable - 0x80) {
    00797         case 0x62: return MapAircraftMovementState(v);  // Current movement state
    00798         case 0x63: return v->u.air.targetairport;       // Airport to which the action refers
    00799         case 0x66: return MapAircraftMovementAction(v); // Current movement action
    00800       }
    00801       break;
    00802
    00803     default: break;
    00804   }
    00805
    00806   DEBUG(grf, 1, "Unhandled vehicle property 0x%X, type 0x%X", variable, v->type);
    00807
    00808   *available = false;
    00809   return UINT_MAX;
    00810 }
    00811
    00812
    00813 static const SpriteGroup *VehicleResolveReal(const ResolverObject *object, const SpriteGroup *group)
    00814 {
    00815   const Vehicle *v = object->u.vehicle.self;
    00816
    00817   if (v == NULL) {
    00818     if (group->g.real.num_loading > 0) return group->g.real.loading[0];
    00819     if (group->g.real.num_loaded  > 0) return group->g.real.loaded[0];
    00820     return NULL;
    00821   }
    00822
    00823   bool in_motion = !v->First()->current_order.IsType(OT_LOADING);
    00824
    00825   uint totalsets = in_motion ? group->g.real.num_loaded : group->g.real.num_loading;
    00826
    00827   uint set = (v->cargo.Count() * totalsets) / max((uint16)1, v->cargo_cap);
    00828   set = min(set, totalsets - 1);
    00829
    00830   return in_motion ? group->g.real.loaded[set] : group->g.real.loading[set];
    00831 }
    00832
    00833
    00834 static inline void NewVehicleResolver(ResolverObject *res, EngineID engine_type, const Vehicle *v)
    00835 {
    00836   res->GetRandomBits = &VehicleGetRandomBits;
    00837   res->GetTriggers   = &VehicleGetTriggers;
    00838   res->SetTriggers   = &VehicleSetTriggers;
    00839   res->GetVariable   = &VehicleGetVariable;
    00840   res->ResolveReal   = &VehicleResolveReal;
    00841
    00842   res->u.vehicle.self   = v;
    00843   res->u.vehicle.parent = (v != NULL) ? v->First() : v;
    00844
    00845   res->u.vehicle.self_type = engine_type;
    00846
    00847   res->info_view = false;
    00848
    00849   res->callback        = CBID_NO_CALLBACK;
    00850   res->callback_param1 = 0;
    00851   res->callback_param2 = 0;
    00852   res->last_value      = 0;
    00853   res->trigger         = 0;
    00854   res->reseed          = 0;
    00855   res->count           = 0;
    00856
    00857   const Engine *e = GetEngine(engine_type);
    00858   res->grffile         = (e != NULL ? e->grffile : NULL);
    00859 }
    00860
    00861
    00870 static const SpriteGroup *GetVehicleSpriteGroup(EngineID engine, const Vehicle *v, bool use_cache = true)
    00871 {
    00872   const SpriteGroup *group;
    00873   CargoID cargo;
    00874
    00875   if (v == NULL) {
    00876     cargo = CT_PURCHASE;
    00877   } else {
    00878     cargo = v->cargo_type;
    00879
    00880     if (v->type == VEH_TRAIN) {
    00881       /* We always use cached value, except for callbacks because the override spriteset
    00882        * to use may be different than the one cached. It happens for callback 0x15 (refit engine),
    00883        * as v->cargo_type is temporary changed to the new type */
    00884       group = use_cache ? v->u.rail.cached_override : GetWagonOverrideSpriteSet(v->engine_type, v->cargo_type, v->u.rail.first_engine);
    00885       if (group != NULL) return group;
    00886     } else if (v->type == VEH_ROAD) {
    00887       group = GetWagonOverrideSpriteSet(v->engine_type, v->cargo_type, v->u.road.first_engine);
    00888       if (group != NULL) return group;
    00889     }
    00890   }
    00891
    00892   const Engine *e = GetEngine(engine);
    00893
    00894   assert(cargo < lengthof(e->group));
    00895   group = e->group[cargo];
    00896   if (group != NULL) return group;
    00897
    00898   /* Fall back to the default set if the selected cargo type is not defined */
    00899   return e->group[CT_DEFAULT];
    00900 }
    00901
    00902
    00903 SpriteID GetCustomEngineSprite(EngineID engine, const Vehicle *v, Direction direction)
    00904 {
    00905   const SpriteGroup *group;
    00906   ResolverObject object;
    00907
    00908   NewVehicleResolver(&object, engine, v);
    00909
    00910   group = Resolve(GetVehicleSpriteGroup(engine, v), &object);
    00911   if (group == NULL || group->type != SGT_RESULT || group->g.result.num_sprites == 0) return 0;
    00912
    00913   return group->g.result.sprite + (direction % group->g.result.num_sprites);
    00914 }
    00915
    00916
    00917 SpriteID GetRotorOverrideSprite(EngineID engine, const Vehicle *v, bool info_view)
    00918 {
    00919   const Engine *e = GetEngine(engine);
    00920
    00921   /* Only valid for helicopters */
    00922   assert(e->type == VEH_AIRCRAFT);
    00923   assert(!(e->u.air.subtype & AIR_CTOL));
    00924
    00925   ResolverObject object;
    00926
    00927   NewVehicleResolver(&object, engine, v);
    00928
    00929   object.info_view = info_view;
    00930
    00931   const SpriteGroup *group = GetWagonOverrideSpriteSet(engine, CT_DEFAULT, engine);
    00932   group = Resolve(group, &object);
    00933
    00934   if (group == NULL || group->type != SGT_RESULT || group->g.result.num_sprites == 0) return 0;
    00935
    00936   if (v == NULL) return group->g.result.sprite;
    00937
    00938   return group->g.result.sprite + (info_view ? 0 : (v->Next()->Next()->u.air.state % group->g.result.num_sprites));
    00939 }
    00940
    00941
    00947 bool UsesWagonOverride(const Vehicle *v)
    00948 {
    00949   assert(v->type == VEH_TRAIN);
    00950   return v->u.rail.cached_override != NULL;
    00951 }
    00952
    00962 uint16 GetVehicleCallback(CallbackID callback, uint32 param1, uint32 param2, EngineID engine, const Vehicle *v)
    00963 {
    00964   const SpriteGroup *group;
    00965   ResolverObject object;
    00966
    00967   NewVehicleResolver(&object, engine, v);
    00968
    00969   object.callback        = callback;
    00970   object.callback_param1 = param1;
    00971   object.callback_param2 = param2;
    00972
    00973   group = Resolve(GetVehicleSpriteGroup(engine, v, false), &object);
    00974   if (group == NULL || group->type != SGT_CALLBACK) return CALLBACK_FAILED;
    00975
    00976   return group->g.callback.result;
    00977 }
    00978
    00989 uint16 GetVehicleCallbackParent(CallbackID callback, uint32 param1, uint32 param2, EngineID engine, const Vehicle *v, const Vehicle *parent)
    00990 {
    00991   const SpriteGroup *group;
    00992   ResolverObject object;
    00993
    00994   NewVehicleResolver(&object, engine, v);
    00995
    00996   object.callback        = callback;
    00997   object.callback_param1 = param1;
    00998   object.callback_param2 = param2;
    00999
    01000   object.u.vehicle.parent = parent;
    01001
    01002   group = Resolve(GetVehicleSpriteGroup(engine, v, false), &object);
    01003   if (group == NULL || group->type != SGT_CALLBACK) return CALLBACK_FAILED;
    01004
    01005   return group->g.callback.result;
    01006 }
    01007
    01008
    01009 /* Callback 36 handlers */
    01010 uint GetVehicleProperty(const Vehicle *v, uint8 property, uint orig_value)
    01011 {
    01012   uint16 callback = GetVehicleCallback(CBID_VEHICLE_MODIFY_PROPERTY, property, 0, v->engine_type, v);
    01013   if (callback != CALLBACK_FAILED) return callback;
    01014
    01015   return orig_value;
    01016 }
    01017
    01018
    01019 uint GetEngineProperty(EngineID engine, uint8 property, uint orig_value)
    01020 {
    01021   uint16 callback = GetVehicleCallback(CBID_VEHICLE_MODIFY_PROPERTY, property, 0, engine, NULL);
    01022   if (callback != CALLBACK_FAILED) return callback;
    01023
    01024   return orig_value;
    01025 }
    01026
    01027
    01028 static void DoTriggerVehicle(Vehicle *v, VehicleTrigger trigger, byte base_random_bits, bool first)
    01029 {
    01030   const SpriteGroup *group;
    01031   ResolverObject object;
    01032   byte new_random_bits;
    01033
    01034   /* We can't trigger a non-existent vehicle... */
    01035   assert(v != NULL);
    01036
    01037   NewVehicleResolver(&object, v->engine_type, v);
    01038   object.callback = CBID_RANDOM_TRIGGER;
    01039   object.trigger = trigger;
    01040
    01041   group = Resolve(GetVehicleSpriteGroup(v->engine_type, v), &object);
    01042   if (group == NULL) return;
    01043
    01044   new_random_bits = Random();
    01045   v->random_bits &= ~object.reseed;
    01046   v->random_bits |= (first ? new_random_bits : base_random_bits) & object.reseed;
    01047
    01048   switch (trigger) {
    01049     case VEHICLE_TRIGGER_NEW_CARGO:
    01050       /* All vehicles in chain get ANY_NEW_CARGO trigger now.
    01051        * So we call it for the first one and they will recurse.
    01052        * Indexing part of vehicle random bits needs to be
    01053        * same for all triggered vehicles in the chain (to get
    01054        * all the random-cargo wagons carry the same cargo,
    01055        * i.e.), so we give them all the NEW_CARGO triggered
    01056        * vehicle's portion of random bits. */
    01057       assert(first);
    01058       DoTriggerVehicle(v->First(), VEHICLE_TRIGGER_ANY_NEW_CARGO, new_random_bits, false);
    01059       break;
    01060
    01061     case VEHICLE_TRIGGER_DEPOT:
    01062       /* We now trigger the next vehicle in chain recursively.
    01063        * The random bits portions may be different for each
    01064        * vehicle in chain. */
    01065       if (v->Next() != NULL) DoTriggerVehicle(v->Next(), trigger, 0, true);
    01066       break;
    01067
    01068     case VEHICLE_TRIGGER_EMPTY:
    01069       /* We now trigger the next vehicle in chain
    01070        * recursively.  The random bits portions must be same
    01071        * for each vehicle in chain, so we give them all
    01072        * first chained vehicle's portion of random bits. */
    01073       if (v->Next() != NULL) DoTriggerVehicle(v->Next(), trigger, first ? new_random_bits : base_random_bits, false);
    01074       break;
    01075
    01076     case VEHICLE_TRIGGER_ANY_NEW_CARGO:
    01077       /* Now pass the trigger recursively to the next vehicle
    01078        * in chain. */
    01079       assert(!first);
    01080       if (v->Next() != NULL) DoTriggerVehicle(v->Next(), VEHICLE_TRIGGER_ANY_NEW_CARGO, base_random_bits, false);
    01081       break;
    01082
    01083     case VEHICLE_TRIGGER_CALLBACK_32:
    01084       /* Do not do any recursion */
    01085       break;
    01086   }
    01087 }
    01088
    01089 void TriggerVehicle(Vehicle *v, VehicleTrigger trigger)
    01090 {
    01091   if (trigger == VEHICLE_TRIGGER_DEPOT) {
    01092     /* store that the vehicle entered a depot this tick */
    01093     VehicleEnteredDepotThisTick(v);
    01094   }
    01095
    01096   DoTriggerVehicle(v, trigger, 0, true);
    01097 }
    01098
    01099 /* Functions for changing the order of vehicle purchase lists
    01100  * This is currently only implemented for rail vehicles. */
    01101
    01108 uint ListPositionOfEngine(EngineID engine)
    01109 {
    01110   const Engine *e = GetEngine(engine);
    01111   if (e->grffile == NULL) return e->list_position;
    01112
    01113   /* Crude sorting to group by GRF ID */
    01114   return (e->grffile->grfid * 256) + e->list_position;
    01115 }
    01116
    01117 struct ListOrderChange {
    01118   EngineID engine;
    01119   EngineID target;
    01120 };
    01121
    01122 static SmallVector<ListOrderChange, 16> _list_order_changes;
    01123
    01124 void AlterVehicleListOrder(EngineID engine, EngineID target)
    01125 {
    01126   /* Add the list order change to a queue */
    01127   ListOrderChange *loc = _list_order_changes.Append();
    01128   loc->engine = engine;
    01129   loc->target = target;
    01130 }
    01131
    01132 void CommitVehicleListOrderChanges()
    01133 {
    01134   /* List position to Engine map */
    01135   typedef SmallMap<uint16, Engine *, 16> ListPositionMap;
    01136   ListPositionMap lptr_map;
    01137
    01138   const ListOrderChange *end = _list_order_changes.End();
    01139   for (const ListOrderChange *it = _list_order_changes.Begin(); it != end; ++it) {
    01140     EngineID engine = it->engine;
    01141     EngineID target = it->target;
    01142
    01143     if (engine == target) continue;
    01144
    01145     Engine *source_e = GetEngine(engine);
    01146     Engine *target_e = NULL;
    01147
    01148     /* Populate map with current list positions */
    01149     Engine *e;
    01150     FOR_ALL_ENGINES_OF_TYPE(e, source_e->type) {
    01151       if (!_settings_game.vehicle.dynamic_engines || e->grffile == source_e->grffile) {
    01152         if (e->internal_id == target) target_e = e;
    01153         lptr_map[e->list_position] = e;
    01154       }
    01155     }
    01156
    01157     /* std::map sorted by default, SmallMap does not */
    01158     lptr_map.SortByKey();
    01159
    01160     /* Get the target position, if it exists */
    01161     if (target_e != NULL) {
    01162       uint16 target_position = target_e->list_position;
    01163
    01164       bool moving = false;
    01165       const ListPositionMap::Pair *end = lptr_map.End();
    01166       for (ListPositionMap::Pair *it = lptr_map.Begin(); it != end; ++it) {
    01167         if (it->first == target_position) moving = true;
    01168         if (moving) it->second->list_position++;
    01169       }
    01170
    01171       source_e->list_position = target_position;
    01172     }
    01173
    01174     lptr_map.Clear();
    01175   }
    01176
    01177   /* Clear out the queue */
    01178   _list_order_changes.Reset();
    01179 }