Translations update
[openttd/fttd.git] / src / newgrf_commons.cpp
blob2dd309976fc303d1ca85e3838a1481bcd123e356
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 /**
11 * @file newgrf_commons.cpp Implementation of the class %OverrideManagerBase
12 * and its descendance, present and future.
15 #include "stdafx.h"
16 #include "string.h"
17 #include "debug.h"
18 #include "landscape.h"
19 #include "house.h"
20 #include "industrytype.h"
21 #include "newgrf_config.h"
22 #include "map/ground.h"
23 #include "map/rail.h"
24 #include "map/slope.h"
25 #include "bridge.h"
26 #include "newgrf_object.h"
27 #include "genworld.h"
28 #include "newgrf_spritegroup.h"
29 #include "newgrf_text.h"
30 #include "company_base.h"
31 #include "error.h"
32 #include "strings_func.h"
34 #include "table/strings.h"
36 /**
37 * Constructor of generic class
38 * @param offset end of original data for this entity. i.e: houses = 110
39 * @param maximum of entities this manager can deal with. i.e: houses = 512
40 * @param invalid is the ID used to identify an invalid entity id
42 OverrideManagerBase::OverrideManagerBase(uint16 offset, uint16 maximum, uint16 invalid)
44 max_offset = offset;
45 max_new_entities = maximum;
46 invalid_ID = invalid;
48 mapping_ID = xcalloct<EntityIDMapping>(max_new_entities);
49 entity_overrides = xmalloct<uint16>(max_offset);
50 for (size_t i = 0; i < max_offset; i++) entity_overrides[i] = invalid;
51 grfid_overrides = xcalloct<uint32>(max_offset);
54 /**
55 * Destructor of the generic class.
56 * Frees allocated memory of constructor
58 OverrideManagerBase::~OverrideManagerBase()
60 free(mapping_ID);
61 free(entity_overrides);
62 free(grfid_overrides);
65 /**
66 * Since the entity IDs defined by the GRF file does not necessarily correlate
67 * to those used by the game, the IDs used for overriding old entities must be
68 * translated when the entity spec is set.
69 * @param local_id ID in grf file
70 * @param grfid ID of the grf file
71 * @param entity_type original entity type
73 void OverrideManagerBase::Add(uint8 local_id, uint32 grfid, uint entity_type)
75 assert(entity_type < max_offset);
76 /* An override can be set only once */
77 if (entity_overrides[entity_type] != invalid_ID) return;
78 entity_overrides[entity_type] = local_id;
79 grfid_overrides[entity_type] = grfid;
82 /** Resets the mapping, which is used while initializing game */
83 void OverrideManagerBase::ResetMapping()
85 memset(mapping_ID, 0, (max_new_entities - 1) * sizeof(EntityIDMapping));
88 /** Resets the override, which is used while initializing game */
89 void OverrideManagerBase::ResetOverride()
91 for (uint16 i = 0; i < max_offset; i++) {
92 entity_overrides[i] = invalid_ID;
93 grfid_overrides[i] = 0;
97 /**
98 * Return the ID (if ever available) of a previously inserted entity.
99 * @param grf_local_id ID of this entity within the grfID
100 * @param grfid ID of the grf file
101 * @return the ID of the candidate, of the Invalid flag item ID
103 uint16 OverrideManagerBase::GetID(uint8 grf_local_id, uint32 grfid) const
105 const EntityIDMapping *map;
107 for (uint16 id = 0; id < max_new_entities; id++) {
108 map = &mapping_ID[id];
109 if (map->entity_id == grf_local_id && map->grfid == grfid) {
110 return id;
114 return invalid_ID;
118 * Reserves a place in the mapping array for an entity to be installed
119 * @param grf_local_id is an arbitrary id given by the grf's author. Also known as setid
120 * @param grfid is the id of the grf file itself
121 * @param substitute_id is the original entity from which data is copied for the new one
122 * @return the proper usable slot id, or invalid marker if none is found
124 uint16 OverrideManagerBase::AddEntityID(byte grf_local_id, uint32 grfid, byte substitute_id)
126 uint16 id = this->GetID(grf_local_id, grfid);
127 EntityIDMapping *map;
129 /* Look to see if this entity has already been added. This is done
130 * separately from the loop below in case a GRF has been deleted, and there
131 * are any gaps in the array.
133 if (id != invalid_ID) {
134 return id;
137 /* This entity hasn't been defined before, so give it an ID now. */
138 for (id = max_offset; id < max_new_entities; id++) {
139 map = &mapping_ID[id];
141 if (CheckValidNewID(id) && map->entity_id == 0 && map->grfid == 0) {
142 map->entity_id = grf_local_id;
143 map->grfid = grfid;
144 map->substitute_id = substitute_id;
145 return id;
149 return invalid_ID;
153 * Gives the GRFID of the file the entity belongs to.
154 * @param entity_id ID of the entity being queried.
155 * @return GRFID.
157 uint32 OverrideManagerBase::GetGRFID(uint16 entity_id) const
159 return mapping_ID[entity_id].grfid;
163 * Gives the substitute of the entity, as specified by the grf file
164 * @param entity_id of the entity being queried
165 * @return mapped id
167 uint16 OverrideManagerBase::GetSubstituteID(uint16 entity_id) const
169 return mapping_ID[entity_id].substitute_id;
173 * Install the specs into the HouseSpecs array
174 * It will find itself the proper slot on which it will go
175 * @param hs HouseSpec read from the grf file, ready for inclusion
177 void HouseOverrideManager::SetEntitySpec(const HouseSpec *hs)
179 HouseID house_id = this->AddEntityID(hs->grf_prop.local_id, hs->grf_prop.grffile->grfid, hs->grf_prop.subst_id);
181 if (house_id == invalid_ID) {
182 grfmsg(1, "House.SetEntitySpec: Too many houses allocated. Ignoring.");
183 return;
186 MemCpyT(HouseSpec::Get(house_id), hs);
188 /* Now add the overrides. */
189 for (int i = 0; i != max_offset; i++) {
190 HouseSpec *overridden_hs = HouseSpec::Get(i);
192 if (entity_overrides[i] != hs->grf_prop.local_id || grfid_overrides[i] != hs->grf_prop.grffile->grfid) continue;
194 overridden_hs->grf_prop.override = house_id;
195 entity_overrides[i] = invalid_ID;
196 grfid_overrides[i] = 0;
201 * Return the ID (if ever available) of a previously inserted entity.
202 * @param grf_local_id ID of this entity within the grfID
203 * @param grfid ID of the grf file
204 * @return the ID of the candidate, of the Invalid flag item ID
206 uint16 IndustryOverrideManager::GetID(uint8 grf_local_id, uint32 grfid) const
208 uint16 id = OverrideManagerBase::GetID(grf_local_id, grfid);
209 if (id != invalid_ID) return id;
211 /* No mapping found, try the overrides */
212 for (id = 0; id < max_offset; id++) {
213 if (entity_overrides[id] == grf_local_id && grfid_overrides[id] == grfid) return id;
216 return invalid_ID;
220 * Method to find an entity ID and to mark it as reserved for the Industry to be included.
221 * @param grf_local_id ID used by the grf file for pre-installation work (equivalent of TTDPatch's setid
222 * @param grfid ID of the current grf file
223 * @param substitute_id industry from which data has been copied
224 * @return a free entity id (slotid) if ever one has been found, or Invalid_ID marker otherwise
226 uint16 IndustryOverrideManager::AddEntityID(byte grf_local_id, uint32 grfid, byte substitute_id)
228 /* This entity hasn't been defined before, so give it an ID now. */
229 for (uint16 id = 0; id < max_new_entities; id++) {
230 /* Skip overridden industries */
231 if (id < max_offset && entity_overrides[id] != invalid_ID) continue;
233 /* Get the real live industry */
234 const IndustrySpec *inds = GetIndustrySpec(id);
236 /* This industry must be one that is not available(enabled), mostly because of climate.
237 * And it must not already be used by a grf (grffile == NULL).
238 * So reserve this slot here, as it is the chosen one */
239 if (!inds->enabled && inds->grf_prop.grffile == NULL) {
240 EntityIDMapping *map = &mapping_ID[id];
242 if (map->entity_id == 0 && map->grfid == 0) {
243 /* winning slot, mark it as been used */
244 map->entity_id = grf_local_id;
245 map->grfid = grfid;
246 map->substitute_id = substitute_id;
247 return id;
252 return invalid_ID;
256 * Method to install the new industry data in its proper slot
257 * The slot assignment is internal of this method, since it requires
258 * checking what is available
259 * @param inds Industryspec that comes from the grf decoding process
261 void IndustryOverrideManager::SetEntitySpec(IndustrySpec *inds)
263 /* First step : We need to find if this industry is already specified in the savegame data. */
264 IndustryType ind_id = this->GetID(inds->grf_prop.local_id, inds->grf_prop.grffile->grfid);
266 if (ind_id == invalid_ID) {
267 /* Not found.
268 * Or it has already been overridden, so you've lost your place old boy.
269 * Or it is a simple substitute.
270 * We need to find a free available slot */
271 ind_id = this->AddEntityID(inds->grf_prop.local_id, inds->grf_prop.grffile->grfid, inds->grf_prop.subst_id);
272 inds->grf_prop.override = invalid_ID; // make sure it will not be detected as overridden
275 if (ind_id == invalid_ID) {
276 grfmsg(1, "Industry.SetEntitySpec: Too many industries allocated. Ignoring.");
277 return;
280 /* Now that we know we can use the given id, copy the spec to its final destination... */
281 memcpy(&_industry_specs[ind_id], inds, sizeof(*inds));
282 /* ... and mark it as usable*/
283 _industry_specs[ind_id].enabled = true;
286 void IndustryTileOverrideManager::SetEntitySpec(const IndustryTileSpec *its)
288 IndustryGfx indt_id = this->AddEntityID(its->grf_prop.local_id, its->grf_prop.grffile->grfid, its->grf_prop.subst_id);
290 if (indt_id == invalid_ID) {
291 grfmsg(1, "IndustryTile.SetEntitySpec: Too many industry tiles allocated. Ignoring.");
292 return;
295 memcpy(&_industry_tile_specs[indt_id], its, sizeof(*its));
297 /* Now add the overrides. */
298 for (int i = 0; i < max_offset; i++) {
299 IndustryTileSpec *overridden_its = &_industry_tile_specs[i];
301 if (entity_overrides[i] != its->grf_prop.local_id || grfid_overrides[i] != its->grf_prop.grffile->grfid) continue;
303 overridden_its->grf_prop.override = indt_id;
304 overridden_its->enabled = false;
305 entity_overrides[i] = invalid_ID;
306 grfid_overrides[i] = 0;
311 * Method to install the new object data in its proper slot
312 * The slot assignment is internal of this method, since it requires
313 * checking what is available
314 * @param spec ObjectSpec that comes from the grf decoding process
316 void ObjectOverrideManager::SetEntitySpec(ObjectSpec *spec)
318 /* First step : We need to find if this object is already specified in the savegame data. */
319 ObjectType type = this->GetID(spec->grf_prop.local_id, spec->grf_prop.grffile->grfid);
321 if (type == invalid_ID) {
322 /* Not found.
323 * Or it has already been overridden, so you've lost your place old boy.
324 * Or it is a simple substitute.
325 * We need to find a free available slot */
326 type = this->AddEntityID(spec->grf_prop.local_id, spec->grf_prop.grffile->grfid, OBJECT_TRANSMITTER);
329 if (type == invalid_ID) {
330 grfmsg(1, "Object.SetEntitySpec: Too many objects allocated. Ignoring.");
331 return;
334 extern ObjectSpec _object_specs[NUM_OBJECTS];
336 /* Now that we know we can use the given id, copy the spec to its final destination. */
337 memcpy(&_object_specs[type], spec, sizeof(*spec));
338 ObjectClass::Assign(&_object_specs[type]);
342 * Function used by houses (and soon industries) to get information
343 * on type of "terrain" the tile it is queries sits on.
344 * @param tile TileIndex of the tile been queried
345 * @param context The context of the tile.
346 * @return value corresponding to the grf expected format:
347 * Terrain type: 0 normal, 1 desert, 2 rainforest, 4 on or above snowline
349 uint32 GetTerrainType(TileIndex tile, TileContext context)
351 switch (_settings_game.game_creation.landscape) {
352 case LT_TROPIC: return GetTropicZone(tile);
353 case LT_ARCTIC: {
354 bool has_snow;
355 switch (GetTileType(tile)) {
356 case TT_GROUND:
357 /* During map generation the snowstate may not be valid yet, as the tileloop may not have run yet. */
358 if (_generating_world || IsTileSubtype(tile, TT_GROUND_VOID)) goto genworld;
359 has_snow = IsSnowTile(tile) && GetClearDensity(tile) >= 2;
360 break;
362 case TT_RAILWAY:
363 if (IsTileSubtype(tile, TT_TRACK)) {
364 /* During map generation the snowstate may not be valid yet, as the tileloop may not have run yet. */
365 if (_generating_world) goto genworld; // we do not care about foundations here
366 RailGroundType ground = GetRailGroundType(tile);
367 has_snow = (ground == RAIL_GROUND_ICE_DESERT || (context == TCX_UPPER_HALFTILE && ground == RAIL_GROUND_HALF_SNOW));
368 break;
370 bridge:
371 if (context == TCX_ON_BRIDGE) {
372 has_snow = (GetBridgeHeight(tile) > GetSnowLine());
373 break;
375 bitcheck:
376 /* During map generation the snowstate may not be valid yet, as the tileloop may not have run yet. */
377 if (_generating_world) goto genworld; // we do not care about foundations here
378 has_snow = IsOnSnow(tile);
379 break;
381 case TT_ROAD:
382 if (IsTileSubtype(tile, TT_BRIDGE)) goto bridge;
383 goto bitcheck;
385 case TT_MISC:
386 if (IsTileSubtype(tile, TT_MISC_AQUEDUCT)) goto bridge;
387 goto bitcheck;
389 case TT_WATER:
390 genworld:
391 has_snow = (GetTileZ(tile) > GetSnowLine());
392 break;
394 default: // objects, stations, industries, houses
395 /* These tiles usually have a levelling foundation. So use max Z */
396 has_snow = (GetTileMaxZ(tile) > GetSnowLine());
397 break;
399 return has_snow ? 4 : 0;
401 default: return 0;
406 * Get the tile at the given offset.
407 * @param parameter The NewGRF "encoded" offset.
408 * @param tile The tile to base the offset from.
409 * @param signed_offsets Whether the offsets are to be interpreted as signed or not.
410 * @param axis Axis of a railways station.
411 * @return The tile at the offset.
413 TileIndex GetNearbyTile(byte parameter, TileIndex tile, bool signed_offsets, Axis axis)
415 int8 x = GB(parameter, 0, 4);
416 int8 y = GB(parameter, 4, 4);
418 if (signed_offsets && x >= 8) x -= 16;
419 if (signed_offsets && y >= 8) y -= 16;
421 /* Swap width and height depending on axis for railway stations */
422 if (axis == INVALID_AXIS && HasStationTileRail(tile)) axis = GetRailStationAxis(tile);
423 if (axis == AXIS_Y) Swap(x, y);
425 /* Make sure we never roam outside of the map, better wrap in that case */
426 return TILE_MASK(tile + TileDiffXY(x, y));
430 * Common part of station var 0x67, house var 0x62, indtile var 0x60, industry var 0x62.
432 * @param tile the tile of interest.
433 * @param grf_version8 True, if we are dealing with a new NewGRF which uses GRF version >= 8.
434 * @return 0czzbbss: c = TileType; zz = TileZ; bb: 7-3 zero, 4-2 TerrainType, 1 water/shore, 0 zero; ss = TileSlope
436 uint32 GetNearbyTileInformation(TileIndex tile, bool grf_version8)
438 enum OldTileType {
439 OLD_MP_CLEAR, ///< A tile without any structures, i.e. grass, docks, farm fields etc.
440 OLD_MP_RAILWAY, ///< A railway
441 OLD_MP_ROAD, ///< A tile with road (or tram tracks)
442 OLD_MP_HOUSE, ///< A house by a town
443 OLD_MP_TREES, ///< Tile got trees
444 OLD_MP_STATION, ///< A tile of a station
445 OLD_MP_WATER, ///< Water tile
446 OLD_MP_VOID, ///< Invisible tiles at the SW and SE border
447 OLD_MP_INDUSTRY, ///< Part of an industry
448 OLD_MP_TUNNELBRIDGE, ///< Tunnel entry/exit and bridge heads
449 OLD_MP_OBJECT, ///< Contains objects such as transmitters and owned land
452 OldTileType tile_type;
454 switch ((int)GetTileType(tile)) {
455 case TT_GROUND:
456 switch (GetTileSubtype(tile)) {
457 case TT_GROUND_VOID:
458 tile_type = OLD_MP_VOID;
459 break;
460 case TT_GROUND_FIELDS:
461 case TT_GROUND_CLEAR:
462 tile_type = OLD_MP_CLEAR;
463 break;
464 case TT_GROUND_TREES:
465 /* Fake tile type for trees on shore */
466 tile_type = (GetClearGround(tile) == GROUND_SHORE) ? OLD_MP_WATER : OLD_MP_TREES;
467 break;
469 break;
471 case TT_OBJECT: tile_type = OLD_MP_OBJECT; break;
472 case TT_WATER: tile_type = OLD_MP_WATER; break;
474 case 3: NOT_REACHED();
476 case TT_RAILWAY:
477 tile_type = (GetTileSubtype(tile) == TT_TRACK ? OLD_MP_RAILWAY : OLD_MP_TUNNELBRIDGE);
478 break;
480 case TT_ROAD:
481 tile_type = (GetTileSubtype(tile) == TT_TRACK ? OLD_MP_ROAD : OLD_MP_TUNNELBRIDGE);
482 break;
484 case TT_MISC:
485 switch (GetTileSubtype(tile)) {
486 case TT_MISC_CROSSING:
487 tile_type = OLD_MP_ROAD;
488 break;
489 case TT_MISC_AQUEDUCT:
490 case TT_MISC_TUNNEL:
491 tile_type = OLD_MP_TUNNELBRIDGE;
492 break;
493 case TT_MISC_DEPOT:
494 tile_type = IsRoadDepot(tile) ? OLD_MP_ROAD : OLD_MP_RAILWAY;
495 break;
497 break;
499 case TT_STATION: tile_type = OLD_MP_STATION; break;
501 case 8: tile_type = OLD_MP_INDUSTRY; break;
503 case 9: case 10: case 11: NOT_REACHED();
505 case 12: case 13: case 14: case 15:
506 tile_type = OLD_MP_HOUSE; break;
509 int z;
510 Slope tileh = GetTilePixelSlope(tile, &z);
511 /* Return 0 if the tile is a land tile */
512 byte terrain_type = (HasTileWaterClass(tile) ? (GetWaterClass(tile) + 1) & 3 : 0) << 5 | GetTerrainType(tile) << 2 | (tile_type == OLD_MP_WATER ? 1 : 0) << 1;
513 if (grf_version8) z /= TILE_HEIGHT;
514 return tile_type << 24 | Clamp(z, 0, 0xFF) << 16 | terrain_type << 8 | tileh;
518 * Returns company information like in vehicle var 43 or station var 43.
519 * @param owner Owner of the object.
520 * @param l Livery of the object; NULL to use default.
521 * @return NewGRF company information.
523 uint32 GetCompanyInfo(CompanyID owner, const Livery *l)
525 if (l == NULL && Company::IsValidID(owner)) l = &Company::Get(owner)->livery[LS_DEFAULT];
526 return owner | (Company::IsValidAiID(owner) ? 0x10000 : 0) | (l != NULL ? (l->colour1 << 24) | (l->colour2 << 28) : 0);
530 * Get the error message from a shape/location/slope check callback result.
531 * @param cb_res Callback result to translate. If bit 10 is set this is a standard error message, otherwise a NewGRF provided string.
532 * @param grffile NewGRF to use to resolve a custom error message.
533 * @param default_error Error message to use for the generic error.
534 * @return CommandCost indicating success or the error message.
536 CommandCost GetErrorMessageFromLocationCallbackResult(uint16 cb_res, const GRFFile *grffile, StringID default_error)
538 CommandCost res;
540 if (cb_res < 0x400) {
541 res = CommandCost(GetGRFStringID(grffile->grfid, 0xD000 + cb_res));
542 } else {
543 switch (cb_res) {
544 case 0x400: return res; // No error.
546 default: // unknown reason -> default error
547 case 0x401: res = CommandCost(default_error); break;
549 case 0x402: res = CommandCost(STR_ERROR_CAN_ONLY_BE_BUILT_IN_RAINFOREST); break;
550 case 0x403: res = CommandCost(STR_ERROR_CAN_ONLY_BE_BUILT_IN_DESERT); break;
551 case 0x404: res = CommandCost(STR_ERROR_CAN_ONLY_BE_BUILT_ABOVE_SNOW_LINE); break;
552 case 0x405: res = CommandCost(STR_ERROR_CAN_ONLY_BE_BUILT_BELOW_SNOW_LINE); break;
553 case 0x406: res = CommandCost(STR_ERROR_CAN_T_BUILD_ON_SEA); break;
554 case 0x407: res = CommandCost(STR_ERROR_CAN_T_BUILD_ON_CANAL); break;
555 case 0x408: res = CommandCost(STR_ERROR_CAN_T_BUILD_ON_RIVER); break;
559 /* Copy some parameters from the registers to the error message text ref. stack */
560 res.UseTextRefStack(grffile, 4);
562 return res;
566 * Record that a NewGRF returned an unknown/invalid callback result.
567 * Also show an error to the user.
568 * @param grfid ID of the NewGRF causing the problem.
569 * @param cbid Callback causing the problem.
570 * @param cb_res Invalid result returned by the callback.
572 void ErrorUnknownCallbackResult(uint32 grfid, uint16 cbid, uint16 cb_res)
574 GRFConfig *grfconfig = GetGRFConfig(grfid);
576 if (!HasBit(grfconfig->grf_bugs, GBUG_UNKNOWN_CB_RESULT)) {
577 SetBit(grfconfig->grf_bugs, GBUG_UNKNOWN_CB_RESULT);
578 SetDParamStr(0, grfconfig->GetName());
579 SetDParam(1, cbid);
580 SetDParam(2, cb_res);
581 ShowErrorMessage(STR_NEWGRF_BUGGY, STR_NEWGRF_BUGGY_UNKNOWN_CALLBACK_RESULT, WL_CRITICAL);
584 /* debug output */
585 char buffer[512];
587 SetDParamStr(0, grfconfig->GetName());
588 GetString (buffer, STR_NEWGRF_BUGGY);
589 DEBUG(grf, 0, "%s", buffer + 3);
591 SetDParam(1, cbid);
592 SetDParam(2, cb_res);
593 GetString (buffer, STR_NEWGRF_BUGGY_UNKNOWN_CALLBACK_RESULT);
594 DEBUG(grf, 0, "%s", buffer + 3);
598 * Converts a callback result into a boolean.
599 * For grf version < 8 the result is checked for zero or non-zero.
600 * For grf version >= 8 the callback result must be 0 or 1.
601 * @param grffile NewGRF returning the value.
602 * @param cbid Callback returning the value.
603 * @param cb_res Callback result.
604 * @return Boolean value. True if cb_res != 0.
606 bool ConvertBooleanCallback(const GRFFile *grffile, uint16 cbid, uint16 cb_res)
608 assert(cb_res != CALLBACK_FAILED); // We do not know what to return
610 if (grffile->grf_version < 8) return cb_res != 0;
612 if (cb_res > 1) ErrorUnknownCallbackResult(grffile->grfid, cbid, cb_res);
613 return cb_res != 0;
617 * Converts a callback result into a boolean.
618 * For grf version < 8 the first 8 bit of the result are checked for zero or non-zero.
619 * For grf version >= 8 the callback result must be 0 or 1.
620 * @param grffile NewGRF returning the value.
621 * @param cbid Callback returning the value.
622 * @param cb_res Callback result.
623 * @return Boolean value. True if cb_res != 0.
625 bool Convert8bitBooleanCallback(const GRFFile *grffile, uint16 cbid, uint16 cb_res)
627 assert(cb_res != CALLBACK_FAILED); // We do not know what to return
629 if (grffile->grf_version < 8) return GB(cb_res, 0, 8) != 0;
631 if (cb_res > 1) ErrorUnknownCallbackResult(grffile->grfid, cbid, cb_res);
632 return cb_res != 0;
636 /* static */ SmallVector<DrawTileSeqStruct, 8> NewGRFSpriteLayout::result_seq;
639 * Clone the building sprites of a spritelayout.
640 * @param source The building sprites to copy.
642 void NewGRFSpriteLayout::Clone(const DrawTileSeqStruct *source)
644 assert(this->seq == NULL);
645 assert(source != NULL);
647 size_t count = 1; // 1 for the terminator
648 const DrawTileSeqStruct *element;
649 foreach_draw_tile_seq(element, source) count++;
651 this->seq = xmemdupt (source, count);
655 * Clone a spritelayout.
656 * @param source The spritelayout to copy.
658 void NewGRFSpriteLayout::Clone(const NewGRFSpriteLayout *source)
660 this->Clone((const DrawTileSprites*)source);
662 if (source->registers != NULL) {
663 size_t count = 1; // 1 for the ground sprite
664 const DrawTileSeqStruct *element;
665 foreach_draw_tile_seq(element, source->seq) count++;
667 this->registers = xmemdupt (source->registers, count);
673 * Allocate a spritelayout for \a num_sprites building sprites.
674 * @param num_sprites Number of building sprites to allocate memory for. (not counting the terminator)
676 void NewGRFSpriteLayout::Allocate(uint num_sprites)
678 assert(this->seq == NULL);
680 DrawTileSeqStruct *sprites = xcalloct<DrawTileSeqStruct>(num_sprites + 1);
681 sprites[num_sprites].MakeTerminator();
682 this->seq = sprites;
686 * Allocate memory for register modifiers.
688 void NewGRFSpriteLayout::AllocateRegisters()
690 assert(this->seq != NULL);
691 assert(this->registers == NULL);
693 size_t count = 1; // 1 for the ground sprite
694 const DrawTileSeqStruct *element;
695 foreach_draw_tile_seq(element, this->seq) count++;
697 this->registers = xcalloct<TileLayoutRegisters>(count);
701 * Prepares a sprite layout before resolving action-1-2-3 chains.
702 * Integrates offsets into the layout and determines which chains to resolve.
703 * @note The function uses statically allocated temporary storage, which is reused everytime when calling the function.
704 * That means, you have to use the sprite layout before calling #PrepareLayout() the next time.
705 * @param orig_offset Offset to apply to non-action-1 sprites.
706 * @param newgrf_ground_offset Offset to apply to action-1 ground sprites.
707 * @param newgrf_offset Offset to apply to action-1 non-ground sprites.
708 * @param constr_stage Construction stage (0-3) to apply to all action-1 sprites.
709 * @param separate_ground Whether the ground sprite shall be resolved by a separate action-1-2-3 chain by default.
710 * @return Bitmask of values for variable 10 to resolve action-1-2-3 chains for.
712 uint32 NewGRFSpriteLayout::PrepareLayout(uint32 orig_offset, uint32 newgrf_ground_offset, uint32 newgrf_offset, uint constr_stage, bool separate_ground) const
714 result_seq.Clear();
715 uint32 var10_values = 0;
717 /* Create a copy of the spritelayout, so we can modify some values.
718 * Also include the groundsprite into the sequence for easier processing. */
719 DrawTileSeqStruct *result = result_seq.Append();
720 result->image = ground;
721 result->delta_x = 0;
722 result->delta_y = 0;
723 result->delta_z = (int8)0x80;
725 const DrawTileSeqStruct *dtss;
726 foreach_draw_tile_seq(dtss, this->seq) {
727 *result_seq.Append() = *dtss;
729 result_seq.Append()->MakeTerminator();
731 /* Determine the var10 values the action-1-2-3 chains needs to be resolved for,
732 * and apply the default sprite offsets (unless disabled). */
733 const TileLayoutRegisters *regs = this->registers;
734 bool ground = true;
735 foreach_draw_tile_seq(result, result_seq.Begin()) {
736 TileLayoutFlags flags = TLF_NOTHING;
737 if (regs != NULL) flags = regs->flags;
739 /* Record var10 value for the sprite */
740 if (HasBit(result->image.sprite, SPRITE_MODIFIER_CUSTOM_SPRITE) || (flags & TLF_SPRITE_REG_FLAGS)) {
741 uint8 var10 = (flags & TLF_SPRITE_VAR10) ? regs->sprite_var10 : (ground && separate_ground ? 1 : 0);
742 SetBit(var10_values, var10);
745 /* Add default sprite offset, unless there is a custom one */
746 if (!(flags & TLF_SPRITE)) {
747 if (HasBit(result->image.sprite, SPRITE_MODIFIER_CUSTOM_SPRITE)) {
748 result->image.sprite += ground ? newgrf_ground_offset : newgrf_offset;
749 if (constr_stage > 0 && regs != NULL) result->image.sprite += GetConstructionStageOffset(constr_stage, regs->max_sprite_offset);
750 } else {
751 result->image.sprite += orig_offset;
755 /* Record var10 value for the palette */
756 if (HasBit(result->image.pal, SPRITE_MODIFIER_CUSTOM_SPRITE) || (flags & TLF_PALETTE_REG_FLAGS)) {
757 uint8 var10 = (flags & TLF_PALETTE_VAR10) ? regs->palette_var10 : (ground && separate_ground ? 1 : 0);
758 SetBit(var10_values, var10);
761 /* Add default palette offset, unless there is a custom one */
762 if (!(flags & TLF_PALETTE)) {
763 if (HasBit(result->image.pal, SPRITE_MODIFIER_CUSTOM_SPRITE)) {
764 result->image.sprite += ground ? newgrf_ground_offset : newgrf_offset;
765 if (constr_stage > 0 && regs != NULL) result->image.sprite += GetConstructionStageOffset(constr_stage, regs->max_palette_offset);
769 ground = false;
770 if (regs != NULL) regs++;
773 return var10_values;
777 * Evaluates the register modifiers and integrates them into the preprocessed sprite layout.
778 * @pre #PrepareLayout() needs calling first.
779 * @param resolved_var10 The value of var10 the action-1-2-3 chain was evaluated for.
780 * @param resolved_sprite Result sprite of the action-1-2-3 chain.
781 * @param separate_ground Whether the ground sprite is resolved by a separate action-1-2-3 chain.
782 * @return Resulting spritelayout after processing the registers.
784 void NewGRFSpriteLayout::ProcessRegisters(uint8 resolved_var10, uint32 resolved_sprite, bool separate_ground) const
786 DrawTileSeqStruct *result;
787 const TileLayoutRegisters *regs = this->registers;
788 bool ground = true;
789 foreach_draw_tile_seq(result, result_seq.Begin()) {
790 TileLayoutFlags flags = TLF_NOTHING;
791 if (regs != NULL) flags = regs->flags;
793 /* Is the sprite or bounding box affected by an action-1-2-3 chain? */
794 if (HasBit(result->image.sprite, SPRITE_MODIFIER_CUSTOM_SPRITE) || (flags & TLF_SPRITE_REG_FLAGS)) {
795 /* Does the var10 value apply to this sprite? */
796 uint8 var10 = (flags & TLF_SPRITE_VAR10) ? regs->sprite_var10 : (ground && separate_ground ? 1 : 0);
797 if (var10 == resolved_var10) {
798 /* Apply registers */
799 if ((flags & TLF_DODRAW) && GetRegister(regs->dodraw) == 0) {
800 result->image.sprite = 0;
801 } else {
802 if (HasBit(result->image.sprite, SPRITE_MODIFIER_CUSTOM_SPRITE)) result->image.sprite += resolved_sprite;
803 if (flags & TLF_SPRITE) {
804 int16 offset = (int16)GetRegister(regs->sprite); // mask to 16 bits to avoid trouble
805 if (!HasBit(result->image.sprite, SPRITE_MODIFIER_CUSTOM_SPRITE) || (offset >= 0 && offset < regs->max_sprite_offset)) {
806 result->image.sprite += offset;
807 } else {
808 result->image.sprite = SPR_IMG_QUERY;
812 if (result->IsParentSprite()) {
813 if (flags & TLF_BB_XY_OFFSET) {
814 result->delta_x += (int32)GetRegister(regs->delta.parent[0]);
815 result->delta_y += (int32)GetRegister(regs->delta.parent[1]);
817 if (flags & TLF_BB_Z_OFFSET) result->delta_z += (int32)GetRegister(regs->delta.parent[2]);
818 } else {
819 if (flags & TLF_CHILD_X_OFFSET) result->delta_x += (int32)GetRegister(regs->delta.child[0]);
820 if (flags & TLF_CHILD_Y_OFFSET) result->delta_y += (int32)GetRegister(regs->delta.child[1]);
826 /* Is the palette affected by an action-1-2-3 chain? */
827 if (result->image.sprite != 0 && (HasBit(result->image.pal, SPRITE_MODIFIER_CUSTOM_SPRITE) || (flags & TLF_PALETTE_REG_FLAGS))) {
828 /* Does the var10 value apply to this sprite? */
829 uint8 var10 = (flags & TLF_PALETTE_VAR10) ? regs->palette_var10 : (ground && separate_ground ? 1 : 0);
830 if (var10 == resolved_var10) {
831 /* Apply registers */
832 if (HasBit(result->image.pal, SPRITE_MODIFIER_CUSTOM_SPRITE)) result->image.pal += resolved_sprite;
833 if (flags & TLF_PALETTE) {
834 int16 offset = (int16)GetRegister(regs->palette); // mask to 16 bits to avoid trouble
835 if (!HasBit(result->image.pal, SPRITE_MODIFIER_CUSTOM_SPRITE) || (offset >= 0 && offset < regs->max_palette_offset)) {
836 result->image.pal += offset;
837 } else {
838 result->image.sprite = SPR_IMG_QUERY;
839 result->image.pal = PAL_NONE;
845 ground = false;
846 if (regs != NULL) regs++;