OpenTTD
newgrf_engine.cpp
Go to the documentation of this file.
1 /*
2  * This file is part of OpenTTD.
3  * 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.
4  * 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.
5  * 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/>.
6  */
7 
10 #include "stdafx.h"
11 #include "debug.h"
12 #include "train.h"
13 #include "roadveh.h"
14 #include "company_func.h"
15 #include "newgrf_cargo.h"
16 #include "newgrf_spritegroup.h"
17 #include "date_func.h"
18 #include "vehicle_func.h"
19 #include "core/random_func.hpp"
20 #include "aircraft.h"
21 #include "station_base.h"
22 #include "company_base.h"
23 #include "newgrf_railtype.h"
24 #include "newgrf_roadtype.h"
25 #include "ship.h"
26 
27 #include "safeguards.h"
28 
29 struct WagonOverride {
30  EngineID *train_id;
31  uint trains;
32  CargoID cargo;
33  const SpriteGroup *group;
34 };
35 
36 void SetWagonOverrideSprites(EngineID engine, CargoID cargo, const SpriteGroup *group, EngineID *train_id, uint trains)
37 {
38  Engine *e = Engine::Get(engine);
39  WagonOverride *wo;
40 
41  assert(cargo < NUM_CARGO + 2); // Include CT_DEFAULT and CT_PURCHASE pseudo cargoes.
42 
43  e->overrides_count++;
44  e->overrides = ReallocT(e->overrides, e->overrides_count);
45 
46  wo = &e->overrides[e->overrides_count - 1];
47  wo->group = group;
48  wo->cargo = cargo;
49  wo->trains = trains;
50  wo->train_id = MallocT<EngineID>(trains);
51  memcpy(wo->train_id, train_id, trains * sizeof *train_id);
52 }
53 
54 const SpriteGroup *GetWagonOverrideSpriteSet(EngineID engine, CargoID cargo, EngineID overriding_engine)
55 {
56  const Engine *e = Engine::Get(engine);
57 
58  for (uint i = 0; i < e->overrides_count; i++) {
59  const WagonOverride *wo = &e->overrides[i];
60 
61  if (wo->cargo != cargo && wo->cargo != CT_DEFAULT) continue;
62 
63  for (uint j = 0; j < wo->trains; j++) {
64  if (wo->train_id[j] == overriding_engine) return wo->group;
65  }
66  }
67  return nullptr;
68 }
69 
74 {
75  for (uint i = 0; i < e->overrides_count; i++) {
76  WagonOverride *wo = &e->overrides[i];
77  free(wo->train_id);
78  }
79  free(e->overrides);
80  e->overrides_count = 0;
81  e->overrides = nullptr;
82 }
83 
84 
85 void SetCustomEngineSprites(EngineID engine, byte cargo, const SpriteGroup *group)
86 {
87  Engine *e = Engine::Get(engine);
88  assert(cargo < lengthof(e->grf_prop.spritegroup));
89 
90  if (e->grf_prop.spritegroup[cargo] != nullptr) {
91  grfmsg(6, "SetCustomEngineSprites: engine %d cargo %d already has group -- replacing", engine, cargo);
92  }
93  e->grf_prop.spritegroup[cargo] = group;
94 }
95 
96 
103 void SetEngineGRF(EngineID engine, const GRFFile *file)
104 {
105  Engine *e = Engine::Get(engine);
106  e->grf_prop.grffile = file;
107 }
108 
109 
110 static int MapOldSubType(const Vehicle *v)
111 {
112  switch (v->type) {
113  case VEH_TRAIN:
114  if (Train::From(v)->IsEngine()) return 0;
115  if (Train::From(v)->IsFreeWagon()) return 4;
116  return 2;
117  case VEH_ROAD:
118  case VEH_SHIP: return 0;
119  case VEH_AIRCRAFT:
120  case VEH_DISASTER: return v->subtype;
121  case VEH_EFFECT: return v->subtype << 1;
122  default: NOT_REACHED();
123  }
124 }
125 
126 
127 /* TTDP style aircraft movement states for GRF Action 2 Var 0xE2 */
128 enum TTDPAircraftMovementStates {
129  AMS_TTDP_HANGAR,
130  AMS_TTDP_TO_HANGAR,
131  AMS_TTDP_TO_PAD1,
132  AMS_TTDP_TO_PAD2,
133  AMS_TTDP_TO_PAD3,
134  AMS_TTDP_TO_ENTRY_2_AND_3,
135  AMS_TTDP_TO_ENTRY_2_AND_3_AND_H,
136  AMS_TTDP_TO_JUNCTION,
137  AMS_TTDP_LEAVE_RUNWAY,
138  AMS_TTDP_TO_INWAY,
139  AMS_TTDP_TO_RUNWAY,
140  AMS_TTDP_TO_OUTWAY,
141  AMS_TTDP_WAITING,
142  AMS_TTDP_TAKEOFF,
143  AMS_TTDP_TO_TAKEOFF,
144  AMS_TTDP_CLIMBING,
145  AMS_TTDP_FLIGHT_APPROACH,
146  AMS_TTDP_UNUSED_0x11,
147  AMS_TTDP_FLIGHT_TO_TOWER,
148  AMS_TTDP_UNUSED_0x13,
149  AMS_TTDP_FLIGHT_FINAL,
150  AMS_TTDP_FLIGHT_DESCENT,
151  AMS_TTDP_BRAKING,
152  AMS_TTDP_HELI_TAKEOFF_AIRPORT,
153  AMS_TTDP_HELI_TO_TAKEOFF_AIRPORT,
154  AMS_TTDP_HELI_LAND_AIRPORT,
155  AMS_TTDP_HELI_TAKEOFF_HELIPORT,
156  AMS_TTDP_HELI_TO_TAKEOFF_HELIPORT,
157  AMS_TTDP_HELI_LAND_HELIPORT,
158 };
159 
160 
165 static byte MapAircraftMovementState(const Aircraft *v)
166 {
167  const Station *st = GetTargetAirportIfValid(v);
168  if (st == nullptr) return AMS_TTDP_FLIGHT_TO_TOWER;
169 
170  const AirportFTAClass *afc = st->airport.GetFTA();
171  uint16 amdflag = afc->MovingData(v->pos)->flag;
172 
173  switch (v->state) {
174  case HANGAR:
175  /* The international airport is a special case as helicopters can land in
176  * front of the hangar. Helicopters also change their air.state to
177  * AMED_HELI_LOWER some time before actually descending. */
178 
179  /* This condition only occurs for helicopters, during descent,
180  * to a landing by the hangar of an international airport. */
181  if (amdflag & AMED_HELI_LOWER) return AMS_TTDP_HELI_LAND_AIRPORT;
182 
183  /* This condition only occurs for helicopters, before starting descent,
184  * to a landing by the hangar of an international airport. */
185  if (amdflag & AMED_SLOWTURN) return AMS_TTDP_FLIGHT_TO_TOWER;
186 
187  /* The final two conditions apply to helicopters or aircraft.
188  * Has reached hangar? */
189  if (amdflag & AMED_EXACTPOS) return AMS_TTDP_HANGAR;
190 
191  /* Still moving towards hangar. */
192  return AMS_TTDP_TO_HANGAR;
193 
194  case TERM1:
195  if (amdflag & AMED_EXACTPOS) return AMS_TTDP_TO_PAD1;
196  return AMS_TTDP_TO_JUNCTION;
197 
198  case TERM2:
199  if (amdflag & AMED_EXACTPOS) return AMS_TTDP_TO_PAD2;
200  return AMS_TTDP_TO_ENTRY_2_AND_3_AND_H;
201 
202  case TERM3:
203  case TERM4:
204  case TERM5:
205  case TERM6:
206  case TERM7:
207  case TERM8:
208  /* TTDPatch only has 3 terminals, so treat these states the same */
209  if (amdflag & AMED_EXACTPOS) return AMS_TTDP_TO_PAD3;
210  return AMS_TTDP_TO_ENTRY_2_AND_3_AND_H;
211 
212  case HELIPAD1:
213  case HELIPAD2:
214  case HELIPAD3:
215  /* Will only occur for helicopters.*/
216  if (amdflag & AMED_HELI_LOWER) return AMS_TTDP_HELI_LAND_AIRPORT; // Descending.
217  if (amdflag & AMED_SLOWTURN) return AMS_TTDP_FLIGHT_TO_TOWER; // Still hasn't started descent.
218  return AMS_TTDP_TO_JUNCTION; // On the ground.
219 
220  case TAKEOFF: // Moving to takeoff position.
221  return AMS_TTDP_TO_OUTWAY;
222 
223  case STARTTAKEOFF: // Accelerating down runway.
224  return AMS_TTDP_TAKEOFF;
225 
226  case ENDTAKEOFF: // Ascent
227  return AMS_TTDP_CLIMBING;
228 
229  case HELITAKEOFF: // Helicopter is moving to take off position.
230  if (afc->delta_z == 0) {
231  return amdflag & AMED_HELI_RAISE ?
232  AMS_TTDP_HELI_TAKEOFF_AIRPORT : AMS_TTDP_TO_JUNCTION;
233  } else {
234  return AMS_TTDP_HELI_TAKEOFF_HELIPORT;
235  }
236 
237  case FLYING:
238  return amdflag & AMED_HOLD ? AMS_TTDP_FLIGHT_APPROACH : AMS_TTDP_FLIGHT_TO_TOWER;
239 
240  case LANDING: // Descent
241  return AMS_TTDP_FLIGHT_DESCENT;
242 
243  case ENDLANDING: // On the runway braking
244  if (amdflag & AMED_BRAKE) return AMS_TTDP_BRAKING;
245  /* Landed - moving off runway */
246  return AMS_TTDP_TO_INWAY;
247 
248  case HELILANDING:
249  case HELIENDLANDING: // Helicoptor is descending.
250  if (amdflag & AMED_HELI_LOWER) {
251  return afc->delta_z == 0 ?
252  AMS_TTDP_HELI_LAND_AIRPORT : AMS_TTDP_HELI_LAND_HELIPORT;
253  } else {
254  return AMS_TTDP_FLIGHT_TO_TOWER;
255  }
256 
257  default:
258  return AMS_TTDP_HANGAR;
259  }
260 }
261 
262 
263 /* TTDP style aircraft movement action for GRF Action 2 Var 0xE6 */
264 enum TTDPAircraftMovementActions {
265  AMA_TTDP_IN_HANGAR,
266  AMA_TTDP_ON_PAD1,
267  AMA_TTDP_ON_PAD2,
268  AMA_TTDP_ON_PAD3,
269  AMA_TTDP_HANGAR_TO_PAD1,
270  AMA_TTDP_HANGAR_TO_PAD2,
271  AMA_TTDP_HANGAR_TO_PAD3,
272  AMA_TTDP_LANDING_TO_PAD1,
273  AMA_TTDP_LANDING_TO_PAD2,
274  AMA_TTDP_LANDING_TO_PAD3,
275  AMA_TTDP_PAD1_TO_HANGAR,
276  AMA_TTDP_PAD2_TO_HANGAR,
277  AMA_TTDP_PAD3_TO_HANGAR,
278  AMA_TTDP_PAD1_TO_TAKEOFF,
279  AMA_TTDP_PAD2_TO_TAKEOFF,
280  AMA_TTDP_PAD3_TO_TAKEOFF,
281  AMA_TTDP_HANGAR_TO_TAKOFF,
282  AMA_TTDP_LANDING_TO_HANGAR,
283  AMA_TTDP_IN_FLIGHT,
284 };
285 
286 
292 static byte MapAircraftMovementAction(const Aircraft *v)
293 {
294  switch (v->state) {
295  case HANGAR:
296  return (v->cur_speed > 0) ? AMA_TTDP_LANDING_TO_HANGAR : AMA_TTDP_IN_HANGAR;
297 
298  case TERM1:
299  case HELIPAD1:
300  return (v->current_order.IsType(OT_LOADING)) ? AMA_TTDP_ON_PAD1 : AMA_TTDP_LANDING_TO_PAD1;
301 
302  case TERM2:
303  case HELIPAD2:
304  return (v->current_order.IsType(OT_LOADING)) ? AMA_TTDP_ON_PAD2 : AMA_TTDP_LANDING_TO_PAD2;
305 
306  case TERM3:
307  case TERM4:
308  case TERM5:
309  case TERM6:
310  case TERM7:
311  case TERM8:
312  case HELIPAD3:
313  return (v->current_order.IsType(OT_LOADING)) ? AMA_TTDP_ON_PAD3 : AMA_TTDP_LANDING_TO_PAD3;
314 
315  case TAKEOFF: // Moving to takeoff position
316  case STARTTAKEOFF: // Accelerating down runway
317  case ENDTAKEOFF: // Ascent
318  case HELITAKEOFF:
319  /* @todo Need to find which terminal (or hangar) we've come from. How? */
320  return AMA_TTDP_PAD1_TO_TAKEOFF;
321 
322  case FLYING:
323  return AMA_TTDP_IN_FLIGHT;
324 
325  case LANDING: // Descent
326  case ENDLANDING: // On the runway braking
327  case HELILANDING:
328  case HELIENDLANDING:
329  /* @todo Need to check terminal we're landing to. Is it known yet? */
330  return (v->current_order.IsType(OT_GOTO_DEPOT)) ?
331  AMA_TTDP_LANDING_TO_HANGAR : AMA_TTDP_LANDING_TO_PAD1;
332 
333  default:
334  return AMA_TTDP_IN_HANGAR;
335  }
336 }
337 
338 
339 /* virtual */ uint32 VehicleScopeResolver::GetRandomBits() const
340 {
341  return this->v == nullptr ? 0 : this->v->random_bits;
342 }
343 
344 /* virtual */ uint32 VehicleScopeResolver::GetTriggers() const
345 {
346  return this->v == nullptr ? 0 : this->v->waiting_triggers;
347 }
348 
349 
351 {
352  switch (scope) {
353  case VSG_SCOPE_SELF: return &this->self_scope;
354  case VSG_SCOPE_PARENT: return &this->parent_scope;
355  case VSG_SCOPE_RELATIVE: {
356  int32 count = GB(relative, 0, 4);
357  if (this->self_scope.v != nullptr && (relative != this->cached_relative_count || count == 0)) {
358  /* Note: This caching only works as long as the VSG_SCOPE_RELATIVE cannot be used in
359  * VarAct2 with procedure calls. */
360  if (count == 0) count = GetRegister(0x100);
361 
362  const Vehicle *v = nullptr;
363  switch (GB(relative, 6, 2)) {
364  default: NOT_REACHED();
365  case 0x00: // count back (away from the engine), starting at this vehicle
366  v = this->self_scope.v;
367  break;
368  case 0x01: // count forward (toward the engine), starting at this vehicle
369  v = this->self_scope.v;
370  count = -count;
371  break;
372  case 0x02: // count back, starting at the engine
373  v = this->parent_scope.v;
374  break;
375  case 0x03: { // count back, starting at the first vehicle in this chain of vehicles with the same ID, as for vehicle variable 41
376  const Vehicle *self = this->self_scope.v;
377  for (const Vehicle *u = self->First(); u != self; u = u->Next()) {
378  if (u->engine_type != self->engine_type) {
379  v = nullptr;
380  } else {
381  if (v == nullptr) v = u;
382  }
383  }
384  if (v == nullptr) v = self;
385  break;
386  }
387  }
388  this->relative_scope.SetVehicle(v->Move(count));
389  }
390  return &this->relative_scope;
391  }
392  default: return ResolverObject::GetScope(scope, relative);
393  }
394 }
395 
405 static const Livery *LiveryHelper(EngineID engine, const Vehicle *v)
406 {
407  const Livery *l;
408 
409  if (v == nullptr) {
410  if (!Company::IsValidID(_current_company)) return nullptr;
411  l = GetEngineLivery(engine, _current_company, INVALID_ENGINE, nullptr, LIT_ALL);
412  } else if (v->IsGroundVehicle()) {
414  } else {
416  }
417 
418  return l;
419 }
420 
428 static uint32 PositionHelper(const Vehicle *v, bool consecutive)
429 {
430  const Vehicle *u;
431  byte chain_before = 0;
432  byte chain_after = 0;
433 
434  for (u = v->First(); u != v; u = u->Next()) {
435  chain_before++;
436  if (consecutive && u->engine_type != v->engine_type) chain_before = 0;
437  }
438 
439  while (u->Next() != nullptr && (!consecutive || u->Next()->engine_type == v->engine_type)) {
440  chain_after++;
441  u = u->Next();
442  }
443 
444  return chain_before | chain_after << 8 | (chain_before + chain_after + consecutive) << 16;
445 }
446 
447 static uint32 VehicleGetVariable(Vehicle *v, const VehicleScopeResolver *object, byte variable, uint32 parameter, bool *available)
448 {
449  /* Calculated vehicle parameters */
450  switch (variable) {
451  case 0x25: // Get engine GRF ID
452  return v->GetGRFID();
453 
454  case 0x40: // Get length of consist
458  }
460 
461  case 0x41: // Get length of same consecutive wagons
465  }
467 
468  case 0x42: { // Consist cargo information
470  const Vehicle *u;
471  byte cargo_classes = 0;
472  uint8 common_cargoes[NUM_CARGO];
473  uint8 common_subtypes[256];
474  byte user_def_data = 0;
475  CargoID common_cargo_type = CT_INVALID;
476  uint8 common_subtype = 0xFF; // Return 0xFF if nothing is carried
477 
478  /* Reset our arrays */
479  memset(common_cargoes, 0, sizeof(common_cargoes));
480  memset(common_subtypes, 0, sizeof(common_subtypes));
481 
482  for (u = v; u != nullptr; u = u->Next()) {
483  if (v->type == VEH_TRAIN) user_def_data |= Train::From(u)->tcache.user_def_data;
484 
485  /* Skip empty engines */
486  if (!u->GetEngine()->CanCarryCargo()) continue;
487 
488  cargo_classes |= CargoSpec::Get(u->cargo_type)->classes;
489  common_cargoes[u->cargo_type]++;
490  }
491 
492  /* Pick the most common cargo type */
493  uint common_cargo_best_amount = 0;
494  for (CargoID cargo = 0; cargo < NUM_CARGO; cargo++) {
495  if (common_cargoes[cargo] > common_cargo_best_amount) {
496  common_cargo_best_amount = common_cargoes[cargo];
497  common_cargo_type = cargo;
498  }
499  }
500 
501  /* Count subcargo types of common_cargo_type */
502  for (u = v; u != nullptr; u = u->Next()) {
503  /* Skip empty engines and engines not carrying common_cargo_type */
504  if (u->cargo_type != common_cargo_type || !u->GetEngine()->CanCarryCargo()) continue;
505 
506  common_subtypes[u->cargo_subtype]++;
507  }
508 
509  /* Pick the most common subcargo type*/
510  uint common_subtype_best_amount = 0;
511  for (uint i = 0; i < lengthof(common_subtypes); i++) {
512  if (common_subtypes[i] > common_subtype_best_amount) {
513  common_subtype_best_amount = common_subtypes[i];
514  common_subtype = i;
515  }
516  }
517 
518  /* Note: We have to store the untranslated cargotype in the cache as the cache can be read by different NewGRFs,
519  * which will need different translations */
520  v->grf_cache.consist_cargo_information = cargo_classes | (common_cargo_type << 8) | (common_subtype << 16) | (user_def_data << 24);
522  }
523 
524  /* The cargo translation is specific to the accessing GRF, and thus cannot be cached. */
525  CargoID common_cargo_type = (v->grf_cache.consist_cargo_information >> 8) & 0xFF;
526 
527  /* Note:
528  * - Unlike everywhere else the cargo translation table is only used since grf version 8, not 7.
529  * - For translating the cargo type we need to use the GRF which is resolving the variable, which
530  * is object->ro.grffile.
531  * In case of CBID_TRAIN_ALLOW_WAGON_ATTACH this is not the same as v->GetGRF().
532  * - The grffile == nullptr case only happens if this function is called for default vehicles.
533  * And this is only done by CheckCaches().
534  */
535  const GRFFile *grffile = object->ro.grffile;
536  uint8 common_bitnum = (common_cargo_type == CT_INVALID) ? 0xFF :
537  (grffile == nullptr || grffile->grf_version < 8) ? CargoSpec::Get(common_cargo_type)->bitnum : grffile->cargo_map[common_cargo_type];
538 
539  return (v->grf_cache.consist_cargo_information & 0xFFFF00FF) | common_bitnum << 8;
540  }
541 
542  case 0x43: // Company information
546  }
547  return v->grf_cache.company_information;
548 
549  case 0x44: // Aircraft information
550  if (v->type != VEH_AIRCRAFT || !Aircraft::From(v)->IsNormalAircraft()) return UINT_MAX;
551 
552  {
553  const Vehicle *w = v->Next();
554  uint16 altitude = ClampToU16(v->z_pos - w->z_pos); // Aircraft height - shadow height
555  byte airporttype = ATP_TTDP_LARGE;
556 
558 
559  if (st != nullptr && st->airport.tile != INVALID_TILE) {
560  airporttype = st->airport.GetSpec()->ttd_airport_type;
561  }
562 
563  return (Clamp(altitude, 0, 0xFF) << 8) | airporttype;
564  }
565 
566  case 0x45: { // Curvature info
567  /* Format: xxxTxBxF
568  * F - previous wagon to current wagon, 0 if vehicle is first
569  * B - current wagon to next wagon, 0 if wagon is last
570  * T - previous wagon to next wagon, 0 in an S-bend
571  */
572  if (!v->IsGroundVehicle()) return 0;
573 
574  const Vehicle *u_p = v->Previous();
575  const Vehicle *u_n = v->Next();
576  DirDiff f = (u_p == nullptr) ? DIRDIFF_SAME : DirDifference(u_p->direction, v->direction);
577  DirDiff b = (u_n == nullptr) ? DIRDIFF_SAME : DirDifference(v->direction, u_n->direction);
578  DirDiff t = ChangeDirDiff(f, b);
579 
580  return ((t > DIRDIFF_REVERSE ? t | 8 : t) << 16) |
581  ((b > DIRDIFF_REVERSE ? b | 8 : b) << 8) |
582  ( f > DIRDIFF_REVERSE ? f | 8 : f);
583  }
584 
585  case 0x46: // Motion counter
586  return v->motion_counter;
587 
588  case 0x47: { // Vehicle cargo info
589  /* Format: ccccwwtt
590  * tt - the cargo type transported by the vehicle,
591  * translated if a translation table has been installed.
592  * ww - cargo unit weight in 1/16 tons, same as cargo prop. 0F.
593  * cccc - the cargo class value of the cargo transported by the vehicle.
594  */
595  const CargoSpec *cs = CargoSpec::Get(v->cargo_type);
596 
597  /* Note:
598  * For translating the cargo type we need to use the GRF which is resolving the variable, which
599  * is object->ro.grffile.
600  * In case of CBID_TRAIN_ALLOW_WAGON_ATTACH this is not the same as v->GetGRF().
601  */
602  return (cs->classes << 16) | (cs->weight << 8) | object->ro.grffile->cargo_map[v->cargo_type];
603  }
604 
605  case 0x48: return v->GetEngine()->flags; // Vehicle Type Info
606  case 0x49: return v->build_year;
607 
608  case 0x4A:
609  switch (v->type) {
610  case VEH_TRAIN: {
611  RailType rt = GetTileRailType(v->tile);
612  return (HasPowerOnRail(Train::From(v)->railtype, rt) ? 0x100 : 0) | GetReverseRailTypeTranslation(rt, object->ro.grffile);
613  }
614 
615  case VEH_ROAD: {
616  RoadType rt = GetRoadType(v->tile, GetRoadTramType(RoadVehicle::From(v)->roadtype));
617  return 0x100 | GetReverseRoadTypeTranslation(rt, object->ro.grffile);
618  }
619 
620  default:
621  return 0;
622  }
623 
624  case 0x4B: // Long date of last service
625  return v->date_of_last_service;
626 
627  case 0x4C: // Current maximum speed in NewGRF units
628  if (!v->IsPrimaryVehicle()) return 0;
629  return v->GetCurrentMaxSpeed();
630 
631  case 0x4D: // Position within articulated vehicle
633  byte artic_before = 0;
634  for (const Vehicle *u = v; u->IsArticulatedPart(); u = u->Previous()) artic_before++;
635  byte artic_after = 0;
636  for (const Vehicle *u = v; u->HasArticulatedPart(); u = u->Next()) artic_after++;
637  v->grf_cache.position_in_vehicle = artic_before | artic_after << 8;
639  }
640  return v->grf_cache.position_in_vehicle;
641 
642  /* Variables which use the parameter */
643  case 0x60: // Count consist's engine ID occurrence
644  if (v->type != VEH_TRAIN) return v->GetEngine()->grf_prop.local_id == parameter ? 1 : 0;
645 
646  {
647  uint count = 0;
648  for (; v != nullptr; v = v->Next()) {
649  if (v->GetEngine()->grf_prop.local_id == parameter) count++;
650  }
651  return count;
652  }
653 
654  case 0x61: // Get variable of n-th vehicle in chain [signed number relative to vehicle]
655  if (!v->IsGroundVehicle() || parameter == 0x61) {
656  /* Not available */
657  break;
658  }
659 
660  /* Only allow callbacks that don't change properties to avoid circular dependencies. */
664  Vehicle *u = v->Move((int32)GetRegister(0x10F));
665  if (u == nullptr) return 0; // available, but zero
666 
667  if (parameter == 0x5F) {
668  /* This seems to be the only variable that makes sense to access via var 61, but is not handled by VehicleGetVariable */
669  return (u->random_bits << 8) | u->waiting_triggers;
670  } else {
671  return VehicleGetVariable(u, object, parameter, GetRegister(0x10E), available);
672  }
673  }
674  /* Not available */
675  break;
676 
677  case 0x62: { // Curvature/position difference for n-th vehicle in chain [signed number relative to vehicle]
678  /* Format: zzyyxxFD
679  * zz - Signed difference of z position between the selected and this vehicle.
680  * yy - Signed difference of y position between the selected and this vehicle.
681  * xx - Signed difference of x position between the selected and this vehicle.
682  * F - Flags, bit 7 corresponds to VS_HIDDEN.
683  * D - Dir difference, like in 0x45.
684  */
685  if (!v->IsGroundVehicle()) return 0;
686 
687  const Vehicle *u = v->Move((int8)parameter);
688  if (u == nullptr) return 0;
689 
690  /* Get direction difference. */
691  bool prev = (int8)parameter < 0;
692  uint32 ret = prev ? DirDifference(u->direction, v->direction) : DirDifference(v->direction, u->direction);
693  if (ret > DIRDIFF_REVERSE) ret |= 0x08;
694 
695  if (u->vehstatus & VS_HIDDEN) ret |= 0x80;
696 
697  /* Get position difference. */
698  ret |= ((prev ? u->x_pos - v->x_pos : v->x_pos - u->x_pos) & 0xFF) << 8;
699  ret |= ((prev ? u->y_pos - v->y_pos : v->y_pos - u->y_pos) & 0xFF) << 16;
700  ret |= ((prev ? u->z_pos - v->z_pos : v->z_pos - u->z_pos) & 0xFF) << 24;
701 
702  return ret;
703  }
704 
705  case 0xFE:
706  case 0xFF: {
707  uint16 modflags = 0;
708 
709  if (v->type == VEH_TRAIN) {
710  const Train *t = Train::From(v);
711  bool is_powered_wagon = HasBit(t->flags, VRF_POWEREDWAGON);
712  const Train *u = is_powered_wagon ? t->First() : t; // for powered wagons the engine defines the type of engine (i.e. railtype)
713  RailType railtype = GetRailType(v->tile);
714  bool powered = t->IsEngine() || is_powered_wagon;
715  bool has_power = HasPowerOnRail(u->railtype, railtype);
716 
717  if (powered && has_power) SetBit(modflags, 5);
718  if (powered && !has_power) SetBit(modflags, 6);
719  if (HasBit(t->flags, VRF_TOGGLE_REVERSE)) SetBit(modflags, 8);
720  }
721  if (HasBit(v->vehicle_flags, VF_CARGO_UNLOADING)) SetBit(modflags, 1);
722  if (HasBit(v->vehicle_flags, VF_BUILT_AS_PROTOTYPE)) SetBit(modflags, 10);
723 
724  return variable == 0xFE ? modflags : GB(modflags, 8, 8);
725  }
726  }
727 
728  /* General vehicle properties */
729  switch (variable - 0x80) {
730  case 0x00: return v->type + 0x10;
731  case 0x01: return MapOldSubType(v);
732  case 0x04: return v->index;
733  case 0x05: return GB(v->index, 8, 8);
734  case 0x0A: return v->current_order.MapOldOrder();
735  case 0x0B: return v->current_order.GetDestination();
736  case 0x0C: return v->GetNumOrders();
737  case 0x0D: return v->cur_real_order_index;
738  case 0x10:
739  case 0x11: {
740  uint ticks;
741  if (v->current_order.IsType(OT_LOADING)) {
742  ticks = v->load_unload_ticks;
743  } else {
744  switch (v->type) {
745  case VEH_TRAIN: ticks = Train::From(v)->wait_counter; break;
746  case VEH_AIRCRAFT: ticks = Aircraft::From(v)->turn_counter; break;
747  default: ticks = 0; break;
748  }
749  }
750  return (variable - 0x80) == 0x10 ? ticks : GB(ticks, 8, 8);
751  }
752  case 0x12: return Clamp(v->date_of_last_service - DAYS_TILL_ORIGINAL_BASE_YEAR, 0, 0xFFFF);
753  case 0x13: return GB(Clamp(v->date_of_last_service - DAYS_TILL_ORIGINAL_BASE_YEAR, 0, 0xFFFF), 8, 8);
754  case 0x14: return v->GetServiceInterval();
755  case 0x15: return GB(v->GetServiceInterval(), 8, 8);
756  case 0x16: return v->last_station_visited;
757  case 0x17: return v->tick_counter;
758  case 0x18:
759  case 0x19: {
760  uint max_speed;
761  switch (v->type) {
762  case VEH_AIRCRAFT:
763  max_speed = Aircraft::From(v)->GetSpeedOldUnits(); // Convert to old units.
764  break;
765 
766  default:
767  max_speed = v->vcache.cached_max_speed;
768  break;
769  }
770  return (variable - 0x80) == 0x18 ? max_speed : GB(max_speed, 8, 8);
771  }
772  case 0x1A: return v->x_pos;
773  case 0x1B: return GB(v->x_pos, 8, 8);
774  case 0x1C: return v->y_pos;
775  case 0x1D: return GB(v->y_pos, 8, 8);
776  case 0x1E: return v->z_pos;
777  case 0x1F: return object->info_view ? DIR_W : v->direction;
778  case 0x28: return 0; // cur_image is a potential desyncer due to Action1 in static NewGRFs.
779  case 0x29: return 0; // cur_image is a potential desyncer due to Action1 in static NewGRFs.
780  case 0x32: return v->vehstatus;
781  case 0x33: return 0; // non-existent high byte of vehstatus
782  case 0x34: return v->type == VEH_AIRCRAFT ? (v->cur_speed * 10) / 128 : v->cur_speed;
783  case 0x35: return GB(v->type == VEH_AIRCRAFT ? (v->cur_speed * 10) / 128 : v->cur_speed, 8, 8);
784  case 0x36: return v->subspeed;
785  case 0x37: return v->acceleration;
786  case 0x39: return v->cargo_type;
787  case 0x3A: return v->cargo_cap;
788  case 0x3B: return GB(v->cargo_cap, 8, 8);
789  case 0x3C: return ClampToU16(v->cargo.StoredCount());
790  case 0x3D: return GB(ClampToU16(v->cargo.StoredCount()), 8, 8);
791  case 0x3E: return v->cargo.Source();
792  case 0x3F: return ClampU(v->cargo.DaysInTransit(), 0, 0xFF);
793  case 0x40: return ClampToU16(v->age);
794  case 0x41: return GB(ClampToU16(v->age), 8, 8);
795  case 0x42: return ClampToU16(v->max_age);
796  case 0x43: return GB(ClampToU16(v->max_age), 8, 8);
798  case 0x45: return v->unitnumber;
799  case 0x46: return v->GetEngine()->grf_prop.local_id;
800  case 0x47: return GB(v->GetEngine()->grf_prop.local_id, 8, 8);
801  case 0x48:
802  if (v->type != VEH_TRAIN || v->spritenum != 0xFD) return v->spritenum;
803  return HasBit(Train::From(v)->flags, VRF_REVERSE_DIRECTION) ? 0xFE : 0xFD;
804 
805  case 0x49: return v->day_counter;
806  case 0x4A: return v->breakdowns_since_last_service;
807  case 0x4B: return v->breakdown_ctr;
808  case 0x4C: return v->breakdown_delay;
809  case 0x4D: return v->breakdown_chance;
810  case 0x4E: return v->reliability;
811  case 0x4F: return GB(v->reliability, 8, 8);
812  case 0x50: return v->reliability_spd_dec;
813  case 0x51: return GB(v->reliability_spd_dec, 8, 8);
814  case 0x52: return ClampToI32(v->GetDisplayProfitThisYear());
815  case 0x53: return GB(ClampToI32(v->GetDisplayProfitThisYear()), 8, 24);
816  case 0x54: return GB(ClampToI32(v->GetDisplayProfitThisYear()), 16, 16);
817  case 0x55: return GB(ClampToI32(v->GetDisplayProfitThisYear()), 24, 8);
818  case 0x56: return ClampToI32(v->GetDisplayProfitLastYear());
819  case 0x57: return GB(ClampToI32(v->GetDisplayProfitLastYear()), 8, 24);
820  case 0x58: return GB(ClampToI32(v->GetDisplayProfitLastYear()), 16, 16);
821  case 0x59: return GB(ClampToI32(v->GetDisplayProfitLastYear()), 24, 8);
822  case 0x5A: return v->Next() == nullptr ? INVALID_VEHICLE : v->Next()->index;
823  case 0x5C: return ClampToI32(v->value);
824  case 0x5D: return GB(ClampToI32(v->value), 8, 24);
825  case 0x5E: return GB(ClampToI32(v->value), 16, 16);
826  case 0x5F: return GB(ClampToI32(v->value), 24, 8);
827  case 0x72: return v->cargo_subtype;
828  case 0x7A: return v->random_bits;
829  case 0x7B: return v->waiting_triggers;
830  }
831 
832  /* Vehicle specific properties */
833  switch (v->type) {
834  case VEH_TRAIN: {
835  Train *t = Train::From(v);
836  switch (variable - 0x80) {
837  case 0x62: return t->track;
838  case 0x66: return t->railtype;
839  case 0x73: return 0x80 + VEHICLE_LENGTH - t->gcache.cached_veh_length;
840  case 0x74: return t->gcache.cached_power;
841  case 0x75: return GB(t->gcache.cached_power, 8, 24);
842  case 0x76: return GB(t->gcache.cached_power, 16, 16);
843  case 0x77: return GB(t->gcache.cached_power, 24, 8);
844  case 0x7C: return t->First()->index;
845  case 0x7D: return GB(t->First()->index, 8, 8);
846  case 0x7F: return 0; // Used for vehicle reversing hack in TTDP
847  }
848  break;
849  }
850 
851  case VEH_ROAD: {
853  switch (variable - 0x80) {
854  case 0x62: return rv->state;
855  case 0x64: return rv->blocked_ctr;
856  case 0x65: return GB(rv->blocked_ctr, 8, 8);
857  case 0x66: return rv->overtaking;
858  case 0x67: return rv->overtaking_ctr;
859  case 0x68: return rv->crashed_ctr;
860  case 0x69: return GB(rv->crashed_ctr, 8, 8);
861  }
862  break;
863  }
864 
865  case VEH_SHIP: {
866  Ship *s = Ship::From(v);
867  switch (variable - 0x80) {
868  case 0x62: return s->state;
869  }
870  break;
871  }
872 
873  case VEH_AIRCRAFT: {
874  Aircraft *a = Aircraft::From(v);
875  switch (variable - 0x80) {
876  case 0x62: return MapAircraftMovementState(a); // Current movement state
877  case 0x63: return a->targetairport; // Airport to which the action refers
878  case 0x66: return MapAircraftMovementAction(a); // Current movement action
879  }
880  break;
881  }
882 
883  default: break;
884  }
885 
886  DEBUG(grf, 1, "Unhandled vehicle variable 0x%X, type 0x%X", variable, (uint)v->type);
887 
888  *available = false;
889  return UINT_MAX;
890 }
891 
892 /* virtual */ uint32 VehicleScopeResolver::GetVariable(byte variable, uint32 parameter, bool *available) const
893 {
894  if (this->v == nullptr) {
895  /* Vehicle does not exist, so we're in a purchase list */
896  switch (variable) {
897  case 0x43: return GetCompanyInfo(_current_company, LiveryHelper(this->self_type, nullptr)); // Owner information
898  case 0x46: return 0; // Motion counter
899  case 0x47: { // Vehicle cargo info
900  const Engine *e = Engine::Get(this->self_type);
901  CargoID cargo_type = e->GetDefaultCargoType();
902  if (cargo_type != CT_INVALID) {
903  const CargoSpec *cs = CargoSpec::Get(cargo_type);
904  return (cs->classes << 16) | (cs->weight << 8) | this->ro.grffile->cargo_map[cargo_type];
905  } else {
906  return 0x000000FF;
907  }
908  }
909  case 0x48: return Engine::Get(this->self_type)->flags; // Vehicle Type Info
910  case 0x49: return _cur_year; // 'Long' format build year
911  case 0x4B: return _date; // Long date of last service
912  case 0x92: return Clamp(_date - DAYS_TILL_ORIGINAL_BASE_YEAR, 0, 0xFFFF); // Date of last service
913  case 0x93: return GB(Clamp(_date - DAYS_TILL_ORIGINAL_BASE_YEAR, 0, 0xFFFF), 8, 8);
914  case 0xC4: return Clamp(_cur_year, ORIGINAL_BASE_YEAR, ORIGINAL_MAX_YEAR) - ORIGINAL_BASE_YEAR; // Build year
915  case 0xDA: return INVALID_VEHICLE; // Next vehicle
916  case 0xF2: return 0; // Cargo subtype
917  }
918 
919  *available = false;
920  return UINT_MAX;
921  }
922 
923  return VehicleGetVariable(const_cast<Vehicle*>(this->v), this, variable, parameter, available);
924 }
925 
926 
927 /* virtual */ const SpriteGroup *VehicleResolverObject::ResolveReal(const RealSpriteGroup *group) const
928 {
929  const Vehicle *v = this->self_scope.v;
930 
931  if (v == nullptr) {
932  if (group->num_loading > 0) return group->loading[0];
933  if (group->num_loaded > 0) return group->loaded[0];
934  return nullptr;
935  }
936 
937  bool in_motion = !v->First()->current_order.IsType(OT_LOADING);
938 
939  uint totalsets = in_motion ? group->num_loaded : group->num_loading;
940 
941  if (totalsets == 0) return nullptr;
942 
943  uint set = (v->cargo.StoredCount() * totalsets) / max((uint16)1, v->cargo_cap);
944  set = min(set, totalsets - 1);
945 
946  return in_motion ? group->loaded[set] : group->loading[set];
947 }
948 
954 static const GRFFile *GetEngineGrfFile(EngineID engine_type)
955 {
956  const Engine *e = Engine::Get(engine_type);
957  return (e != nullptr) ? e->GetGRF() : nullptr;
958 }
959 
970 VehicleResolverObject::VehicleResolverObject(EngineID engine_type, const Vehicle *v, WagonOverride wagon_override, bool info_view,
971  CallbackID callback, uint32 callback_param1, uint32 callback_param2)
972  : ResolverObject(GetEngineGrfFile(engine_type), callback, callback_param1, callback_param2),
973  self_scope(*this, engine_type, v, info_view),
974  parent_scope(*this, engine_type, ((v != nullptr) ? v->First() : v), info_view),
975  relative_scope(*this, engine_type, v, info_view),
976  cached_relative_count(0)
977 {
978  if (wagon_override == WO_SELF) {
979  this->root_spritegroup = GetWagonOverrideSpriteSet(engine_type, CT_DEFAULT, engine_type);
980  } else {
981  if (wagon_override != WO_NONE && v != nullptr && v->IsGroundVehicle()) {
982  assert(v->engine_type == engine_type); // overrides make little sense with fake scopes
983 
984  /* For trains we always use cached value, except for callbacks because the override spriteset
985  * to use may be different than the one cached. It happens for callback 0x15 (refit engine),
986  * as v->cargo_type is temporary changed to the new type */
987  if (wagon_override == WO_CACHED && v->type == VEH_TRAIN) {
988  this->root_spritegroup = Train::From(v)->tcache.cached_override;
989  } else {
990  this->root_spritegroup = GetWagonOverrideSpriteSet(v->engine_type, v->cargo_type, v->GetGroundVehicleCache()->first_engine);
991  }
992  }
993 
994  if (this->root_spritegroup == nullptr) {
995  const Engine *e = Engine::Get(engine_type);
996  CargoID cargo = v != nullptr ? v->cargo_type : CT_PURCHASE;
997  assert(cargo < lengthof(e->grf_prop.spritegroup));
998  this->root_spritegroup = e->grf_prop.spritegroup[cargo] != nullptr ? e->grf_prop.spritegroup[cargo] : e->grf_prop.spritegroup[CT_DEFAULT];
999  }
1000  }
1001 }
1002 
1003 
1004 
1005 void GetCustomEngineSprite(EngineID engine, const Vehicle *v, Direction direction, EngineImageType image_type, VehicleSpriteSeq *result)
1006 {
1008  result->Clear();
1009 
1010  bool sprite_stack = HasBit(EngInfo(engine)->misc_flags, EF_SPRITE_STACK);
1011  uint max_stack = sprite_stack ? lengthof(result->seq) : 1;
1012  for (uint stack = 0; stack < max_stack; ++stack) {
1013  object.ResetState();
1014  object.callback_param1 = image_type | (stack << 8);
1015  const SpriteGroup *group = object.Resolve();
1016  uint32 reg100 = sprite_stack ? GetRegister(0x100) : 0;
1017  if (group != nullptr && group->GetNumResults() != 0) {
1018  result->seq[result->count].sprite = group->GetResult() + (direction % group->GetNumResults());
1019  result->seq[result->count].pal = GB(reg100, 0, 16); // zero means default recolouring
1020  result->count++;
1021  }
1022  if (!HasBit(reg100, 31)) break;
1023  }
1024 }
1025 
1026 
1027 void GetRotorOverrideSprite(EngineID engine, const struct Aircraft *v, bool info_view, EngineImageType image_type, VehicleSpriteSeq *result)
1028 {
1029  const Engine *e = Engine::Get(engine);
1030 
1031  /* Only valid for helicopters */
1032  assert(e->type == VEH_AIRCRAFT);
1033  assert(!(e->u.air.subtype & AIR_CTOL));
1034 
1036  result->Clear();
1037  uint rotor_pos = v == nullptr || info_view ? 0 : v->Next()->Next()->state;
1038 
1039  bool sprite_stack = HasBit(e->info.misc_flags, EF_SPRITE_STACK);
1040  uint max_stack = sprite_stack ? lengthof(result->seq) : 1;
1041  for (uint stack = 0; stack < max_stack; ++stack) {
1042  object.ResetState();
1043  object.callback_param1 = image_type | (stack << 8);
1044  const SpriteGroup *group = object.Resolve();
1045  uint32 reg100 = sprite_stack ? GetRegister(0x100) : 0;
1046  if (group != nullptr && group->GetNumResults() != 0) {
1047  result->seq[result->count].sprite = group->GetResult() + (rotor_pos % group->GetNumResults());
1048  result->seq[result->count].pal = GB(reg100, 0, 16); // zero means default recolouring
1049  result->count++;
1050  }
1051  if (!HasBit(reg100, 31)) break;
1052  }
1053 }
1054 
1055 
1062 {
1063  assert(v->type == VEH_TRAIN);
1064  return Train::From(v)->tcache.cached_override != nullptr;
1065 }
1066 
1076 uint16 GetVehicleCallback(CallbackID callback, uint32 param1, uint32 param2, EngineID engine, const Vehicle *v)
1077 {
1078  VehicleResolverObject object(engine, v, VehicleResolverObject::WO_UNCACHED, false, callback, param1, param2);
1079  return object.ResolveCallback();
1080 }
1081 
1092 uint16 GetVehicleCallbackParent(CallbackID callback, uint32 param1, uint32 param2, EngineID engine, const Vehicle *v, const Vehicle *parent)
1093 {
1094  VehicleResolverObject object(engine, v, VehicleResolverObject::WO_NONE, false, callback, param1, param2);
1095  object.parent_scope.SetVehicle(parent);
1096  return object.ResolveCallback();
1097 }
1098 
1099 
1100 /* Callback 36 handlers */
1101 uint GetVehicleProperty(const Vehicle *v, PropertyID property, uint orig_value)
1102 {
1103  return GetEngineProperty(v->engine_type, property, orig_value, v);
1104 }
1105 
1106 
1107 uint GetEngineProperty(EngineID engine, PropertyID property, uint orig_value, const Vehicle *v)
1108 {
1109  uint16 callback = GetVehicleCallback(CBID_VEHICLE_MODIFY_PROPERTY, property, 0, engine, v);
1110  if (callback != CALLBACK_FAILED) return callback;
1111 
1112  return orig_value;
1113 }
1114 
1115 
1116 static void DoTriggerVehicle(Vehicle *v, VehicleTrigger trigger, byte base_random_bits, bool first)
1117 {
1118  /* We can't trigger a non-existent vehicle... */
1119  assert(v != nullptr);
1120 
1122  object.waiting_triggers = v->waiting_triggers | trigger;
1123  v->waiting_triggers = object.waiting_triggers; // store now for var 5F
1124 
1125  const SpriteGroup *group = object.Resolve();
1126  if (group == nullptr) return;
1127 
1128  /* Store remaining triggers. */
1129  v->waiting_triggers = object.GetRemainingTriggers();
1130 
1131  /* Rerandomise bits. Scopes other than SELF are invalid for rerandomisation. For bug-to-bug-compatibility with TTDP we ignore the scope. */
1132  byte new_random_bits = Random();
1133  uint32 reseed = object.GetReseedSum();
1134  v->random_bits &= ~reseed;
1135  v->random_bits |= (first ? new_random_bits : base_random_bits) & reseed;
1136 
1137  switch (trigger) {
1138  case VEHICLE_TRIGGER_NEW_CARGO:
1139  /* All vehicles in chain get ANY_NEW_CARGO trigger now.
1140  * So we call it for the first one and they will recurse.
1141  * Indexing part of vehicle random bits needs to be
1142  * same for all triggered vehicles in the chain (to get
1143  * all the random-cargo wagons carry the same cargo,
1144  * i.e.), so we give them all the NEW_CARGO triggered
1145  * vehicle's portion of random bits. */
1146  assert(first);
1147  DoTriggerVehicle(v->First(), VEHICLE_TRIGGER_ANY_NEW_CARGO, new_random_bits, false);
1148  break;
1149 
1150  case VEHICLE_TRIGGER_DEPOT:
1151  /* We now trigger the next vehicle in chain recursively.
1152  * The random bits portions may be different for each
1153  * vehicle in chain. */
1154  if (v->Next() != nullptr) DoTriggerVehicle(v->Next(), trigger, 0, true);
1155  break;
1156 
1157  case VEHICLE_TRIGGER_EMPTY:
1158  /* We now trigger the next vehicle in chain
1159  * recursively. The random bits portions must be same
1160  * for each vehicle in chain, so we give them all
1161  * first chained vehicle's portion of random bits. */
1162  if (v->Next() != nullptr) DoTriggerVehicle(v->Next(), trigger, first ? new_random_bits : base_random_bits, false);
1163  break;
1164 
1165  case VEHICLE_TRIGGER_ANY_NEW_CARGO:
1166  /* Now pass the trigger recursively to the next vehicle
1167  * in chain. */
1168  assert(!first);
1169  if (v->Next() != nullptr) DoTriggerVehicle(v->Next(), VEHICLE_TRIGGER_ANY_NEW_CARGO, base_random_bits, false);
1170  break;
1171 
1172  case VEHICLE_TRIGGER_CALLBACK_32:
1173  /* Do not do any recursion */
1174  break;
1175  }
1176 }
1177 
1178 void TriggerVehicle(Vehicle *v, VehicleTrigger trigger)
1179 {
1180  if (trigger == VEHICLE_TRIGGER_DEPOT) {
1181  /* store that the vehicle entered a depot this tick */
1183  }
1184 
1186  DoTriggerVehicle(v, trigger, 0, true);
1188 }
1189 
1190 /* Functions for changing the order of vehicle purchase lists */
1191 
1193  EngineID engine;
1194  uint target;
1195 };
1196 
1197 static std::vector<ListOrderChange> _list_order_changes;
1198 
1205 void AlterVehicleListOrder(EngineID engine, uint target)
1206 {
1207  /* Add the list order change to a queue */
1208  _list_order_changes.push_back({engine, target});
1209 }
1210 
1217 static bool EnginePreSort(const EngineID &a, const EngineID &b)
1218 {
1219  const EngineIDMapping &id_a = _engine_mngr.at(a);
1220  const EngineIDMapping &id_b = _engine_mngr.at(b);
1221 
1222  /* 1. Sort by engine type */
1223  if (id_a.type != id_b.type) return (int)id_a.type < (int)id_b.type;
1224 
1225  /* 2. Sort by scope-GRFID */
1226  if (id_a.grfid != id_b.grfid) return id_a.grfid < id_b.grfid;
1227 
1228  /* 3. Sort by local ID */
1229  return (int)id_a.internal_id < (int)id_b.internal_id;
1230 }
1231 
1236 {
1237  /* Pre-sort engines by scope-grfid and local index */
1238  std::vector<EngineID> ordering;
1239  for (const Engine *e : Engine::Iterate()) {
1240  ordering.push_back(e->index);
1241  }
1242  std::sort(ordering.begin(), ordering.end(), EnginePreSort);
1243 
1244  /* Apply Insertion-Sort operations */
1245  for (const ListOrderChange &it : _list_order_changes) {
1246  EngineID source = it.engine;
1247  uint local_target = it.target;
1248 
1249  const EngineIDMapping *id_source = _engine_mngr.data() + source;
1250  if (id_source->internal_id == local_target) continue;
1251 
1252  EngineID target = _engine_mngr.GetID(id_source->type, local_target, id_source->grfid);
1253  if (target == INVALID_ENGINE) continue;
1254 
1255  int source_index = find_index(ordering, source);
1256  int target_index = find_index(ordering, target);
1257 
1258  assert(source_index >= 0 && target_index >= 0);
1259  assert(source_index != target_index);
1260 
1261  EngineID *list = ordering.data();
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;
1269  }
1270  }
1271 
1272  /* Store final sort-order */
1273  uint index = 0;
1274  for (const EngineID &eid : ordering) {
1275  Engine::Get(eid)->list_position = index;
1276  ++index;
1277  }
1278 
1279  /* Clear out the queue */
1280  _list_order_changes.clear();
1281  _list_order_changes.shrink_to_fit();
1282 }
1283 
1289 {
1291 
1292  /* These variables we have to check; these are the ones with a cache. */
1293  static const int cache_entries[][2] = {
1294  { 0x40, NCVV_POSITION_CONSIST_LENGTH },
1295  { 0x41, NCVV_POSITION_SAME_ID_LENGTH },
1297  { 0x43, NCVV_COMPANY_INFORMATION },
1298  { 0x4D, NCVV_POSITION_IN_VEHICLE },
1299  };
1300  assert_compile(NCVV_END == lengthof(cache_entries));
1301 
1302  /* Resolve all the variables, so their caches are set. */
1303  for (size_t i = 0; i < lengthof(cache_entries); i++) {
1304  /* Only resolve when the cache isn't valid. */
1305  if (HasBit(v->grf_cache.cache_valid, cache_entries[i][1])) continue;
1306  bool stub;
1307  ro.GetScope(VSG_SCOPE_SELF)->GetVariable(cache_entries[i][0], 0, &stub);
1308  }
1309 
1310  /* Make sure really all bits are set. */
1311  assert(v->grf_cache.cache_valid == (1 << NCVV_END) - 1);
1312 }
StationID Source() const
Returns source of the first cargo packet in this list.
Definition: cargopacket.h:322
Road vehicle states.
static bool HasPowerOnRail(RailType enginetype, RailType tiletype)
Checks if an engine of the given RailType got power on a tile with a given RailType.
Definition: rail.h:332
TTDPAirportType ttd_airport_type
ttdpatch airport type (Small/Large/Helipad/Oilrig)
Interface to query and set values specific to a single VarSpriteGroupScope (action 2 scope)...
Date max_age
Maximum age.
Definition: vehicle_base.h:257
This bit will be set if the NewGRF var 41 currently stored is valid.
Definition: vehicle_base.h:57
Vehicle * Previous() const
Get the previous vehicle of this vehicle.
Definition: vehicle_base.h:586
Airplane wants to leave the airport.
Definition: airport.h:71
VehicleCargoList cargo
The cargo this vehicle is carrying.
Definition: vehicle_base.h:307
byte state
Definition: roadveh.h:109
Resolver for a vehicle scope.
Definition: newgrf_engine.h:22
Heading for hangar.
Definition: airport.h:62
Definition of stuff that is very close to a company, like the company struct itself.
uint32 motion_counter
counter to occasionally play a vehicle sound.
Definition: vehicle_base.h:294
Heading for terminal 1.
Definition: airport.h:63
Money value
Value of the vehicle.
Definition: vehicle_base.h:239
Airplane has reached end-point of the take-off runway.
Definition: airport.h:73
NewGRF handling of rail types.
static const uint CALLBACK_FAILED
Different values for Callback result evaluations.
Finite sTate mAchine (FTA) of an airport.
Definition: airport.h:143
Heading for helipad 2.
Definition: airport.h:70
This bit will be set if the NewGRF var 40 currently stored is valid.
Definition: vehicle_base.h:56
Direction direction
facing
Definition: vehicle_base.h:269
const AirportSpec * GetSpec() const
Get the AirportSpec that from the airport type of this airport.
Definition: station_base.h:320
uint8 weight
Weight of a single unit of this cargo type in 1/16 ton (62.5 kg).
Definition: cargotype.h:60
bool UsesWagonOverride(const Vehicle *v)
Check if a wagon is currently using a wagon override.
StationID targetairport
Airport to go to next.
Definition: aircraft.h:78
void AlterVehicleListOrder(EngineID engine, uint target)
Record a vehicle ListOrderChange.
void UnloadWagonOverrides(Engine *e)
Unload all wagon override sprite groups.
Money GetDisplayProfitThisYear() const
Gets the profit vehicle had this year.
Definition: vehicle_base.h:564
uint target
local ID
uint32 grfid
The GRF ID of the file the entity belongs to.
Definition: engine_base.h:158
ResolverObject & ro
Surrounding resolver object.
uint32 GetTriggers() const override
Get the triggers.
#define DAYS_TILL_ORIGINAL_BASE_YEAR
The offset in days from the &#39;_date == 0&#39; till &#39;ConvertYMDToDate(ORIGINAL_BASE_YEAR, 0, 1)&#39;.
Definition: date_type.h:80
VarSpriteGroupScope
Train vehicle type.
Definition: vehicle_type.h:24
static const GRFFile * GetEngineGrfFile(EngineID engine_type)
Get the grf file associated with an engine type.
static Titem * Get(size_t index)
Returns Titem with given index.
Definition: pool_type.hpp:291
bool CanCarryCargo() const
Determines whether an engine can carry something.
Definition: engine.cpp:171
Functions related to dates.
uint8 GetReverseRoadTypeTranslation(RoadType roadtype, const GRFFile *grffile)
Perform a reverse roadtype lookup to get the GRF internal ID.
Conventional Take Off and Landing, i.e. planes.
Definition: engine_type.h:92
Heading for terminal 6.
Definition: airport.h:68
static const Year ORIGINAL_MAX_YEAR
The maximum year of the original TTD.
Definition: date_type.h:53
const AirportFTAClass * GetFTA() const
Get the finite-state machine for this airport or the finite-state machine for the dummy airport in ca...
Definition: station_base.h:332
byte breakdown_delay
Counter for managing breakdown length.
Definition: vehicle_base.h:262
West.
Helicopter landing.
Definition: airport.h:55
Base for the train class.
uint16 GetVehicleCallbackParent(CallbackID callback, uint32 param1, uint32 param2, EngineID engine, const Vehicle *v, const Vehicle *parent)
Evaluate a newgrf callback for vehicles with a different vehicle for parent scope.
Functions related to debugging.
static T SetBit(T &x, const uint8 y)
Set a bit in a variable.
Called to spawn visual effects for vehicles.
byte pos
Next desired position of the aircraft.
Definition: aircraft.h:76
uint16 cur_speed
current speed
Definition: vehicle_base.h:291
Taxiing at the airport.
Definition: airport.h:53
Interface for SpriteGroup-s to access the gamestate.
const SpriteGroup * ResolveReal(const RealSpriteGroup *group) const override
Get the real sprites of the grf.
Ship vehicle type.
Definition: vehicle_type.h:26
GRFFilePropsBase< NUM_CARGO+2 > grf_prop
Properties related the the grf file.
Definition: engine_base.h:58
Maximal number of cargo types in a game.
Definition: cargo_type.h:64
static byte MapAircraftMovementState(const Aircraft *v)
Map OTTD aircraft movement states to TTDPatch style movement states (VarAction 2 Variable 0xE2) ...
byte spritenum
currently displayed sprite index 0xfd == custom sprite, 0xfe == custom second head sprite 0xff == res...
Definition: vehicle_base.h:277
Both directions faces to the same direction.
Specification of a cargo type.
Definition: cargotype.h:55
static const Livery * LiveryHelper(EngineID engine, const Vehicle *v)
Determines the livery of an engine.
uint16 wait_counter
Ticks waiting in front of a signal, ticks being stuck or a counter for forced proceeding through sign...
Definition: train.h:100
Functions related to vehicles.
Aircraft, helicopters, rotors and their shadows belong to this class.
Definition: aircraft.h:74
This bit will be set if the NewGRF var 43 currently stored is valid.
Definition: vehicle_base.h:59
Called when the company (or AI) tries to start or stop a vehicle.
const Livery * GetEngineLivery(EngineID engine_type, CompanyID company, EngineID parent_engine_type, const Vehicle *v, byte livery_setting)
Determines the livery for a vehicle.
Definition: vehicle.cpp:1894
Vehicle data structure.
Definition: vehicle_base.h:210
void Clear()
Clear all information.
Definition: vehicle_base.h:153
uint DaysInTransit() const
Returns average number of days in transit for a cargo entity.
Definition: cargopacket.h:255
Set when using the callback resolve system, but not to resolve a callback.
Tindex index
Index of this pool item.
Definition: pool_type.hpp:189
Vehicle is flying in the air.
Definition: airport.h:75
EngineID GetID(VehicleType type, uint16 grf_local_id, uint32 grfid)
Looks up an EngineID in the EngineOverrideManager.
Definition: engine.cpp:510
void CommitVehicleListOrderChanges()
Deternine default engine sorting and execute recorded ListOrderChanges from AlterVehicleListOrder.
T * First() const
Get the first vehicle in the chain.
Definition: vehicle_base.h:996
Vehicle is unloading cargo.
Definition: vehicle_base.h:43
Base for aircraft.
PropertyID
List of NewGRF properties used in Action 0 or Callback 0x36 (CBID_VEHICLE_MODIFY_PROPERTY).
virtual ScopeResolver * GetScope(VarSpriteGroupScope scope=VSG_SCOPE_SELF, byte relative=0)
Get a resolver for the scope.
StationID last_station_visited
The last station we stopped at.
Definition: vehicle_base.h:300
uint16 reliability_spd_dec
Reliability decrease speed.
Definition: vehicle_base.h:260
uint32 position_consist_length
Cache for NewGRF var 40.
Definition: vehicle_base.h:67
byte user_def_data
Cached property 0x25. Can be set by Callback 0x36.
Definition: train.h:76
Determine whether a wagon can be attached to an already existing train.
Relative position (vehicles only)
byte num_loaded
Number of loaded groups.
uint32 cached_power
Total power of the consist (valid only for the first engine).
uint32 reseed[VSG_END]
Collects bits to rerandomise while triggering triggers.
static const VehicleID INVALID_VEHICLE
Constant representing a non-existing vehicle.
Definition: vehicle_type.h:55
RoadType
The different roadtypes we support.
Definition: road_type.h:22
static T max(const T a, const T b)
Returns the maximum of two values.
Definition: math_func.hpp:24
uint16 MapOldOrder() const
Pack this order into a 16 bits integer as close to the TTD representation as possible.
Definition: order_cmd.cpp:207
uint16 classes
Classes of this cargo type.
Definition: cargotype.h:78
byte vehstatus
Status.
Definition: vehicle_base.h:315
EngineImageType
Visualisation contexts of vehicles and engines.
Definition: vehicle_type.h:85
byte flags
Flags of the engine.
Definition: engine_base.h:33
Year _cur_year
Current year, starting at 0.
Definition: date.cpp:24
Helicopter wants to land.
Definition: airport.h:78
uint StoredCount() const
Returns sum of cargo on board the vehicle (ie not only reserved).
Definition: cargopacket.h:351
uint32 GetRandomBits() const override
Get a few random bits.
byte overtaking
Set to RVSB_DRIVE_SIDE when overtaking, otherwise 0.
Definition: roadveh.h:112
static Train * From(Vehicle *v)
Converts a Vehicle to SpecializedVehicle with type checking.
uint16 cached_max_speed
Maximum speed of the consist (minimum of the max speed of all vehicles in the consist).
Definition: vehicle_base.h:121
const Engine * GetEngine() const
Retrieves the engine of the vehicle.
Definition: vehicle.cpp:741
CargoID GetDefaultCargoType() const
Determines the default cargo type of an engine.
Definition: engine_base.h:79
bool IsNormalAircraft() const
Check if the aircraft type is a normal flying device; eg not a rotor or a shadow. ...
Definition: aircraft.h:121
Go exactly to the destination coordinates.
Definition: airport.h:52
static uint ClampU(const uint a, const uint min, const uint max)
Clamp an unsigned integer between an interval.
Definition: math_func.hpp:182
EngineID first_engine
Cached EngineID of the front vehicle. INVALID_ENGINE for the front vehicle itself.
Holding pattern movement (above the airport).
Definition: airport.h:56
Pseudo random number generator.
const SpriteGroup * root_spritegroup
Root SpriteGroup to use for resolving.
byte breakdown_ctr
Counter for managing breakdown events.
Definition: vehicle_base.h:261
Invalid cargo type.
Definition: cargo_type.h:68
Vehicle * Move(int n)
Get the vehicle at offset n of this vehicle chain.
Definition: vehicle_base.h:621
byte subtype
subtype (Filled with values from AircraftSubType/DisasterSubType/EffectVehicleType/GroundVehicleSubty...
Definition: vehicle_base.h:325
Buses, trucks and trams belong to this class.
Definition: roadveh.h:107
uint16 cargo_cap
total capacity
Definition: vehicle_base.h:305
Vehicle is a prototype (accepted as exclusive preview).
Definition: vehicle_base.h:44
Turn slowly (mostly used in the air).
Definition: airport.h:50
byte acceleration
used by train & aircraft
Definition: vehicle_base.h:293
static uint32 GetRegister(uint i)
Gets the value of a so-called newgrf "register".
Resolve no wagon overrides.
Definition: newgrf_engine.h:50
virtual const SpriteGroup * Resolve(ResolverObject &object) const
Base sprite group resolver.
Action 2 handling.
uint16 internal_id
The internal ID within the GRF file.
Definition: engine_base.h:159
virtual bool IsPrimaryVehicle() const
Whether this is the primary vehicle in the chain.
Definition: vehicle_base.h:431
UnitID unitnumber
unit number, for display purposes only
Definition: vehicle_base.h:289
const SpriteGroup ** loaded
List of loaded groups (can be SpriteIDs or Callback results)
byte cargo_subtype
Used for livery refits (NewGRF variations)
Definition: vehicle_base.h:304
byte subtype
Type of aircraft.
Definition: engine_type.h:101
static byte MapAircraftMovementAction(const Aircraft *v)
Map OTTD aircraft movement states to TTDPatch style movement actions (VarAction 2 Variable 0xE6) This...
Resolve wagon overrides.
Definition: newgrf_engine.h:51
Heading for terminal 7.
Definition: airport.h:80
GroundVehicleCache * GetGroundVehicleCache()
Access the ground vehicle cache of the vehicle.
Definition: vehicle.cpp:2824
bool IsType(OrderType type) const
Check whether this order is of the given type.
Definition: order_base.h:61
Called to modify various vehicle properties.
Resolver for a vehicle (chain)
Definition: newgrf_engine.h:47
T * Next() const
Get next vehicle in the chain.
Heading for terminal 2.
Definition: airport.h:64
Draw vehicle by stacking multiple sprites.
Definition: engine_type.h:161
Definition of base types and functions in a cross-platform compatible way.
static const uint VEHICLE_LENGTH
The length of a vehicle in tile units.
Definition: vehicle_type.h:76
bool IsArticulatedPart() const
Check if the vehicle is an articulated part of an engine.
Definition: vehicle_base.h:890
A number of safeguards to prevent using unsafe methods.
void InvalidateNewGRFCacheOfChain()
Invalidates cached NewGRF variables of all vehicles in the chain (after the current vehicle) ...
Definition: vehicle_base.h:458
Direction
Defines the 8 directions on the map.
void VehicleEnteredDepotThisTick(Vehicle *v)
Adds a vehicle to the list of vehicles that visited a depot this tick.
Definition: vehicle.cpp:892
byte waiting_triggers
Triggers to be yet matched before rerandomizing the random bits.
Definition: vehicle_base.h:298
DirDiff
Enumeration for the difference between two directions.
Station * GetTargetAirportIfValid(const Aircraft *v)
Returns aircraft&#39;s target station if v->target_airport is a valid station with airport.
uint32 position_same_id_length
Cache for NewGRF var 41.
Definition: vehicle_base.h:68
void FillNewGRFVehicleCache(const Vehicle *v)
Fill the grf_cache of the given vehicle.
VehicleType type
Vehicle type, ie VEH_ROAD, VEH_TRAIN, etc.
Definition: engine_base.h:40
virtual int GetCurrentMaxSpeed() const
Calculates the maximum speed of the vehicle under its current conditions.
Definition: vehicle_base.h:490
CargoID cargo_type
type of cargo this vehicle is carrying
Definition: vehicle_base.h:303
Information about a particular livery.
Definition: livery.h:78
NewGRF handling of road types.
static T * ReallocT(T *t_ptr, size_t num_elements)
Simplified reallocation function that allocates the specified number of elements of the given type...
Definition: alloc_func.hpp:111
uint16 load_unload_ticks
Ticks to wait before starting next cycle.
Definition: vehicle_base.h:323
static const byte LIT_ALL
Show the liveries of all companies.
Definition: livery.h:17
byte misc_flags
Miscellaneous flags.
Definition: engine_type.h:142
TileIndex tile
Current tile index.
Definition: vehicle_base.h:228
VehicleResolverObject(EngineID engine_type, const Vehicle *v, WagonOverride wagon_override, bool info_view=false, CallbackID callback=CBID_NO_CALLBACK, uint32 callback_param1=0, uint32 callback_param2=0)
Resolver of a vehicle (chain).
Disaster vehicle type.
Definition: vehicle_type.h:32
This bit will be set if the NewGRF var 42 currently stored is valid.
Definition: vehicle_base.h:58
bool HasArticulatedPart() const
Check if an engine has an articulated part.
Definition: vehicle_base.h:899
const SpriteGroup ** loading
List of loading groups (can be SpriteIDs or Callback results)
static DirDiff DirDifference(Direction d0, Direction d1)
Calculate the difference between two directions.
Heading for helipad 3.
Definition: airport.h:82
Owner owner
Which company owns the vehicle?
Definition: vehicle_base.h:271
Sprite sequence for a vehicle part.
Definition: vehicle_base.h:128
static bool EnginePreSort(const EngineID &a, const EngineID &b)
Comparator function to sort engines via scope-GRFID and local ID.
Heading for terminal 3.
Definition: airport.h:65
uint8 cargo_map[NUM_CARGO]
Inverse cargo translation table (CargoID -> local ID)
Definition: newgrf.h:127
Called to determine if a specific colour map should be used for a vehicle instead of the default live...
Airplane has arrived at a runway for take-off.
Definition: airport.h:72
#define lengthof(x)
Return the length of an fixed size array.
Definition: depend.cpp:40
const AirportMovingData * MovingData(byte position) const
Get movement data at a position.
Definition: airport.h:170
static T min(const T a, const T b)
Returns the minimum of two values.
Definition: math_func.hpp:40
Resolved object itself.
byte random_bits
Bits used for determining which randomized variational spritegroups to use when drawing.
Definition: vehicle_base.h:297
byte breakdowns_since_last_service
Counter for the amount of breakdowns.
Definition: vehicle_base.h:263
uint16 reliability
Reliability.
Definition: vehicle_base.h:259
static const Year ORIGINAL_BASE_YEAR
The minimum starting year/base year of the original TTD.
Definition: date_type.h:49
Vehicle * First() const
Get the first vehicle of this vehicle chain.
Definition: vehicle_base.h:592
byte tick_counter
Increased by one for each tick.
Definition: vehicle_base.h:312
uint16 crashed_ctr
Animation counter when the vehicle has crashed.
Definition: roadveh.h:114
const struct SpriteGroup * spritegroup[Tcnt]
pointer to the different sprites of the entity
All ships have this type.
Definition: ship.h:26
Year build_year
Year the vehicle has been built.
Definition: vehicle_base.h:255
byte state
State of the airport.
Definition: aircraft.h:79
virtual uint32 GetVariable(byte variable, uint32 parameter, bool *available) const
Get a variable value.
byte turn_counter
Ticks between each turn to prevent > 45 degree turns.
Definition: aircraft.h:82
static T Clamp(const T a, const T min, const T max)
Clamp a value between an interval.
Definition: math_func.hpp:137
#define DEBUG(name, level,...)
Output a line of debugging information.
Definition: debug.h:35
&#39;Train&#39; is either a loco or a wagon.
Definition: train.h:85
VehicleType type
The engine type.
Definition: engine_base.h:160
TileIndex tile
The base tile of the area.
Definition: tilearea_type.h:17
byte breakdown_chance
Current chance of breakdowns.
Definition: vehicle_base.h:264
This bit will be set if the NewGRF var 4D currently stored is valid.
Definition: vehicle_base.h:60
byte num_loading
Number of loading groups.
Wagon is powered.
Definition: train.h:27
Effect vehicle type (smoke, explosions, sparks, bubbles)
Definition: vehicle_type.h:31
static const EngineID INVALID_ENGINE
Constant denoting an invalid engine.
Definition: engine_type.h:174
const GRFFile * grffile
GRFFile the resolved SpriteGroup belongs to.
static int32 ClampToI32(const int64 a)
Reduce a signed 64-bit int to a signed 32-bit one.
Definition: math_func.hpp:201
Functions related to companies.
uint32 company_information
Cache for NewGRF var 43.
Definition: vehicle_base.h:70
Called for every vehicle every 32 days (not all on same date though).
RailType GetTileRailType(TileIndex tile)
Return the rail type of tile, or INVALID_RAILTYPE if this is no rail tile.
Definition: rail.cpp:155
TrackBits state
The "track" the ship is following.
Definition: ship.h:27
RailType
Enumeration for all possible railtypes.
Definition: rail_type.h:27
bool IsGroundVehicle() const
Check if the vehicle is a ground vehicle.
Definition: vehicle_base.h:469
const GRFFile * GetGRF() const
Retrieve the NewGRF the engine is tied to.
Definition: engine_base.h:138
DestinationID GetDestination() const
Gets the destination of this order.
Definition: order_base.h:94
static Pool::IterateWrapper< Titem > Iterate(size_t from=0)
Returns an iterable ensemble of all valid Titem.
Definition: pool_type.hpp:340
byte subspeed
fractional speed
Definition: vehicle_base.h:292
Used for vehicle var 0xFE bit 8 (toggled each time the train is reversed, accurate for first vehicle ...
Definition: train.h:31
uint16 EngineID
Unique identification number of an engine.
Definition: engine_type.h:21
static CargoSpec * Get(size_t index)
Retrieve cargo details for the given cargo ID.
Definition: cargotype.h:117
Cargo support for NewGRFs.
Vehicle * Next() const
Get the next vehicle of this vehicle.
Definition: vehicle_base.h:579
Date date_of_last_service
Last date the vehicle had a service at a depot.
Definition: vehicle_base.h:258
Airplane wants to land.
Definition: airport.h:76
uint32 GetVariable(byte variable, uint32 parameter, bool *available) const override
Get a variable value.
uint32 consist_cargo_information
Cache for NewGRF var 42. (Note: The cargotype is untranslated in the cache because the accessing GRF ...
Definition: vehicle_base.h:69
Related object of the resolved one.
Resolve self-override (helicopter rotors and such).
Definition: newgrf_engine.h:53
uint32 position_in_vehicle
Cache for NewGRF var 4D.
Definition: vehicle_base.h:71
void CDECL grfmsg(int severity, const char *str,...)
DEBUG() function dedicated to newGRF debugging messages Function is essentially the same as DEBUG(grf...
Definition: newgrf.cpp:375
CallbackID callback
Callback being resolved.
static uint GB(const T x, const uint8 s, const uint8 n)
Fetch n bits from x, started at bit s.
Heading for terminal 8.
Definition: airport.h:81
VehicleType type
Type of vehicle.
Definition: vehicle_type.h:52
uint32 GetCompanyInfo(CompanyID owner, const Livery *l)
Returns company information like in vehicle var 43 or station var 43.
Reverse the visible direction of the vehicle.
Definition: train.h:28
End of the bits.
Definition: vehicle_base.h:61
uint8 GetReverseRailTypeTranslation(RailType railtype, const GRFFile *grffile)
Perform a reverse railtype lookup to get the GRF internal ID.
int32 z_pos
z coordinate.
Definition: vehicle_base.h:268
Vehicle is not visible.
Definition: vehicle_base.h:30
Same as AT_LARGE.
CompanyID _current_company
Company currently doing an action.
Definition: company_cmd.cpp:45
static bool IsValidID(size_t index)
Tests whether given index can be used to get valid (non-nullptr) Titem.
Definition: pool_type.hpp:280
uint16 local_id
id defined by the grf file for this entity
Heading for terminal 5.
Definition: airport.h:67
uint32 GetGRFID() const
Retrieve the GRF ID of the NewGRF the vehicle is tied to.
Definition: vehicle.cpp:761
Base for ships.
Heading for terminal 4.
Definition: airport.h:66
ScopeResolver * GetScope(VarSpriteGroupScope scope=VSG_SCOPE_SELF, byte relative=0) override
Get a resolver for the scope.
VehicleOrderID GetNumOrders() const
Get the number of orders this vehicle has.
Definition: vehicle_base.h:685
uint16 GetVehicleCallback(CallbackID callback, uint32 param1, uint32 param2, EngineID engine, const Vehicle *v)
Evaluate a newgrf callback for vehicles.
Aircraft vehicle type.
Definition: vehicle_type.h:27
static void free(const void *ptr)
Version of the standard free that accepts const pointers.
Definition: depend.cpp:129
uint8 cached_veh_length
Length of this vehicle in units of 1/VEHICLE_LENGTH of normal length. It is cached because this can b...
Airport airport
Tile area the airport covers.
Definition: station_base.h:464
static DirDiff ChangeDirDiff(DirDiff d, DirDiff delta)
Applies two differences together.
EngineID engine_type
The type of engine used for this vehicle.
Definition: vehicle_base.h:286
const struct GRFFile * grffile
grf file that introduced this entity
uint8 bitnum
Cargo bit number, is INVALID_CARGO for a non-used spec.
Definition: cargotype.h:56
CallbackID
List of implemented NewGRF callbacks.
Heading for helipad 1.
Definition: airport.h:69
int32 x_pos
x coordinate.
Definition: vehicle_base.h:266
Helicopter wants to finish landing.
Definition: airport.h:79
uint16 vehicle_flags
Used for gradual loading and other miscellaneous things (.
Definition: base_consist.h:30
static bool HasBit(const T x, const uint8 y)
Checks if a bit in a value is set.
Helicopter take-off.
Definition: airport.h:54
Set when calling a randomizing trigger (almost undocumented).
uint8 cache_valid
Bitset that indicates which cache values are valid.
Definition: vehicle_base.h:72
static const TileIndex INVALID_TILE
The very nice invalid tile marker.
Definition: tile_type.h:83
uint16 flag
special flags when moving towards the destination.
Definition: airport.h:134
byte CargoID
Cargo slots to indicate a cargo type within a game.
Definition: cargo_type.h:20
int32 y_pos
y coordinate.
Definition: vehicle_base.h:267
One direction is the opposite of the other one.
static uint32 PositionHelper(const Vehicle *v, bool consecutive)
Helper to get the position of a vehicle within a chain of vehicles.
SpriteID sprite
The &#39;real&#39; sprite.
Definition: gfx_type.h:23
Base classes/functions for stations.
VehicleCache vcache
Cache of often used vehicle values.
Definition: vehicle_base.h:328
Date _date
Current date in days (day counter)
Definition: date.cpp:26
Date age
Age in days.
Definition: vehicle_base.h:256
VehicleOrderID cur_real_order_index
The index to the current real (non-implicit) order.
Definition: base_consist.h:27
Airplane wants to finish landing.
Definition: airport.h:77
static uint16 ClampToU16(const uint64 a)
Reduce an unsigned 64-bit int to an unsigned 16-bit one.
Definition: math_func.hpp:213
Station data structure.
Definition: station_base.h:450
NewGRFCache grf_cache
Cache of often used calculated NewGRF values.
Definition: vehicle_base.h:327
Money GetDisplayProfitLastYear() const
Gets the profit vehicle had last year.
Definition: vehicle_base.h:570
Road vehicle type.
Definition: vehicle_type.h:25
int find_index(std::vector< T > const &vec, T const &item)
Helper function to get the index of an item Consider using std::set, std::unordered_set or std::flat_...
byte day_counter
Increased by one for each day.
Definition: vehicle_base.h:311
static RailType GetRailType(TileIndex t)
Gets the rail type of the given tile.
Definition: rail_map.h:115
byte delta_z
Z adjustment for helicopter pads.
Definition: airport.h:183
Order current_order
The current order (+ status, like: loading)
Definition: vehicle_base.h:316
bool IsEngine() const
Check if a vehicle is an engine (can be first in a consist).
GroundVehicleCache gcache
Cache of often calculated values.
byte overtaking_ctr
The length of the current overtake attempt.
Definition: roadveh.h:113
Dynamic data of a loaded NewGRF.
Definition: newgrf.h:105
Helicopter wants to leave the airport.
Definition: airport.h:74
PaletteID pal
The palette (use PAL_NONE) if not needed)
Definition: gfx_type.h:24
void SetEngineGRF(EngineID engine, const GRFFile *file)
Tie a GRFFile entry to an engine, to allow us to retrieve GRF parameters etc during a game...
Resolve wagon overrides using TrainCache::cached_override.
Definition: newgrf_engine.h:52