# newgrf_engine.cpp

Go to the documentation of this file.

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