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_cargo.h"
00018 #include "newgrf_spritegroup.h"
00019 #include "date_func.h"
00020 #include "vehicle_func.h"
00021 #include "core/random_func.hpp"
00022 #include "aircraft.h"
00023 #include "station_base.h"
00024 #include "company_base.h"
00025 #include "newgrf_railtype.h"
00026 #include "ship.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 cargoes.
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 
00114 static int MapOldSubType(const Vehicle *v)
00115 {
00116   switch (v->type) {
00117     case VEH_TRAIN:
00118       if (Train::From(v)->IsEngine()) return 0;
00119       if (Train::From(v)->IsFreeWagon()) return 4;
00120       return 2;
00121     case VEH_ROAD:
00122     case VEH_SHIP:     return 0;
00123     case VEH_AIRCRAFT:
00124     case VEH_DISASTER: return v->subtype;
00125     case VEH_EFFECT:   return v->subtype << 1;
00126     default: NOT_REACHED();
00127   }
00128 }
00129 
00130 
00131 /* TTDP style aircraft movement states for GRF Action 2 Var 0xE2 */
00132 enum TTDPAircraftMovementStates {
00133   AMS_TTDP_HANGAR,
00134   AMS_TTDP_TO_HANGAR,
00135   AMS_TTDP_TO_PAD1,
00136   AMS_TTDP_TO_PAD2,
00137   AMS_TTDP_TO_PAD3,
00138   AMS_TTDP_TO_ENTRY_2_AND_3,
00139   AMS_TTDP_TO_ENTRY_2_AND_3_AND_H,
00140   AMS_TTDP_TO_JUNCTION,
00141   AMS_TTDP_LEAVE_RUNWAY,
00142   AMS_TTDP_TO_INWAY,
00143   AMS_TTDP_TO_RUNWAY,
00144   AMS_TTDP_TO_OUTWAY,
00145   AMS_TTDP_WAITING,
00146   AMS_TTDP_TAKEOFF,
00147   AMS_TTDP_TO_TAKEOFF,
00148   AMS_TTDP_CLIMBING,
00149   AMS_TTDP_FLIGHT_APPROACH,
00150   AMS_TTDP_UNUSED_0x11,
00151   AMS_TTDP_FLIGHT_TO_TOWER,
00152   AMS_TTDP_UNUSED_0x13,
00153   AMS_TTDP_FLIGHT_FINAL,
00154   AMS_TTDP_FLIGHT_DESCENT,
00155   AMS_TTDP_BRAKING,
00156   AMS_TTDP_HELI_TAKEOFF_AIRPORT,
00157   AMS_TTDP_HELI_TO_TAKEOFF_AIRPORT,
00158   AMS_TTDP_HELI_LAND_AIRPORT,
00159   AMS_TTDP_HELI_TAKEOFF_HELIPORT,
00160   AMS_TTDP_HELI_TO_TAKEOFF_HELIPORT,
00161   AMS_TTDP_HELI_LAND_HELIPORT,
00162 };
00163 
00164 
00169 static byte MapAircraftMovementState(const Aircraft *v)
00170 {
00171   const Station *st = GetTargetAirportIfValid(v);
00172   if (st == NULL) return AMS_TTDP_FLIGHT_TO_TOWER;
00173 
00174   const AirportFTAClass *afc = st->airport.GetFTA();
00175   uint16 amdflag = afc->MovingData(v->pos)->flag;
00176 
00177   switch (v->state) {
00178     case HANGAR:
00179       /* The international airport is a special case as helicopters can land in
00180        * front of the hanger. Helicopters also change their air.state to
00181        * AMED_HELI_LOWER some time before actually descending. */
00182 
00183       /* This condition only occurs for helicopters, during descent,
00184        * to a landing by the hanger of an international airport. */
00185       if (amdflag & AMED_HELI_LOWER) return AMS_TTDP_HELI_LAND_AIRPORT;
00186 
00187       /* This condition only occurs for helicopters, before starting descent,
00188        * to a landing by the hanger of an international airport. */
00189       if (amdflag & AMED_SLOWTURN) return AMS_TTDP_FLIGHT_TO_TOWER;
00190 
00191       /* The final two conditions apply to helicopters or aircraft.
00192        * Has reached hanger? */
00193       if (amdflag & AMED_EXACTPOS) return AMS_TTDP_HANGAR;
00194 
00195       /* Still moving towards hanger. */
00196       return AMS_TTDP_TO_HANGAR;
00197 
00198     case TERM1:
00199       if (amdflag & AMED_EXACTPOS) return AMS_TTDP_TO_PAD1;
00200       return AMS_TTDP_TO_JUNCTION;
00201 
00202     case TERM2:
00203       if (amdflag & AMED_EXACTPOS) return AMS_TTDP_TO_PAD2;
00204       return AMS_TTDP_TO_ENTRY_2_AND_3_AND_H;
00205 
00206     case TERM3:
00207     case TERM4:
00208     case TERM5:
00209     case TERM6:
00210     case TERM7:
00211     case TERM8:
00212       /* TTDPatch only has 3 terminals, so treat these states the same */
00213       if (amdflag & AMED_EXACTPOS) return AMS_TTDP_TO_PAD3;
00214       return AMS_TTDP_TO_ENTRY_2_AND_3_AND_H;
00215 
00216     case HELIPAD1:
00217     case HELIPAD2:
00218     case HELIPAD3:
00219       /* Will only occur for helicopters.*/
00220       if (amdflag & AMED_HELI_LOWER) return AMS_TTDP_HELI_LAND_AIRPORT; // Descending.
00221       if (amdflag & AMED_SLOWTURN)   return AMS_TTDP_FLIGHT_TO_TOWER;   // Still hasn't started descent.
00222       return AMS_TTDP_TO_JUNCTION; // On the ground.
00223 
00224     case TAKEOFF: // Moving to takeoff position.
00225       return AMS_TTDP_TO_OUTWAY;
00226 
00227     case STARTTAKEOFF: // Accelerating down runway.
00228       return AMS_TTDP_TAKEOFF;
00229 
00230     case ENDTAKEOFF: // Ascent
00231       return AMS_TTDP_CLIMBING;
00232 
00233     case HELITAKEOFF: // Helicopter is moving to take off position.
00234       if (afc->delta_z == 0) {
00235         return amdflag & AMED_HELI_RAISE ?
00236           AMS_TTDP_HELI_TAKEOFF_AIRPORT : AMS_TTDP_TO_JUNCTION;
00237       } else {
00238         return AMS_TTDP_HELI_TAKEOFF_HELIPORT;
00239       }
00240 
00241     case FLYING:
00242       return amdflag & AMED_HOLD ? AMS_TTDP_FLIGHT_APPROACH : AMS_TTDP_FLIGHT_TO_TOWER;
00243 
00244     case LANDING: // Descent
00245       return AMS_TTDP_FLIGHT_DESCENT;
00246 
00247     case ENDLANDING: // On the runway braking
00248       if (amdflag & AMED_BRAKE) return AMS_TTDP_BRAKING;
00249       /* Landed - moving off runway */
00250       return AMS_TTDP_TO_INWAY;
00251 
00252     case HELILANDING:
00253     case HELIENDLANDING: // Helicoptor is decending.
00254       if (amdflag & AMED_HELI_LOWER) {
00255         return afc->delta_z == 0 ?
00256           AMS_TTDP_HELI_LAND_AIRPORT : AMS_TTDP_HELI_LAND_HELIPORT;
00257       } else {
00258         return AMS_TTDP_FLIGHT_TO_TOWER;
00259       }
00260 
00261     default:
00262       return AMS_TTDP_HANGAR;
00263   }
00264 }
00265 
00266 
00267 /* TTDP style aircraft movement action for GRF Action 2 Var 0xE6 */
00268 enum TTDPAircraftMovementActions {
00269   AMA_TTDP_IN_HANGAR,
00270   AMA_TTDP_ON_PAD1,
00271   AMA_TTDP_ON_PAD2,
00272   AMA_TTDP_ON_PAD3,
00273   AMA_TTDP_HANGAR_TO_PAD1,
00274   AMA_TTDP_HANGAR_TO_PAD2,
00275   AMA_TTDP_HANGAR_TO_PAD3,
00276   AMA_TTDP_LANDING_TO_PAD1,
00277   AMA_TTDP_LANDING_TO_PAD2,
00278   AMA_TTDP_LANDING_TO_PAD3,
00279   AMA_TTDP_PAD1_TO_HANGAR,
00280   AMA_TTDP_PAD2_TO_HANGAR,
00281   AMA_TTDP_PAD3_TO_HANGAR,
00282   AMA_TTDP_PAD1_TO_TAKEOFF,
00283   AMA_TTDP_PAD2_TO_TAKEOFF,
00284   AMA_TTDP_PAD3_TO_TAKEOFF,
00285   AMA_TTDP_HANGAR_TO_TAKOFF,
00286   AMA_TTDP_LANDING_TO_HANGAR,
00287   AMA_TTDP_IN_FLIGHT,
00288 };
00289 
00290 
00296 static byte MapAircraftMovementAction(const Aircraft *v)
00297 {
00298   switch (v->state) {
00299     case HANGAR:
00300       return (v->cur_speed > 0) ? AMA_TTDP_LANDING_TO_HANGAR : AMA_TTDP_IN_HANGAR;
00301 
00302     case TERM1:
00303     case HELIPAD1:
00304       return (v->current_order.IsType(OT_LOADING)) ? AMA_TTDP_ON_PAD1 : AMA_TTDP_LANDING_TO_PAD1;
00305 
00306     case TERM2:
00307     case HELIPAD2:
00308       return (v->current_order.IsType(OT_LOADING)) ? AMA_TTDP_ON_PAD2 : AMA_TTDP_LANDING_TO_PAD2;
00309 
00310     case TERM3:
00311     case TERM4:
00312     case TERM5:
00313     case TERM6:
00314     case TERM7:
00315     case TERM8:
00316     case HELIPAD3:
00317       return (v->current_order.IsType(OT_LOADING)) ? AMA_TTDP_ON_PAD3 : AMA_TTDP_LANDING_TO_PAD3;
00318 
00319     case TAKEOFF:      // Moving to takeoff position
00320     case STARTTAKEOFF: // Accelerating down runway
00321     case ENDTAKEOFF:   // Ascent
00322     case HELITAKEOFF:
00323       /* @todo Need to find which terminal (or hanger) we've come from. How? */
00324       return AMA_TTDP_PAD1_TO_TAKEOFF;
00325 
00326     case FLYING:
00327       return AMA_TTDP_IN_FLIGHT;
00328 
00329     case LANDING:    // Descent
00330     case ENDLANDING: // On the runway braking
00331     case HELILANDING:
00332     case HELIENDLANDING:
00333       /* @todo Need to check terminal we're landing to. Is it known yet? */
00334       return (v->current_order.IsType(OT_GOTO_DEPOT)) ?
00335         AMA_TTDP_LANDING_TO_HANGAR : AMA_TTDP_LANDING_TO_PAD1;
00336 
00337     default:
00338       return AMA_TTDP_IN_HANGAR;
00339   }
00340 }
00341 
00342 
00343 /* Vehicle Resolver Functions */
00344 static inline const Vehicle *GRV(const ResolverObject *object)
00345 {
00346   switch (object->scope) {
00347     default: NOT_REACHED();
00348     case VSG_SCOPE_SELF: return object->u.vehicle.self;
00349     case VSG_SCOPE_PARENT: return object->u.vehicle.parent;
00350     case VSG_SCOPE_RELATIVE: {
00351       if (object->u.vehicle.self == NULL) return NULL;
00352 
00353       int32 count = GB(object->count, 0, 4);
00354       if (count == 0) count = GetRegister(0x100);
00355 
00356       const Vehicle *v = NULL;
00357       switch (GB(object->count, 6, 2)) {
00358         default: NOT_REACHED();
00359         case 0x00: // count back (away from the engine), starting at this vehicle
00360           v = object->u.vehicle.self;
00361           break;
00362         case 0x01: // count forward (toward the engine), starting at this vehicle
00363           v = object->u.vehicle.self;
00364           count = -count;
00365           break;
00366         case 0x02: // count back, starting at the engine
00367           v = object->u.vehicle.parent;
00368           break;
00369         case 0x03: { // count back, starting at the first vehicle in this chain of vehicles with the same ID, as for vehicle variable 41
00370           const Vehicle *self = object->u.vehicle.self;
00371           for (const Vehicle *u = self->First(); u != self; u = u->Next()) {
00372             if (u->engine_type != self->engine_type) {
00373               v = NULL;
00374             } else {
00375               if (v == NULL) v = u;
00376             }
00377           }
00378           if (v == NULL) v = self;
00379           break;
00380         }
00381       }
00382       return v->Move(count);
00383     }
00384   }
00385 }
00386 
00387 
00388 static uint32 VehicleGetRandomBits(const ResolverObject *object)
00389 {
00390   return GRV(object) == NULL ? 0 : GRV(object)->random_bits;
00391 }
00392 
00393 
00394 static uint32 VehicleGetTriggers(const ResolverObject *object)
00395 {
00396   return GRV(object) == NULL ? 0 : GRV(object)->waiting_triggers;
00397 }
00398 
00399 
00400 static void VehicleSetTriggers(const ResolverObject *object, int triggers)
00401 {
00402   /* Evil cast to get around const-ness. This used to be achieved by an
00403    * innocent looking function pointer cast... Currently I cannot see a
00404    * way of avoiding this without removing consts deep within gui code.
00405    */
00406   Vehicle *v = const_cast<Vehicle *>(GRV(object));
00407 
00408   /* This function must only be called when processing triggers -- any
00409    * other time is an error. */
00410   assert(object->trigger != 0);
00411 
00412   if (v != NULL) v->waiting_triggers = triggers;
00413 }
00414 
00415 
00425 static const Livery *LiveryHelper(EngineID engine, const Vehicle *v)
00426 {
00427   const Livery *l;
00428 
00429   if (v == NULL) {
00430     if (!Company::IsValidID(_current_company)) return NULL;
00431     l = GetEngineLivery(engine, _current_company, INVALID_ENGINE, NULL, LIT_ALL);
00432   } else if (v->IsGroundVehicle()) {
00433     l = GetEngineLivery(v->engine_type, v->owner, v->GetGroundVehicleCache()->first_engine, v, LIT_ALL);
00434   } else {
00435     l = GetEngineLivery(v->engine_type, v->owner, INVALID_ENGINE, v, LIT_ALL);
00436   }
00437 
00438   return l;
00439 }
00440 
00448 static uint32 PositionHelper(const Vehicle *v, bool consecutive)
00449 {
00450   const Vehicle *u;
00451   byte chain_before = 0;
00452   byte chain_after  = 0;
00453 
00454   for (u = v->First(); u != v; u = u->Next()) {
00455     chain_before++;
00456     if (consecutive && u->engine_type != v->engine_type) chain_before = 0;
00457   }
00458 
00459   while (u->Next() != NULL && (!consecutive || u->Next()->engine_type == v->engine_type)) {
00460     chain_after++;
00461     u = u->Next();
00462   }
00463 
00464   return chain_before | chain_after << 8 | (chain_before + chain_after + consecutive) << 16;
00465 }
00466 
00467 static uint32 VehicleGetVariable(Vehicle *v, const ResolverObject *object, byte variable, uint32 parameter, bool *available)
00468 {
00469   /* Calculated vehicle parameters */
00470   switch (variable) {
00471     case 0x25: // Get engine GRF ID
00472       return v->GetGRFID();
00473 
00474     case 0x40: // Get length of consist
00475       if (!HasBit(v->grf_cache.cache_valid, NCVV_POSITION_CONSIST_LENGTH)) {
00476         v->grf_cache.position_consist_length = PositionHelper(v, false);
00477         SetBit(v->grf_cache.cache_valid, NCVV_POSITION_CONSIST_LENGTH);
00478       }
00479       return v->grf_cache.position_consist_length;
00480 
00481     case 0x41: // Get length of same consecutive wagons
00482       if (!HasBit(v->grf_cache.cache_valid, NCVV_POSITION_SAME_ID_LENGTH)) {
00483         v->grf_cache.position_same_id_length = PositionHelper(v, true);
00484         SetBit(v->grf_cache.cache_valid, NCVV_POSITION_SAME_ID_LENGTH);
00485       }
00486       return v->grf_cache.position_same_id_length;
00487 
00488     case 0x42: { // Consist cargo information
00489       if (!HasBit(v->grf_cache.cache_valid, NCVV_CONSIST_CARGO_INFORMATION)) {
00490         const Vehicle *u;
00491         byte cargo_classes = 0;
00492         uint8 common_cargoes[NUM_CARGO];
00493         uint8 common_subtypes[256];
00494         byte user_def_data = 0;
00495         CargoID common_cargo_type = CT_INVALID;
00496         uint8 common_subtype = 0xFF; // Return 0xFF if nothing is carried
00497 
00498         /* Reset our arrays */
00499         memset(common_cargoes, 0, sizeof(common_cargoes));
00500         memset(common_subtypes, 0, sizeof(common_subtypes));
00501 
00502         for (u = v; u != NULL; u = u->Next()) {
00503           if (v->type == VEH_TRAIN) user_def_data |= Train::From(u)->tcache.user_def_data;
00504 
00505           /* Skip empty engines */
00506           if (!u->GetEngine()->CanCarryCargo()) continue;
00507 
00508           cargo_classes |= CargoSpec::Get(u->cargo_type)->classes;
00509           common_cargoes[u->cargo_type]++;
00510         }
00511 
00512         /* Pick the most common cargo type */
00513         uint common_cargo_best_amount = 0;
00514         for (CargoID cargo = 0; cargo < NUM_CARGO; cargo++) {
00515           if (common_cargoes[cargo] > common_cargo_best_amount) {
00516             common_cargo_best_amount = common_cargoes[cargo];
00517             common_cargo_type = cargo;
00518           }
00519         }
00520 
00521         /* Count subcargo types of common_cargo_type */
00522         for (u = v; u != NULL; u = u->Next()) {
00523           /* Skip empty engines and engines not carrying common_cargo_type */
00524           if (u->cargo_type != common_cargo_type || !u->GetEngine()->CanCarryCargo()) continue;
00525 
00526           common_subtypes[u->cargo_subtype]++;
00527         }
00528 
00529         /* Pick the most common subcargo type*/
00530         uint common_subtype_best_amount = 0;
00531         for (uint i = 0; i < lengthof(common_subtypes); i++) {
00532           if (common_subtypes[i] > common_subtype_best_amount) {
00533             common_subtype_best_amount = common_subtypes[i];
00534             common_subtype = i;
00535           }
00536         }
00537 
00538         /* Note: We have to store the untranslated cargotype in the cache as the cache can be read by different NewGRFs,
00539          *       which will need different translations */
00540         v->grf_cache.consist_cargo_information = cargo_classes | (common_cargo_type << 8) | (common_subtype << 16) | (user_def_data << 24);
00541         SetBit(v->grf_cache.cache_valid, NCVV_CONSIST_CARGO_INFORMATION);
00542       }
00543 
00544       /* The cargo translation is specific to the accessing GRF, and thus cannot be cached. */
00545       CargoID common_cargo_type = (v->grf_cache.consist_cargo_information >> 8) & 0xFF;
00546 
00547       /* Unlike everywhere else the cargo translation table is only used since grf version 8, not 7.
00548        * Note: The grffile == NULL case only happens if this function is called for default vehicles.
00549        *       And this is only done by CheckCaches(). */
00550       const GRFFile *grffile = object->grffile;
00551       uint8 common_bitnum = (common_cargo_type == CT_INVALID) ? 0xFF :
00552         (grffile == NULL || grffile->grf_version < 8) ? CargoSpec::Get(common_cargo_type)->bitnum : grffile->cargo_map[common_cargo_type];
00553 
00554       return (v->grf_cache.consist_cargo_information & 0xFFFF00FF) | common_bitnum << 8;
00555     }
00556 
00557     case 0x43: // Company information
00558       if (!HasBit(v->grf_cache.cache_valid, NCVV_COMPANY_INFORMATION)) {
00559         v->grf_cache.company_information = GetCompanyInfo(v->owner, LiveryHelper(v->engine_type, v));
00560         SetBit(v->grf_cache.cache_valid, NCVV_COMPANY_INFORMATION);
00561       }
00562       return v->grf_cache.company_information;
00563 
00564     case 0x44: // Aircraft information
00565       if (v->type != VEH_AIRCRAFT || !Aircraft::From(v)->IsNormalAircraft()) return UINT_MAX;
00566 
00567       {
00568         const Vehicle *w = v->Next();
00569         uint16 altitude = v->z_pos - w->z_pos; // Aircraft height - shadow height
00570         byte airporttype = ATP_TTDP_LARGE;
00571 
00572         const Station *st = GetTargetAirportIfValid(Aircraft::From(v));
00573 
00574         if (st != NULL && st->airport.tile != INVALID_TILE) {
00575           airporttype = st->airport.GetSpec()->ttd_airport_type;
00576         }
00577 
00578         return (Clamp(altitude, 0, 0xFF) << 8) | airporttype;
00579       }
00580 
00581     case 0x45: { // Curvature info
00582       /* Format: xxxTxBxF
00583        * F - previous wagon to current wagon, 0 if vehicle is first
00584        * B - current wagon to next wagon, 0 if wagon is last
00585        * T - previous wagon to next wagon, 0 in an S-bend
00586        */
00587       if (!v->IsGroundVehicle()) return 0;
00588 
00589       const Vehicle *u_p = v->Previous();
00590       const Vehicle *u_n = v->Next();
00591       DirDiff f = (u_p == NULL) ?  DIRDIFF_SAME : DirDifference(u_p->direction, v->direction);
00592       DirDiff b = (u_n == NULL) ?  DIRDIFF_SAME : DirDifference(v->direction, u_n->direction);
00593       DirDiff t = ChangeDirDiff(f, b);
00594 
00595       return ((t > DIRDIFF_REVERSE ? t | 8 : t) << 16) |
00596              ((b > DIRDIFF_REVERSE ? b | 8 : b) <<  8) |
00597              ( f > DIRDIFF_REVERSE ? f | 8 : f);
00598     }
00599 
00600     case 0x46: // Motion counter
00601       return v->motion_counter;
00602 
00603     case 0x47: { // Vehicle cargo info
00604       /* Format: ccccwwtt
00605        * tt - the cargo type transported by the vehicle,
00606        *     translated if a translation table has been installed.
00607        * ww - cargo unit weight in 1/16 tons, same as cargo prop. 0F.
00608        * cccc - the cargo class value of the cargo transported by the vehicle.
00609        */
00610       const CargoSpec *cs = CargoSpec::Get(v->cargo_type);
00611 
00612       return (cs->classes << 16) | (cs->weight << 8) | v->GetGRF()->cargo_map[v->cargo_type];
00613     }
00614 
00615     case 0x48: return v->GetEngine()->flags; // Vehicle Type Info
00616     case 0x49: return v->build_year;
00617 
00618     case 0x4A: {
00619       if (v->type != VEH_TRAIN) return 0;
00620       RailType rt = GetTileRailType(v->tile);
00621       return (HasPowerOnRail(Train::From(v)->railtype, rt) ? 0x100 : 0) | GetReverseRailTypeTranslation(rt, object->grffile);
00622     }
00623 
00624     case 0x4B: // Long date of last service
00625       return v->date_of_last_service;
00626 
00627     case 0x4C: // Current maximum speed in NewGRF units
00628       if (!v->IsPrimaryVehicle()) return 0;
00629       return v->GetCurrentMaxSpeed();
00630 
00631     /* Variables which use the parameter */
00632     case 0x60: // Count consist's engine ID occurance
00633       if (v->type != VEH_TRAIN) return v->GetEngine()->grf_prop.local_id == parameter ? 1 : 0;
00634 
00635       {
00636         uint count = 0;
00637         for (; v != NULL; v = v->Next()) {
00638           if (v->GetEngine()->grf_prop.local_id == parameter) count++;
00639         }
00640         return count;
00641       }
00642 
00643     case 0x61: // Get variable of n-th vehicle in chain [signed number relative to vehicle]
00644       if (!v->IsGroundVehicle() || parameter == 0x61) return 0;
00645 
00646       /* Only allow callbacks that don't change properties to avoid circular dependencies. */
00647       if (object->callback == CBID_NO_CALLBACK || object->callback == CBID_RANDOM_TRIGGER || object->callback == CBID_TRAIN_ALLOW_WAGON_ATTACH ||
00648           object->callback == CBID_VEHICLE_START_STOP_CHECK || object->callback == CBID_VEHICLE_32DAY_CALLBACK || object->callback == CBID_VEHICLE_COLOUR_MAPPING) {
00649         Vehicle *u = v->Move((int32)GetRegister(0x10F));
00650         if (u == NULL) return 0;
00651 
00652         if (parameter == 0x5F) {
00653           /* This seems to be the only variable that makes sense to access via var 61, but is not handled by VehicleGetVariable */
00654           return (u->random_bits << 8) | u->waiting_triggers;
00655         } else {
00656           return VehicleGetVariable(u, object, parameter, GetRegister(0x10E), available);
00657         }
00658       }
00659       return 0;
00660 
00661     case 0x62: { // Curvature/position difference for n-th vehicle in chain [signed number relative to vehicle]
00662       /* Format: zzyyxxFD
00663        * zz - Signed difference of z position between the selected and this vehicle.
00664        * yy - Signed difference of y position between the selected and this vehicle.
00665        * xx - Signed difference of x position between the selected and this vehicle.
00666        * F  - Flags, bit 7 corresponds to VS_HIDDEN.
00667        * D  - Dir difference, like in 0x45.
00668        */
00669       if (!v->IsGroundVehicle()) return 0;
00670 
00671       const Vehicle *u = v->Move((int8)parameter);
00672       if (u == NULL) return 0;
00673 
00674       /* Get direction difference. */
00675       bool prev = (int8)parameter < 0;
00676       uint32 ret = prev ? DirDifference(u->direction, v->direction) : DirDifference(v->direction, u->direction);
00677       if (ret > DIRDIFF_REVERSE) ret |= 0x08;
00678 
00679       if (u->vehstatus & VS_HIDDEN) ret |= 0x80;
00680 
00681       /* Get position difference. */
00682       ret |= ((prev ? u->x_pos - v->x_pos : v->x_pos - u->x_pos) & 0xFF) << 8;
00683       ret |= ((prev ? u->y_pos - v->y_pos : v->y_pos - u->y_pos) & 0xFF) << 16;
00684       ret |= ((prev ? u->z_pos - v->z_pos : v->z_pos - u->z_pos) & 0xFF) << 24;
00685 
00686       return ret;
00687     }
00688 
00689     case 0xFE:
00690     case 0xFF: {
00691       uint16 modflags = 0;
00692 
00693       if (v->type == VEH_TRAIN) {
00694         const Train *t = Train::From(v);
00695         bool is_powered_wagon = HasBit(t->flags, VRF_POWEREDWAGON);
00696         const Train *u = is_powered_wagon ? t->First() : t; // for powered wagons the engine defines the type of engine (i.e. railtype)
00697         RailType railtype = GetRailType(v->tile);
00698         bool powered = t->IsEngine() || is_powered_wagon;
00699         bool has_power = HasPowerOnRail(u->railtype, railtype);
00700 
00701         if (powered && has_power) SetBit(modflags, 5);
00702         if (powered && !has_power) SetBit(modflags, 6);
00703         if (HasBit(t->flags, VRF_TOGGLE_REVERSE)) SetBit(modflags, 8);
00704       }
00705       if (HasBit(v->vehicle_flags, VF_BUILT_AS_PROTOTYPE)) SetBit(modflags, 10);
00706 
00707       return variable == 0xFE ? modflags : GB(modflags, 8, 8);
00708     }
00709   }
00710 
00711   /* General vehicle properties */
00712   switch (variable - 0x80) {
00713     case 0x00: return v->type + 0x10;
00714     case 0x01: return MapOldSubType(v);
00715     case 0x04: return v->index;
00716     case 0x05: return GB(v->index, 8, 8);
00717     case 0x0A: return v->current_order.MapOldOrder();
00718     case 0x0B: return v->current_order.GetDestination();
00719     case 0x0C: return v->GetNumOrders();
00720     case 0x0D: return v->cur_real_order_index;
00721     case 0x10:
00722     case 0x11: {
00723       uint ticks;
00724       if (v->current_order.IsType(OT_LOADING)) {
00725         ticks = v->load_unload_ticks;
00726       } else {
00727         switch (v->type) {
00728           case VEH_TRAIN:    ticks = Train::From(v)->wait_counter; break;
00729           case VEH_AIRCRAFT: ticks = Aircraft::From(v)->turn_counter; break;
00730           default:           ticks = 0; break;
00731         }
00732       }
00733       return (variable - 0x80) == 0x10 ? ticks : GB(ticks, 8, 8);
00734     }
00735     case 0x12: return Clamp(v->date_of_last_service - DAYS_TILL_ORIGINAL_BASE_YEAR, 0, 0xFFFF);
00736     case 0x13: return GB(Clamp(v->date_of_last_service - DAYS_TILL_ORIGINAL_BASE_YEAR, 0, 0xFFFF), 8, 8);
00737     case 0x14: return v->service_interval;
00738     case 0x15: return GB(v->service_interval, 8, 8);
00739     case 0x16: return v->last_station_visited;
00740     case 0x17: return v->tick_counter;
00741     case 0x18:
00742     case 0x19: {
00743       uint max_speed;
00744       switch (v->type) {
00745         case VEH_AIRCRAFT:
00746           max_speed = Aircraft::From(v)->GetSpeedOldUnits(); // Convert to old units.
00747           break;
00748 
00749         default:
00750           max_speed = v->vcache.cached_max_speed;
00751           break;
00752       }
00753       return (variable - 0x80) == 0x18 ? max_speed : GB(max_speed, 8, 8);
00754     }
00755     case 0x1A: return v->x_pos;
00756     case 0x1B: return GB(v->x_pos, 8, 8);
00757     case 0x1C: return v->y_pos;
00758     case 0x1D: return GB(v->y_pos, 8, 8);
00759     case 0x1E: return v->z_pos;
00760     case 0x1F: return object->u.vehicle.info_view ? DIR_W : v->direction;
00761     case 0x28: return 0; // cur_image is a potential desyncer due to Action1 in static NewGRFs.
00762     case 0x29: return 0; // cur_image is a potential desyncer due to Action1 in static NewGRFs.
00763     case 0x32: return v->vehstatus;
00764     case 0x33: return 0; // non-existent high byte of vehstatus
00765     case 0x34: return v->type == VEH_AIRCRAFT ? (v->cur_speed * 10) / 128 : v->cur_speed;
00766     case 0x35: return GB(v->type == VEH_AIRCRAFT ? (v->cur_speed * 10) / 128 : v->cur_speed, 8, 8);
00767     case 0x36: return v->subspeed;
00768     case 0x37: return v->acceleration;
00769     case 0x39: return v->cargo_type;
00770     case 0x3A: return v->cargo_cap;
00771     case 0x3B: return GB(v->cargo_cap, 8, 8);
00772     case 0x3C: return ClampToU16(v->cargo.Count());
00773     case 0x3D: return GB(ClampToU16(v->cargo.Count()), 8, 8);
00774     case 0x3E: return v->cargo.Source();
00775     case 0x3F: return ClampU(v->cargo.DaysInTransit(), 0, 0xFF);
00776     case 0x40: return ClampToU16(v->age);
00777     case 0x41: return GB(ClampToU16(v->age), 8, 8);
00778     case 0x42: return ClampToU16(v->max_age);
00779     case 0x43: return GB(ClampToU16(v->max_age), 8, 8);
00780     case 0x44: return Clamp(v->build_year, ORIGINAL_BASE_YEAR, ORIGINAL_MAX_YEAR) - ORIGINAL_BASE_YEAR;
00781     case 0x45: return v->unitnumber;
00782     case 0x46: return v->GetEngine()->grf_prop.local_id;
00783     case 0x47: return GB(v->GetEngine()->grf_prop.local_id, 8, 8);
00784     case 0x48:
00785       if (v->type != VEH_TRAIN || v->spritenum != 0xFD) return v->spritenum;
00786       return HasBit(Train::From(v)->flags, VRF_REVERSE_DIRECTION) ? 0xFE : 0xFD;
00787 
00788     case 0x49: return v->day_counter;
00789     case 0x4A: return v->breakdowns_since_last_service;
00790     case 0x4B: return v->breakdown_ctr;
00791     case 0x4C: return v->breakdown_delay;
00792     case 0x4D: return v->breakdown_chance;
00793     case 0x4E: return v->reliability;
00794     case 0x4F: return GB(v->reliability, 8, 8);
00795     case 0x50: return v->reliability_spd_dec;
00796     case 0x51: return GB(v->reliability_spd_dec, 8, 8);
00797     case 0x52: return ClampToI32(v->GetDisplayProfitThisYear());
00798     case 0x53: return GB(ClampToI32(v->GetDisplayProfitThisYear()),  8, 24);
00799     case 0x54: return GB(ClampToI32(v->GetDisplayProfitThisYear()), 16, 16);
00800     case 0x55: return GB(ClampToI32(v->GetDisplayProfitThisYear()), 24,  8);
00801     case 0x56: return ClampToI32(v->GetDisplayProfitLastYear());
00802     case 0x57: return GB(ClampToI32(v->GetDisplayProfitLastYear()),  8, 24);
00803     case 0x58: return GB(ClampToI32(v->GetDisplayProfitLastYear()), 16, 16);
00804     case 0x59: return GB(ClampToI32(v->GetDisplayProfitLastYear()), 24,  8);
00805     case 0x5A: return v->Next() == NULL ? INVALID_VEHICLE : v->Next()->index;
00806     case 0x5C: return ClampToI32(v->value);
00807     case 0x5D: return GB(ClampToI32(v->value),  8, 24);
00808     case 0x5E: return GB(ClampToI32(v->value), 16, 16);
00809     case 0x5F: return GB(ClampToI32(v->value), 24,  8);
00810     case 0x72: return v->cargo_subtype;
00811     case 0x7A: return v->random_bits;
00812     case 0x7B: return v->waiting_triggers;
00813   }
00814 
00815   /* Vehicle specific properties */
00816   switch (v->type) {
00817     case VEH_TRAIN: {
00818       Train *t = Train::From(v);
00819       switch (variable - 0x80) {
00820         case 0x62: return t->track;
00821         case 0x66: return t->railtype;
00822         case 0x73: return 0x80 + VEHICLE_LENGTH - t->gcache.cached_veh_length;
00823         case 0x74: return t->gcache.cached_power;
00824         case 0x75: return GB(t->gcache.cached_power,  8, 24);
00825         case 0x76: return GB(t->gcache.cached_power, 16, 16);
00826         case 0x77: return GB(t->gcache.cached_power, 24,  8);
00827         case 0x7C: return t->First()->index;
00828         case 0x7D: return GB(t->First()->index, 8, 8);
00829         case 0x7F: return 0; // Used for vehicle reversing hack in TTDP
00830       }
00831       break;
00832     }
00833 
00834     case VEH_ROAD: {
00835       RoadVehicle *rv = RoadVehicle::From(v);
00836       switch (variable - 0x80) {
00837         case 0x62: return rv->state;
00838         case 0x64: return rv->blocked_ctr;
00839         case 0x65: return GB(rv->blocked_ctr, 8, 8);
00840         case 0x66: return rv->overtaking;
00841         case 0x67: return rv->overtaking_ctr;
00842         case 0x68: return rv->crashed_ctr;
00843         case 0x69: return GB(rv->crashed_ctr, 8, 8);
00844       }
00845       break;
00846     }
00847 
00848     case VEH_SHIP: {
00849       Ship *s = Ship::From(v);
00850       switch (variable - 0x80) {
00851         case 0x62: return s->state;
00852       }
00853       break;
00854     }
00855 
00856     case VEH_AIRCRAFT: {
00857       Aircraft *a = Aircraft::From(v);
00858       switch (variable - 0x80) {
00859         case 0x62: return MapAircraftMovementState(a);  // Current movement state
00860         case 0x63: return a->targetairport;             // Airport to which the action refers
00861         case 0x66: return MapAircraftMovementAction(a); // Current movement action
00862       }
00863       break;
00864     }
00865 
00866     default: break;
00867   }
00868 
00869   DEBUG(grf, 1, "Unhandled vehicle variable 0x%X, type 0x%X", variable, (uint)v->type);
00870 
00871   *available = false;
00872   return UINT_MAX;
00873 }
00874 
00875 static uint32 VehicleGetVariable(const ResolverObject *object, byte variable, uint32 parameter, bool *available)
00876 {
00877   Vehicle *v = const_cast<Vehicle*>(GRV(object));
00878 
00879   if (v == NULL) {
00880     /* Vehicle does not exist, so we're in a purchase list */
00881     switch (variable) {
00882       case 0x43: return GetCompanyInfo(_current_company, LiveryHelper(object->u.vehicle.self_type, NULL)); // Owner information
00883       case 0x46: return 0;               // Motion counter
00884       case 0x47: { // Vehicle cargo info
00885         const Engine *e = Engine::Get(object->u.vehicle.self_type);
00886         CargoID cargo_type = e->GetDefaultCargoType();
00887         if (cargo_type != CT_INVALID) {
00888           const CargoSpec *cs = CargoSpec::Get(cargo_type);
00889           return (cs->classes << 16) | (cs->weight << 8) | e->GetGRF()->cargo_map[cargo_type];
00890         } else {
00891           return 0x000000FF;
00892         }
00893       }
00894       case 0x48: return Engine::Get(object->u.vehicle.self_type)->flags; // Vehicle Type Info
00895       case 0x49: return _cur_year; // 'Long' format build year
00896       case 0x4B: return _date; // Long date of last service
00897       case 0x92: return Clamp(_date - DAYS_TILL_ORIGINAL_BASE_YEAR, 0, 0xFFFF); // Date of last service
00898       case 0x93: return GB(Clamp(_date - DAYS_TILL_ORIGINAL_BASE_YEAR, 0, 0xFFFF), 8, 8);
00899       case 0xC4: return Clamp(_cur_year, ORIGINAL_BASE_YEAR, ORIGINAL_MAX_YEAR) - ORIGINAL_BASE_YEAR; // Build year
00900       case 0xDA: return INVALID_VEHICLE; // Next vehicle
00901       case 0xF2: return 0; // Cargo subtype
00902     }
00903 
00904     *available = false;
00905     return UINT_MAX;
00906   }
00907 
00908   return VehicleGetVariable(v, object, variable, parameter, available);
00909 }
00910 
00911 
00912 static const SpriteGroup *VehicleResolveReal(const ResolverObject *object, const RealSpriteGroup *group)
00913 {
00914   const Vehicle *v = object->u.vehicle.self;
00915 
00916   if (v == NULL) {
00917     if (group->num_loading > 0) return group->loading[0];
00918     if (group->num_loaded  > 0) return group->loaded[0];
00919     return NULL;
00920   }
00921 
00922   bool in_motion = !v->First()->current_order.IsType(OT_LOADING);
00923 
00924   uint totalsets = in_motion ? group->num_loaded : group->num_loading;
00925 
00926   if (totalsets == 0) return NULL;
00927 
00928   uint set = (v->cargo.Count() * totalsets) / max((uint16)1, v->cargo_cap);
00929   set = min(set, totalsets - 1);
00930 
00931   return in_motion ? group->loaded[set] : group->loading[set];
00932 }
00933 
00934 
00935 static inline void NewVehicleResolver(ResolverObject *res, EngineID engine_type, const Vehicle *v)
00936 {
00937   res->GetRandomBits = &VehicleGetRandomBits;
00938   res->GetTriggers   = &VehicleGetTriggers;
00939   res->SetTriggers   = &VehicleSetTriggers;
00940   res->GetVariable   = &VehicleGetVariable;
00941   res->ResolveReal   = &VehicleResolveReal;
00942 
00943   res->u.vehicle.self   = v;
00944   res->u.vehicle.parent = (v != NULL) ? v->First() : v;
00945 
00946   res->u.vehicle.self_type = engine_type;
00947   res->u.vehicle.info_view = false;
00948 
00949   res->callback        = CBID_NO_CALLBACK;
00950   res->callback_param1 = 0;
00951   res->callback_param2 = 0;
00952   res->ResetState();
00953 
00954   const Engine *e = Engine::Get(engine_type);
00955   res->grffile         = (e != NULL ? e->GetGRF() : NULL);
00956 }
00957 
00958 
00968 static const SpriteGroup *GetVehicleSpriteGroup(EngineID engine, const Vehicle *v, bool use_cache = true)
00969 {
00970   const SpriteGroup *group;
00971   CargoID cargo;
00972 
00973   if (v == NULL) {
00974     cargo = CT_PURCHASE;
00975   } else {
00976     cargo = v->cargo_type;
00977 
00978     if (v->IsGroundVehicle()) {
00979       /* For trains we always use cached value, except for callbacks because the override spriteset
00980        * to use may be different than the one cached. It happens for callback 0x15 (refit engine),
00981        * as v->cargo_type is temporary changed to the new type */
00982       if (use_cache && v->type == VEH_TRAIN) {
00983         group = Train::From(v)->tcache.cached_override;
00984       } else {
00985         group = GetWagonOverrideSpriteSet(v->engine_type, v->cargo_type, v->GetGroundVehicleCache()->first_engine);
00986       }
00987       if (group != NULL) return group;
00988     }
00989   }
00990 
00991   const Engine *e = Engine::Get(engine);
00992 
00993   assert(cargo < lengthof(e->grf_prop.spritegroup));
00994   group = e->grf_prop.spritegroup[cargo];
00995   if (group != NULL) return group;
00996 
00997   /* Fall back to the default set if the selected cargo type is not defined */
00998   return e->grf_prop.spritegroup[CT_DEFAULT];
00999 }
01000 
01001 
01002 SpriteID GetCustomEngineSprite(EngineID engine, const Vehicle *v, Direction direction, EngineImageType image_type)
01003 {
01004   const SpriteGroup *group;
01005   ResolverObject object;
01006 
01007   NewVehicleResolver(&object, engine, v);
01008 
01009   object.callback_param1 = image_type;
01010 
01011   group = SpriteGroup::Resolve(GetVehicleSpriteGroup(engine, v), &object);
01012   if (group == NULL || group->GetNumResults() == 0) return 0;
01013 
01014   return group->GetResult() + (direction % group->GetNumResults());
01015 }
01016 
01017 
01018 SpriteID GetRotorOverrideSprite(EngineID engine, const Aircraft *v, bool info_view, EngineImageType image_type)
01019 {
01020   const Engine *e = Engine::Get(engine);
01021 
01022   /* Only valid for helicopters */
01023   assert(e->type == VEH_AIRCRAFT);
01024   assert(!(e->u.air.subtype & AIR_CTOL));
01025 
01026   ResolverObject object;
01027 
01028   NewVehicleResolver(&object, engine, v);
01029 
01030   object.callback_param1 = image_type;
01031   object.u.vehicle.info_view = info_view;
01032 
01033   const SpriteGroup *group = GetWagonOverrideSpriteSet(engine, CT_DEFAULT, engine);
01034   group = SpriteGroup::Resolve(group, &object);
01035 
01036   if (group == NULL || group->GetNumResults() == 0) return 0;
01037 
01038   if (v == NULL) return group->GetResult();
01039 
01040   return group->GetResult() + (info_view ? 0 : (v->Next()->Next()->state % group->GetNumResults()));
01041 }
01042 
01043 
01049 bool UsesWagonOverride(const Vehicle *v)
01050 {
01051   assert(v->type == VEH_TRAIN);
01052   return Train::From(v)->tcache.cached_override != NULL;
01053 }
01054 
01064 uint16 GetVehicleCallback(CallbackID callback, uint32 param1, uint32 param2, EngineID engine, const Vehicle *v)
01065 {
01066   const SpriteGroup *group;
01067   ResolverObject object;
01068 
01069   NewVehicleResolver(&object, engine, v);
01070 
01071   object.callback        = callback;
01072   object.callback_param1 = param1;
01073   object.callback_param2 = param2;
01074 
01075   group = SpriteGroup::Resolve(GetVehicleSpriteGroup(engine, v, false), &object);
01076   if (group == NULL) return CALLBACK_FAILED;
01077 
01078   return group->GetCallbackResult();
01079 }
01080 
01091 uint16 GetVehicleCallbackParent(CallbackID callback, uint32 param1, uint32 param2, EngineID engine, const Vehicle *v, const Vehicle *parent)
01092 {
01093   const SpriteGroup *group;
01094   ResolverObject object;
01095 
01096   NewVehicleResolver(&object, engine, v);
01097 
01098   object.callback        = callback;
01099   object.callback_param1 = param1;
01100   object.callback_param2 = param2;
01101 
01102   object.u.vehicle.parent = parent;
01103 
01104   group = SpriteGroup::Resolve(GetVehicleSpriteGroup(engine, v, false), &object);
01105   if (group == NULL) return CALLBACK_FAILED;
01106 
01107   return group->GetCallbackResult();
01108 }
01109 
01110 
01111 /* Callback 36 handlers */
01112 uint GetVehicleProperty(const Vehicle *v, PropertyID property, uint orig_value)
01113 {
01114   return GetEngineProperty(v->engine_type, property, orig_value, v);
01115 }
01116 
01117 
01118 uint GetEngineProperty(EngineID engine, PropertyID property, uint orig_value, const Vehicle *v)
01119 {
01120   uint16 callback = GetVehicleCallback(CBID_VEHICLE_MODIFY_PROPERTY, property, 0, engine, v);
01121   if (callback != CALLBACK_FAILED) return callback;
01122 
01123   return orig_value;
01124 }
01125 
01126 
01127 static void DoTriggerVehicle(Vehicle *v, VehicleTrigger trigger, byte base_random_bits, bool first)
01128 {
01129   const SpriteGroup *group;
01130   ResolverObject object;
01131   byte new_random_bits;
01132 
01133   /* We can't trigger a non-existent vehicle... */
01134   assert(v != NULL);
01135 
01136   NewVehicleResolver(&object, v->engine_type, v);
01137   object.callback = CBID_RANDOM_TRIGGER;
01138   object.trigger = trigger;
01139 
01140   group = SpriteGroup::Resolve(GetVehicleSpriteGroup(v->engine_type, v), &object);
01141   if (group == NULL) return;
01142 
01143   new_random_bits = Random();
01144   uint32 reseed = object.GetReseedSum(); // The scope only affects triggers, not the reseeding
01145   v->random_bits &= ~reseed;
01146   v->random_bits |= (first ? new_random_bits : base_random_bits) & reseed;
01147 
01148   switch (trigger) {
01149     case VEHICLE_TRIGGER_NEW_CARGO:
01150       /* All vehicles in chain get ANY_NEW_CARGO trigger now.
01151        * So we call it for the first one and they will recurse.
01152        * Indexing part of vehicle random bits needs to be
01153        * same for all triggered vehicles in the chain (to get
01154        * all the random-cargo wagons carry the same cargo,
01155        * i.e.), so we give them all the NEW_CARGO triggered
01156        * vehicle's portion of random bits. */
01157       assert(first);
01158       DoTriggerVehicle(v->First(), VEHICLE_TRIGGER_ANY_NEW_CARGO, new_random_bits, false);
01159       break;
01160 
01161     case VEHICLE_TRIGGER_DEPOT:
01162       /* We now trigger the next vehicle in chain recursively.
01163        * The random bits portions may be different for each
01164        * vehicle in chain. */
01165       if (v->Next() != NULL) DoTriggerVehicle(v->Next(), trigger, 0, true);
01166       break;
01167 
01168     case VEHICLE_TRIGGER_EMPTY:
01169       /* We now trigger the next vehicle in chain
01170        * recursively.  The random bits portions must be same
01171        * for each vehicle in chain, so we give them all
01172        * first chained vehicle's portion of random bits. */
01173       if (v->Next() != NULL) DoTriggerVehicle(v->Next(), trigger, first ? new_random_bits : base_random_bits, false);
01174       break;
01175 
01176     case VEHICLE_TRIGGER_ANY_NEW_CARGO:
01177       /* Now pass the trigger recursively to the next vehicle
01178        * in chain. */
01179       assert(!first);
01180       if (v->Next() != NULL) DoTriggerVehicle(v->Next(), VEHICLE_TRIGGER_ANY_NEW_CARGO, base_random_bits, false);
01181       break;
01182 
01183     case VEHICLE_TRIGGER_CALLBACK_32:
01184       /* Do not do any recursion */
01185       break;
01186   }
01187 }
01188 
01189 void TriggerVehicle(Vehicle *v, VehicleTrigger trigger)
01190 {
01191   if (trigger == VEHICLE_TRIGGER_DEPOT) {
01192     /* store that the vehicle entered a depot this tick */
01193     VehicleEnteredDepotThisTick(v);
01194   }
01195 
01196   v->InvalidateNewGRFCacheOfChain();
01197   DoTriggerVehicle(v, trigger, 0, true);
01198   v->InvalidateNewGRFCacheOfChain();
01199 }
01200 
01201 /* Functions for changing the order of vehicle purchase lists */
01202 
01203 struct ListOrderChange {
01204   EngineID engine;
01205   uint target;      
01206 };
01207 
01208 static SmallVector<ListOrderChange, 16> _list_order_changes;
01209 
01216 void AlterVehicleListOrder(EngineID engine, uint target)
01217 {
01218   /* Add the list order change to a queue */
01219   ListOrderChange *loc = _list_order_changes.Append();
01220   loc->engine = engine;
01221   loc->target = target;
01222 }
01223 
01230 static int CDECL EnginePreSort(const EngineID *a, const EngineID *b)
01231 {
01232   const EngineIDMapping *id_a = _engine_mngr.Get(*a);
01233   const EngineIDMapping *id_b = _engine_mngr.Get(*b);
01234 
01235   /* 1. Sort by engine type */
01236   if (id_a->type != id_b->type) return (int)id_a->type - (int)id_b->type;
01237 
01238   /* 2. Sort by scope-GRFID */
01239   if (id_a->grfid != id_b->grfid) return id_a->grfid < id_b->grfid ? -1 : 1;
01240 
01241   /* 3. Sort by local ID */
01242   return (int)id_a->internal_id - (int)id_b->internal_id;
01243 }
01244 
01248 void CommitVehicleListOrderChanges()
01249 {
01250   /* Pre-sort engines by scope-grfid and local index */
01251   SmallVector<EngineID, 16> ordering;
01252   Engine *e;
01253   FOR_ALL_ENGINES(e) {
01254     *ordering.Append() = e->index;
01255   }
01256   QSortT(ordering.Begin(), ordering.Length(), EnginePreSort);
01257 
01258   /* Apply Insertion-Sort opeations */
01259   const ListOrderChange *end = _list_order_changes.End();
01260   for (const ListOrderChange *it = _list_order_changes.Begin(); it != end; ++it) {
01261     EngineID source = it->engine;
01262     uint local_target = it->target;
01263 
01264     const EngineIDMapping *id_source = _engine_mngr.Get(source);
01265     if (id_source->internal_id == local_target) continue;
01266 
01267     EngineID target = _engine_mngr.GetID(id_source->type, local_target, id_source->grfid);
01268     if (target == INVALID_ENGINE) continue;
01269 
01270     int source_index = ordering.FindIndex(source);
01271     int target_index = ordering.FindIndex(target);
01272 
01273     assert(source_index >= 0 && target_index >= 0);
01274     assert(source_index != target_index);
01275 
01276     EngineID *list = ordering.Begin();
01277     if (source_index < target_index) {
01278       --target_index;
01279       for (int i = source_index; i < target_index; ++i) list[i] = list[i + 1];
01280       list[target_index] = source;
01281     } else {
01282       for (int i = source_index; i > target_index; --i) list[i] = list[i - 1];
01283       list[target_index] = source;
01284     }
01285   }
01286 
01287   /* Store final sort-order */
01288   const EngineID *idend = ordering.End();
01289   uint index = 0;
01290   for (const EngineID *it = ordering.Begin(); it != idend; ++it, ++index) {
01291     Engine::Get(*it)->list_position = index;
01292   }
01293 
01294   /* Clear out the queue */
01295   _list_order_changes.Reset();
01296 }
01297 
01303 void GetVehicleResolver(ResolverObject *ro, uint index)
01304 {
01305   Vehicle *v = Vehicle::Get(index);
01306   NewVehicleResolver(ro, v->engine_type, v);
01307 }
01308 
01313 void FillNewGRFVehicleCache(const Vehicle *v)
01314 {
01315   ResolverObject ro;
01316   memset(&ro, 0, sizeof(ro));
01317   GetVehicleResolver(&ro, v->index);
01318 
01319   /* These variables we have to check; these are the ones with a cache. */
01320   static const int cache_entries[][2] = {
01321     { 0x40, NCVV_POSITION_CONSIST_LENGTH },
01322     { 0x41, NCVV_POSITION_SAME_ID_LENGTH },
01323     { 0x42, NCVV_CONSIST_CARGO_INFORMATION },
01324     { 0x43, NCVV_COMPANY_INFORMATION },
01325   };
01326   assert_compile(NCVV_END == lengthof(cache_entries));
01327 
01328   /* Resolve all the variables, so their caches are set. */
01329   for (size_t i = 0; i < lengthof(cache_entries); i++) {
01330     /* Only resolve when the cache isn't valid. */
01331     if (HasBit(v->grf_cache.cache_valid, cache_entries[i][1])) continue;
01332     bool stub;
01333     ro.GetVariable(&ro, cache_entries[i][0], 0, &stub);
01334   }
01335 
01336   /* Make sure really all bits are set. */
01337   assert(v->grf_cache.cache_valid == (1 << NCVV_END) - 1);
01338 }