Fix incorrect tile and trackdir in reserve through program execution
[openttd-joker.git] / src / newgrf_engine.cpp
blobb717608cbe740bb3063353aaca50ebd0f2fabc30
1 /* $Id$ */
3 /*
4 * This file is part of OpenTTD.
5 * 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.
6 * 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.
7 * 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/>.
8 */
10 /** @file newgrf_engine.cpp NewGRF handling of engines. */
12 #include "stdafx.h"
13 #include "debug.h"
14 #include "train.h"
15 #include "roadveh.h"
16 #include "company_func.h"
17 #include "newgrf_cargo.h"
18 #include "newgrf_spritegroup.h"
19 #include "date_func.h"
20 #include "vehicle_func.h"
21 #include "core/random_func.hpp"
22 #include "aircraft.h"
23 #include "station_base.h"
24 #include "company_base.h"
25 #include "newgrf_railtype.h"
26 #include "ship.h"
28 #include "safeguards.h"
30 struct WagonOverride {
31 EngineID *train_id;
32 uint trains;
33 CargoID cargo;
34 const SpriteGroup *group;
37 void SetWagonOverrideSprites(EngineID engine, CargoID cargo, const SpriteGroup *group, EngineID *train_id, uint trains)
39 Engine *e = Engine::Get(engine);
40 WagonOverride *wo;
42 assert(cargo < NUM_CARGO + 2); // Include CT_DEFAULT and CT_PURCHASE pseudo cargoes.
44 e->overrides_count++;
45 e->overrides = ReallocT(e->overrides, e->overrides_count);
47 wo = &e->overrides[e->overrides_count - 1];
48 wo->group = group;
49 wo->cargo = cargo;
50 wo->trains = trains;
51 wo->train_id = MallocT<EngineID>(trains);
52 memcpy(wo->train_id, train_id, trains * sizeof *train_id);
55 const SpriteGroup *GetWagonOverrideSpriteSet(EngineID engine, CargoID cargo, EngineID overriding_engine)
57 const Engine *e = Engine::Get(engine);
59 for (uint i = 0; i < e->overrides_count; i++) {
60 const WagonOverride *wo = &e->overrides[i];
62 if (wo->cargo != cargo && wo->cargo != CT_DEFAULT) continue;
64 for (uint j = 0; j < wo->trains; j++) {
65 if (wo->train_id[j] == overriding_engine) return wo->group;
68 return NULL;
71 /**
72 * Unload all wagon override sprite groups.
74 void UnloadWagonOverrides(Engine *e)
76 for (uint i = 0; i < e->overrides_count; i++) {
77 WagonOverride *wo = &e->overrides[i];
78 free(wo->train_id);
80 free(e->overrides);
81 e->overrides_count = 0;
82 e->overrides = NULL;
86 void SetCustomEngineSprites(EngineID engine, byte cargo, const SpriteGroup *group)
88 Engine *e = Engine::Get(engine);
89 assert(cargo < lengthof(e->grf_prop.spritegroup));
91 if (e->grf_prop.spritegroup[cargo] != NULL) {
92 grfmsg(6, "SetCustomEngineSprites: engine %d cargo %d already has group -- replacing", engine, cargo);
94 e->grf_prop.spritegroup[cargo] = group;
98 /**
99 * Tie a GRFFile entry to an engine, to allow us to retrieve GRF parameters
100 * etc during a game.
101 * @param engine Engine ID to tie the GRFFile to.
102 * @param file Pointer of GRFFile to tie.
104 void SetEngineGRF(EngineID engine, const GRFFile *file)
106 Engine *e = Engine::Get(engine);
107 e->grf_prop.grffile = file;
111 static int MapOldSubType(const Vehicle *v)
113 switch (v->type) {
114 case VEH_TRAIN:
115 if (Train::From(v)->IsEngine()) return 0;
116 if (Train::From(v)->IsFreeWagon()) return 4;
117 return 2;
118 case VEH_ROAD:
119 case VEH_SHIP: return 0;
120 case VEH_AIRCRAFT:
121 case VEH_DISASTER: return v->subtype;
122 case VEH_EFFECT: return v->subtype << 1;
123 default: NOT_REACHED();
128 /* TTDP style aircraft movement states for GRF Action 2 Var 0xE2 */
129 enum TTDPAircraftMovementStates {
130 AMS_TTDP_HANGAR,
131 AMS_TTDP_TO_HANGAR,
132 AMS_TTDP_TO_PAD1,
133 AMS_TTDP_TO_PAD2,
134 AMS_TTDP_TO_PAD3,
135 AMS_TTDP_TO_ENTRY_2_AND_3,
136 AMS_TTDP_TO_ENTRY_2_AND_3_AND_H,
137 AMS_TTDP_TO_JUNCTION,
138 AMS_TTDP_LEAVE_RUNWAY,
139 AMS_TTDP_TO_INWAY,
140 AMS_TTDP_TO_RUNWAY,
141 AMS_TTDP_TO_OUTWAY,
142 AMS_TTDP_WAITING,
143 AMS_TTDP_TAKEOFF,
144 AMS_TTDP_TO_TAKEOFF,
145 AMS_TTDP_CLIMBING,
146 AMS_TTDP_FLIGHT_APPROACH,
147 AMS_TTDP_UNUSED_0x11,
148 AMS_TTDP_FLIGHT_TO_TOWER,
149 AMS_TTDP_UNUSED_0x13,
150 AMS_TTDP_FLIGHT_FINAL,
151 AMS_TTDP_FLIGHT_DESCENT,
152 AMS_TTDP_BRAKING,
153 AMS_TTDP_HELI_TAKEOFF_AIRPORT,
154 AMS_TTDP_HELI_TO_TAKEOFF_AIRPORT,
155 AMS_TTDP_HELI_LAND_AIRPORT,
156 AMS_TTDP_HELI_TAKEOFF_HELIPORT,
157 AMS_TTDP_HELI_TO_TAKEOFF_HELIPORT,
158 AMS_TTDP_HELI_LAND_HELIPORT,
163 * Map OTTD aircraft movement states to TTDPatch style movement states
164 * (VarAction 2 Variable 0xE2)
166 static byte MapAircraftMovementState(const Aircraft *v)
168 const Station *st = GetTargetAirportIfValid(v);
169 if (st == NULL) return AMS_TTDP_FLIGHT_TO_TOWER;
171 const AirportFTAClass *afc = st->airport.GetFTA();
172 uint16 amdflag = afc->MovingData(v->pos)->flag;
174 switch (v->state) {
175 case HANGAR:
176 /* The international airport is a special case as helicopters can land in
177 * front of the hangar. Helicopters also change their air.state to
178 * AMED_HELI_LOWER some time before actually descending. */
180 /* This condition only occurs for helicopters, during descent,
181 * to a landing by the hangar of an international airport. */
182 if (amdflag & AMED_HELI_LOWER) return AMS_TTDP_HELI_LAND_AIRPORT;
184 /* This condition only occurs for helicopters, before starting descent,
185 * to a landing by the hangar of an international airport. */
186 if (amdflag & AMED_SLOWTURN) return AMS_TTDP_FLIGHT_TO_TOWER;
188 /* The final two conditions apply to helicopters or aircraft.
189 * Has reached hangar? */
190 if (amdflag & AMED_EXACTPOS) return AMS_TTDP_HANGAR;
192 /* Still moving towards hangar. */
193 return AMS_TTDP_TO_HANGAR;
195 case TERM1:
196 if (amdflag & AMED_EXACTPOS) return AMS_TTDP_TO_PAD1;
197 return AMS_TTDP_TO_JUNCTION;
199 case TERM2:
200 if (amdflag & AMED_EXACTPOS) return AMS_TTDP_TO_PAD2;
201 return AMS_TTDP_TO_ENTRY_2_AND_3_AND_H;
203 case TERM3:
204 case TERM4:
205 case TERM5:
206 case TERM6:
207 case TERM7:
208 case TERM8:
209 /* TTDPatch only has 3 terminals, so treat these states the same */
210 if (amdflag & AMED_EXACTPOS) return AMS_TTDP_TO_PAD3;
211 return AMS_TTDP_TO_ENTRY_2_AND_3_AND_H;
213 case HELIPAD1:
214 case HELIPAD2:
215 case HELIPAD3:
216 /* Will only occur for helicopters.*/
217 if (amdflag & AMED_HELI_LOWER) return AMS_TTDP_HELI_LAND_AIRPORT; // Descending.
218 if (amdflag & AMED_SLOWTURN) return AMS_TTDP_FLIGHT_TO_TOWER; // Still hasn't started descent.
219 return AMS_TTDP_TO_JUNCTION; // On the ground.
221 case TAKEOFF: // Moving to takeoff position.
222 return AMS_TTDP_TO_OUTWAY;
224 case STARTTAKEOFF: // Accelerating down runway.
225 return AMS_TTDP_TAKEOFF;
227 case ENDTAKEOFF: // Ascent
228 return AMS_TTDP_CLIMBING;
230 case HELITAKEOFF: // Helicopter is moving to take off position.
231 if (afc->delta_z == 0) {
232 return amdflag & AMED_HELI_RAISE ?
233 AMS_TTDP_HELI_TAKEOFF_AIRPORT : AMS_TTDP_TO_JUNCTION;
234 } else {
235 return AMS_TTDP_HELI_TAKEOFF_HELIPORT;
238 case FLYING:
239 return amdflag & AMED_HOLD ? AMS_TTDP_FLIGHT_APPROACH : AMS_TTDP_FLIGHT_TO_TOWER;
241 case LANDING: // Descent
242 return AMS_TTDP_FLIGHT_DESCENT;
244 case ENDLANDING: // On the runway braking
245 if (amdflag & AMED_BRAKE) return AMS_TTDP_BRAKING;
246 /* Landed - moving off runway */
247 return AMS_TTDP_TO_INWAY;
249 case HELILANDING:
250 case HELIENDLANDING: // Helicoptor is decending.
251 if (amdflag & AMED_HELI_LOWER) {
252 return afc->delta_z == 0 ?
253 AMS_TTDP_HELI_LAND_AIRPORT : AMS_TTDP_HELI_LAND_HELIPORT;
254 } else {
255 return AMS_TTDP_FLIGHT_TO_TOWER;
258 default:
259 return AMS_TTDP_HANGAR;
264 /* TTDP style aircraft movement action for GRF Action 2 Var 0xE6 */
265 enum TTDPAircraftMovementActions {
266 AMA_TTDP_IN_HANGAR,
267 AMA_TTDP_ON_PAD1,
268 AMA_TTDP_ON_PAD2,
269 AMA_TTDP_ON_PAD3,
270 AMA_TTDP_HANGAR_TO_PAD1,
271 AMA_TTDP_HANGAR_TO_PAD2,
272 AMA_TTDP_HANGAR_TO_PAD3,
273 AMA_TTDP_LANDING_TO_PAD1,
274 AMA_TTDP_LANDING_TO_PAD2,
275 AMA_TTDP_LANDING_TO_PAD3,
276 AMA_TTDP_PAD1_TO_HANGAR,
277 AMA_TTDP_PAD2_TO_HANGAR,
278 AMA_TTDP_PAD3_TO_HANGAR,
279 AMA_TTDP_PAD1_TO_TAKEOFF,
280 AMA_TTDP_PAD2_TO_TAKEOFF,
281 AMA_TTDP_PAD3_TO_TAKEOFF,
282 AMA_TTDP_HANGAR_TO_TAKOFF,
283 AMA_TTDP_LANDING_TO_HANGAR,
284 AMA_TTDP_IN_FLIGHT,
289 * Map OTTD aircraft movement states to TTDPatch style movement actions
290 * (VarAction 2 Variable 0xE6)
291 * This is not fully supported yet but it's enough for Planeset.
293 static byte MapAircraftMovementAction(const Aircraft *v)
295 switch (v->state) {
296 case HANGAR:
297 return (v->cur_speed > 0) ? AMA_TTDP_LANDING_TO_HANGAR : AMA_TTDP_IN_HANGAR;
299 case TERM1:
300 case HELIPAD1:
301 return (v->current_order.IsType(OT_LOADING)) ? AMA_TTDP_ON_PAD1 : AMA_TTDP_LANDING_TO_PAD1;
303 case TERM2:
304 case HELIPAD2:
305 return (v->current_order.IsType(OT_LOADING)) ? AMA_TTDP_ON_PAD2 : AMA_TTDP_LANDING_TO_PAD2;
307 case TERM3:
308 case TERM4:
309 case TERM5:
310 case TERM6:
311 case TERM7:
312 case TERM8:
313 case HELIPAD3:
314 return (v->current_order.IsType(OT_LOADING)) ? AMA_TTDP_ON_PAD3 : AMA_TTDP_LANDING_TO_PAD3;
316 case TAKEOFF: // Moving to takeoff position
317 case STARTTAKEOFF: // Accelerating down runway
318 case ENDTAKEOFF: // Ascent
319 case HELITAKEOFF:
320 /* @todo Need to find which terminal (or hangar) we've come from. How? */
321 return AMA_TTDP_PAD1_TO_TAKEOFF;
323 case FLYING:
324 return AMA_TTDP_IN_FLIGHT;
326 case LANDING: // Descent
327 case ENDLANDING: // On the runway braking
328 case HELILANDING:
329 case HELIENDLANDING:
330 /* @todo Need to check terminal we're landing to. Is it known yet? */
331 return (v->current_order.IsType(OT_GOTO_DEPOT)) ?
332 AMA_TTDP_LANDING_TO_HANGAR : AMA_TTDP_LANDING_TO_PAD1;
334 default:
335 return AMA_TTDP_IN_HANGAR;
340 /* virtual */ uint32 VehicleScopeResolver::GetRandomBits() const
342 return this->v == NULL ? 0 : this->v->random_bits;
345 /* virtual */ uint32 VehicleScopeResolver::GetTriggers() const
347 return this->v == NULL ? 0 : this->v->waiting_triggers;
351 /* virtual */ ScopeResolver *VehicleResolverObject::GetScope(VarSpriteGroupScope scope, byte relative)
353 switch (scope) {
354 case VSG_SCOPE_SELF: return &this->self_scope;
355 case VSG_SCOPE_PARENT: return &this->parent_scope;
356 case VSG_SCOPE_RELATIVE: {
357 int32 count = GB(relative, 0, 4);
358 if (this->self_scope.v != NULL && (relative != this->cached_relative_count || count == 0)) {
359 /* Note: This caching only works as long as the VSG_SCOPE_RELATIVE cannot be used in
360 * VarAct2 with procedure calls. */
361 if (count == 0) count = GetRegister(0x100);
363 const Vehicle *v = NULL;
364 switch (GB(relative, 6, 2)) {
365 default: NOT_REACHED();
366 case 0x00: // count back (away from the engine), starting at this vehicle
367 v = this->self_scope.v;
368 break;
369 case 0x01: // count forward (toward the engine), starting at this vehicle
370 v = this->self_scope.v;
371 count = -count;
372 break;
373 case 0x02: // count back, starting at the engine
374 v = this->parent_scope.v;
375 break;
376 case 0x03: { // count back, starting at the first vehicle in this chain of vehicles with the same ID, as for vehicle variable 41
377 const Vehicle *self = this->self_scope.v;
378 for (const Vehicle *u = self->First(); u != self; u = u->Next()) {
379 if (u->engine_type != self->engine_type) {
380 v = NULL;
381 } else {
382 if (v == NULL) v = u;
385 if (v == NULL) v = self;
386 break;
389 this->relative_scope.SetVehicle(v->Move(count));
391 return &this->relative_scope;
393 default: return ResolverObject::GetScope(scope, relative);
398 * Determines the livery of an engine.
400 * This always uses dual company colours independent of GUI settings. So it is desync-safe.
402 * @param engine Engine type
403 * @param v Vehicle, NULL in purchase list.
404 * @return Livery to use
406 static const Livery *LiveryHelper(EngineID engine, const Vehicle *v)
408 const Livery *l;
410 if (v == NULL) {
411 if (!Company::IsValidID(_current_company)) return NULL;
412 l = GetEngineLivery(engine, _current_company, INVALID_ENGINE, NULL, LIT_ALL);
413 } else if (v->IsGroundVehicle()) {
414 l = GetEngineLivery(v->engine_type, v->owner, v->GetGroundVehicleCache()->first_engine, v, LIT_ALL);
415 } else {
416 l = GetEngineLivery(v->engine_type, v->owner, INVALID_ENGINE, v, LIT_ALL);
419 return l;
423 * Helper to get the position of a vehicle within a chain of vehicles.
424 * @param v the vehicle to get the position of.
425 * @param consecutive whether to look at the whole chain or the vehicles
426 * with the same 'engine type'.
427 * @return the position in the chain from front and tail and chain length.
429 static uint32 PositionHelper(const Vehicle *v, bool consecutive)
431 const Vehicle *u;
432 byte chain_before = 0;
433 byte chain_after = 0;
435 for (u = v->First(); u != v; u = u->Next()) {
436 chain_before++;
437 if (consecutive && u->engine_type != v->engine_type) chain_before = 0;
440 while (u->Next() != NULL && (!consecutive || u->Next()->engine_type == v->engine_type)) {
441 chain_after++;
442 u = u->Next();
445 return chain_before | chain_after << 8 | (chain_before + chain_after + consecutive) << 16;
448 static uint32 VehicleGetVariable(Vehicle *v, const VehicleScopeResolver *object, byte variable, uint32 parameter, bool *available)
450 /* Calculated vehicle parameters */
451 switch (variable) {
452 case 0x25: // Get engine GRF ID
453 return v->GetGRFID();
455 case 0x40: // Get length of consist
456 if (!HasBit(v->grf_cache.cache_valid, NCVV_POSITION_CONSIST_LENGTH)) {
457 v->grf_cache.position_consist_length = PositionHelper(v, false);
458 SetBit(v->grf_cache.cache_valid, NCVV_POSITION_CONSIST_LENGTH);
460 return v->grf_cache.position_consist_length;
462 case 0x41: // Get length of same consecutive wagons
463 if (!HasBit(v->grf_cache.cache_valid, NCVV_POSITION_SAME_ID_LENGTH)) {
464 v->grf_cache.position_same_id_length = PositionHelper(v, true);
465 SetBit(v->grf_cache.cache_valid, NCVV_POSITION_SAME_ID_LENGTH);
467 return v->grf_cache.position_same_id_length;
469 case 0x42: { // Consist cargo information
470 if (!HasBit(v->grf_cache.cache_valid, NCVV_CONSIST_CARGO_INFORMATION)) {
471 const Vehicle *u;
472 byte cargo_classes = 0;
473 uint8 common_cargoes[NUM_CARGO];
474 uint8 common_subtypes[256];
475 byte user_def_data = 0;
476 CargoID common_cargo_type = CT_INVALID;
477 uint8 common_subtype = 0xFF; // Return 0xFF if nothing is carried
479 /* Reset our arrays */
480 memset(common_cargoes, 0, sizeof(common_cargoes));
481 memset(common_subtypes, 0, sizeof(common_subtypes));
483 for (u = v; u != NULL; u = u->Next()) {
484 if (v->type == VEH_TRAIN) user_def_data |= Train::From(u)->tcache.user_def_data;
486 /* Skip empty engines */
487 if (!u->GetEngine()->CanCarryCargo()) continue;
489 cargo_classes |= CargoSpec::Get(u->cargo_type)->classes;
490 common_cargoes[u->cargo_type]++;
493 /* Pick the most common cargo type */
494 uint common_cargo_best_amount = 0;
495 for (CargoID cargo = 0; cargo < NUM_CARGO; cargo++) {
496 if (common_cargoes[cargo] > common_cargo_best_amount) {
497 common_cargo_best_amount = common_cargoes[cargo];
498 common_cargo_type = cargo;
502 /* Count subcargo types of common_cargo_type */
503 for (u = v; u != NULL; u = u->Next()) {
504 /* Skip empty engines and engines not carrying common_cargo_type */
505 if (u->cargo_type != common_cargo_type || !u->GetEngine()->CanCarryCargo()) continue;
507 common_subtypes[u->cargo_subtype]++;
510 /* Pick the most common subcargo type*/
511 uint common_subtype_best_amount = 0;
512 for (uint i = 0; i < lengthof(common_subtypes); i++) {
513 if (common_subtypes[i] > common_subtype_best_amount) {
514 common_subtype_best_amount = common_subtypes[i];
515 common_subtype = i;
519 /* Note: We have to store the untranslated cargotype in the cache as the cache can be read by different NewGRFs,
520 * which will need different translations */
521 v->grf_cache.consist_cargo_information = cargo_classes | (common_cargo_type << 8) | (common_subtype << 16) | (user_def_data << 24);
522 SetBit(v->grf_cache.cache_valid, NCVV_CONSIST_CARGO_INFORMATION);
525 /* The cargo translation is specific to the accessing GRF, and thus cannot be cached. */
526 CargoID common_cargo_type = (v->grf_cache.consist_cargo_information >> 8) & 0xFF;
528 /* Note:
529 * - Unlike everywhere else the cargo translation table is only used since grf version 8, not 7.
530 * - For translating the cargo type we need to use the GRF which is resolving the variable, which
531 * is object->ro.grffile.
532 * In case of CBID_TRAIN_ALLOW_WAGON_ATTACH this is not the same as v->GetGRF().
533 * - The grffile == NULL case only happens if this function is called for default vehicles.
534 * And this is only done by CheckCaches().
536 const GRFFile *grffile = object->ro.grffile;
537 uint8 common_bitnum = (common_cargo_type == CT_INVALID) ? 0xFF :
538 (grffile == NULL || grffile->grf_version < 8) ? CargoSpec::Get(common_cargo_type)->bitnum : grffile->cargo_map[common_cargo_type];
540 return (v->grf_cache.consist_cargo_information & 0xFFFF00FF) | common_bitnum << 8;
543 case 0x43: // Company information
544 if (!HasBit(v->grf_cache.cache_valid, NCVV_COMPANY_INFORMATION)) {
545 v->grf_cache.company_information = GetCompanyInfo(v->owner, LiveryHelper(v->engine_type, v));
546 SetBit(v->grf_cache.cache_valid, NCVV_COMPANY_INFORMATION);
548 return v->grf_cache.company_information;
550 case 0x44: // Aircraft information
551 if (v->type != VEH_AIRCRAFT || !Aircraft::From(v)->IsNormalAircraft()) return UINT_MAX;
554 const Vehicle *w = v->Next();
555 uint16 altitude = ClampToU16(v->z_pos - w->z_pos); // Aircraft height - shadow height
556 byte airporttype = ATP_TTDP_LARGE;
558 const Station *st = GetTargetAirportIfValid(Aircraft::From(v));
560 if (st != NULL && st->airport.tile != INVALID_TILE) {
561 airporttype = st->airport.GetSpec()->ttd_airport_type;
564 return (Clamp(altitude, 0, 0xFF) << 8) | airporttype;
567 case 0x45: { // Curvature info
568 /* Format: xxxTxBxF
569 * F - previous wagon to current wagon, 0 if vehicle is first
570 * B - current wagon to next wagon, 0 if wagon is last
571 * T - previous wagon to next wagon, 0 in an S-bend
573 if (!v->IsGroundVehicle()) return 0;
575 const Vehicle *u_p = v->Previous();
576 const Vehicle *u_n = v->Next();
577 DirDiff f = (u_p == NULL) ? DIRDIFF_SAME : DirDifference(u_p->direction, v->direction);
578 DirDiff b = (u_n == NULL) ? DIRDIFF_SAME : DirDifference(v->direction, u_n->direction);
579 DirDiff t = ChangeDirDiff(f, b);
581 return ((t > DIRDIFF_REVERSE ? t | 8 : t) << 16) |
582 ((b > DIRDIFF_REVERSE ? b | 8 : b) << 8) |
583 ( f > DIRDIFF_REVERSE ? f | 8 : f);
586 case 0x46: // Motion counter
587 return v->motion_counter;
589 case 0x47: { // Vehicle cargo info
590 /* Format: ccccwwtt
591 * tt - the cargo type transported by the vehicle,
592 * translated if a translation table has been installed.
593 * ww - cargo unit weight in 1/16 tons, same as cargo prop. 0F.
594 * cccc - the cargo class value of the cargo transported by the vehicle.
596 const CargoSpec *cs = CargoSpec::Get(v->cargo_type);
598 /* Note:
599 * For translating the cargo type we need to use the GRF which is resolving the variable, which
600 * is object->ro.grffile.
601 * In case of CBID_TRAIN_ALLOW_WAGON_ATTACH this is not the same as v->GetGRF().
603 return (cs->classes << 16) | (cs->weight << 8) | object->ro.grffile->cargo_map[v->cargo_type];
606 case 0x48: return v->GetEngine()->flags; // Vehicle Type Info
607 case 0x49: return v->build_year;
609 case 0x4A: {
610 if (v->type != VEH_TRAIN) return 0;
611 if (Train::From(v)->IsVirtual()) return 0x1FF;
612 RailType rt = GetTileRailType(v->tile);
613 return (HasPowerOnRail(Train::From(v)->railtype, rt) ? 0x100 : 0) | GetReverseRailTypeTranslation(rt, object->ro.grffile);
616 case 0x4B: // Long date of last service
617 return v->date_of_last_service;
619 case 0x4C: // Current maximum speed in NewGRF units
620 if (!v->IsPrimaryVehicle()) return 0;
621 return v->GetCurrentMaxSpeed();
623 case 0x4D: // Position within articulated vehicle
624 if (!HasBit(v->grf_cache.cache_valid, NCVV_POSITION_IN_VEHICLE)) {
625 byte artic_before = 0;
626 for (const Vehicle *u = v; u->IsArticulatedPart(); u = u->Previous()) artic_before++;
627 byte artic_after = 0;
628 for (const Vehicle *u = v; u->HasArticulatedPart(); u = u->Next()) artic_after++;
629 v->grf_cache.position_in_vehicle = artic_before | artic_after << 8;
630 SetBit(v->grf_cache.cache_valid, NCVV_POSITION_IN_VEHICLE);
632 return v->grf_cache.position_in_vehicle;
634 /* Variables which use the parameter */
635 case 0x60: // Count consist's engine ID occurrence
636 if (v->type != VEH_TRAIN) return v->GetEngine()->grf_prop.local_id == parameter ? 1 : 0;
639 uint count = 0;
640 for (; v != NULL; v = v->Next()) {
641 if (v->GetEngine()->grf_prop.local_id == parameter) count++;
643 return count;
646 case 0x61: // Get variable of n-th vehicle in chain [signed number relative to vehicle]
647 if (!v->IsGroundVehicle() || parameter == 0x61) {
648 /* Not available */
649 break;
652 /* Only allow callbacks that don't change properties to avoid circular dependencies. */
653 if (object->ro.callback == CBID_NO_CALLBACK || object->ro.callback == CBID_RANDOM_TRIGGER || object->ro.callback == CBID_TRAIN_ALLOW_WAGON_ATTACH ||
654 object->ro.callback == CBID_VEHICLE_START_STOP_CHECK || object->ro.callback == CBID_VEHICLE_32DAY_CALLBACK || object->ro.callback == CBID_VEHICLE_COLOUR_MAPPING ||
655 object->ro.callback == CBID_VEHICLE_SPAWN_VISUAL_EFFECT) {
656 Vehicle *u = v->Move((int32)GetRegister(0x10F));
657 if (u == NULL) return 0; // available, but zero
659 if (parameter == 0x5F) {
660 /* This seems to be the only variable that makes sense to access via var 61, but is not handled by VehicleGetVariable */
661 return (u->random_bits << 8) | u->waiting_triggers;
662 } else {
663 return VehicleGetVariable(u, object, parameter, GetRegister(0x10E), available);
666 /* Not available */
667 break;
669 case 0x62: { // Curvature/position difference for n-th vehicle in chain [signed number relative to vehicle]
670 /* Format: zzyyxxFD
671 * zz - Signed difference of z position between the selected and this vehicle.
672 * yy - Signed difference of y position between the selected and this vehicle.
673 * xx - Signed difference of x position between the selected and this vehicle.
674 * F - Flags, bit 7 corresponds to VS_HIDDEN.
675 * D - Dir difference, like in 0x45.
677 if (!v->IsGroundVehicle()) return 0;
679 const Vehicle *u = v->Move((int8)parameter);
680 if (u == NULL) return 0;
682 /* Get direction difference. */
683 bool prev = (int8)parameter < 0;
684 uint32 ret = prev ? DirDifference(u->direction, v->direction) : DirDifference(v->direction, u->direction);
685 if (ret > DIRDIFF_REVERSE) ret |= 0x08;
687 if (u->vehstatus & VS_HIDDEN) ret |= 0x80;
689 /* Get position difference. */
690 ret |= ((prev ? u->x_pos - v->x_pos : v->x_pos - u->x_pos) & 0xFF) << 8;
691 ret |= ((prev ? u->y_pos - v->y_pos : v->y_pos - u->y_pos) & 0xFF) << 16;
692 ret |= ((prev ? u->z_pos - v->z_pos : v->z_pos - u->z_pos) & 0xFF) << 24;
694 return ret;
697 case 0xFE:
698 case 0xFF: {
699 uint16 modflags = 0;
701 if (v->type == VEH_TRAIN) {
702 const Train *t = Train::From(v);
703 bool is_powered_wagon = HasBit(t->flags, VRF_POWEREDWAGON);
704 const Train *u = is_powered_wagon ? t->First() : t; // for powered wagons the engine defines the type of engine (i.e. railtype)
705 bool powered = t->IsEngine() || is_powered_wagon;
706 bool has_power;
707 if (u->IsVirtual()) {
708 has_power = true;
709 } else {
710 RailType railtype = GetRailType(v->tile);
711 has_power = HasPowerOnRail(u->railtype, railtype);
714 if (powered && has_power) SetBit(modflags, 5);
715 if (powered && !has_power) SetBit(modflags, 6);
716 if (HasBit(t->flags, VRF_TOGGLE_REVERSE)) SetBit(modflags, 8);
718 if (HasBit(v->vehicle_flags, VF_CARGO_UNLOADING)) SetBit(modflags, 1);
719 if (HasBit(v->vehicle_flags, VF_BUILT_AS_PROTOTYPE)) SetBit(modflags, 10);
721 return variable == 0xFE ? modflags : GB(modflags, 8, 8);
725 /* General vehicle properties */
726 switch (variable - 0x80) {
727 case 0x00: return v->type + 0x10;
728 case 0x01: return MapOldSubType(v);
729 case 0x04: return v->index;
730 case 0x05: return GB(v->index, 8, 8);
731 case 0x0A: return v->current_order.MapOldOrder();
732 case 0x0B: return v->current_order.GetDestination();
733 case 0x0C: return v->GetNumOrders();
734 case 0x0D: return v->cur_real_order_index;
735 case 0x10:
736 case 0x11: {
737 uint ticks;
738 if (v->current_order.IsType(OT_LOADING)) {
739 ticks = v->load_unload_ticks;
740 } else {
741 switch (v->type) {
742 case VEH_TRAIN: ticks = Train::From(v)->wait_counter; break;
743 case VEH_AIRCRAFT: ticks = Aircraft::From(v)->turn_counter; break;
744 default: ticks = 0; break;
747 return (variable - 0x80) == 0x10 ? ticks : GB(ticks, 8, 8);
749 case 0x12: return Clamp(v->date_of_last_service - DAYS_TILL_ORIGINAL_BASE_YEAR, 0, 0xFFFF);
750 case 0x13: return GB(Clamp(v->date_of_last_service - DAYS_TILL_ORIGINAL_BASE_YEAR, 0, 0xFFFF), 8, 8);
751 case 0x14: return v->GetServiceInterval();
752 case 0x15: return GB(v->GetServiceInterval(), 8, 8);
753 case 0x16: return v->last_station_visited;
754 case 0x17: return v->tick_counter;
755 case 0x18:
756 case 0x19: {
757 uint max_speed;
758 switch (v->type) {
759 case VEH_AIRCRAFT:
760 max_speed = Aircraft::From(v)->GetSpeedOldUnits(); // Convert to old units.
761 break;
763 default:
764 max_speed = v->vcache.cached_max_speed;
765 break;
767 return (variable - 0x80) == 0x18 ? max_speed : GB(max_speed, 8, 8);
769 case 0x1A: return v->x_pos;
770 case 0x1B: return GB(v->x_pos, 8, 8);
771 case 0x1C: return v->y_pos;
772 case 0x1D: return GB(v->y_pos, 8, 8);
773 case 0x1E: return v->z_pos;
774 case 0x1F: return object->info_view ? DIR_W : v->direction;
775 case 0x28: return 0; // cur_image is a potential desyncer due to Action1 in static NewGRFs.
776 case 0x29: return 0; // cur_image is a potential desyncer due to Action1 in static NewGRFs.
777 case 0x32: return v->vehstatus;
778 case 0x33: return 0; // non-existent high byte of vehstatus
779 case 0x34: return v->type == VEH_AIRCRAFT ? (v->cur_speed * 10) / 128 : v->cur_speed;
780 case 0x35: return GB(v->type == VEH_AIRCRAFT ? (v->cur_speed * 10) / 128 : v->cur_speed, 8, 8);
781 case 0x36: return v->subspeed;
782 case 0x37: return v->acceleration;
783 case 0x39: return v->cargo_type;
784 case 0x3A: return v->cargo_cap;
785 case 0x3B: return GB(v->cargo_cap, 8, 8);
786 case 0x3C: return ClampToU16(v->cargo.StoredCount());
787 case 0x3D: return GB(ClampToU16(v->cargo.StoredCount()), 8, 8);
788 case 0x3E: return v->cargo.Source();
789 case 0x3F: return ClampU(v->cargo.DaysInTransit(), 0, 0xFF);
790 case 0x40: return ClampToU16(v->age);
791 case 0x41: return GB(ClampToU16(v->age), 8, 8);
792 case 0x42: return ClampToU16(v->max_age);
793 case 0x43: return GB(ClampToU16(v->max_age), 8, 8);
794 case 0x44: return Clamp(v->build_year, ORIGINAL_BASE_YEAR, ORIGINAL_MAX_YEAR) - ORIGINAL_BASE_YEAR;
795 case 0x45: return v->unitnumber;
796 case 0x46: return v->GetEngine()->grf_prop.local_id;
797 case 0x47: return GB(v->GetEngine()->grf_prop.local_id, 8, 8);
798 case 0x48:
799 if (v->type != VEH_TRAIN || v->spritenum != 0xFD) return v->spritenum;
800 return HasBit(Train::From(v)->flags, VRF_REVERSE_DIRECTION) ? 0xFE : 0xFD;
802 case 0x49: return v->day_counter;
803 case 0x4A: return v->breakdowns_since_last_service;
804 case 0x4B: return v->breakdown_ctr;
805 case 0x4C: return v->breakdown_delay;
806 case 0x4D: return v->breakdown_chance;
807 case 0x4E: return v->reliability;
808 case 0x4F: return GB(v->reliability, 8, 8);
809 case 0x50: return v->reliability_spd_dec;
810 case 0x51: return GB(v->reliability_spd_dec, 8, 8);
811 case 0x52: return ClampToI32(v->GetDisplayProfitThisYear());
812 case 0x53: return GB(ClampToI32(v->GetDisplayProfitThisYear()), 8, 24);
813 case 0x54: return GB(ClampToI32(v->GetDisplayProfitThisYear()), 16, 16);
814 case 0x55: return GB(ClampToI32(v->GetDisplayProfitThisYear()), 24, 8);
815 case 0x56: return ClampToI32(v->GetDisplayProfitLastYear());
816 case 0x57: return GB(ClampToI32(v->GetDisplayProfitLastYear()), 8, 24);
817 case 0x58: return GB(ClampToI32(v->GetDisplayProfitLastYear()), 16, 16);
818 case 0x59: return GB(ClampToI32(v->GetDisplayProfitLastYear()), 24, 8);
819 case 0x5A: return v->Next() == NULL ? INVALID_VEHICLE : v->Next()->index;
820 case 0x5C: return ClampToI32(v->value);
821 case 0x5D: return GB(ClampToI32(v->value), 8, 24);
822 case 0x5E: return GB(ClampToI32(v->value), 16, 16);
823 case 0x5F: return GB(ClampToI32(v->value), 24, 8);
824 case 0x72: return v->cargo_subtype;
825 case 0x7A: return v->random_bits;
826 case 0x7B: return v->waiting_triggers;
829 /* Vehicle specific properties */
830 switch (v->type) {
831 case VEH_TRAIN: {
832 Train *t = Train::From(v);
833 switch (variable - 0x80) {
834 case 0x62: return t->track;
835 case 0x66: return t->railtype;
836 case 0x73: return 0x80 + VEHICLE_LENGTH - t->gcache.cached_veh_length;
837 case 0x74: return t->gcache.cached_power;
838 case 0x75: return GB(t->gcache.cached_power, 8, 24);
839 case 0x76: return GB(t->gcache.cached_power, 16, 16);
840 case 0x77: return GB(t->gcache.cached_power, 24, 8);
841 case 0x7C: return t->First()->index;
842 case 0x7D: return GB(t->First()->index, 8, 8);
843 case 0x7F: return 0; // Used for vehicle reversing hack in TTDP
845 break;
848 case VEH_ROAD: {
849 RoadVehicle *rv = RoadVehicle::From(v);
850 switch (variable - 0x80) {
851 case 0x62: return rv->state;
852 case 0x64: return rv->blocked_ctr;
853 case 0x65: return GB(rv->blocked_ctr, 8, 8);
854 case 0x66: return rv->overtaking;
855 case 0x67: return rv->overtaking_ctr;
856 case 0x68: return rv->crashed_ctr;
857 case 0x69: return GB(rv->crashed_ctr, 8, 8);
859 break;
862 case VEH_SHIP: {
863 Ship *s = Ship::From(v);
864 switch (variable - 0x80) {
865 case 0x62: return s->state;
867 break;
870 case VEH_AIRCRAFT: {
871 Aircraft *a = Aircraft::From(v);
872 switch (variable - 0x80) {
873 case 0x62: return MapAircraftMovementState(a); // Current movement state
874 case 0x63: return a->targetairport; // Airport to which the action refers
875 case 0x66: return MapAircraftMovementAction(a); // Current movement action
877 break;
880 default: break;
883 DEBUG(grf, 1, "Unhandled vehicle variable 0x%X, type 0x%X", variable, (uint)v->type);
885 *available = false;
886 return UINT_MAX;
889 /* virtual */ uint32 VehicleScopeResolver::GetVariable(byte variable, uint32 parameter, bool *available) const
891 if (this->v == NULL) {
892 /* Vehicle does not exist, so we're in a purchase list */
893 switch (variable) {
894 case 0x43: return GetCompanyInfo(_current_company, LiveryHelper(this->self_type, NULL)); // Owner information
895 case 0x46: return 0; // Motion counter
896 case 0x47: { // Vehicle cargo info
897 const Engine *e = Engine::Get(this->self_type);
898 CargoID cargo_type = e->GetDefaultCargoType();
899 if (cargo_type != CT_INVALID) {
900 const CargoSpec *cs = CargoSpec::Get(cargo_type);
901 return (cs->classes << 16) | (cs->weight << 8) | this->ro.grffile->cargo_map[cargo_type];
902 } else {
903 return 0x000000FF;
906 case 0x48: return Engine::Get(this->self_type)->flags; // Vehicle Type Info
907 case 0x49: return _cur_year; // 'Long' format build year
908 case 0x4B: return _date; // Long date of last service
909 case 0x92: return Clamp(_date - DAYS_TILL_ORIGINAL_BASE_YEAR, 0, 0xFFFF); // Date of last service
910 case 0x93: return GB(Clamp(_date - DAYS_TILL_ORIGINAL_BASE_YEAR, 0, 0xFFFF), 8, 8);
911 case 0xC4: return Clamp(_cur_year, ORIGINAL_BASE_YEAR, ORIGINAL_MAX_YEAR) - ORIGINAL_BASE_YEAR; // Build year
912 case 0xDA: return INVALID_VEHICLE; // Next vehicle
913 case 0xF2: return 0; // Cargo subtype
916 *available = false;
917 return UINT_MAX;
920 return VehicleGetVariable(const_cast<Vehicle*>(this->v), this, variable, parameter, available);
924 /* virtual */ const SpriteGroup *VehicleResolverObject::ResolveReal(const RealSpriteGroup *group) const
926 const Vehicle *v = this->self_scope.v;
928 if (v == NULL) {
929 if (group->num_loading > 0) return group->loading[0];
930 if (group->num_loaded > 0) return group->loaded[0];
931 return NULL;
934 bool in_motion = !v->First()->current_order.IsType(OT_LOADING);
936 uint totalsets = in_motion ? group->num_loaded : group->num_loading;
938 if (totalsets == 0) return NULL;
940 uint set = (v->cargo.StoredCount() * totalsets) / max((uint16)1, v->cargo_cap);
941 set = min(set, totalsets - 1);
943 return in_motion ? group->loaded[set] : group->loading[set];
947 * Get the grf file associated with an engine type.
948 * @param engine_type Engine to query.
949 * @return grf file associated with the engine.
951 static const GRFFile *GetEngineGrfFile(EngineID engine_type)
953 const Engine *e = Engine::Get(engine_type);
954 return (e != NULL) ? e->GetGRF() : NULL;
958 * Resolver of a vehicle (chain).
959 * @param engine_type Engine type
960 * @param v %Vehicle being resolved.
961 * @param wagon_override Application of wagon overrides.
962 * @param info_view Indicates if the item is being drawn in an info window.
963 * @param callback Callback ID.
964 * @param callback_param1 First parameter (var 10) of the callback.
965 * @param callback_param2 Second parameter (var 18) of the callback.
967 VehicleResolverObject::VehicleResolverObject(EngineID engine_type, const Vehicle *v, WagonOverride wagon_override, bool info_view,
968 CallbackID callback, uint32 callback_param1, uint32 callback_param2)
969 : ResolverObject(GetEngineGrfFile(engine_type), callback, callback_param1, callback_param2),
970 self_scope(*this, engine_type, v, info_view),
971 parent_scope(*this, engine_type, ((v != NULL) ? v->First() : v), info_view),
972 relative_scope(*this, engine_type, v, info_view),
973 cached_relative_count(0)
975 if (wagon_override == WO_SELF) {
976 this->root_spritegroup = GetWagonOverrideSpriteSet(engine_type, CT_DEFAULT, engine_type);
977 } else {
978 if (wagon_override != WO_NONE && v != NULL && v->IsGroundVehicle()) {
979 assert(v->engine_type == engine_type); // overrides make little sense with fake scopes
981 /* For trains we always use cached value, except for callbacks because the override spriteset
982 * to use may be different than the one cached. It happens for callback 0x15 (refit engine),
983 * as v->cargo_type is temporary changed to the new type */
984 if (wagon_override == WO_CACHED && v->type == VEH_TRAIN) {
985 this->root_spritegroup = Train::From(v)->tcache.cached_override;
986 } else {
987 this->root_spritegroup = GetWagonOverrideSpriteSet(v->engine_type, v->cargo_type, v->GetGroundVehicleCache()->first_engine);
991 if (this->root_spritegroup == NULL) {
992 const Engine *e = Engine::Get(engine_type);
993 CargoID cargo = v != NULL ? v->cargo_type : CT_PURCHASE;
994 assert(cargo < lengthof(e->grf_prop.spritegroup));
995 this->root_spritegroup = e->grf_prop.spritegroup[cargo] != NULL ? e->grf_prop.spritegroup[cargo] : e->grf_prop.spritegroup[CT_DEFAULT];
1002 void GetCustomEngineSprite(EngineID engine, const Vehicle *v, Direction direction, EngineImageType image_type, VehicleSpriteSeq *result)
1004 VehicleResolverObject object(engine, v, VehicleResolverObject::WO_CACHED, false, CBID_NO_CALLBACK);
1005 result->Clear();
1007 bool sprite_stack = HasBit(EngInfo(engine)->misc_flags, EF_SPRITE_STACK);
1008 uint max_stack = sprite_stack ? lengthof(result->seq) : 1;
1009 for (uint stack = 0; stack < max_stack; ++stack) {
1010 object.ResetState();
1011 object.callback_param1 = image_type | (stack << 8);
1012 const SpriteGroup *group = object.Resolve();
1013 uint32 reg100 = sprite_stack ? GetRegister(0x100) : 0;
1014 if (group != NULL && group->GetNumResults() != 0) {
1015 result->seq[result->count].sprite = group->GetResult() + (direction % group->GetNumResults());
1016 result->seq[result->count].pal = GB(reg100, 0, 16); // zero means default recolouring
1017 result->count++;
1019 if (!HasBit(reg100, 31)) break;
1024 void GetRotorOverrideSprite(EngineID engine, const struct Aircraft *v, bool info_view, EngineImageType image_type, VehicleSpriteSeq *result)
1026 const Engine *e = Engine::Get(engine);
1028 /* Only valid for helicopters */
1029 assert(e->type == VEH_AIRCRAFT);
1030 assert(!(e->u.air.subtype & AIR_CTOL));
1032 VehicleResolverObject object(engine, v, VehicleResolverObject::WO_SELF, info_view, CBID_NO_CALLBACK);
1033 result->Clear();
1034 uint rotor_pos = v == NULL || info_view ? 0 : v->Next()->Next()->state;
1036 bool sprite_stack = HasBit(e->info.misc_flags, EF_SPRITE_STACK);
1037 uint max_stack = sprite_stack ? lengthof(result->seq) : 1;
1038 for (uint stack = 0; stack < max_stack; ++stack) {
1039 object.ResetState();
1040 object.callback_param1 = image_type | (stack << 8);
1041 const SpriteGroup *group = object.Resolve();
1042 uint32 reg100 = sprite_stack ? GetRegister(0x100) : 0;
1043 if (group != NULL && group->GetNumResults() != 0) {
1044 result->seq[result->count].sprite = group->GetResult() + (rotor_pos % group->GetNumResults());
1045 result->seq[result->count].pal = GB(reg100, 0, 16); // zero means default recolouring
1046 result->count++;
1048 if (!HasBit(reg100, 31)) break;
1053 * Check if a wagon is currently using a wagon override
1054 * @param v The wagon to check
1055 * @return true if it is using an override, false otherwise
1057 bool UsesWagonOverride(const Vehicle *v)
1059 assert(v->type == VEH_TRAIN);
1060 return Train::From(v)->tcache.cached_override != NULL;
1064 * Evaluate a newgrf callback for vehicles
1065 * @param callback The callback to evaluate
1066 * @param param1 First parameter of the callback
1067 * @param param2 Second parameter of the callback
1068 * @param engine Engine type of the vehicle to evaluate the callback for
1069 * @param v The vehicle to evaluate the callback for, or NULL if it doesnt exist yet
1070 * @return The value the callback returned, or CALLBACK_FAILED if it failed
1072 uint16 GetVehicleCallback(CallbackID callback, uint32 param1, uint32 param2, EngineID engine, const Vehicle *v)
1074 VehicleResolverObject object(engine, v, VehicleResolverObject::WO_UNCACHED, false, callback, param1, param2);
1075 return object.ResolveCallback();
1079 * Evaluate a newgrf callback for vehicles with a different vehicle for parent scope.
1080 * @param callback The callback to evaluate
1081 * @param param1 First parameter of the callback
1082 * @param param2 Second parameter of the callback
1083 * @param engine Engine type of the vehicle to evaluate the callback for
1084 * @param v The vehicle to evaluate the callback for, or NULL if it doesn't exist yet
1085 * @param parent The vehicle to use for parent scope
1086 * @return The value the callback returned, or CALLBACK_FAILED if it failed
1088 uint16 GetVehicleCallbackParent(CallbackID callback, uint32 param1, uint32 param2, EngineID engine, const Vehicle *v, const Vehicle *parent)
1090 VehicleResolverObject object(engine, v, VehicleResolverObject::WO_NONE, false, callback, param1, param2);
1091 object.parent_scope.SetVehicle(parent);
1092 return object.ResolveCallback();
1096 /* Callback 36 handlers */
1097 uint GetVehicleProperty(const Vehicle *v, PropertyID property, uint orig_value)
1099 return GetEngineProperty(v->engine_type, property, orig_value, v);
1103 uint GetEngineProperty(EngineID engine, PropertyID property, uint orig_value, const Vehicle *v)
1105 uint16 callback = GetVehicleCallback(CBID_VEHICLE_MODIFY_PROPERTY, property, 0, engine, v);
1106 if (callback != CALLBACK_FAILED) return callback;
1108 return orig_value;
1112 static void DoTriggerVehicle(Vehicle *v, VehicleTrigger trigger, byte base_random_bits, bool first)
1114 /* We can't trigger a non-existent vehicle... */
1115 assert(v != NULL);
1117 VehicleResolverObject object(v->engine_type, v, VehicleResolverObject::WO_CACHED, false, CBID_RANDOM_TRIGGER);
1118 object.waiting_triggers = v->waiting_triggers | trigger;
1119 v->waiting_triggers = object.waiting_triggers; // store now for var 5F
1121 const SpriteGroup *group = object.Resolve();
1122 if (group == NULL) return;
1124 /* Store remaining triggers. */
1125 v->waiting_triggers = object.GetRemainingTriggers();
1127 /* Rerandomise bits. Scopes other than SELF are invalid for rerandomisation. For bug-to-bug-compatibility with TTDP we ignore the scope. */
1128 byte new_random_bits = Random();
1129 uint32 reseed = object.GetReseedSum();
1130 v->random_bits &= ~reseed;
1131 v->random_bits |= (first ? new_random_bits : base_random_bits) & reseed;
1133 switch (trigger) {
1134 case VEHICLE_TRIGGER_NEW_CARGO:
1135 /* All vehicles in chain get ANY_NEW_CARGO trigger now.
1136 * So we call it for the first one and they will recurse.
1137 * Indexing part of vehicle random bits needs to be
1138 * same for all triggered vehicles in the chain (to get
1139 * all the random-cargo wagons carry the same cargo,
1140 * i.e.), so we give them all the NEW_CARGO triggered
1141 * vehicle's portion of random bits. */
1142 assert(first);
1143 DoTriggerVehicle(v->First(), VEHICLE_TRIGGER_ANY_NEW_CARGO, new_random_bits, false);
1144 break;
1146 case VEHICLE_TRIGGER_DEPOT:
1147 /* We now trigger the next vehicle in chain recursively.
1148 * The random bits portions may be different for each
1149 * vehicle in chain. */
1150 if (v->Next() != NULL) DoTriggerVehicle(v->Next(), trigger, 0, true);
1151 break;
1153 case VEHICLE_TRIGGER_EMPTY:
1154 /* We now trigger the next vehicle in chain
1155 * recursively. The random bits portions must be same
1156 * for each vehicle in chain, so we give them all
1157 * first chained vehicle's portion of random bits. */
1158 if (v->Next() != NULL) DoTriggerVehicle(v->Next(), trigger, first ? new_random_bits : base_random_bits, false);
1159 break;
1161 case VEHICLE_TRIGGER_ANY_NEW_CARGO:
1162 /* Now pass the trigger recursively to the next vehicle
1163 * in chain. */
1164 assert(!first);
1165 if (v->Next() != NULL) DoTriggerVehicle(v->Next(), VEHICLE_TRIGGER_ANY_NEW_CARGO, base_random_bits, false);
1166 break;
1168 case VEHICLE_TRIGGER_CALLBACK_32:
1169 /* Do not do any recursion */
1170 break;
1174 void TriggerVehicle(Vehicle *v, VehicleTrigger trigger)
1176 if (trigger == VEHICLE_TRIGGER_DEPOT) {
1177 /* store that the vehicle entered a depot this tick */
1178 VehicleEnteredDepotThisTick(v);
1181 v->InvalidateNewGRFCacheOfChain();
1182 DoTriggerVehicle(v, trigger, 0, true);
1183 v->InvalidateNewGRFCacheOfChain();
1186 /* Functions for changing the order of vehicle purchase lists */
1188 struct ListOrderChange {
1189 EngineID engine;
1190 uint target; ///< local ID
1193 static SmallVector<ListOrderChange, 16> _list_order_changes;
1196 * Record a vehicle ListOrderChange.
1197 * @param engine Engine to move
1198 * @param target Local engine ID to move \a engine in front of
1199 * @note All sorting is done later in CommitVehicleListOrderChanges
1201 void AlterVehicleListOrder(EngineID engine, uint target)
1203 /* Add the list order change to a queue */
1204 ListOrderChange *loc = _list_order_changes.Append();
1205 loc->engine = engine;
1206 loc->target = target;
1210 * Comparator function to sort engines via scope-GRFID and local ID.
1211 * @param a left side
1212 * @param b right side
1213 * @return comparison result
1215 static int CDECL EnginePreSort(const EngineID *a, const EngineID *b)
1217 const EngineIDMapping *id_a = _engine_mngr.Get(*a);
1218 const EngineIDMapping *id_b = _engine_mngr.Get(*b);
1220 /* 1. Sort by engine type */
1221 if (id_a->type != id_b->type) return (int)id_a->type - (int)id_b->type;
1223 /* 2. Sort by scope-GRFID */
1224 if (id_a->grfid != id_b->grfid) return id_a->grfid < id_b->grfid ? -1 : 1;
1226 /* 3. Sort by local ID */
1227 return (int)id_a->internal_id - (int)id_b->internal_id;
1231 * Deternine default engine sorting and execute recorded ListOrderChanges from AlterVehicleListOrder.
1233 void CommitVehicleListOrderChanges()
1235 /* Pre-sort engines by scope-grfid and local index */
1236 SmallVector<EngineID, 16> ordering;
1237 Engine *e;
1238 FOR_ALL_ENGINES(e) {
1239 *ordering.Append() = e->index;
1241 QSortT(ordering.Begin(), ordering.Length(), EnginePreSort);
1243 /* Apply Insertion-Sort operations */
1244 const ListOrderChange *end = _list_order_changes.End();
1245 for (const ListOrderChange *it = _list_order_changes.Begin(); it != end; ++it) {
1246 EngineID source = it->engine;
1247 uint local_target = it->target;
1249 const EngineIDMapping *id_source = _engine_mngr.Get(source);
1250 if (id_source->internal_id == local_target) continue;
1252 EngineID target = _engine_mngr.GetID(id_source->type, local_target, id_source->grfid);
1253 if (target == INVALID_ENGINE) continue;
1255 int source_index = ordering.FindIndex(source);
1256 int target_index = ordering.FindIndex(target);
1258 assert(source_index >= 0 && target_index >= 0);
1259 assert(source_index != target_index);
1261 EngineID *list = ordering.Begin();
1262 if (source_index < target_index) {
1263 --target_index;
1264 for (int i = source_index; i < target_index; ++i) list[i] = list[i + 1];
1265 list[target_index] = source;
1266 } else {
1267 for (int i = source_index; i > target_index; --i) list[i] = list[i - 1];
1268 list[target_index] = source;
1272 /* Store final sort-order */
1273 const EngineID *idend = ordering.End();
1274 uint index = 0;
1275 for (const EngineID *it = ordering.Begin(); it != idend; ++it, ++index) {
1276 Engine::Get(*it)->list_position = index;
1279 /* Clear out the queue */
1280 _list_order_changes.Reset();
1284 * Fill the grf_cache of the given vehicle.
1285 * @param v The vehicle to fill the cache for.
1287 void FillNewGRFVehicleCache(const Vehicle *v)
1289 VehicleResolverObject ro(v->engine_type, v, VehicleResolverObject::WO_NONE);
1291 /* These variables we have to check; these are the ones with a cache. */
1292 static const int cache_entries[][2] = {
1293 { 0x40, NCVV_POSITION_CONSIST_LENGTH },
1294 { 0x41, NCVV_POSITION_SAME_ID_LENGTH },
1295 { 0x42, NCVV_CONSIST_CARGO_INFORMATION },
1296 { 0x43, NCVV_COMPANY_INFORMATION },
1297 { 0x4D, NCVV_POSITION_IN_VEHICLE },
1299 assert_compile(NCVV_END == lengthof(cache_entries));
1301 /* Resolve all the variables, so their caches are set. */
1302 for (size_t i = 0; i < lengthof(cache_entries); i++) {
1303 /* Only resolve when the cache isn't valid. */
1304 if (HasBit(v->grf_cache.cache_valid, cache_entries[i][1])) continue;
1305 bool stub;
1306 ro.GetScope(VSG_SCOPE_SELF)->GetVariable(cache_entries[i][0], 0, &stub);
1309 /* Make sure really all bits are set. */
1310 assert(v->grf_cache.cache_valid == (1 << NCVV_END) - 1);