newgrf_engine.cpp

Go to the documentation of this file.
00001 /* $Id: newgrf_engine.cpp 26157 2013-12-13 20:21:04Z frosch $ */
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 hangar. 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 hangar 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 hangar 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 hangar? */
00193       if (amdflag & AMED_EXACTPOS) return AMS_TTDP_HANGAR;
00194 
00195       /* Still moving towards hangar. */
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 hangar) 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 /* virtual */ uint32 VehicleScopeResolver::GetRandomBits() const
00344 {
00345   return this->v == NULL ? 0 : this->v->random_bits;
00346 }
00347 
00348 /* virtual */ uint32 VehicleScopeResolver::GetTriggers() const
00349 {
00350   return this->v == NULL ? 0 : this->v->waiting_triggers;
00351 }
00352 
00353 /* virtual */ void VehicleScopeResolver::SetTriggers(int triggers) const
00354 {
00355   /* Evil cast to get around const-ness. This used to be achieved by an
00356    * innocent looking function pointer cast... Currently I cannot see a
00357    * way of avoiding this without removing consts deep within gui code.
00358    */
00359   Vehicle *v = const_cast<Vehicle *>(this->v);
00360 
00361   /* This function must only be called when processing triggers -- any
00362    * other time is an error. */
00363   assert(this->ro.trigger != 0);
00364 
00365   if (v != NULL) v->waiting_triggers = triggers;
00366 }
00367 
00368 
00369 /* virtual */ ScopeResolver *VehicleResolverObject::GetScope(VarSpriteGroupScope scope, byte relative)
00370 {
00371   switch (scope) {
00372     case VSG_SCOPE_SELF:   return &this->self_scope;
00373     case VSG_SCOPE_PARENT: return &this->parent_scope;
00374     case VSG_SCOPE_RELATIVE: {
00375       int32 count = GB(relative, 0, 4);
00376       if (this->self_scope.v != NULL && (relative != this->cached_relative_count || count == 0)) {
00377         /* Note: This caching only works as long as the VSG_SCOPE_RELATIVE cannot be used in
00378          *       VarAct2 with procedure calls. */
00379         if (count == 0) count = GetRegister(0x100);
00380 
00381         const Vehicle *v = NULL;
00382         switch (GB(relative, 6, 2)) {
00383           default: NOT_REACHED();
00384           case 0x00: // count back (away from the engine), starting at this vehicle
00385             v = this->self_scope.v;
00386             break;
00387           case 0x01: // count forward (toward the engine), starting at this vehicle
00388             v = this->self_scope.v;
00389             count = -count;
00390             break;
00391           case 0x02: // count back, starting at the engine
00392             v = this->parent_scope.v;
00393             break;
00394           case 0x03: { // count back, starting at the first vehicle in this chain of vehicles with the same ID, as for vehicle variable 41
00395             const Vehicle *self = this->self_scope.v;
00396             for (const Vehicle *u = self->First(); u != self; u = u->Next()) {
00397               if (u->engine_type != self->engine_type) {
00398                 v = NULL;
00399               } else {
00400                 if (v == NULL) v = u;
00401               }
00402             }
00403             if (v == NULL) v = self;
00404             break;
00405           }
00406         }
00407         this->relative_scope.SetVehicle(v->Move(count));
00408       }
00409       return &this->relative_scope;
00410     }
00411     default: return ResolverObject::GetScope(scope, relative);
00412   }
00413 }
00414 
00424 static const Livery *LiveryHelper(EngineID engine, const Vehicle *v)
00425 {
00426   const Livery *l;
00427 
00428   if (v == NULL) {
00429     if (!Company::IsValidID(_current_company)) return NULL;
00430     l = GetEngineLivery(engine, _current_company, INVALID_ENGINE, NULL, LIT_ALL);
00431   } else if (v->IsGroundVehicle()) {
00432     l = GetEngineLivery(v->engine_type, v->owner, v->GetGroundVehicleCache()->first_engine, v, LIT_ALL);
00433   } else {
00434     l = GetEngineLivery(v->engine_type, v->owner, INVALID_ENGINE, v, LIT_ALL);
00435   }
00436 
00437   return l;
00438 }
00439 
00447 static uint32 PositionHelper(const Vehicle *v, bool consecutive)
00448 {
00449   const Vehicle *u;
00450   byte chain_before = 0;
00451   byte chain_after  = 0;
00452 
00453   for (u = v->First(); u != v; u = u->Next()) {
00454     chain_before++;
00455     if (consecutive && u->engine_type != v->engine_type) chain_before = 0;
00456   }
00457 
00458   while (u->Next() != NULL && (!consecutive || u->Next()->engine_type == v->engine_type)) {
00459     chain_after++;
00460     u = u->Next();
00461   }
00462 
00463   return chain_before | chain_after << 8 | (chain_before + chain_after + consecutive) << 16;
00464 }
00465 
00466 static uint32 VehicleGetVariable(Vehicle *v, const VehicleScopeResolver *object, byte variable, uint32 parameter, bool *available)
00467 {
00468   /* Calculated vehicle parameters */
00469   switch (variable) {
00470     case 0x25: // Get engine GRF ID
00471       return v->GetGRFID();
00472 
00473     case 0x40: // Get length of consist
00474       if (!HasBit(v->grf_cache.cache_valid, NCVV_POSITION_CONSIST_LENGTH)) {
00475         v->grf_cache.position_consist_length = PositionHelper(v, false);
00476         SetBit(v->grf_cache.cache_valid, NCVV_POSITION_CONSIST_LENGTH);
00477       }
00478       return v->grf_cache.position_consist_length;
00479 
00480     case 0x41: // Get length of same consecutive wagons
00481       if (!HasBit(v->grf_cache.cache_valid, NCVV_POSITION_SAME_ID_LENGTH)) {
00482         v->grf_cache.position_same_id_length = PositionHelper(v, true);
00483         SetBit(v->grf_cache.cache_valid, NCVV_POSITION_SAME_ID_LENGTH);
00484       }
00485       return v->grf_cache.position_same_id_length;
00486 
00487     case 0x42: { // Consist cargo information
00488       if (!HasBit(v->grf_cache.cache_valid, NCVV_CONSIST_CARGO_INFORMATION)) {
00489         const Vehicle *u;
00490         byte cargo_classes = 0;
00491         uint8 common_cargoes[NUM_CARGO];
00492         uint8 common_subtypes[256];
00493         byte user_def_data = 0;
00494         CargoID common_cargo_type = CT_INVALID;
00495         uint8 common_subtype = 0xFF; // Return 0xFF if nothing is carried
00496 
00497         /* Reset our arrays */
00498         memset(common_cargoes, 0, sizeof(common_cargoes));
00499         memset(common_subtypes, 0, sizeof(common_subtypes));
00500 
00501         for (u = v; u != NULL; u = u->Next()) {
00502           if (v->type == VEH_TRAIN) user_def_data |= Train::From(u)->tcache.user_def_data;
00503 
00504           /* Skip empty engines */
00505           if (!u->GetEngine()->CanCarryCargo()) continue;
00506 
00507           cargo_classes |= CargoSpec::Get(u->cargo_type)->classes;
00508           common_cargoes[u->cargo_type]++;
00509         }
00510 
00511         /* Pick the most common cargo type */
00512         uint common_cargo_best_amount = 0;
00513         for (CargoID cargo = 0; cargo < NUM_CARGO; cargo++) {
00514           if (common_cargoes[cargo] > common_cargo_best_amount) {
00515             common_cargo_best_amount = common_cargoes[cargo];
00516             common_cargo_type = cargo;
00517           }
00518         }
00519 
00520         /* Count subcargo types of common_cargo_type */
00521         for (u = v; u != NULL; u = u->Next()) {
00522           /* Skip empty engines and engines not carrying common_cargo_type */
00523           if (u->cargo_type != common_cargo_type || !u->GetEngine()->CanCarryCargo()) continue;
00524 
00525           common_subtypes[u->cargo_subtype]++;
00526         }
00527 
00528         /* Pick the most common subcargo type*/
00529         uint common_subtype_best_amount = 0;
00530         for (uint i = 0; i < lengthof(common_subtypes); i++) {
00531           if (common_subtypes[i] > common_subtype_best_amount) {
00532             common_subtype_best_amount = common_subtypes[i];
00533             common_subtype = i;
00534           }
00535         }
00536 
00537         /* Note: We have to store the untranslated cargotype in the cache as the cache can be read by different NewGRFs,
00538          *       which will need different translations */
00539         v->grf_cache.consist_cargo_information = cargo_classes | (common_cargo_type << 8) | (common_subtype << 16) | (user_def_data << 24);
00540         SetBit(v->grf_cache.cache_valid, NCVV_CONSIST_CARGO_INFORMATION);
00541       }
00542 
00543       /* The cargo translation is specific to the accessing GRF, and thus cannot be cached. */
00544       CargoID common_cargo_type = (v->grf_cache.consist_cargo_information >> 8) & 0xFF;
00545 
00546       /* Unlike everywhere else the cargo translation table is only used since grf version 8, not 7.
00547        * Note: The grffile == NULL case only happens if this function is called for default vehicles.
00548        *       And this is only done by CheckCaches(). */
00549       const GRFFile *grffile = object->ro.grffile;
00550       uint8 common_bitnum = (common_cargo_type == CT_INVALID) ? 0xFF :
00551         (grffile == NULL || grffile->grf_version < 8) ? CargoSpec::Get(common_cargo_type)->bitnum : grffile->cargo_map[common_cargo_type];
00552 
00553       return (v->grf_cache.consist_cargo_information & 0xFFFF00FF) | common_bitnum << 8;
00554     }
00555 
00556     case 0x43: // Company information
00557       if (!HasBit(v->grf_cache.cache_valid, NCVV_COMPANY_INFORMATION)) {
00558         v->grf_cache.company_information = GetCompanyInfo(v->owner, LiveryHelper(v->engine_type, v));
00559         SetBit(v->grf_cache.cache_valid, NCVV_COMPANY_INFORMATION);
00560       }
00561       return v->grf_cache.company_information;
00562 
00563     case 0x44: // Aircraft information
00564       if (v->type != VEH_AIRCRAFT || !Aircraft::From(v)->IsNormalAircraft()) return UINT_MAX;
00565 
00566       {
00567         const Vehicle *w = v->Next();
00568         uint16 altitude = v->z_pos - w->z_pos; // Aircraft height - shadow height
00569         byte airporttype = ATP_TTDP_LARGE;
00570 
00571         const Station *st = GetTargetAirportIfValid(Aircraft::From(v));
00572 
00573         if (st != NULL && st->airport.tile != INVALID_TILE) {
00574           airporttype = st->airport.GetSpec()->ttd_airport_type;
00575         }
00576 
00577         return (Clamp(altitude, 0, 0xFF) << 8) | airporttype;
00578       }
00579 
00580     case 0x45: { // Curvature info
00581       /* Format: xxxTxBxF
00582        * F - previous wagon to current wagon, 0 if vehicle is first
00583        * B - current wagon to next wagon, 0 if wagon is last
00584        * T - previous wagon to next wagon, 0 in an S-bend
00585        */
00586       if (!v->IsGroundVehicle()) return 0;
00587 
00588       const Vehicle *u_p = v->Previous();
00589       const Vehicle *u_n = v->Next();
00590       DirDiff f = (u_p == NULL) ?  DIRDIFF_SAME : DirDifference(u_p->direction, v->direction);
00591       DirDiff b = (u_n == NULL) ?  DIRDIFF_SAME : DirDifference(v->direction, u_n->direction);
00592       DirDiff t = ChangeDirDiff(f, b);
00593 
00594       return ((t > DIRDIFF_REVERSE ? t | 8 : t) << 16) |
00595              ((b > DIRDIFF_REVERSE ? b | 8 : b) <<  8) |
00596              ( f > DIRDIFF_REVERSE ? f | 8 : f);
00597     }
00598 
00599     case 0x46: // Motion counter
00600       return v->motion_counter;
00601 
00602     case 0x47: { // Vehicle cargo info
00603       /* Format: ccccwwtt
00604        * tt - the cargo type transported by the vehicle,
00605        *     translated if a translation table has been installed.
00606        * ww - cargo unit weight in 1/16 tons, same as cargo prop. 0F.
00607        * cccc - the cargo class value of the cargo transported by the vehicle.
00608        */
00609       const CargoSpec *cs = CargoSpec::Get(v->cargo_type);
00610 
00611       return (cs->classes << 16) | (cs->weight << 8) | v->GetGRF()->cargo_map[v->cargo_type];
00612     }
00613 
00614     case 0x48: return v->GetEngine()->flags; // Vehicle Type Info
00615     case 0x49: return v->build_year;
00616 
00617     case 0x4A: {
00618       if (v->type != VEH_TRAIN) return 0;
00619       RailType rt = GetTileRailType(v->tile);
00620       return (HasPowerOnRail(Train::From(v)->railtype, rt) ? 0x100 : 0) | GetReverseRailTypeTranslation(rt, object->ro.grffile);
00621     }
00622 
00623     case 0x4B: // Long date of last service
00624       return v->date_of_last_service;
00625 
00626     case 0x4C: // Current maximum speed in NewGRF units
00627       if (!v->IsPrimaryVehicle()) return 0;
00628       return v->GetCurrentMaxSpeed();
00629 
00630     case 0x4D: // Position within articulated vehicle
00631       if (!HasBit(v->grf_cache.cache_valid, NCVV_POSITION_IN_VEHICLE)) {
00632         byte artic_before = 0;
00633         for (const Vehicle *u = v; u->IsArticulatedPart(); u = u->Previous()) artic_before++;
00634         byte artic_after = 0;
00635         for (const Vehicle *u = v; u->HasArticulatedPart(); u = u->Next()) artic_after++;
00636         v->grf_cache.position_in_vehicle = artic_before | artic_after << 8;
00637         SetBit(v->grf_cache.cache_valid, NCVV_POSITION_IN_VEHICLE);
00638       }
00639       return v->grf_cache.position_in_vehicle;
00640 
00641     /* Variables which use the parameter */
00642     case 0x60: // Count consist's engine ID occurrence
00643       if (v->type != VEH_TRAIN) return v->GetEngine()->grf_prop.local_id == parameter ? 1 : 0;
00644 
00645       {
00646         uint count = 0;
00647         for (; v != NULL; v = v->Next()) {
00648           if (v->GetEngine()->grf_prop.local_id == parameter) count++;
00649         }
00650         return count;
00651       }
00652 
00653     case 0x61: // Get variable of n-th vehicle in chain [signed number relative to vehicle]
00654       if (!v->IsGroundVehicle() || parameter == 0x61) return 0;
00655 
00656       /* Only allow callbacks that don't change properties to avoid circular dependencies. */
00657       if (object->ro.callback == CBID_NO_CALLBACK || object->ro.callback == CBID_RANDOM_TRIGGER || object->ro.callback == CBID_TRAIN_ALLOW_WAGON_ATTACH ||
00658           object->ro.callback == CBID_VEHICLE_START_STOP_CHECK || object->ro.callback == CBID_VEHICLE_32DAY_CALLBACK || object->ro.callback == CBID_VEHICLE_COLOUR_MAPPING) {
00659         Vehicle *u = v->Move((int32)GetRegister(0x10F));
00660         if (u == NULL) return 0;
00661 
00662         if (parameter == 0x5F) {
00663           /* This seems to be the only variable that makes sense to access via var 61, but is not handled by VehicleGetVariable */
00664           return (u->random_bits << 8) | u->waiting_triggers;
00665         } else {
00666           return VehicleGetVariable(u, object, parameter, GetRegister(0x10E), available);
00667         }
00668       }
00669       return 0;
00670 
00671     case 0x62: { // Curvature/position difference for n-th vehicle in chain [signed number relative to vehicle]
00672       /* Format: zzyyxxFD
00673        * zz - Signed difference of z position between the selected and this vehicle.
00674        * yy - Signed difference of y position between the selected and this vehicle.
00675        * xx - Signed difference of x position between the selected and this vehicle.
00676        * F  - Flags, bit 7 corresponds to VS_HIDDEN.
00677        * D  - Dir difference, like in 0x45.
00678        */
00679       if (!v->IsGroundVehicle()) return 0;
00680 
00681       const Vehicle *u = v->Move((int8)parameter);
00682       if (u == NULL) return 0;
00683 
00684       /* Get direction difference. */
00685       bool prev = (int8)parameter < 0;
00686       uint32 ret = prev ? DirDifference(u->direction, v->direction) : DirDifference(v->direction, u->direction);
00687       if (ret > DIRDIFF_REVERSE) ret |= 0x08;
00688 
00689       if (u->vehstatus & VS_HIDDEN) ret |= 0x80;
00690 
00691       /* Get position difference. */
00692       ret |= ((prev ? u->x_pos - v->x_pos : v->x_pos - u->x_pos) & 0xFF) << 8;
00693       ret |= ((prev ? u->y_pos - v->y_pos : v->y_pos - u->y_pos) & 0xFF) << 16;
00694       ret |= ((prev ? u->z_pos - v->z_pos : v->z_pos - u->z_pos) & 0xFF) << 24;
00695 
00696       return ret;
00697     }
00698 
00699     case 0xFE:
00700     case 0xFF: {
00701       uint16 modflags = 0;
00702 
00703       if (v->type == VEH_TRAIN) {
00704         const Train *t = Train::From(v);
00705         bool is_powered_wagon = HasBit(t->flags, VRF_POWEREDWAGON);
00706         const Train *u = is_powered_wagon ? t->First() : t; // for powered wagons the engine defines the type of engine (i.e. railtype)
00707         RailType railtype = GetRailType(v->tile);
00708         bool powered = t->IsEngine() || is_powered_wagon;
00709         bool has_power = HasPowerOnRail(u->railtype, railtype);
00710 
00711         if (powered && has_power) SetBit(modflags, 5);
00712         if (powered && !has_power) SetBit(modflags, 6);
00713         if (HasBit(t->flags, VRF_TOGGLE_REVERSE)) SetBit(modflags, 8);
00714       }
00715       if (HasBit(v->vehicle_flags, VF_BUILT_AS_PROTOTYPE)) SetBit(modflags, 10);
00716 
00717       return variable == 0xFE ? modflags : GB(modflags, 8, 8);
00718     }
00719   }
00720 
00721   /* General vehicle properties */
00722   switch (variable - 0x80) {
00723     case 0x00: return v->type + 0x10;
00724     case 0x01: return MapOldSubType(v);
00725     case 0x04: return v->index;
00726     case 0x05: return GB(v->index, 8, 8);
00727     case 0x0A: return v->current_order.MapOldOrder();
00728     case 0x0B: return v->current_order.GetDestination();
00729     case 0x0C: return v->GetNumOrders();
00730     case 0x0D: return v->cur_real_order_index;
00731     case 0x10:
00732     case 0x11: {
00733       uint ticks;
00734       if (v->current_order.IsType(OT_LOADING)) {
00735         ticks = v->load_unload_ticks;
00736       } else {
00737         switch (v->type) {
00738           case VEH_TRAIN:    ticks = Train::From(v)->wait_counter; break;
00739           case VEH_AIRCRAFT: ticks = Aircraft::From(v)->turn_counter; break;
00740           default:           ticks = 0; break;
00741         }
00742       }
00743       return (variable - 0x80) == 0x10 ? ticks : GB(ticks, 8, 8);
00744     }
00745     case 0x12: return Clamp(v->date_of_last_service - DAYS_TILL_ORIGINAL_BASE_YEAR, 0, 0xFFFF);
00746     case 0x13: return GB(Clamp(v->date_of_last_service - DAYS_TILL_ORIGINAL_BASE_YEAR, 0, 0xFFFF), 8, 8);
00747     case 0x14: return v->GetServiceInterval();
00748     case 0x15: return GB(v->GetServiceInterval(), 8, 8);
00749     case 0x16: return v->last_station_visited;
00750     case 0x17: return v->tick_counter;
00751     case 0x18:
00752     case 0x19: {
00753       uint max_speed;
00754       switch (v->type) {
00755         case VEH_AIRCRAFT:
00756           max_speed = Aircraft::From(v)->GetSpeedOldUnits(); // Convert to old units.
00757           break;
00758 
00759         default:
00760           max_speed = v->vcache.cached_max_speed;
00761           break;
00762       }
00763       return (variable - 0x80) == 0x18 ? max_speed : GB(max_speed, 8, 8);
00764     }
00765     case 0x1A: return v->x_pos;
00766     case 0x1B: return GB(v->x_pos, 8, 8);
00767     case 0x1C: return v->y_pos;
00768     case 0x1D: return GB(v->y_pos, 8, 8);
00769     case 0x1E: return v->z_pos;
00770     case 0x1F: return object->info_view ? DIR_W : v->direction;
00771     case 0x28: return 0; // cur_image is a potential desyncer due to Action1 in static NewGRFs.
00772     case 0x29: return 0; // cur_image is a potential desyncer due to Action1 in static NewGRFs.
00773     case 0x32: return v->vehstatus;
00774     case 0x33: return 0; // non-existent high byte of vehstatus
00775     case 0x34: return v->type == VEH_AIRCRAFT ? (v->cur_speed * 10) / 128 : v->cur_speed;
00776     case 0x35: return GB(v->type == VEH_AIRCRAFT ? (v->cur_speed * 10) / 128 : v->cur_speed, 8, 8);
00777     case 0x36: return v->subspeed;
00778     case 0x37: return v->acceleration;
00779     case 0x39: return v->cargo_type;
00780     case 0x3A: return v->cargo_cap;
00781     case 0x3B: return GB(v->cargo_cap, 8, 8);
00782     case 0x3C: return ClampToU16(v->cargo.StoredCount());
00783     case 0x3D: return GB(ClampToU16(v->cargo.StoredCount()), 8, 8);
00784     case 0x3E: return v->cargo.Source();
00785     case 0x3F: return ClampU(v->cargo.DaysInTransit(), 0, 0xFF);
00786     case 0x40: return ClampToU16(v->age);
00787     case 0x41: return GB(ClampToU16(v->age), 8, 8);
00788     case 0x42: return ClampToU16(v->max_age);
00789     case 0x43: return GB(ClampToU16(v->max_age), 8, 8);
00790     case 0x44: return Clamp(v->build_year, ORIGINAL_BASE_YEAR, ORIGINAL_MAX_YEAR) - ORIGINAL_BASE_YEAR;
00791     case 0x45: return v->unitnumber;
00792     case 0x46: return v->GetEngine()->grf_prop.local_id;
00793     case 0x47: return GB(v->GetEngine()->grf_prop.local_id, 8, 8);
00794     case 0x48:
00795       if (v->type != VEH_TRAIN || v->spritenum != 0xFD) return v->spritenum;
00796       return HasBit(Train::From(v)->flags, VRF_REVERSE_DIRECTION) ? 0xFE : 0xFD;
00797 
00798     case 0x49: return v->day_counter;
00799     case 0x4A: return v->breakdowns_since_last_service;
00800     case 0x4B: return v->breakdown_ctr;
00801     case 0x4C: return v->breakdown_delay;
00802     case 0x4D: return v->breakdown_chance;
00803     case 0x4E: return v->reliability;
00804     case 0x4F: return GB(v->reliability, 8, 8);
00805     case 0x50: return v->reliability_spd_dec;
00806     case 0x51: return GB(v->reliability_spd_dec, 8, 8);
00807     case 0x52: return ClampToI32(v->GetDisplayProfitThisYear());
00808     case 0x53: return GB(ClampToI32(v->GetDisplayProfitThisYear()),  8, 24);
00809     case 0x54: return GB(ClampToI32(v->GetDisplayProfitThisYear()), 16, 16);
00810     case 0x55: return GB(ClampToI32(v->GetDisplayProfitThisYear()), 24,  8);
00811     case 0x56: return ClampToI32(v->GetDisplayProfitLastYear());
00812     case 0x57: return GB(ClampToI32(v->GetDisplayProfitLastYear()),  8, 24);
00813     case 0x58: return GB(ClampToI32(v->GetDisplayProfitLastYear()), 16, 16);
00814     case 0x59: return GB(ClampToI32(v->GetDisplayProfitLastYear()), 24,  8);
00815     case 0x5A: return v->Next() == NULL ? INVALID_VEHICLE : v->Next()->index;
00816     case 0x5C: return ClampToI32(v->value);
00817     case 0x5D: return GB(ClampToI32(v->value),  8, 24);
00818     case 0x5E: return GB(ClampToI32(v->value), 16, 16);
00819     case 0x5F: return GB(ClampToI32(v->value), 24,  8);
00820     case 0x72: return v->cargo_subtype;
00821     case 0x7A: return v->random_bits;
00822     case 0x7B: return v->waiting_triggers;
00823   }
00824 
00825   /* Vehicle specific properties */
00826   switch (v->type) {
00827     case VEH_TRAIN: {
00828       Train *t = Train::From(v);
00829       switch (variable - 0x80) {
00830         case 0x62: return t->track;
00831         case 0x66: return t->railtype;
00832         case 0x73: return 0x80 + VEHICLE_LENGTH - t->gcache.cached_veh_length;
00833         case 0x74: return t->gcache.cached_power;
00834         case 0x75: return GB(t->gcache.cached_power,  8, 24);
00835         case 0x76: return GB(t->gcache.cached_power, 16, 16);
00836         case 0x77: return GB(t->gcache.cached_power, 24,  8);
00837         case 0x7C: return t->First()->index;
00838         case 0x7D: return GB(t->First()->index, 8, 8);
00839         case 0x7F: return 0; // Used for vehicle reversing hack in TTDP
00840       }
00841       break;
00842     }
00843 
00844     case VEH_ROAD: {
00845       RoadVehicle *rv = RoadVehicle::From(v);
00846       switch (variable - 0x80) {
00847         case 0x62: return rv->state;
00848         case 0x64: return rv->blocked_ctr;
00849         case 0x65: return GB(rv->blocked_ctr, 8, 8);
00850         case 0x66: return rv->overtaking;
00851         case 0x67: return rv->overtaking_ctr;
00852         case 0x68: return rv->crashed_ctr;
00853         case 0x69: return GB(rv->crashed_ctr, 8, 8);
00854       }
00855       break;
00856     }
00857 
00858     case VEH_SHIP: {
00859       Ship *s = Ship::From(v);
00860       switch (variable - 0x80) {
00861         case 0x62: return s->state;
00862       }
00863       break;
00864     }
00865 
00866     case VEH_AIRCRAFT: {
00867       Aircraft *a = Aircraft::From(v);
00868       switch (variable - 0x80) {
00869         case 0x62: return MapAircraftMovementState(a);  // Current movement state
00870         case 0x63: return a->targetairport;             // Airport to which the action refers
00871         case 0x66: return MapAircraftMovementAction(a); // Current movement action
00872       }
00873       break;
00874     }
00875 
00876     default: break;
00877   }
00878 
00879   DEBUG(grf, 1, "Unhandled vehicle variable 0x%X, type 0x%X", variable, (uint)v->type);
00880 
00881   *available = false;
00882   return UINT_MAX;
00883 }
00884 
00885 /* virtual */ uint32 VehicleScopeResolver::GetVariable(byte variable, uint32 parameter, bool *available) const
00886 {
00887   if (this->v == NULL) {
00888     /* Vehicle does not exist, so we're in a purchase list */
00889     switch (variable) {
00890       case 0x43: return GetCompanyInfo(_current_company, LiveryHelper(this->self_type, NULL)); // Owner information
00891       case 0x46: return 0;               // Motion counter
00892       case 0x47: { // Vehicle cargo info
00893         const Engine *e = Engine::Get(this->self_type);
00894         CargoID cargo_type = e->GetDefaultCargoType();
00895         if (cargo_type != CT_INVALID) {
00896           const CargoSpec *cs = CargoSpec::Get(cargo_type);
00897           return (cs->classes << 16) | (cs->weight << 8) | e->GetGRF()->cargo_map[cargo_type];
00898         } else {
00899           return 0x000000FF;
00900         }
00901       }
00902       case 0x48: return Engine::Get(this->self_type)->flags; // Vehicle Type Info
00903       case 0x49: return _cur_year; // 'Long' format build year
00904       case 0x4B: return _date; // Long date of last service
00905       case 0x92: return Clamp(_date - DAYS_TILL_ORIGINAL_BASE_YEAR, 0, 0xFFFF); // Date of last service
00906       case 0x93: return GB(Clamp(_date - DAYS_TILL_ORIGINAL_BASE_YEAR, 0, 0xFFFF), 8, 8);
00907       case 0xC4: return Clamp(_cur_year, ORIGINAL_BASE_YEAR, ORIGINAL_MAX_YEAR) - ORIGINAL_BASE_YEAR; // Build year
00908       case 0xDA: return INVALID_VEHICLE; // Next vehicle
00909       case 0xF2: return 0; // Cargo subtype
00910     }
00911 
00912     *available = false;
00913     return UINT_MAX;
00914   }
00915 
00916   return VehicleGetVariable(const_cast<Vehicle*>(this->v), this, variable, parameter, available);
00917 }
00918 
00919 
00920 /* virtual */ const SpriteGroup *VehicleResolverObject::ResolveReal(const RealSpriteGroup *group) const
00921 {
00922   const Vehicle *v = this->self_scope.v;
00923 
00924   if (v == NULL) {
00925     if (group->num_loading > 0) return group->loading[0];
00926     if (group->num_loaded  > 0) return group->loaded[0];
00927     return NULL;
00928   }
00929 
00930   bool in_motion = !v->First()->current_order.IsType(OT_LOADING);
00931 
00932   uint totalsets = in_motion ? group->num_loaded : group->num_loading;
00933 
00934   if (totalsets == 0) return NULL;
00935 
00936   uint set = (v->cargo.StoredCount() * totalsets) / max((uint16)1, v->cargo_cap);
00937   set = min(set, totalsets - 1);
00938 
00939   return in_motion ? group->loaded[set] : group->loading[set];
00940 }
00941 
00949 VehicleScopeResolver::VehicleScopeResolver(ResolverObject &ro, EngineID engine_type, const Vehicle *v, bool info_view)
00950     : ScopeResolver(ro)
00951 {
00952   this->v = v;
00953   this->self_type = engine_type;
00954   this->info_view = info_view;
00955 }
00956 
00962 static const GRFFile *GetEngineGrfFile(EngineID engine_type)
00963 {
00964   const Engine *e = Engine::Get(engine_type);
00965   return (e != NULL) ? e->GetGRF() : NULL;
00966 }
00967 
00977 VehicleResolverObject::VehicleResolverObject(EngineID engine_type, const Vehicle *v, bool info_view,
00978     CallbackID callback, uint32 callback_param1, uint32 callback_param2)
00979   : ResolverObject(GetEngineGrfFile(engine_type), callback, callback_param1, callback_param2),
00980   self_scope(*this, engine_type, v, info_view),
00981   parent_scope(*this, engine_type, ((v != NULL) ? v->First() : v), info_view),
00982   relative_scope(*this, engine_type, v, info_view),
00983   cached_relative_count(0)
00984 {
00985 }
00986 
00996 static const SpriteGroup *GetVehicleSpriteGroup(EngineID engine, const Vehicle *v, bool use_cache = true)
00997 {
00998   const SpriteGroup *group;
00999   CargoID cargo;
01000 
01001   if (v == NULL) {
01002     cargo = CT_PURCHASE;
01003   } else {
01004     cargo = v->cargo_type;
01005 
01006     if (v->IsGroundVehicle()) {
01007       /* For trains we always use cached value, except for callbacks because the override spriteset
01008        * to use may be different than the one cached. It happens for callback 0x15 (refit engine),
01009        * as v->cargo_type is temporary changed to the new type */
01010       if (use_cache && v->type == VEH_TRAIN) {
01011         group = Train::From(v)->tcache.cached_override;
01012       } else {
01013         group = GetWagonOverrideSpriteSet(v->engine_type, v->cargo_type, v->GetGroundVehicleCache()->first_engine);
01014       }
01015       if (group != NULL) return group;
01016     }
01017   }
01018 
01019   const Engine *e = Engine::Get(engine);
01020 
01021   assert(cargo < lengthof(e->grf_prop.spritegroup));
01022   group = e->grf_prop.spritegroup[cargo];
01023   if (group != NULL) return group;
01024 
01025   /* Fall back to the default set if the selected cargo type is not defined */
01026   return e->grf_prop.spritegroup[CT_DEFAULT];
01027 }
01028 
01029 
01030 SpriteID GetCustomEngineSprite(EngineID engine, const Vehicle *v, Direction direction, EngineImageType image_type)
01031 {
01032   VehicleResolverObject object(engine, v, false, CBID_NO_CALLBACK, image_type);
01033   const SpriteGroup *group = SpriteGroup::Resolve(GetVehicleSpriteGroup(engine, v), object);
01034   if (group == NULL || group->GetNumResults() == 0) return 0;
01035 
01036   return group->GetResult() + (direction % group->GetNumResults());
01037 }
01038 
01039 
01040 SpriteID GetRotorOverrideSprite(EngineID engine, const Aircraft *v, bool info_view, EngineImageType image_type)
01041 {
01042   const Engine *e = Engine::Get(engine);
01043 
01044   /* Only valid for helicopters */
01045   assert(e->type == VEH_AIRCRAFT);
01046   assert(!(e->u.air.subtype & AIR_CTOL));
01047 
01048   VehicleResolverObject object(engine, v, info_view, CBID_NO_CALLBACK, image_type);
01049   const SpriteGroup *group = GetWagonOverrideSpriteSet(engine, CT_DEFAULT, engine);
01050   group = SpriteGroup::Resolve(group, object);
01051 
01052   if (group == NULL || group->GetNumResults() == 0) return 0;
01053 
01054   if (v == NULL) return group->GetResult();
01055 
01056   return group->GetResult() + (info_view ? 0 : (v->Next()->Next()->state % group->GetNumResults()));
01057 }
01058 
01059 
01065 bool UsesWagonOverride(const Vehicle *v)
01066 {
01067   assert(v->type == VEH_TRAIN);
01068   return Train::From(v)->tcache.cached_override != NULL;
01069 }
01070 
01080 uint16 GetVehicleCallback(CallbackID callback, uint32 param1, uint32 param2, EngineID engine, const Vehicle *v)
01081 {
01082   VehicleResolverObject object(engine, v, false, callback, param1, param2);
01083   const SpriteGroup *group = SpriteGroup::Resolve(GetVehicleSpriteGroup(engine, v, false), object);
01084   if (group == NULL) return CALLBACK_FAILED;
01085 
01086   return group->GetCallbackResult();
01087 }
01088 
01099 uint16 GetVehicleCallbackParent(CallbackID callback, uint32 param1, uint32 param2, EngineID engine, const Vehicle *v, const Vehicle *parent)
01100 {
01101   VehicleResolverObject object(engine, v, false, callback, param1, param2);
01102   object.parent_scope.SetVehicle(parent);
01103 
01104   const SpriteGroup *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   /* We can't trigger a non-existent vehicle... */
01130   assert(v != NULL);
01131 
01132   VehicleResolverObject object(v->engine_type, v, false, CBID_RANDOM_TRIGGER);
01133   object.trigger = trigger;
01134 
01135   const SpriteGroup *group = SpriteGroup::Resolve(GetVehicleSpriteGroup(v->engine_type, v), object);
01136   if (group == NULL) return;
01137 
01138   byte new_random_bits = Random();
01139   uint32 reseed = object.GetReseedSum(); // The scope only affects triggers, not the reseeding
01140   v->random_bits &= ~reseed;
01141   v->random_bits |= (first ? new_random_bits : base_random_bits) & reseed;
01142 
01143   switch (trigger) {
01144     case VEHICLE_TRIGGER_NEW_CARGO:
01145       /* All vehicles in chain get ANY_NEW_CARGO trigger now.
01146        * So we call it for the first one and they will recurse.
01147        * Indexing part of vehicle random bits needs to be
01148        * same for all triggered vehicles in the chain (to get
01149        * all the random-cargo wagons carry the same cargo,
01150        * i.e.), so we give them all the NEW_CARGO triggered
01151        * vehicle's portion of random bits. */
01152       assert(first);
01153       DoTriggerVehicle(v->First(), VEHICLE_TRIGGER_ANY_NEW_CARGO, new_random_bits, false);
01154       break;
01155 
01156     case VEHICLE_TRIGGER_DEPOT:
01157       /* We now trigger the next vehicle in chain recursively.
01158        * The random bits portions may be different for each
01159        * vehicle in chain. */
01160       if (v->Next() != NULL) DoTriggerVehicle(v->Next(), trigger, 0, true);
01161       break;
01162 
01163     case VEHICLE_TRIGGER_EMPTY:
01164       /* We now trigger the next vehicle in chain
01165        * recursively.  The random bits portions must be same
01166        * for each vehicle in chain, so we give them all
01167        * first chained vehicle's portion of random bits. */
01168       if (v->Next() != NULL) DoTriggerVehicle(v->Next(), trigger, first ? new_random_bits : base_random_bits, false);
01169       break;
01170 
01171     case VEHICLE_TRIGGER_ANY_NEW_CARGO:
01172       /* Now pass the trigger recursively to the next vehicle
01173        * in chain. */
01174       assert(!first);
01175       if (v->Next() != NULL) DoTriggerVehicle(v->Next(), VEHICLE_TRIGGER_ANY_NEW_CARGO, base_random_bits, false);
01176       break;
01177 
01178     case VEHICLE_TRIGGER_CALLBACK_32:
01179       /* Do not do any recursion */
01180       break;
01181   }
01182 }
01183 
01184 void TriggerVehicle(Vehicle *v, VehicleTrigger trigger)
01185 {
01186   if (trigger == VEHICLE_TRIGGER_DEPOT) {
01187     /* store that the vehicle entered a depot this tick */
01188     VehicleEnteredDepotThisTick(v);
01189   }
01190 
01191   v->InvalidateNewGRFCacheOfChain();
01192   DoTriggerVehicle(v, trigger, 0, true);
01193   v->InvalidateNewGRFCacheOfChain();
01194 }
01195 
01196 /* Functions for changing the order of vehicle purchase lists */
01197 
01198 struct ListOrderChange {
01199   EngineID engine;
01200   uint target;      
01201 };
01202 
01203 static SmallVector<ListOrderChange, 16> _list_order_changes;
01204 
01211 void AlterVehicleListOrder(EngineID engine, uint target)
01212 {
01213   /* Add the list order change to a queue */
01214   ListOrderChange *loc = _list_order_changes.Append();
01215   loc->engine = engine;
01216   loc->target = target;
01217 }
01218 
01225 static int CDECL EnginePreSort(const EngineID *a, const EngineID *b)
01226 {
01227   const EngineIDMapping *id_a = _engine_mngr.Get(*a);
01228   const EngineIDMapping *id_b = _engine_mngr.Get(*b);
01229 
01230   /* 1. Sort by engine type */
01231   if (id_a->type != id_b->type) return (int)id_a->type - (int)id_b->type;
01232 
01233   /* 2. Sort by scope-GRFID */
01234   if (id_a->grfid != id_b->grfid) return id_a->grfid < id_b->grfid ? -1 : 1;
01235 
01236   /* 3. Sort by local ID */
01237   return (int)id_a->internal_id - (int)id_b->internal_id;
01238 }
01239 
01243 void CommitVehicleListOrderChanges()
01244 {
01245   /* Pre-sort engines by scope-grfid and local index */
01246   SmallVector<EngineID, 16> ordering;
01247   Engine *e;
01248   FOR_ALL_ENGINES(e) {
01249     *ordering.Append() = e->index;
01250   }
01251   QSortT(ordering.Begin(), ordering.Length(), EnginePreSort);
01252 
01253   /* Apply Insertion-Sort operations */
01254   const ListOrderChange *end = _list_order_changes.End();
01255   for (const ListOrderChange *it = _list_order_changes.Begin(); it != end; ++it) {
01256     EngineID source = it->engine;
01257     uint local_target = it->target;
01258 
01259     const EngineIDMapping *id_source = _engine_mngr.Get(source);
01260     if (id_source->internal_id == local_target) continue;
01261 
01262     EngineID target = _engine_mngr.GetID(id_source->type, local_target, id_source->grfid);
01263     if (target == INVALID_ENGINE) continue;
01264 
01265     int source_index = ordering.FindIndex(source);
01266     int target_index = ordering.FindIndex(target);
01267 
01268     assert(source_index >= 0 && target_index >= 0);
01269     assert(source_index != target_index);
01270 
01271     EngineID *list = ordering.Begin();
01272     if (source_index < target_index) {
01273       --target_index;
01274       for (int i = source_index; i < target_index; ++i) list[i] = list[i + 1];
01275       list[target_index] = source;
01276     } else {
01277       for (int i = source_index; i > target_index; --i) list[i] = list[i - 1];
01278       list[target_index] = source;
01279     }
01280   }
01281 
01282   /* Store final sort-order */
01283   const EngineID *idend = ordering.End();
01284   uint index = 0;
01285   for (const EngineID *it = ordering.Begin(); it != idend; ++it, ++index) {
01286     Engine::Get(*it)->list_position = index;
01287   }
01288 
01289   /* Clear out the queue */
01290   _list_order_changes.Reset();
01291 }
01292 
01297 void FillNewGRFVehicleCache(const Vehicle *v)
01298 {
01299   VehicleResolverObject ro(v->engine_type, v);
01300 
01301   /* These variables we have to check; these are the ones with a cache. */
01302   static const int cache_entries[][2] = {
01303     { 0x40, NCVV_POSITION_CONSIST_LENGTH },
01304     { 0x41, NCVV_POSITION_SAME_ID_LENGTH },
01305     { 0x42, NCVV_CONSIST_CARGO_INFORMATION },
01306     { 0x43, NCVV_COMPANY_INFORMATION },
01307     { 0x4D, NCVV_POSITION_IN_VEHICLE },
01308   };
01309   assert_compile(NCVV_END == lengthof(cache_entries));
01310 
01311   /* Resolve all the variables, so their caches are set. */
01312   for (size_t i = 0; i < lengthof(cache_entries); i++) {
01313     /* Only resolve when the cache isn't valid. */
01314     if (HasBit(v->grf_cache.cache_valid, cache_entries[i][1])) continue;
01315     bool stub;
01316     ro.GetScope(VSG_SCOPE_SELF)->GetVariable(cache_entries[i][0], 0, &stub);
01317   }
01318 
01319   /* Make sure really all bits are set. */
01320   assert(v->grf_cache.cache_valid == (1 << NCVV_END) - 1);
01321 }