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 
8 /** @file newgrf_airport.cpp NewGRF handling of airports. */
9 
10 #include "stdafx.h"
11 #include "debug.h"
12 #include "date_func.h"
13 #include "newgrf_spritegroup.h"
14 #include "newgrf_text.h"
15 #include "station_base.h"
16 #include "newgrf_class_func.h"
17 
18 #include "safeguards.h"
19 
20 /** Resolver for the airport scope. */
21 struct AirportScopeResolver : public ScopeResolver {
22 	struct Station *st; ///< Station of the airport for which the callback is run, or \c nullptr for build gui.
23 	byte airport_id;    ///< Type of airport for which the callback is run.
24 	byte layout;        ///< Layout of the airport to build.
25 	TileIndex tile;     ///< Tile for the callback, only valid for airporttile callbacks.
26 
27 	/**
28 	 * Constructor of the scope resolver for an airport.
29 	 * @param ro Surrounding resolver.
30 	 * @param tile %Tile for the callback, only valid for airporttile callbacks.
31 	 * @param st %Station of the airport for which the callback is run, or \c nullptr for build gui.
32 	 * @param airport_id Type of airport for which the callback is run.
33 	 * @param layout Layout of the airport to build.
34 	 */
AirportScopeResolverAirportScopeResolver35 	AirportScopeResolver(ResolverObject &ro, TileIndex tile, Station *st, byte airport_id, byte layout)
36 			: ScopeResolver(ro), st(st), airport_id(airport_id), layout(layout), tile(tile)
37 	{
38 	}
39 
40 	uint32 GetRandomBits() const override;
41 	uint32 GetVariable(byte variable, uint32 parameter, bool *available) const override;
42 	void StorePSA(uint pos, int32 value) override;
43 };
44 
45 /** Resolver object for airports. */
46 struct AirportResolverObject : public ResolverObject {
47 	AirportScopeResolver airport_scope;
48 
49 	AirportResolverObject(TileIndex tile, Station *st, byte airport_id, byte layout,
50 			CallbackID callback = CBID_NO_CALLBACK, uint32 callback_param1 = 0, uint32 callback_param2 = 0);
51 
GetScopeAirportResolverObject52 	ScopeResolver *GetScope(VarSpriteGroupScope scope = VSG_SCOPE_SELF, byte relative = 0) override
53 	{
54 		switch (scope) {
55 			case VSG_SCOPE_SELF: return &this->airport_scope;
56 			default: return ResolverObject::GetScope(scope, relative);
57 		}
58 	}
59 
60 	GrfSpecFeature GetFeature() const override;
61 	uint32 GetDebugID() const override;
62 };
63 
64 /**
65  * Reset airport classes to their default state.
66  * This includes initialising the defaults classes with an empty
67  * entry, for standard airports.
68  */
69 template <typename Tspec, typename Tid, Tid Tmax>
InsertDefaults()70 /* static */ void NewGRFClass<Tspec, Tid, Tmax>::InsertDefaults()
71 {
72 	AirportClass::Get(AirportClass::Allocate('SMAL'))->name = STR_AIRPORT_CLASS_SMALL;
73 	AirportClass::Get(AirportClass::Allocate('LARG'))->name = STR_AIRPORT_CLASS_LARGE;
74 	AirportClass::Get(AirportClass::Allocate('HUB_'))->name = STR_AIRPORT_CLASS_HUB;
75 	AirportClass::Get(AirportClass::Allocate('HELI'))->name = STR_AIRPORT_CLASS_HELIPORTS;
76 }
77 
78 template <typename Tspec, typename Tid, Tid Tmax>
IsUIAvailable(uint index) const79 bool NewGRFClass<Tspec, Tid, Tmax>::IsUIAvailable(uint index) const
80 {
81 	return true;
82 }
83 
84 INSTANTIATE_NEWGRF_CLASS_METHODS(AirportClass, AirportSpec, AirportClassID, APC_MAX)
85 
86 
87 AirportOverrideManager _airport_mngr(NEW_AIRPORT_OFFSET, NUM_AIRPORTS, AT_INVALID);
88 
89 AirportSpec AirportSpec::specs[NUM_AIRPORTS]; ///< Airport specifications.
90 
91 /**
92  * Retrieve airport spec for the given airport. If an override is available
93  *  it is returned.
94  * @param type index of airport
95  * @return A pointer to the corresponding AirportSpec
96  */
Get(byte type)97 /* static */ const AirportSpec *AirportSpec::Get(byte type)
98 {
99 	assert(type < lengthof(AirportSpec::specs));
100 	const AirportSpec *as = &AirportSpec::specs[type];
101 	if (type >= NEW_AIRPORT_OFFSET && !as->enabled) {
102 		if (_airport_mngr.GetGRFID(type) == 0) return as;
103 		byte subst_id = _airport_mngr.GetSubstituteID(type);
104 		if (subst_id == AT_INVALID) return as;
105 		as = &AirportSpec::specs[subst_id];
106 	}
107 	if (as->grf_prop.override != AT_INVALID) return &AirportSpec::specs[as->grf_prop.override];
108 	return as;
109 }
110 
111 /**
112  * Retrieve airport spec for the given airport. Even if an override is
113  *  available the base spec is returned.
114  * @param type index of airport
115  * @return A pointer to the corresponding AirportSpec
116  */
GetWithoutOverride(byte type)117 /* static */ AirportSpec *AirportSpec::GetWithoutOverride(byte type)
118 {
119 	assert(type < lengthof(AirportSpec::specs));
120 	return &AirportSpec::specs[type];
121 }
122 
123 /** Check whether this airport is available to build. */
IsAvailable() const124 bool AirportSpec::IsAvailable() const
125 {
126 	if (!this->enabled) return false;
127 	if (_cur_year < this->min_year) return false;
128 	if (_settings_game.station.never_expire_airports) return true;
129 	return _cur_year <= this->max_year;
130 }
131 
132 /**
133  * Check if the airport would be within the map bounds at the given tile.
134  * @param table Selected layout table. This affects airport rotation, and therefore dimensions.
135  * @param tile Top corner of the airport.
136  * @return true iff the airport would be within the map bounds at the given tile.
137  */
IsWithinMapBounds(byte table,TileIndex tile) const138 bool AirportSpec::IsWithinMapBounds(byte table, TileIndex tile) const
139 {
140 	if (table >= this->num_table) return false;
141 
142 	byte w = this->size_x;
143 	byte h = this->size_y;
144 	if (this->rotation[table] == DIR_E || this->rotation[table] == DIR_W) Swap(w, h);
145 
146 	return TileX(tile) + w < MapSizeX() &&
147 		TileY(tile) + h < MapSizeY();
148 }
149 
150 /**
151  * This function initializes the airportspec array.
152  */
ResetAirports()153 void AirportSpec::ResetAirports()
154 {
155 	extern const AirportSpec _origin_airport_specs[];
156 	memset(&AirportSpec::specs, 0, sizeof(AirportSpec::specs));
157 	memcpy(&AirportSpec::specs, &_origin_airport_specs, sizeof(AirportSpec) * NEW_AIRPORT_OFFSET);
158 
159 	_airport_mngr.ResetOverride();
160 }
161 
162 /**
163  * Tie all airportspecs to their class.
164  */
BindAirportSpecs()165 void BindAirportSpecs()
166 {
167 	for (int i = 0; i < NUM_AIRPORTS; i++) {
168 		AirportSpec *as = AirportSpec::GetWithoutOverride(i);
169 		if (as->enabled) AirportClass::Assign(as);
170 	}
171 }
172 
173 
SetEntitySpec(AirportSpec * as)174 void AirportOverrideManager::SetEntitySpec(AirportSpec *as)
175 {
176 	byte airport_id = this->AddEntityID(as->grf_prop.local_id, as->grf_prop.grffile->grfid, as->grf_prop.subst_id);
177 
178 	if (airport_id == invalid_ID) {
179 		grfmsg(1, "Airport.SetEntitySpec: Too many airports allocated. Ignoring.");
180 		return;
181 	}
182 
183 	memcpy(AirportSpec::GetWithoutOverride(airport_id), as, sizeof(*as));
184 
185 	/* Now add the overrides. */
186 	for (int i = 0; i < max_offset; i++) {
187 		AirportSpec *overridden_as = AirportSpec::GetWithoutOverride(i);
188 
189 		if (entity_overrides[i] != as->grf_prop.local_id || grfid_overrides[i] != as->grf_prop.grffile->grfid) continue;
190 
191 		overridden_as->grf_prop.override = airport_id;
192 		overridden_as->enabled = false;
193 		entity_overrides[i] = invalid_ID;
194 		grfid_overrides[i] = 0;
195 	}
196 }
197 
GetVariable(byte variable,uint32 parameter,bool * available) const198 /* virtual */ uint32 AirportScopeResolver::GetVariable(byte variable, uint32 parameter, bool *available) const
199 {
200 	switch (variable) {
201 		case 0x40: return this->layout;
202 	}
203 
204 	if (this->st == nullptr) {
205 		*available = false;
206 		return UINT_MAX;
207 	}
208 
209 	switch (variable) {
210 		/* Get a variable from the persistent storage */
211 		case 0x7C: return (this->st->airport.psa != nullptr) ? this->st->airport.psa->GetValue(parameter) : 0;
212 
213 		case 0xF0: return this->st->facilities;
214 		case 0xFA: return Clamp(this->st->build_date - DAYS_TILL_ORIGINAL_BASE_YEAR, 0, 65535);
215 	}
216 
217 	return this->st->GetNewGRFVariable(this->ro, variable, parameter, available);
218 }
219 
GetFeature() const220 GrfSpecFeature AirportResolverObject::GetFeature() const
221 {
222 	return GSF_AIRPORTS;
223 }
224 
GetDebugID() const225 uint32 AirportResolverObject::GetDebugID() const
226 {
227 	return AirportSpec::Get(this->airport_scope.airport_id)->grf_prop.local_id;
228 }
229 
GetRandomBits() const230 /* virtual */ uint32 AirportScopeResolver::GetRandomBits() const
231 {
232 	return this->st == nullptr ? 0 : this->st->random_bits;
233 }
234 
235 /**
236  * Store a value into the object's persistent storage.
237  * @param pos Position in the persistent storage to use.
238  * @param value Value to store.
239  */
StorePSA(uint pos,int32 value)240 /* virtual */ void AirportScopeResolver::StorePSA(uint pos, int32 value)
241 {
242 	if (this->st == nullptr) return;
243 
244 	if (this->st->airport.psa == nullptr) {
245 		/* There is no need to create a storage if the value is zero. */
246 		if (value == 0) return;
247 
248 		/* Create storage on first modification. */
249 		uint32 grfid = (this->ro.grffile != nullptr) ? this->ro.grffile->grfid : 0;
250 		assert(PersistentStorage::CanAllocateItem());
251 		this->st->airport.psa = new PersistentStorage(grfid, GSF_AIRPORTS, this->st->airport.tile);
252 	}
253 	this->st->airport.psa->StoreValue(pos, value);
254 }
255 
256 /**
257  * Constructor of the airport resolver.
258  * @param tile %Tile for the callback, only valid for airporttile callbacks.
259  * @param st %Station of the airport for which the callback is run, or \c nullptr for build gui.
260  * @param airport_id Type of airport for which the callback is run.
261  * @param layout Layout of the airport to build.
262  * @param callback Callback ID.
263  * @param param1 First parameter (var 10) of the callback.
264  * @param param2 Second parameter (var 18) of the callback.
265  */
AirportResolverObject(TileIndex tile,Station * st,byte airport_id,byte layout,CallbackID callback,uint32 param1,uint32 param2)266 AirportResolverObject::AirportResolverObject(TileIndex tile, Station *st, byte airport_id, byte layout,
267 		CallbackID callback, uint32 param1, uint32 param2)
268 	: ResolverObject(AirportSpec::Get(airport_id)->grf_prop.grffile, callback, param1, param2), airport_scope(*this, tile, st, airport_id, layout)
269 {
270 	this->root_spritegroup = AirportSpec::Get(airport_id)->grf_prop.spritegroup[0];
271 }
272 
GetCustomAirportSprite(const AirportSpec * as,byte layout)273 SpriteID GetCustomAirportSprite(const AirportSpec *as, byte layout)
274 {
275 	AirportResolverObject object(INVALID_TILE, nullptr, as->GetIndex(), layout);
276 	const SpriteGroup *group = object.Resolve();
277 	if (group == nullptr) return as->preview_sprite;
278 
279 	return group->GetResult();
280 }
281 
GetAirportCallback(CallbackID callback,uint32 param1,uint32 param2,Station * st,TileIndex tile)282 uint16 GetAirportCallback(CallbackID callback, uint32 param1, uint32 param2, Station *st, TileIndex tile)
283 {
284 	AirportResolverObject object(tile, st, st->airport.type, st->airport.layout, callback, param1, param2);
285 	return object.ResolveCallback();
286 }
287 
288 /**
289  * Get a custom text for the airport.
290  * @param as The airport type's specification.
291  * @param layout The layout index.
292  * @param callback The callback to call.
293  * @return The custom text.
294  */
GetAirportTextCallback(const AirportSpec * as,byte layout,uint16 callback)295 StringID GetAirportTextCallback(const AirportSpec *as, byte layout, uint16 callback)
296 {
297 	AirportResolverObject object(INVALID_TILE, nullptr, as->GetIndex(), layout, (CallbackID)callback);
298 	uint16 cb_res = object.ResolveCallback();
299 	if (cb_res == CALLBACK_FAILED || cb_res == 0x400) return STR_UNDEFINED;
300 	if (cb_res > 0x400) {
301 		ErrorUnknownCallbackResult(as->grf_prop.grffile->grfid, callback, cb_res);
302 		return STR_UNDEFINED;
303 	}
304 
305 	return GetGRFStringID(as->grf_prop.grffile->grfid, 0xD000 + cb_res);
306 }
307