# newgrf_engine.cpp

Go to the documentation of this file.

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