# newgrf_engine.cpp

Go to the documentation of this file.

    00001 /* $Id: newgrf_engine.cpp 18935 2010-01-28 18:19:34Z 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       const Vehicle *v = NULL;
    00387       switch (GB(object->count, 6, 2)) {
    00388         default: NOT_REACHED();
    00389         case 0x00: // count back (away from the engine), starting at this vehicle
    00390         case 0x01: // count forward (toward the engine), starting at this vehicle
    00391           v = object->u.vehicle.self;
    00392           break;
    00393         case 0x02: // count back, starting at the engine
    00394           v = object->u.vehicle.parent;
    00395           break;
    00396         case 0x03: { // count back, starting at the first vehicle in this chain of vehicles with the same ID, as for vehicle variable 41
    00397           const Vehicle *self = object->u.vehicle.self;
    00398           for (const Vehicle *u = self->First(); u != self; u = u->Next()) {
    00399             if (u->engine_type != self->engine_type) {
    00400               v = NULL;
    00401             } else {
    00402               if (v == NULL) v = u;
    00403             }
    00404           }
    00405           if (v == NULL) v = self;
    00406         } break;
    00407       }
    00408       uint32 count = GB(object->count, 0, 4);
    00409       if (count == 0) count = GetRegister(0x100);
    00410       while (v != NULL && count-- != 0) v = (GB(object->count, 6, 2) == 0x01) ? v->Previous() : v->Next();
    00411       return v;
    00412     }
    00413   }
    00414 }
    00415
    00416
    00417 static uint32 VehicleGetRandomBits(const ResolverObject *object)
    00418 {
    00419   return GRV(object) == NULL ? 0 : GRV(object)->random_bits;
    00420 }
    00421
    00422
    00423 static uint32 VehicleGetTriggers(const ResolverObject *object)
    00424 {
    00425   return GRV(object) == NULL ? 0 : GRV(object)->waiting_triggers;
    00426 }
    00427
    00428
    00429 static void VehicleSetTriggers(const ResolverObject *object, int triggers)
    00430 {
    00431   /* Evil cast to get around const-ness. This used to be achieved by an
    00432    * innocent looking function pointer cast... Currently I cannot see a
    00433    * way of avoiding this without removing consts deep within gui code.
    00434    */
    00435   Vehicle *v = const_cast<Vehicle *>(GRV(object));
    00436
    00437   /* This function must only be called when processing triggers -- any
    00438    * other time is an error. */
    00439   assert(object->trigger != 0);
    00440
    00441   if (v != NULL) v->waiting_triggers = triggers;
    00442 }
    00443
    00444
    00445 static uint8 LiveryHelper(EngineID engine, const Vehicle *v)
    00446 {
    00447   const Livery *l;
    00448
    00449   if (v == NULL) {
    00450     if (!Company::IsValidID(_current_company)) return 0;
    00451     l = GetEngineLivery(engine, _current_company, INVALID_ENGINE, NULL);
    00452   } else if (v->type == VEH_TRAIN) {
    00453     l = GetEngineLivery(v->engine_type, v->owner, Train::From(v)->tcache.first_engine, v);
    00454   } else if (v->type == VEH_ROAD) {
    00455     l = GetEngineLivery(v->engine_type, v->owner, RoadVehicle::From(v)->rcache.first_engine, v);
    00456   } else {
    00457     l = GetEngineLivery(v->engine_type, v->owner, INVALID_ENGINE, v);
    00458   }
    00459
    00460   return l->colour1 + l->colour2 * 16;
    00461 }
    00462
    00470 static uint32 PositionHelper(const Vehicle *v, bool consecutive)
    00471 {
    00472   const Vehicle *u;
    00473   byte chain_before = 0;
    00474   byte chain_after  = 0;
    00475
    00476   for (u = v->First(); u != v; u = u->Next()) {
    00477     chain_before++;
    00478     if (consecutive && u->engine_type != v->engine_type) chain_before = 0;
    00479   }
    00480
    00481   while (u->Next() != NULL && (!consecutive || u->Next()->engine_type == v->engine_type)) {
    00482     chain_after++;
    00483     u = u->Next();
    00484   }
    00485
    00486   return chain_before | chain_after << 8 | (chain_before + chain_after + consecutive) << 16;
    00487 }
    00488
    00489 static uint32 VehicleGetVariable(const ResolverObject *object, byte variable, byte parameter, bool *available)
    00490 {
    00491   Vehicle *v = const_cast<Vehicle*>(GRV(object));
    00492
    00493   if (v == NULL) {
    00494     /* Vehicle does not exist, so we're in a purchase list */
    00495     switch (variable) {
    00496       case 0x43: return _current_company | (LiveryHelper(object->u.vehicle.self_type, NULL) << 24); // Owner information
    00497       case 0x46: return 0;               // Motion counter
    00498       case 0x47: { // Vehicle cargo info
    00499         const Engine *e = Engine::Get(object->u.vehicle.self_type);
    00500         CargoID cargo_type = e->GetDefaultCargoType();
    00501         if (cargo_type != CT_INVALID) {
    00502           const CargoSpec *cs = CargoSpec::Get(cargo_type);
    00503           return (cs->classes << 16) | (cs->weight << 8) | GetEngineGRF(e->index)->cargo_map[cargo_type];
    00504         } else {
    00505           return 0x000000FF;
    00506         }
    00507       }
    00508       case 0x48: return Engine::Get(object->u.vehicle.self_type)->flags; // Vehicle Type Info
    00509       case 0x49: return _cur_year; // 'Long' format build year
    00510       case 0xC4: return Clamp(_cur_year, ORIGINAL_BASE_YEAR, ORIGINAL_MAX_YEAR) - ORIGINAL_BASE_YEAR; // Build year
    00511       case 0xDA: return INVALID_VEHICLE; // Next vehicle
    00512       case 0xF2: return 0; // Cargo subtype
    00513     }
    00514
    00515     *available = false;
    00516     return UINT_MAX;
    00517   }
    00518
    00519   /* Calculated vehicle parameters */
    00520   switch (variable) {
    00521     case 0x25: // Get engine GRF ID
    00522       return GetEngineGRFID(v->engine_type);
    00523
    00524     case 0x40: // Get length of consist
    00525       if (!HasBit(v->vcache.cache_valid, 0)) {
    00526         v->vcache.cached_var40 = PositionHelper(v, false);
    00527         SetBit(v->vcache.cache_valid, 0);
    00528       }
    00529       return v->vcache.cached_var40;
    00530
    00531     case 0x41: // Get length of same consecutive wagons
    00532       if (!HasBit(v->vcache.cache_valid, 1)) {
    00533         v->vcache.cached_var41 = PositionHelper(v, true);
    00534         SetBit(v->vcache.cache_valid, 1);
    00535       }
    00536       return v->vcache.cached_var41;
    00537
    00538     case 0x42: // Consist cargo information
    00539       if (!HasBit(v->vcache.cache_valid, 2)) {
    00540         const Vehicle *u;
    00541         byte cargo_classes = 0;
    00542         uint8 common_cargos[NUM_CARGO];
    00543         uint8 common_subtypes[256];
    00544         byte user_def_data = 0;
    00545         CargoID common_cargo_type = CT_INVALID;
    00546         uint8 common_subtype = 0xFF; // Return 0xFF if nothing is carried
    00547
    00548         /* Reset our arrays */
    00549         memset(common_cargos, 0, sizeof(common_cargos));
    00550         memset(common_subtypes, 0, sizeof(common_subtypes));
    00551
    00552         for (u = v; u != NULL; u = u->Next()) {
    00553           if (v->type == VEH_TRAIN) user_def_data |= Train::From(u)->tcache.user_def_data;
    00554
    00555           /* Skip empty engines */
    00556           if (u->cargo_cap == 0) continue;
    00557
    00558           cargo_classes |= CargoSpec::Get(u->cargo_type)->classes;
    00559           common_cargos[u->cargo_type]++;
    00560         }
    00561
    00562         /* Pick the most common cargo type */
    00563         uint common_cargo_best_amount = 0;
    00564         for (CargoID cargo = 0; cargo < NUM_CARGO; cargo++) {
    00565           if (common_cargos[cargo] > common_cargo_best_amount) {
    00566             common_cargo_best_amount = common_cargos[cargo];
    00567             common_cargo_type = cargo;
    00568           }
    00569         }
    00570
    00571         /* Count subcargo types of common_cargo_type */
    00572         for (u = v; u != NULL; u = u->Next()) {
    00573           /* Skip empty engines and engines not carrying common_cargo_type */
    00574           if (u->cargo_cap == 0 || u->cargo_type != common_cargo_type) continue;
    00575
    00576           common_subtypes[u->cargo_subtype]++;
    00577         }
    00578
    00579         /* Pick the most common subcargo type*/
    00580         uint common_subtype_best_amount = 0;
    00581         for (uint i = 0; i < lengthof(common_subtypes); i++) {
    00582           if (common_subtypes[i] > common_subtype_best_amount) {
    00583             common_subtype_best_amount = common_subtypes[i];
    00584             common_subtype = i;
    00585           }
    00586         }
    00587
    00588         uint8 common_bitnum = (common_cargo_type == CT_INVALID ? 0xFF : CargoSpec::Get(common_cargo_type)->bitnum);
    00589         v->vcache.cached_var42 = cargo_classes | (common_bitnum << 8) | (common_subtype << 16) | (user_def_data << 24);
    00590         SetBit(v->vcache.cache_valid, 2);
    00591       }
    00592       return v->vcache.cached_var42;
    00593
    00594     case 0x43: // Company information
    00595       if (!HasBit(v->vcache.cache_valid, 3)) {
    00596         v->vcache.cached_var43 = v->owner | (Company::IsHumanID(v->owner) ? 0 : 0x10000) | (LiveryHelper(v->engine_type, v) << 24);
    00597         SetBit(v->vcache.cache_valid, 3);
    00598       }
    00599       return v->vcache.cached_var43;
    00600
    00601     case 0x44: // Aircraft information
    00602       if (v->type != VEH_AIRCRAFT) return UINT_MAX;
    00603
    00604       {
    00605         const Vehicle *w = v->Next();
    00606         uint16 altitude = v->z_pos - w->z_pos; // Aircraft height - shadow height
    00607         byte airporttype = ATP_TTDP_LARGE;
    00608
    00609         const Station *st = GetTargetAirportIfValid(Aircraft::From(v));
    00610
    00611         if (st != NULL) {
    00612           switch (st->airport_type) {
    00613             /* Note, Helidepot and Helistation are treated as small airports
    00614              * as they are at ground level. */
    00615             case AT_HELIDEPOT:
    00616             case AT_HELISTATION:
    00617             case AT_COMMUTER:
    00618             case AT_SMALL:         airporttype = ATP_TTDP_SMALL; break;
    00619             case AT_METROPOLITAN:
    00620             case AT_INTERNATIONAL:
    00621             case AT_INTERCON:
    00622             case AT_LARGE:         airporttype = ATP_TTDP_LARGE; break;
    00623             case AT_HELIPORT:      airporttype = ATP_TTDP_HELIPORT; break;
    00624             case AT_OILRIG:        airporttype = ATP_TTDP_OILRIG; break;
    00625             default:               airporttype = ATP_TTDP_LARGE; break;
    00626           }
    00627         }
    00628
    00629         return (altitude << 8) | airporttype;
    00630       }
    00631
    00632     case 0x45: { // Curvature info
    00633       /* Format: xxxTxBxF
    00634        * F - previous wagon to current wagon, 0 if vehicle is first
    00635        * B - current wagon to next wagon, 0 if wagon is last
    00636        * T - previous wagon to next wagon, 0 in an S-bend
    00637        */
    00638       if (v->type != VEH_TRAIN && v->type != VEH_ROAD) return 0;
    00639
    00640       const Vehicle *u_p = v->Previous();
    00641       const Vehicle *u_n = v->Next();
    00642       DirDiff f = (u_p == NULL) ?  DIRDIFF_SAME : DirDifference(u_p->direction, v->direction);
    00643       DirDiff b = (u_n == NULL) ?  DIRDIFF_SAME : DirDifference(v->direction, u_n->direction);
    00644       DirDiff t = ChangeDirDiff(f, b);
    00645
    00646       return ((t > DIRDIFF_REVERSE ? t | 8 : t) << 16) |
    00647              ((b > DIRDIFF_REVERSE ? b | 8 : b) <<  8) |
    00648              ( f > DIRDIFF_REVERSE ? f | 8 : f);
    00649     }
    00650
    00651     case 0x46: // Motion counter
    00652       return v->motion_counter;
    00653
    00654     case 0x47: { // Vehicle cargo info
    00655       /* Format: ccccwwtt
    00656        * tt - the cargo type transported by the vehicle,
    00657        *     translated if a translation table has been installed.
    00658        * ww - cargo unit weight in 1/16 tons, same as cargo prop. 0F.
    00659        * cccc - the cargo class value of the cargo transported by the vehicle.
    00660        */
    00661       const CargoSpec *cs = CargoSpec::Get(v->cargo_type);
    00662
    00663       return (cs->classes << 16) | (cs->weight << 8) | GetEngineGRF(v->engine_type)->cargo_map[v->cargo_type];
    00664     }
    00665
    00666     case 0x48: return Engine::Get(v->engine_type)->flags; // Vehicle Type Info
    00667     case 0x49: return v->build_year;
    00668
    00669     /* Variables which use the parameter */
    00670     case 0x60: // Count consist's engine ID occurance
    00671       //EngineID engine = GetNewEngineID(GetEngineGRF(v->engine_type), v->type, parameter);
    00672       if (v->type != VEH_TRAIN) return Engine::Get(v->engine_type)->internal_id == parameter;
    00673
    00674       {
    00675         uint count = 0;
    00676         for (; v != NULL; v = v->Next()) {
    00677           if (Engine::Get(v->engine_type)->internal_id == parameter) count++;
    00678         }
    00679         return count;
    00680       }
    00681
    00682     case 0xFE:
    00683     case 0xFF: {
    00684       uint16 modflags = 0;
    00685
    00686       if (v->type == VEH_TRAIN) {
    00687         const Train *t = Train::From(v);
    00688         const Train *u = t->IsWagon() && HasBit(t->vehicle_flags, VRF_POWEREDWAGON) ? t->First() : t;
    00689         RailType railtype = GetRailType(v->tile);
    00690         bool powered = t->IsEngine() || (t->IsWagon() && HasBit(t->vehicle_flags, VRF_POWEREDWAGON));
    00691         bool has_power = powered && HasPowerOnRail(u->railtype, railtype);
    00692         bool is_electric = powered && u->railtype == RAILTYPE_ELECTRIC;
    00693
    00694         if (has_power) SetBit(modflags, 5);
    00695         if (is_electric && !has_power) SetBit(modflags, 6);
    00696         if (HasBit(t->flags, VRF_TOGGLE_REVERSE)) SetBit(modflags, 8);
    00697       }
    00698       if (HasBit(v->vehicle_flags, VF_BUILT_AS_PROTOTYPE)) SetBit(modflags, 10);
    00699
    00700       return variable == 0xFE ? modflags : GB(modflags, 8, 8);
    00701     }
    00702   }
    00703
    00704   /* General vehicle properties */
    00705   switch (variable - 0x80) {
    00706     case 0x00: return v->type + 0x10;
    00707     case 0x01: return MapOldSubType(v);
    00708     case 0x04: return v->index;
    00709     case 0x05: return GB(v->index, 8, 8);
    00710     case 0x0A: return v->current_order.MapOldOrder();
    00711     case 0x0B: return v->current_order.GetDestination();
    00712     case 0x0C: return v->GetNumOrders();
    00713     case 0x0D: return v->cur_order_index;
    00714     case 0x10:
    00715     case 0x11: {
    00716       uint ticks;
    00717       if (v->current_order.IsType(OT_LOADING)) {
    00718         ticks = v->load_unload_ticks;
    00719       } else {
    00720         switch (v->type) {
    00721           case VEH_TRAIN:    ticks = Train::From(v)->wait_counter; break;
    00722           case VEH_AIRCRAFT: ticks = Aircraft::From(v)->turn_counter; break;
    00723           default:           ticks = 0; break;
    00724         }
    00725       }
    00726       return (variable - 0x80) == 0x10 ? ticks : GB(ticks, 8, 8);
    00727     }
    00728     case 0x12: return max(v->date_of_last_service - DAYS_TILL_ORIGINAL_BASE_YEAR, 0);
    00729     case 0x13: return GB(max(v->date_of_last_service - DAYS_TILL_ORIGINAL_BASE_YEAR, 0), 8, 8);
    00730     case 0x14: return v->service_interval;
    00731     case 0x15: return GB(v->service_interval, 8, 8);
    00732     case 0x16: return v->last_station_visited;
    00733     case 0x17: return v->tick_counter;
    00734     case 0x18: return v->max_speed;
    00735     case 0x19: return GB(v->max_speed, 8, 8);
    00736     case 0x1A: return v->x_pos;
    00737     case 0x1B: return GB(v->x_pos, 8, 8);
    00738     case 0x1C: return v->y_pos;
    00739     case 0x1D: return GB(v->y_pos, 8, 8);
    00740     case 0x1E: return v->z_pos;
    00741     case 0x1F: return object->u.vehicle.info_view ? DIR_W : v->direction;
    00742     case 0x28: return v->cur_image;
    00743     case 0x29: return GB(v->cur_image, 8, 8);
    00744     case 0x32: return v->vehstatus;
    00745     case 0x33: return 0; // non-existent high byte of vehstatus
    00746     case 0x34: return v->cur_speed;
    00747     case 0x35: return GB(v->cur_speed, 8, 8);
    00748     case 0x36: return v->subspeed;
    00749     case 0x37: return v->acceleration;
    00750     case 0x39: return v->cargo_type;
    00751     case 0x3A: return v->cargo_cap;
    00752     case 0x3B: return GB(v->cargo_cap, 8, 8);
    00753     case 0x3C: return v->cargo.Count();
    00754     case 0x3D: return GB(v->cargo.Count(), 8, 8);
    00755     case 0x3E: return v->cargo.Source();
    00756     case 0x3F: return v->cargo.DaysInTransit();
    00757     case 0x40: return v->age;
    00758     case 0x41: return GB(v->age, 8, 8);
    00759     case 0x42: return v->max_age;
    00760     case 0x43: return GB(v->max_age, 8, 8);
    00761     case 0x44: return Clamp(v->build_year, ORIGINAL_BASE_YEAR, ORIGINAL_MAX_YEAR) - ORIGINAL_BASE_YEAR;
    00762     case 0x45: return v->unitnumber;
    00763     case 0x46: return Engine::Get(v->engine_type)->internal_id;
    00764     case 0x47: return GB(Engine::Get(v->engine_type)->internal_id, 8, 8);
    00765     case 0x48:
    00766       if (v->type != VEH_TRAIN || v->spritenum != 0xFD) return v->spritenum;
    00767       return HasBit(Train::From(v)->flags, VRF_REVERSE_DIRECTION) ? 0xFE : 0xFD;
    00768
    00769     case 0x49: return v->day_counter;
    00770     case 0x4A: return v->breakdowns_since_last_service;
    00771     case 0x4B: return v->breakdown_ctr;
    00772     case 0x4C: return v->breakdown_delay;
    00773     case 0x4D: return v->breakdown_chance;
    00774     case 0x4E: return v->reliability;
    00775     case 0x4F: return GB(v->reliability, 8, 8);
    00776     case 0x50: return v->reliability_spd_dec;
    00777     case 0x51: return GB(v->reliability_spd_dec, 8, 8);
    00778     case 0x52: return ClampToI32(v->GetDisplayProfitThisYear());
    00779     case 0x53: return GB(ClampToI32(v->GetDisplayProfitThisYear()),  8, 24);
    00780     case 0x54: return GB(ClampToI32(v->GetDisplayProfitThisYear()), 16, 16);
    00781     case 0x55: return GB(ClampToI32(v->GetDisplayProfitThisYear()), 24,  8);
    00782     case 0x56: return ClampToI32(v->GetDisplayProfitLastYear());
    00783     case 0x57: return GB(ClampToI32(v->GetDisplayProfitLastYear()),  8, 24);
    00784     case 0x58: return GB(ClampToI32(v->GetDisplayProfitLastYear()), 16, 16);
    00785     case 0x59: return GB(ClampToI32(v->GetDisplayProfitLastYear()), 24,  8);
    00786     case 0x5A: return v->Next() == NULL ? INVALID_VEHICLE : v->Next()->index;
    00787     case 0x5C: return ClampToI32(v->value);
    00788     case 0x5D: return GB(ClampToI32(v->value),  8, 24);
    00789     case 0x5E: return GB(ClampToI32(v->value), 16, 16);
    00790     case 0x5F: return GB(ClampToI32(v->value), 24,  8);
    00791     case 0x72: return v->cargo_subtype;
    00792     case 0x7A: return v->random_bits;
    00793     case 0x7B: return v->waiting_triggers;
    00794   }
    00795
    00796   /* Vehicle specific properties */
    00797   switch (v->type) {
    00798     case VEH_TRAIN: {
    00799       Train *t = Train::From(v);
    00800       switch (variable - 0x80) {
    00801         case 0x62: return t->track;
    00802         case 0x66: return t->railtype;
    00803         case 0x73: return t->tcache.cached_veh_length;
    00804         case 0x74: return t->tcache.cached_power;
    00805         case 0x75: return GB(t->tcache.cached_power,  8, 24);
    00806         case 0x76: return GB(t->tcache.cached_power, 16, 16);
    00807         case 0x77: return GB(t->tcache.cached_power, 24,  8);
    00808         case 0x7C: return t->First()->index;
    00809         case 0x7D: return GB(t->First()->index, 8, 8);
    00810         case 0x7F: return 0; // Used for vehicle reversing hack in TTDP
    00811       }
    00812     } break;
    00813
    00814     case VEH_ROAD: {
    00815       RoadVehicle *rv = RoadVehicle::From(v);
    00816       switch (variable - 0x80) {
    00817         case 0x62: return rv->state;
    00818         case 0x64: return rv->blocked_ctr;
    00819         case 0x65: return GB(rv->blocked_ctr, 8, 8);
    00820         case 0x66: return rv->overtaking;
    00821         case 0x67: return rv->overtaking_ctr;
    00822         case 0x68: return rv->crashed_ctr;
    00823         case 0x69: return GB(rv->crashed_ctr, 8, 8);
    00824       }
    00825     } break;
    00826
    00827     case VEH_AIRCRAFT: {
    00828       Aircraft *a = Aircraft::From(v);
    00829       switch (variable - 0x80) {
    00830         case 0x62: return MapAircraftMovementState(a);  // Current movement state
    00831         case 0x63: return a->targetairport;             // Airport to which the action refers
    00832         case 0x66: return MapAircraftMovementAction(a); // Current movement action
    00833       }
    00834     } break;
    00835
    00836     default: break;
    00837   }
    00838
    00839   DEBUG(grf, 1, "Unhandled vehicle property 0x%X, type 0x%X", variable, (uint)v->type);
    00840
    00841   *available = false;
    00842   return UINT_MAX;
    00843 }
    00844
    00845
    00846 static const SpriteGroup *VehicleResolveReal(const ResolverObject *object, const RealSpriteGroup *group)
    00847 {
    00848   const Vehicle *v = object->u.vehicle.self;
    00849
    00850   if (v == NULL) {
    00851     if (group->num_loading > 0) return group->loading[0];
    00852     if (group->num_loaded  > 0) return group->loaded[0];
    00853     return NULL;
    00854   }
    00855
    00856   bool in_motion = !v->First()->current_order.IsType(OT_LOADING);
    00857
    00858   uint totalsets = in_motion ? group->num_loaded : group->num_loading;
    00859
    00860   uint set = (v->cargo.Count() * totalsets) / max((uint16)1, v->cargo_cap);
    00861   set = min(set, totalsets - 1);
    00862
    00863   return in_motion ? group->loaded[set] : group->loading[set];
    00864 }
    00865
    00866
    00867 static inline void NewVehicleResolver(ResolverObject *res, EngineID engine_type, const Vehicle *v)
    00868 {
    00869   res->GetRandomBits = &VehicleGetRandomBits;
    00870   res->GetTriggers   = &VehicleGetTriggers;
    00871   res->SetTriggers   = &VehicleSetTriggers;
    00872   res->GetVariable   = &VehicleGetVariable;
    00873   res->ResolveReal   = &VehicleResolveReal;
    00874
    00875   res->u.vehicle.self   = v;
    00876   res->u.vehicle.parent = (v != NULL) ? v->First() : v;
    00877
    00878   res->u.vehicle.self_type = engine_type;
    00879   res->u.vehicle.info_view = false;
    00880
    00881   res->callback        = CBID_NO_CALLBACK;
    00882   res->callback_param1 = 0;
    00883   res->callback_param2 = 0;
    00884   res->last_value      = 0;
    00885   res->trigger         = 0;
    00886   res->reseed          = 0;
    00887   res->count           = 0;
    00888
    00889   const Engine *e = Engine::Get(engine_type);
    00890   res->grffile         = (e != NULL ? e->grffile : NULL);
    00891 }
    00892
    00893
    00902 static const SpriteGroup *GetVehicleSpriteGroup(EngineID engine, const Vehicle *v, bool use_cache = true)
    00903 {
    00904   const SpriteGroup *group;
    00905   CargoID cargo;
    00906
    00907   if (v == NULL) {
    00908     cargo = CT_PURCHASE;
    00909   } else {
    00910     cargo = v->cargo_type;
    00911
    00912     if (v->type == VEH_TRAIN) {
    00913       /* We always use cached value, except for callbacks because the override spriteset
    00914        * to use may be different than the one cached. It happens for callback 0x15 (refit engine),
    00915        * as v->cargo_type is temporary changed to the new type */
    00916       group = use_cache ? Train::From(v)->tcache.cached_override : GetWagonOverrideSpriteSet(v->engine_type, v->cargo_type, Train::From(v)->tcache.first_engine);
    00917       if (group != NULL) return group;
    00918     } else if (v->type == VEH_ROAD) {
    00919       group = GetWagonOverrideSpriteSet(v->engine_type, v->cargo_type, RoadVehicle::From(v)->rcache.first_engine);
    00920       if (group != NULL) return group;
    00921     }
    00922   }
    00923
    00924   const Engine *e = Engine::Get(engine);
    00925
    00926   assert(cargo < lengthof(e->group));
    00927   group = e->group[cargo];
    00928   if (group != NULL) return group;
    00929
    00930   /* Fall back to the default set if the selected cargo type is not defined */
    00931   return e->group[CT_DEFAULT];
    00932 }
    00933
    00934
    00935 SpriteID GetCustomEngineSprite(EngineID engine, const Vehicle *v, Direction direction)
    00936 {
    00937   const SpriteGroup *group;
    00938   ResolverObject object;
    00939
    00940   NewVehicleResolver(&object, engine, v);
    00941
    00942   group = SpriteGroup::Resolve(GetVehicleSpriteGroup(engine, v), &object);
    00943   if (group == NULL || group->GetNumResults() == 0) return 0;
    00944
    00945   return group->GetResult() + (direction % group->GetNumResults());
    00946 }
    00947
    00948
    00949 SpriteID GetRotorOverrideSprite(EngineID engine, const Aircraft *v, bool info_view)
    00950 {
    00951   const Engine *e = Engine::Get(engine);
    00952
    00953   /* Only valid for helicopters */
    00954   assert(e->type == VEH_AIRCRAFT);
    00955   assert(!(e->u.air.subtype & AIR_CTOL));
    00956
    00957   ResolverObject object;
    00958
    00959   NewVehicleResolver(&object, engine, v);
    00960
    00961   object.u.vehicle.info_view = info_view;
    00962
    00963   const SpriteGroup *group = GetWagonOverrideSpriteSet(engine, CT_DEFAULT, engine);
    00964   group = SpriteGroup::Resolve(group, &object);
    00965
    00966   if (group == NULL || group->GetNumResults() == 0) return 0;
    00967
    00968   if (v == NULL) return group->GetResult();
    00969
    00970   return group->GetResult() + (info_view ? 0 : (v->Next()->Next()->state % group->GetNumResults()));
    00971 }
    00972
    00973
    00979 bool UsesWagonOverride(const Vehicle *v)
    00980 {
    00981   assert(v->type == VEH_TRAIN);
    00982   return Train::From(v)->tcache.cached_override != NULL;
    00983 }
    00984
    00994 uint16 GetVehicleCallback(CallbackID callback, uint32 param1, uint32 param2, EngineID engine, const Vehicle *v)
    00995 {
    00996   const SpriteGroup *group;
    00997   ResolverObject object;
    00998
    00999   NewVehicleResolver(&object, engine, v);
    01000
    01001   object.callback        = callback;
    01002   object.callback_param1 = param1;
    01003   object.callback_param2 = param2;
    01004
    01005   group = SpriteGroup::Resolve(GetVehicleSpriteGroup(engine, v, false), &object);
    01006   if (group == NULL) return CALLBACK_FAILED;
    01007
    01008   return group->GetCallbackResult();
    01009 }
    01010
    01021 uint16 GetVehicleCallbackParent(CallbackID callback, uint32 param1, uint32 param2, EngineID engine, const Vehicle *v, const Vehicle *parent)
    01022 {
    01023   const SpriteGroup *group;
    01024   ResolverObject object;
    01025
    01026   NewVehicleResolver(&object, engine, v);
    01027
    01028   object.callback        = callback;
    01029   object.callback_param1 = param1;
    01030   object.callback_param2 = param2;
    01031
    01032   object.u.vehicle.parent = parent;
    01033
    01034   group = SpriteGroup::Resolve(GetVehicleSpriteGroup(engine, v, false), &object);
    01035   if (group == NULL) return CALLBACK_FAILED;
    01036
    01037   return group->GetCallbackResult();
    01038 }
    01039
    01040
    01041 /* Callback 36 handlers */
    01042 uint GetVehicleProperty(const Vehicle *v, PropertyID property, uint orig_value)
    01043 {
    01044   uint16 callback = GetVehicleCallback(CBID_VEHICLE_MODIFY_PROPERTY, property, 0, v->engine_type, v);
    01045   if (callback != CALLBACK_FAILED) return callback;
    01046
    01047   return orig_value;
    01048 }
    01049
    01050
    01051 uint GetEngineProperty(EngineID engine, PropertyID property, uint orig_value)
    01052 {
    01053   uint16 callback = GetVehicleCallback(CBID_VEHICLE_MODIFY_PROPERTY, property, 0, engine, NULL);
    01054   if (callback != CALLBACK_FAILED) return callback;
    01055
    01056   return orig_value;
    01057 }
    01058
    01059
    01060 static void DoTriggerVehicle(Vehicle *v, VehicleTrigger trigger, byte base_random_bits, bool first)
    01061 {
    01062   const SpriteGroup *group;
    01063   ResolverObject object;
    01064   byte new_random_bits;
    01065
    01066   /* We can't trigger a non-existent vehicle... */
    01067   assert(v != NULL);
    01068
    01069   NewVehicleResolver(&object, v->engine_type, v);
    01070   object.callback = CBID_RANDOM_TRIGGER;
    01071   object.trigger = trigger;
    01072
    01073   group = SpriteGroup::Resolve(GetVehicleSpriteGroup(v->engine_type, v), &object);
    01074   if (group == NULL) return;
    01075
    01076   new_random_bits = Random();
    01077   v->random_bits &= ~object.reseed;
    01078   v->random_bits |= (first ? new_random_bits : base_random_bits) & object.reseed;
    01079
    01080   switch (trigger) {
    01081     case VEHICLE_TRIGGER_NEW_CARGO:
    01082       /* All vehicles in chain get ANY_NEW_CARGO trigger now.
    01083        * So we call it for the first one and they will recurse.
    01084        * Indexing part of vehicle random bits needs to be
    01085        * same for all triggered vehicles in the chain (to get
    01086        * all the random-cargo wagons carry the same cargo,
    01087        * i.e.), so we give them all the NEW_CARGO triggered
    01088        * vehicle's portion of random bits. */
    01089       assert(first);
    01090       DoTriggerVehicle(v->First(), VEHICLE_TRIGGER_ANY_NEW_CARGO, new_random_bits, false);
    01091       break;
    01092
    01093     case VEHICLE_TRIGGER_DEPOT:
    01094       /* We now trigger the next vehicle in chain recursively.
    01095        * The random bits portions may be different for each
    01096        * vehicle in chain. */
    01097       if (v->Next() != NULL) DoTriggerVehicle(v->Next(), trigger, 0, true);
    01098       break;
    01099
    01100     case VEHICLE_TRIGGER_EMPTY:
    01101       /* We now trigger the next vehicle in chain
    01102        * recursively.  The random bits portions must be same
    01103        * for each vehicle in chain, so we give them all
    01104        * first chained vehicle's portion of random bits. */
    01105       if (v->Next() != NULL) DoTriggerVehicle(v->Next(), trigger, first ? new_random_bits : base_random_bits, false);
    01106       break;
    01107
    01108     case VEHICLE_TRIGGER_ANY_NEW_CARGO:
    01109       /* Now pass the trigger recursively to the next vehicle
    01110        * in chain. */
    01111       assert(!first);
    01112       if (v->Next() != NULL) DoTriggerVehicle(v->Next(), VEHICLE_TRIGGER_ANY_NEW_CARGO, base_random_bits, false);
    01113       break;
    01114
    01115     case VEHICLE_TRIGGER_CALLBACK_32:
    01116       /* Do not do any recursion */
    01117       break;
    01118   }
    01119 }
    01120
    01121 void TriggerVehicle(Vehicle *v, VehicleTrigger trigger)
    01122 {
    01123   if (trigger == VEHICLE_TRIGGER_DEPOT) {
    01124     /* store that the vehicle entered a depot this tick */
    01125     VehicleEnteredDepotThisTick(v);
    01126   }
    01127
    01128   v->InvalidateNewGRFCacheOfChain();
    01129   DoTriggerVehicle(v, trigger, 0, true);
    01130   v->InvalidateNewGRFCacheOfChain();
    01131 }
    01132
    01133 /* Functions for changing the order of vehicle purchase lists
    01134  * This is currently only implemented for rail vehicles. */
    01135
    01142 uint ListPositionOfEngine(EngineID engine)
    01143 {
    01144   const Engine *e = Engine::Get(engine);
    01145   if (e->grffile == NULL) return e->list_position;
    01146
    01147   /* Crude sorting to group by GRF ID */
    01148   return (e->grffile->grfid * 256) + e->list_position;
    01149 }
    01150
    01151 struct ListOrderChange {
    01152   EngineID engine;
    01153   EngineID target;
    01154 };
    01155
    01156 static SmallVector<ListOrderChange, 16> _list_order_changes;
    01157
    01158 void AlterVehicleListOrder(EngineID engine, EngineID target)
    01159 {
    01160   /* Add the list order change to a queue */
    01161   ListOrderChange *loc = _list_order_changes.Append();
    01162   loc->engine = engine;
    01163   loc->target = target;
    01164 }
    01165
    01166 void CommitVehicleListOrderChanges()
    01167 {
    01168   /* List position to Engine map */
    01169   typedef SmallMap<uint16, Engine *, 16> ListPositionMap;
    01170   ListPositionMap lptr_map;
    01171
    01172   const ListOrderChange *end = _list_order_changes.End();
    01173   for (const ListOrderChange *it = _list_order_changes.Begin(); it != end; ++it) {
    01174     EngineID engine = it->engine;
    01175     EngineID target = it->target;
    01176
    01177     if (engine == target) continue;
    01178
    01179     Engine *source_e = Engine::Get(engine);
    01180     Engine *target_e = NULL;
    01181
    01182     /* Populate map with current list positions */
    01183     Engine *e;
    01184     FOR_ALL_ENGINES_OF_TYPE(e, source_e->type) {
    01185       if (!_settings_game.vehicle.dynamic_engines || e->grffile == source_e->grffile) {
    01186         if (e->internal_id == target) target_e = e;
    01187         lptr_map[e->list_position] = e;
    01188       }
    01189     }
    01190
    01191     /* std::map sorted by default, SmallMap does not */
    01192     lptr_map.SortByKey();
    01193
    01194     /* Get the target position, if it exists */
    01195     if (target_e != NULL) {
    01196       uint16 target_position = target_e->list_position;
    01197
    01198       bool moving = false;
    01199       const ListPositionMap::Pair *end = lptr_map.End();
    01200       for (ListPositionMap::Pair *it = lptr_map.Begin(); it != end; ++it) {
    01201         if (it->first == target_position) moving = true;
    01202         if (moving) it->second->list_position++;
    01203       }
    01204
    01205       source_e->list_position = target_position;
    01206     }
    01207
    01208     lptr_map.Clear();
    01209   }
    01210
    01211   /* Clear out the queue */
    01212   _list_order_changes.Reset();
    01213 }