# newgrf_engine.cpp

Go to the documentation of this file.

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