Translations update
[openttd/fttd.git] / src / newgrf_station.cpp
blobca1b45611a23b495f5dfdd56f81a73c75ef22584
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_station.cpp Functions for dealing with station classes and custom stations. */
12 #include "stdafx.h"
13 #include "debug.h"
14 #include "station_base.h"
15 #include "waypoint_base.h"
16 #include "roadstop_base.h"
17 #include "newgrf_cargo.h"
18 #include "newgrf_station.h"
19 #include "newgrf_spritegroup.h"
20 #include "newgrf_sound.h"
21 #include "newgrf_railtype.h"
22 #include "town.h"
23 #include "newgrf_town.h"
24 #include "company_func.h"
25 #include "map/slope.h"
26 #include "newgrf_animation_base.h"
27 #include "newgrf_class_func.h"
28 #include "tile_cmd.h"
29 #include "station_func.h"
32 template <>
33 /* static */ void NewGRFClass <StationSpec, StationClassID, STAT_CLASS_MAX>::InsertDefaults()
35 /* Set up initial data */
36 classes[0].global_id = 'DFLT';
37 classes[0].name = STR_STATION_CLASS_DFLT;
38 classes[0].Insert(NULL);
40 classes[1].global_id = 'WAYP';
41 classes[1].name = STR_STATION_CLASS_WAYP;
42 classes[1].Insert(NULL);
45 template <>
46 bool NewGRFClass <StationSpec, StationClassID, STAT_CLASS_MAX>::IsUIAvailable (uint index) const
48 return true;
51 INSTANTIATE_NEWGRF_CLASS_METHODS(StationClass)
53 static const uint NUM_STATIONSSPECS_PER_STATION = 255; ///< Maximum number of parts per station.
55 enum TriggerArea {
56 TA_TILE,
57 TA_PLATFORM,
58 TA_WHOLE,
61 struct ETileArea : TileArea {
62 ETileArea(const BaseStation *st, TileIndex tile, TriggerArea ta)
64 switch (ta) {
65 default: NOT_REACHED();
67 case TA_TILE:
68 this->tile = tile;
69 this->w = 1;
70 this->h = 1;
71 break;
73 case TA_PLATFORM: {
74 TileIndex start, end;
75 Axis axis = GetRailStationAxis(tile);
76 TileIndexDiff delta = TileOffsByDiagDir(AxisToDiagDir(axis));
78 for (end = tile; IsRailStationTile(end + delta) && IsCompatibleTrainStationTile(end + delta, tile); end += delta) { /* Nothing */ }
79 for (start = tile; IsRailStationTile(start - delta) && IsCompatibleTrainStationTile(start - delta, tile); start -= delta) { /* Nothing */ }
81 this->tile = start;
82 this->w = TileX(end) - TileX(start) + 1;
83 this->h = TileY(end) - TileY(start) + 1;
84 break;
87 case TA_WHOLE:
88 st->GetTileArea(this, st->IsWaypoint() ? STATION_WAYPOINT : STATION_RAIL);
89 break;
95 /**
96 * Evaluate a tile's position within a station, and return the result in a bit-stuffed format.
97 * if not centered: .TNLcCpP, if centered: .TNL..CP
98 * - T = Tile layout number (#GetStationGfx)
99 * - N = Number of platforms
100 * - L = Length of platforms
101 * - C = Current platform number from start, c = from end
102 * - P = Position along platform from start, p = from end
104 * if centered, C/P start from the centre and c/p are not available.
105 * @return Platform information in bit-stuffed format.
107 uint32 GetPlatformInfo(Axis axis, byte tile, int platforms, int length, int x, int y, bool centred)
109 uint32 retval = 0;
111 if (axis == AXIS_X) {
112 Swap(platforms, length);
113 Swap(x, y);
116 if (centred) {
117 x -= platforms / 2;
118 y -= length / 2;
119 x = Clamp(x, -8, 7);
120 y = Clamp(y, -8, 7);
121 SB(retval, 0, 4, y & 0xF);
122 SB(retval, 4, 4, x & 0xF);
123 } else {
124 SB(retval, 0, 4, min(15, y));
125 SB(retval, 4, 4, min(15, length - y - 1));
126 SB(retval, 8, 4, min(15, x));
127 SB(retval, 12, 4, min(15, platforms - x - 1));
129 SB(retval, 16, 4, min(15, length));
130 SB(retval, 20, 4, min(15, platforms));
131 SB(retval, 24, 4, tile);
133 return retval;
138 * Find the end of a railway station, from the \a tile, in the direction of \a delta.
139 * @param tile Start tile.
140 * @param delta Movement direction.
141 * @param check_type Stop when the custom station type changes.
142 * @param check_axis Stop when the station direction changes.
143 * @return Found end of the railway station.
145 static TileIndex FindRailStationEnd(TileIndex tile, TileIndexDiff delta, bool check_type, bool check_axis)
147 byte orig_type = 0;
148 Axis orig_axis = AXIS_X;
149 StationID sid = GetStationIndex(tile);
151 if (check_type) orig_type = GetCustomStationSpecIndex(tile);
152 if (check_axis) orig_axis = GetRailStationAxis(tile);
154 for (;;) {
155 TileIndex new_tile = TILE_ADD(tile, delta);
157 if (!IsStationTile(new_tile) || GetStationIndex(new_tile) != sid) break;
158 if (!HasStationRail(new_tile)) break;
159 if (check_type && GetCustomStationSpecIndex(new_tile) != orig_type) break;
160 if (check_axis && GetRailStationAxis(new_tile) != orig_axis) break;
162 tile = new_tile;
164 return tile;
168 static uint32 GetPlatformInfoHelper(TileIndex tile, bool check_type, bool check_axis, bool centred)
170 int tx = TileX(tile);
171 int ty = TileY(tile);
172 int sx = TileX(FindRailStationEnd(tile, TileDiffXY(-1, 0), check_type, check_axis));
173 int sy = TileY(FindRailStationEnd(tile, TileDiffXY( 0, -1), check_type, check_axis));
174 int ex = TileX(FindRailStationEnd(tile, TileDiffXY( 1, 0), check_type, check_axis)) + 1;
175 int ey = TileY(FindRailStationEnd(tile, TileDiffXY( 0, 1), check_type, check_axis)) + 1;
177 tx -= sx; ex -= sx;
178 ty -= sy; ey -= sy;
180 return GetPlatformInfo(GetRailStationAxis(tile), GetStationGfx(tile), ex, ey, tx, ty, centred);
184 static uint32 GetRailContinuationInfo(TileIndex tile)
186 struct DataPair {
187 Direction dir;
188 DiagDirection exit;
191 /* Tile offsets and exit dirs for X axis */
192 static const DataPair data_x[8] = {
193 { DIR_SW, DIAGDIR_SW },
194 { DIR_NE, DIAGDIR_NE },
195 { DIR_SE, DIAGDIR_SE },
196 { DIR_NW, DIAGDIR_NW },
197 { DIR_S, DIAGDIR_SW },
198 { DIR_E, DIAGDIR_NE },
199 { DIR_W, DIAGDIR_SW },
200 { DIR_N, DIAGDIR_NE },
203 /* Tile offsets and exit dirs for Y axis */
204 static const DataPair data_y[8] = {
205 { DIR_SE, DIAGDIR_SE },
206 { DIR_NW, DIAGDIR_NW },
207 { DIR_SW, DIAGDIR_SW },
208 { DIR_NE, DIAGDIR_NE },
209 { DIR_S, DIAGDIR_SE },
210 { DIR_W, DIAGDIR_NW },
211 { DIR_E, DIAGDIR_SE },
212 { DIR_N, DIAGDIR_NW },
215 Axis axis = GetRailStationAxis(tile);
217 /* Choose appropriate lookup table to use */
218 const DataPair *data = (axis == AXIS_X) ? data_x : data_y;
220 uint32 res = 0;
221 for (uint i = 0; i < lengthof(data_x); i++, data++) {
222 TileIndex neighbour_tile = tile + TileOffsByDir (data->dir);
223 TrackBits trackbits = TrackStatusToTrackBits(GetTileRailwayStatus(neighbour_tile));
224 if (trackbits != TRACK_BIT_NONE) {
225 /* If there is any track on the tile, set the bit in the second byte */
226 SetBit(res, i + 8);
228 /* With tunnels and bridges the tile has tracks, but they are not necessarily connected
229 * with the next tile because the ramp is not going in the right direction. */
230 if (IsTunnelTile (neighbour_tile)) {
231 if (GetTunnelBridgeDirection (neighbour_tile) != data->exit) {
232 continue;
234 } else if (IsBridgeHeadTile (neighbour_tile)) {
235 if (GetTunnelBridgeDirection (neighbour_tile) == ReverseDiagDir (data->exit)) {
236 continue;
240 /* If any track reaches our exit direction, set the bit in the lower byte */
241 if (trackbits & DiagdirReachesTracks(data->exit)) SetBit(res, i);
245 return res;
249 /* Station Resolver Functions */
250 /* virtual */ uint32 StationScopeResolver::GetRandomBits() const
252 return (this->st == NULL ? 0 : this->st->random_bits) | (this->tile == INVALID_TILE ? 0 : GetStationTileRandomBits(this->tile) << 16);
256 /* virtual */ uint32 StationScopeResolver::GetTriggers() const
258 return this->st == NULL ? 0 : this->st->waiting_triggers;
262 /* virtual */ void StationScopeResolver::SetTriggers(int triggers) const
264 BaseStation *st = const_cast<BaseStation *>(this->st);
265 assert(st != NULL);
266 st->waiting_triggers = triggers;
270 * Station variable cache
271 * This caches 'expensive' station variable lookups which iterate over
272 * several tiles that may be called multiple times per Resolve().
274 static struct {
275 uint32 v40;
276 uint32 v41;
277 uint32 v45;
278 uint32 v46;
279 uint32 v47;
280 uint32 v49;
281 uint8 valid; ///< Bits indicating what variable is valid (for each bit, \c 0 is invalid, \c 1 is valid).
282 } _svc;
285 * Get the town scope associated with a station, if it exists.
286 * On the first call, the town scope is created (if possible).
287 * @return Town scope, if available.
289 TownScopeResolver *StationResolverObject::GetTown()
291 if (this->town_scope == NULL) {
292 Town *t = NULL;
293 if (this->station_scope.st != NULL) {
294 t = this->station_scope.st->town;
295 } else if (this->station_scope.tile != INVALID_TILE) {
296 t = ClosestTownFromTile(this->station_scope.tile);
298 if (t == NULL) return NULL;
299 this->town_scope = new TownScopeResolver (this->grffile, t, this->station_scope.st == NULL);
301 return this->town_scope;
304 /* virtual */ uint32 StationScopeResolver::GetVariable(byte variable, uint32 parameter, bool *available) const
306 if (this->st == NULL) {
307 /* Station does not exist, so we're in a purchase list or the land slope check callback. */
308 switch (variable) {
309 case 0x40:
310 case 0x41:
311 case 0x46:
312 case 0x47:
313 case 0x49: return 0x2110000; // Platforms, tracks & position
314 case 0x42: return 0; // Rail type (XXX Get current type from GUI?)
315 case 0x43: return GetCompanyInfo(_current_company); // Station owner
316 case 0x44: return 2; // PBS status
317 case 0x67: // Land info of nearby tile
318 if (this->axis != INVALID_AXIS && this->tile != INVALID_TILE) {
319 TileIndex tile = this->tile;
320 if (parameter != 0) tile = GetNearbyTile(parameter, tile, true, this->axis); // only perform if it is required
322 Slope tileh = GetTileSlope(tile);
323 bool swap = (this->axis == AXIS_Y && HasBit(tileh, CORNER_W) != HasBit(tileh, CORNER_E));
325 return GetNearbyTileInformation (tile, this->grffile->grf_version >= 8) ^ (swap ? SLOPE_EW : 0);
327 break;
329 case 0xFA: return Clamp(_date - DAYS_TILL_ORIGINAL_BASE_YEAR, 0, 65535); // Build date, clamped to a 16 bit value
332 *available = false;
333 return UINT_MAX;
336 switch (variable) {
337 /* Calculated station variables */
338 case 0x40:
339 if (!HasBit(_svc.valid, 0)) { _svc.v40 = GetPlatformInfoHelper(this->tile, false, false, false); SetBit(_svc.valid, 0); }
340 return _svc.v40;
342 case 0x41:
343 if (!HasBit(_svc.valid, 1)) { _svc.v41 = GetPlatformInfoHelper(this->tile, true, false, false); SetBit(_svc.valid, 1); }
344 return _svc.v41;
346 case 0x42: return GetTerrainType(this->tile) | (GetReverseRailTypeTranslation(GetRailType(this->tile), this->statspec->grf_prop.grffile) << 8);
347 case 0x43: return GetCompanyInfo(this->st->owner); // Station owner
348 case 0x44: return HasStationReservation(this->tile) ? 7 : 4; // PBS status
349 case 0x45:
350 if (!HasBit(_svc.valid, 2)) { _svc.v45 = GetRailContinuationInfo(this->tile); SetBit(_svc.valid, 2); }
351 return _svc.v45;
353 case 0x46:
354 if (!HasBit(_svc.valid, 3)) { _svc.v46 = GetPlatformInfoHelper(this->tile, false, false, true); SetBit(_svc.valid, 3); }
355 return _svc.v46;
357 case 0x47:
358 if (!HasBit(_svc.valid, 4)) { _svc.v47 = GetPlatformInfoHelper(this->tile, true, false, true); SetBit(_svc.valid, 4); }
359 return _svc.v47;
361 case 0x49:
362 if (!HasBit(_svc.valid, 5)) { _svc.v49 = GetPlatformInfoHelper(this->tile, false, true, false); SetBit(_svc.valid, 5); }
363 return _svc.v49;
365 case 0x4A: // Animation frame of tile
366 return GetAnimationFrame(this->tile);
368 /* Variables which use the parameter */
369 /* Variables 0x60 to 0x65 and 0x69 are handled separately below */
370 case 0x66: { // Animation frame of nearby tile
371 TileIndex tile = this->tile;
372 if (parameter != 0) tile = GetNearbyTile(parameter, tile);
373 return this->st->TileBelongsToRailStation(tile) ? GetAnimationFrame(tile) : UINT_MAX;
376 case 0x67: { // Land info of nearby tile
377 Axis axis = GetRailStationAxis(this->tile);
378 TileIndex tile = this->tile;
379 if (parameter != 0) tile = GetNearbyTile(parameter, tile); // only perform if it is required
381 Slope tileh = GetTileSlope(tile);
382 bool swap = (axis == AXIS_Y && HasBit(tileh, CORNER_W) != HasBit(tileh, CORNER_E));
384 return GetNearbyTileInformation (tile, this->grffile->grf_version >= 8) ^ (swap ? SLOPE_EW : 0);
387 case 0x68: { // Station info of nearby tiles
388 TileIndex nearby_tile = GetNearbyTile(parameter, this->tile);
390 if (!HasStationTileRail(nearby_tile)) return 0xFFFFFFFF;
392 uint32 grfid = this->st->speclist[GetCustomStationSpecIndex(this->tile)].grfid;
393 bool perpendicular = GetRailStationAxis(this->tile) != GetRailStationAxis(nearby_tile);
394 bool same_station = this->st->TileBelongsToRailStation(nearby_tile);
395 uint32 res = GB(GetStationGfx(nearby_tile), 1, 2) << 12 | !!perpendicular << 11 | !!same_station << 10;
397 uint spec_index = GetCustomStationSpecIndex (nearby_tile);
398 if (spec_index != 0) {
399 const StationSpecList ssl = BaseStation::GetByTile(nearby_tile)->speclist[spec_index];
400 res |= 1 << (ssl.grfid != grfid ? 9 : 8) | ssl.localidx;
402 return res;
405 /* General station variables */
406 case 0x82: return 50;
407 case 0x84: return this->st->string_id;
408 case 0x86: return 0;
409 case 0xF0: return this->st->facilities;
410 case 0xFA: return Clamp(this->st->build_date - DAYS_TILL_ORIGINAL_BASE_YEAR, 0, 65535);
413 return this->st->GetNewGRFVariable (this->grffile, variable, parameter, available);
416 uint32 Station::GetNewGRFVariable (const GRFFile *grffile, byte variable, byte parameter, bool *available) const
418 switch (variable) {
419 case 0x48: { // Accepted cargo types
420 CargoID cargo_type;
421 uint32 value = 0;
423 for (cargo_type = 0; cargo_type < NUM_CARGO; cargo_type++) {
424 if (HasBit(this->goods[cargo_type].status, GoodsEntry::GES_ACCEPTANCE)) SetBit(value, cargo_type);
426 return value;
429 case 0x8A: return this->had_vehicle_of_type;
430 case 0xF1: return (this->airport.tile != INVALID_TILE) ? this->airport.GetSpec()->ttd_airport_type : ATP_TTDP_LARGE;
431 case 0xF2: return (this->truck_stops != NULL) ? this->truck_stops->status : 0;
432 case 0xF3: return (this->bus_stops != NULL) ? this->bus_stops->status : 0;
433 case 0xF6: return this->airport.flags;
434 case 0xF7: return GB(this->airport.flags, 8, 8);
437 /* Handle cargo variables with parameter, 0x60 to 0x65 and 0x69 */
438 if ((variable >= 0x60 && variable <= 0x65) || variable == 0x69) {
439 CargoID c = GetCargoTranslation (parameter, grffile);
441 if (c == CT_INVALID) {
442 switch (variable) {
443 case 0x62: return 0xFFFFFFFF;
444 case 0x64: return 0xFF00;
445 default: return 0;
448 const GoodsEntry *ge = &this->goods[c];
450 switch (variable) {
451 case 0x60: return min(ge->cargo.TotalCount(), 4095);
452 case 0x61: return ge->HasVehicleEverTriedLoading() ? ge->time_since_pickup : 0;
453 case 0x62: return ge->HasRating() ? ge->rating : 0xFFFFFFFF;
454 case 0x63: return ge->cargo.DaysInTransit();
455 case 0x64: return ge->HasVehicleEverTriedLoading() ? ge->last_speed | (ge->last_age << 8) : 0xFF00;
456 case 0x65: return GB(ge->status, GoodsEntry::GES_ACCEPTANCE, 1) << 3;
457 case 0x69: {
458 assert_compile((int)GoodsEntry::GES_EVER_ACCEPTED + 1 == (int)GoodsEntry::GES_LAST_MONTH);
459 assert_compile((int)GoodsEntry::GES_EVER_ACCEPTED + 2 == (int)GoodsEntry::GES_CURRENT_MONTH);
460 assert_compile((int)GoodsEntry::GES_EVER_ACCEPTED + 3 == (int)GoodsEntry::GES_ACCEPTED_BIGTICK);
461 return GB(ge->status, GoodsEntry::GES_EVER_ACCEPTED, 4);
466 /* Handle cargo variables (deprecated) */
467 if (variable >= 0x8C && variable <= 0xEC) {
468 const GoodsEntry *g = &this->goods[GB(variable - 0x8C, 3, 4)];
469 switch (GB(variable - 0x8C, 0, 3)) {
470 case 0: return g->cargo.TotalCount();
471 case 1: return GB(min(g->cargo.TotalCount(), 4095), 0, 4) | (GB(g->status, GoodsEntry::GES_ACCEPTANCE, 1) << 7);
472 case 2: return g->time_since_pickup;
473 case 3: return g->rating;
474 case 4: return g->cargo.Source();
475 case 5: return g->cargo.DaysInTransit();
476 case 6: return g->last_speed;
477 case 7: return g->last_age;
481 DEBUG(grf, 1, "Unhandled station variable 0x%X", variable);
483 *available = false;
484 return UINT_MAX;
487 uint32 Waypoint::GetNewGRFVariable (const GRFFile *grffile, byte variable, byte parameter, bool *available) const
489 switch (variable) {
490 case 0x48: return 0; // Accepted cargo types
491 case 0x8A: return HVOT_WAYPOINT;
492 case 0xF1: return 0; // airport type
493 case 0xF2: return 0; // truck stop status
494 case 0xF3: return 0; // bus stop status
495 case 0xF6: return 0; // airport flags
496 case 0xF7: return 0; // airport flags cont.
499 /* Handle cargo variables with parameter, 0x60 to 0x65 */
500 if (variable >= 0x60 && variable <= 0x65) {
501 return 0;
504 /* Handle cargo variables (deprecated) */
505 if (variable >= 0x8C && variable <= 0xEC) {
506 switch (GB(variable - 0x8C, 0, 3)) {
507 case 3: return INITIAL_STATION_RATING;
508 case 4: return INVALID_STATION;
509 default: return 0;
513 DEBUG(grf, 1, "Unhandled station variable 0x%X", variable);
515 *available = false;
516 return UINT_MAX;
519 /* virtual */ const SpriteGroup *StationResolverObject::ResolveReal(const RealSpriteGroup *group) const
521 if (this->station_scope.st == NULL || this->station_scope.statspec->cls_id == STAT_CLASS_WAYP) {
522 return group->loading[0];
525 uint cargo = 0;
526 const Station *st = Station::From(this->station_scope.st);
528 switch (this->station_scope.cargo_type) {
529 case CT_INVALID:
530 case CT_DEFAULT_NA:
531 case CT_PURCHASE:
532 cargo = 0;
533 break;
535 case CT_DEFAULT:
536 for (CargoID cargo_type = 0; cargo_type < NUM_CARGO; cargo_type++) {
537 cargo += st->goods[cargo_type].cargo.TotalCount();
539 break;
541 default:
542 cargo = st->goods[this->station_scope.cargo_type].cargo.TotalCount();
543 break;
546 if (HasBit(this->station_scope.statspec->flags, SSF_DIV_BY_STATION_SIZE)) cargo /= (st->train_station.w + st->train_station.h);
547 cargo = min(0xfff, cargo);
549 if (cargo > this->station_scope.statspec->cargo_threshold) {
550 if (group->num_loading > 0) {
551 uint set = ((cargo - this->station_scope.statspec->cargo_threshold) * group->num_loading) / (4096 - this->station_scope.statspec->cargo_threshold);
552 return group->loading[set];
554 } else {
555 if (group->num_loaded > 0) {
556 uint set = (cargo * group->num_loaded) / (this->station_scope.statspec->cargo_threshold + 1);
557 return group->loaded[set];
561 return group->loading[0];
565 * Resolver for stations.
566 * @param statspec Station (type) specification.
567 * @param st Instance of the station.
568 * @param tile %Tile of the station.
569 * @param callback Callback ID.
570 * @param callback_param1 First parameter (var 10) of the callback.
571 * @param callback_param2 Second parameter (var 18) of the callback.
573 StationResolverObject::StationResolverObject(const StationSpec *statspec, BaseStation *st, TileIndex tile,
574 CallbackID callback, uint32 callback_param1, uint32 callback_param2)
575 : ResolverObject(statspec->grf_prop.grffile, callback, callback_param1, callback_param2),
576 station_scope (this->grffile, statspec, st, tile), town_scope(NULL)
578 /* Invalidate all cached vars */
579 _svc.valid = 0;
581 CargoID ctype = CT_DEFAULT_NA;
583 if (this->station_scope.st == NULL) {
584 /* No station, so we are in a purchase list */
585 ctype = CT_PURCHASE;
586 } else if (!this->station_scope.st->IsWaypoint()) {
587 const Station *st = Station::From(this->station_scope.st);
588 /* Pick the first cargo that we have waiting */
589 const CargoSpec *cs;
590 FOR_ALL_CARGOSPECS(cs) {
591 if (this->station_scope.statspec->grf_prop.spritegroup[cs->Index()] != NULL &&
592 st->goods[cs->Index()].cargo.TotalCount() > 0) {
593 ctype = cs->Index();
594 break;
599 if (this->station_scope.statspec->grf_prop.spritegroup[ctype] == NULL) {
600 ctype = CT_DEFAULT;
603 /* Remember the cargo type we've picked */
604 this->station_scope.cargo_type = ctype;
605 this->root_spritegroup = this->station_scope.statspec->grf_prop.spritegroup[this->station_scope.cargo_type];
608 StationResolverObject::~StationResolverObject()
610 delete this->town_scope;
614 * Constructor for station scopes.
615 * @param grffile GRFFile the resolved SpriteGroup belongs to.
616 * @param statspec Station (type) specification.
617 * @param st Instance of the station.
618 * @param tile %Tile of the station.
620 StationScopeResolver::StationScopeResolver (const GRFFile *grffile, const StationSpec *statspec, BaseStation *st, TileIndex tile)
621 : ScopeResolver(), grffile(grffile)
623 this->tile = tile;
624 this->st = st;
625 this->statspec = statspec;
626 this->cargo_type = CT_INVALID;
627 this->axis = INVALID_AXIS;
631 * Resolve sprites for drawing a station tile.
632 * @param statspec Station spec
633 * @param st Station (NULL in GUI)
634 * @param tile Station tile being drawn (INVALID_TILE in GUI)
635 * @param var10 Value to put in variable 10; normally 0; 1 when resolving the groundsprite and SSF_SEPARATE_GROUND is set.
636 * @return First sprite of the Action 1 spriteset to use, minus an offset of 0x42D to accommodate for weird NewGRF specs.
638 SpriteID GetCustomStationRelocation(const StationSpec *statspec, BaseStation *st, TileIndex tile, uint32 var10)
640 StationResolverObject object(statspec, st, tile, CBID_NO_CALLBACK, var10);
641 const SpriteGroup *group = object.Resolve();
642 if (group == NULL || group->type != SGT_RESULT) return 0;
643 return group->GetResult() - 0x42D;
647 * Resolve the sprites for custom station foundations.
648 * @param statspec Station spec
649 * @param st Station
650 * @param tile Station tile being drawn
651 * @param layout Spritelayout as returned by previous callback
652 * @param edge_info Information about northern tile edges; whether they need foundations or merge into adjacent tile's foundations.
653 * @return First sprite of a set of foundation sprites for various slopes, or 0 if default foundations shall be drawn.
655 SpriteID GetCustomStationFoundationRelocation(const StationSpec *statspec, BaseStation *st, TileIndex tile, uint layout, uint edge_info)
657 /* callback_param1 == 2 means we are resolving the foundation sprites. */
658 StationResolverObject object(statspec, st, tile, CBID_NO_CALLBACK, 2, layout | (edge_info << 16));
660 const SpriteGroup *group = object.Resolve();
661 if (group == NULL || group->type != SGT_RESULT) return 0;
663 /* Note: SpriteGroup::Resolve zeroes all registers, so register 0x100 is initialised to 0. (compatibility) */
664 return group->GetResult() + GetRegister(0x100);
668 uint16 GetStationCallback(CallbackID callback, uint32 param1, uint32 param2, const StationSpec *statspec, BaseStation *st, TileIndex tile)
670 StationResolverObject object(statspec, st, tile, callback, param1, param2);
671 return SpriteGroup::CallbackResult (object.Resolve());
675 * Check the slope of a tile of a new station.
676 * @param north_tile Norther tile of the station rect.
677 * @param cur_tile Tile to check.
678 * @param statspec Station spec.
679 * @param axis Axis of the new station.
680 * @param plat_len Platform length.
681 * @param numtracks Number of platforms.
682 * @return Succeeded or failed command.
684 CommandCost PerformStationTileSlopeCheck(TileIndex north_tile, TileIndex cur_tile, const StationSpec *statspec, Axis axis, byte plat_len, byte numtracks)
686 TileIndexDiff diff = cur_tile - north_tile;
687 Slope slope = GetTileSlope(cur_tile);
689 StationResolverObject object(statspec, NULL, cur_tile, CBID_STATION_LAND_SLOPE_CHECK,
690 (slope << 4) | (slope ^ (axis == AXIS_Y && HasBit(slope, CORNER_W) != HasBit(slope, CORNER_E) ? SLOPE_EW : 0)),
691 (numtracks << 24) | (plat_len << 16) | (axis == AXIS_Y ? TileX(diff) << 8 | TileY(diff) : TileY(diff) << 8 | TileX(diff)));
692 object.station_scope.axis = axis;
694 uint16 cb_res = SpriteGroup::CallbackResult (object.Resolve());
696 /* Failed callback means success. */
697 if (cb_res == CALLBACK_FAILED) return CommandCost();
699 /* The meaning of bit 10 is inverted for a grf version < 8. */
700 if (statspec->grf_prop.grffile->grf_version < 8) ToggleBit(cb_res, 10);
701 return GetErrorMessageFromLocationCallbackResult(cb_res, statspec->grf_prop.grffile, STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION);
706 * Allocate a StationSpec to a Station. This is called once per build operation.
707 * @param statspec StationSpec to allocate.
708 * @param st Station to allocate it to.
709 * @param exec Whether to actually allocate the spec.
710 * @return Index within the Station's spec list, or -1 if the allocation failed.
712 int AllocateSpecToStation(const StationSpec *statspec, BaseStation *st, bool exec)
714 uint i;
716 if (statspec == NULL || st == NULL) return 0;
718 for (i = 1; i < st->num_specs && i < NUM_STATIONSSPECS_PER_STATION; i++) {
719 if (st->speclist[i].spec == NULL && st->speclist[i].grfid == 0) break;
722 if (i == NUM_STATIONSSPECS_PER_STATION) {
723 /* As final effort when the spec list is already full...
724 * try to find the same spec and return that one. This might
725 * result in slightly "wrong" (as per specs) looking stations,
726 * but it's fairly unlikely that one reaches the limit anyways.
728 for (i = 1; i < st->num_specs && i < NUM_STATIONSSPECS_PER_STATION; i++) {
729 if (st->speclist[i].spec == statspec) return i;
732 return -1;
735 if (exec) {
736 if (i >= st->num_specs) {
737 st->num_specs = i + 1;
738 st->speclist = xrealloct (st->speclist, st->num_specs);
740 if (st->num_specs == 2) {
741 /* Initial allocation */
742 st->speclist[0].spec = NULL;
743 st->speclist[0].grfid = 0;
744 st->speclist[0].localidx = 0;
748 st->speclist[i].spec = statspec;
749 st->speclist[i].grfid = statspec->grf_prop.grffile->grfid;
750 st->speclist[i].localidx = statspec->grf_prop.local_id;
752 StationUpdateCachedTriggers(st);
755 return i;
760 * Deallocate a StationSpec from a Station. Called when removing a single station tile.
761 * @param st Station to work with.
762 * @param specindex Index of the custom station within the Station's spec list.
763 * @return Indicates whether the StationSpec was deallocated.
765 void DeallocateSpecFromStation(BaseStation *st, byte specindex)
767 /* specindex of 0 (default) is never freeable */
768 if (specindex == 0) return;
770 ETileArea area = ETileArea(st, INVALID_TILE, TA_WHOLE);
771 /* Check all tiles over the station to check if the specindex is still in use */
772 TILE_AREA_LOOP(tile, area) {
773 if (st->TileBelongsToRailStation(tile) && GetCustomStationSpecIndex(tile) == specindex) {
774 return;
778 /* This specindex is no longer in use, so deallocate it */
779 st->speclist[specindex].spec = NULL;
780 st->speclist[specindex].grfid = 0;
781 st->speclist[specindex].localidx = 0;
783 /* If this was the highest spec index, reallocate */
784 if (specindex == st->num_specs - 1) {
785 for (; st->speclist[st->num_specs - 1].grfid == 0 && st->num_specs > 1; st->num_specs--) {}
787 if (st->num_specs > 1) {
788 st->speclist = xrealloct (st->speclist, st->num_specs);
789 } else {
790 free(st->speclist);
791 st->num_specs = 0;
792 st->speclist = NULL;
793 st->cached_anim_triggers = 0;
794 st->cached_cargo_triggers = 0;
795 return;
799 StationUpdateCachedTriggers(st);
803 * Draw representation of a station tile for GUI purposes.
804 * @param dpi The area to draw on.
805 * @param x Position x of image.
806 * @param y Position y of image.
807 * @param axis Axis.
808 * @param railtype Rail type.
809 * @param sclass, station Type of station.
810 * @param station station ID
811 * @return True if the tile was drawn (allows for fallback to default graphic)
813 bool DrawStationTile (BlitArea *dpi, int x, int y, RailType railtype,
814 Axis axis, StationClassID sclass, uint station)
816 const DrawTileSprites *sprites = NULL;
817 const RailtypeInfo *rti = GetRailTypeInfo(railtype);
818 PaletteID palette = COMPANY_SPRITE_COLOUR(_local_company);
819 uint tile = 2;
821 const StationSpec *statspec = StationClass::Get(sclass)->GetSpec(station);
822 if (statspec == NULL) return false;
824 if (HasBit(statspec->callback_mask, CBM_STATION_SPRITE_LAYOUT)) {
825 uint16 callback = GetStationCallback(CBID_STATION_SPRITE_LAYOUT, 0x2110000, 0, statspec, NULL, INVALID_TILE);
826 if (callback != CALLBACK_FAILED) tile = callback;
829 uint32 total_offset = rti->GetRailtypeSpriteOffset();
830 uint32 relocation = 0;
831 uint32 ground_relocation = 0;
832 const NewGRFSpriteLayout *layout = NULL;
833 DrawTileSprites tmp_rail_layout;
835 if (statspec->renderdata == NULL) {
836 sprites = GetStationTileLayout(STATION_RAIL, tile + axis);
837 } else {
838 layout = &statspec->renderdata[(tile < statspec->tiles) ? tile + axis : (uint)axis];
839 if (!layout->NeedsPreprocessing()) {
840 sprites = layout;
841 layout = NULL;
845 if (layout != NULL) {
846 /* Sprite layout which needs preprocessing */
847 bool separate_ground = HasBit(statspec->flags, SSF_SEPARATE_GROUND);
848 uint32 var10_values = layout->PrepareLayout(total_offset, rti->fallback_railtype, 0, 0, separate_ground);
849 uint8 var10;
850 FOR_EACH_SET_BIT(var10, var10_values) {
851 uint32 var10_relocation = GetCustomStationRelocation(statspec, NULL, INVALID_TILE, var10);
852 layout->ProcessRegisters(var10, var10_relocation, separate_ground);
855 tmp_rail_layout.seq = layout->GetLayout(&tmp_rail_layout.ground);
856 sprites = &tmp_rail_layout;
857 total_offset = 0;
858 } else {
859 /* Simple sprite layout */
860 ground_relocation = relocation = GetCustomStationRelocation(statspec, NULL, INVALID_TILE, 0);
861 if (HasBit(sprites->ground.sprite, SPRITE_MODIFIER_CUSTOM_SPRITE)) {
862 ground_relocation = GetCustomStationRelocation(statspec, NULL, INVALID_TILE, 1);
864 ground_relocation += rti->fallback_railtype;
867 SpriteID image = sprites->ground.sprite;
868 PaletteID pal = sprites->ground.pal;
869 RailTrackOffset overlay_offset;
870 if (rti->UsesOverlay() && SplitGroundSpriteForOverlay(NULL, &image, &overlay_offset)) {
871 SpriteID ground = GetCustomRailSprite(rti, INVALID_TILE, RTSG_GROUND);
872 DrawSprite (dpi, image, PAL_NONE, x, y);
873 DrawSprite (dpi, ground + overlay_offset, PAL_NONE, x, y);
874 } else {
875 image += HasBit(image, SPRITE_MODIFIER_CUSTOM_SPRITE) ? ground_relocation : total_offset;
876 if (HasBit(pal, SPRITE_MODIFIER_CUSTOM_SPRITE)) pal += ground_relocation;
877 DrawSprite (dpi, image, GroundSpritePaletteTransform (image, pal, palette), x, y);
880 DrawRailTileSeqInGUI (dpi, x, y, sprites, total_offset, relocation, palette);
882 return true;
886 const StationSpec *GetStationSpec(TileIndex t)
888 uint specindex = GetCustomStationSpecIndex(t);
889 if (specindex == 0) return NULL;
891 const BaseStation *st = BaseStation::GetByTile(t);
892 return specindex < st->num_specs ? st->speclist[specindex].spec : NULL;
897 * Check whether a rail station tile is NOT traversable.
898 * @param tile %Tile to test.
899 * @return Station tile is blocked.
900 * @note This could be cached (during build) in the map array to save on all the dereferencing.
902 bool IsStationTileBlocked(TileIndex tile)
904 const StationSpec *statspec = GetStationSpec(tile);
906 return statspec != NULL && HasBit(statspec->blocked, GetStationGfx(tile));
910 * Check if a rail station tile shall have pylons when electrified.
911 * @param tile %Tile to test.
912 * @return Tile shall have pylons.
913 * @note This could be cached (during build) in the map array to save on all the dereferencing.
915 bool CanStationTileHavePylons(TileIndex tile)
917 const StationSpec *statspec = GetStationSpec(tile);
918 uint gfx = GetStationGfx(tile);
919 /* Default stations do not draw pylons under roofs (gfx >= 4) */
920 return statspec != NULL ? HasBit(statspec->pylons, gfx) : gfx < 4;
924 * Check if a rail station tile shall have wires when electrified.
925 * @param tile %Tile to test.
926 * @return Tile shall have wires.
927 * @note This could be cached (during build) in the map array to save on all the dereferencing.
929 bool CanStationTileHaveWires(TileIndex tile)
931 const StationSpec *statspec = GetStationSpec(tile);
932 return statspec == NULL || !HasBit(statspec->wires, GetStationGfx(tile));
935 /** Wrapper for animation control, see #GetStationCallback. */
936 uint16 GetAnimStationCallback(CallbackID callback, uint32 param1, uint32 param2, const StationSpec *statspec, BaseStation *st, TileIndex tile, int extra_data)
938 return GetStationCallback(callback, param1, param2, statspec, st, tile);
941 /** Helper class for animation control. */
942 struct StationAnimationBase : public AnimationBase<StationAnimationBase, StationSpec, BaseStation, int, GetAnimStationCallback> {
943 static const CallbackID cb_animation_speed = CBID_STATION_ANIMATION_SPEED;
944 static const CallbackID cb_animation_next_frame = CBID_STATION_ANIM_NEXT_FRAME;
946 static const StationCallbackMask cbm_animation_speed = CBM_STATION_ANIMATION_SPEED;
947 static const StationCallbackMask cbm_animation_next_frame = CBM_STATION_ANIMATION_NEXT_FRAME;
950 void AnimateStationTile(TileIndex tile)
952 const StationSpec *ss = GetStationSpec(tile);
953 if (ss == NULL) return;
955 StationAnimationBase::AnimateTile(ss, BaseStation::GetByTile(tile), tile, HasBit(ss->flags, SSF_CB141_RANDOM_BITS));
958 void TriggerStationAnimation(BaseStation *st, TileIndex tile, StationAnimationTrigger trigger, CargoID cargo_type)
960 /* List of coverage areas for each animation trigger */
961 static const TriggerArea tas[] = {
962 TA_TILE, TA_WHOLE, TA_WHOLE, TA_PLATFORM, TA_PLATFORM, TA_PLATFORM, TA_WHOLE
965 /* Get Station if it wasn't supplied */
966 if (st == NULL) st = BaseStation::GetByTile(tile);
968 /* Check the cached animation trigger bitmask to see if we need
969 * to bother with any further processing. */
970 if (!HasBit(st->cached_anim_triggers, trigger)) return;
972 uint16 random_bits = Random();
973 ETileArea area = ETileArea(st, tile, tas[trigger]);
975 /* Check all tiles over the station to check if the specindex is still in use */
976 TILE_AREA_LOOP(tile, area) {
977 if (st->TileBelongsToRailStation(tile)) {
978 const StationSpec *ss = GetStationSpec(tile);
979 if (ss != NULL && HasBit(ss->animation.triggers, trigger)) {
980 CargoID cargo;
981 if (cargo_type == CT_INVALID) {
982 cargo = CT_INVALID;
983 } else {
984 cargo = ss->grf_prop.grffile->cargo_map[cargo_type];
986 StationAnimationBase::ChangeAnimationFrame(CBID_STATION_ANIM_START_STOP, ss, st, tile, (random_bits << 16) | Random(), (uint8)trigger | (cargo << 8));
993 * Trigger station randomisation
994 * @param st station being triggered
995 * @param tile specific tile of platform to trigger
996 * @param trigger trigger type
997 * @param cargo_type cargo type causing trigger
999 void TriggerStationRandomisation(Station *st, TileIndex tile, StationRandomTrigger trigger, CargoID cargo_type)
1001 /* List of coverage areas for each animation trigger */
1002 static const TriggerArea tas[] = {
1003 TA_WHOLE, TA_WHOLE, TA_PLATFORM, TA_PLATFORM, TA_PLATFORM, TA_PLATFORM
1006 /* Get Station if it wasn't supplied */
1007 if (st == NULL) st = Station::GetByTile(tile);
1009 /* Check the cached cargo trigger bitmask to see if we need
1010 * to bother with any further processing. */
1011 if (st->cached_cargo_triggers == 0) return;
1012 if (cargo_type != CT_INVALID && !HasBit(st->cached_cargo_triggers, cargo_type)) return;
1014 uint32 whole_reseed = 0;
1015 ETileArea area = ETileArea(st, tile, tas[trigger]);
1017 uint32 empty_mask = 0;
1018 if (trigger == SRT_CARGO_TAKEN) {
1019 /* Create a bitmask of completely empty cargo types to be matched */
1020 for (CargoID i = 0; i < NUM_CARGO; i++) {
1021 if (st->goods[i].cargo.TotalCount() == 0) {
1022 SetBit(empty_mask, i);
1027 /* Convert trigger to bit */
1028 uint8 trigger_bit = 1 << trigger;
1030 /* Check all tiles over the station to check if the specindex is still in use */
1031 TILE_AREA_LOOP(tile, area) {
1032 if (st->TileBelongsToRailStation(tile)) {
1033 const StationSpec *ss = GetStationSpec(tile);
1034 if (ss == NULL) continue;
1036 /* Cargo taken "will only be triggered if all of those
1037 * cargo types have no more cargo waiting." */
1038 if (trigger == SRT_CARGO_TAKEN) {
1039 if ((ss->cargo_triggers & ~empty_mask) != 0) continue;
1042 if (cargo_type == CT_INVALID || HasBit(ss->cargo_triggers, cargo_type)) {
1043 StationResolverObject object(ss, st, tile, CBID_RANDOM_TRIGGER, 0);
1044 object.trigger = trigger_bit;
1046 const SpriteGroup *group = object.Resolve();
1047 if (group == NULL) continue;
1049 uint32 reseed = object.GetReseedSum();
1050 if (reseed != 0) {
1051 whole_reseed |= reseed;
1052 reseed >>= 16;
1054 /* Set individual tile random bits */
1055 uint8 random_bits = GetStationTileRandomBits(tile);
1056 random_bits &= ~reseed;
1057 random_bits |= Random() & reseed;
1058 SetStationTileRandomBits(tile, random_bits);
1060 MarkTileDirtyByTile(tile);
1066 /* Update whole station random bits */
1067 if ((whole_reseed & 0xFFFF) != 0) {
1068 st->random_bits &= ~whole_reseed;
1069 st->random_bits |= Random() & whole_reseed;
1074 * Update the cached animation trigger bitmask for a station.
1075 * @param st Station to update.
1077 void StationUpdateCachedTriggers(BaseStation *st)
1079 st->cached_anim_triggers = 0;
1080 st->cached_cargo_triggers = 0;
1082 /* Combine animation trigger bitmask for all station specs
1083 * of this station. */
1084 for (uint i = 0; i < st->num_specs; i++) {
1085 const StationSpec *ss = st->speclist[i].spec;
1086 if (ss != NULL) {
1087 st->cached_anim_triggers |= ss->animation.triggers;
1088 st->cached_cargo_triggers |= ss->cargo_triggers;