# newgrf_engine.cpp

Go to the documentation of this file.

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