newgrf_engine.cpp

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

Generated on Fri Apr 30 21:55:22 2010 for OpenTTD by  doxygen 1.6.1