(svn r27707) -Fix: Make the result of NewGRF's CARGO_NAME string code reliably print...
[openttd.git] / src / newgrf_commons.cpp
blob4caf3a5d4791ceca76e2e2744b9352c4d324245d
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 "debug.h"
17 #include "landscape.h"
18 #include "house.h"
19 #include "industrytype.h"
20 #include "newgrf_config.h"
21 #include "clear_map.h"
22 #include "station_map.h"
23 #include "tree_map.h"
24 #include "tunnelbridge_map.h"
25 #include "newgrf_object.h"
26 #include "genworld.h"
27 #include "newgrf_spritegroup.h"
28 #include "newgrf_text.h"
29 #include "company_base.h"
30 #include "error.h"
31 #include "strings_func.h"
33 #include "table/strings.h"
35 #include "safeguards.h"
37 /**
38 * Constructor of generic class
39 * @param offset end of original data for this entity. i.e: houses = 110
40 * @param maximum of entities this manager can deal with. i.e: houses = 512
41 * @param invalid is the ID used to identify an invalid entity id
43 OverrideManagerBase::OverrideManagerBase(uint16 offset, uint16 maximum, uint16 invalid)
45 max_offset = offset;
46 max_new_entities = maximum;
47 invalid_ID = invalid;
49 mapping_ID = CallocT<EntityIDMapping>(max_new_entities);
50 entity_overrides = MallocT<uint16>(max_offset);
51 for (size_t i = 0; i < max_offset; i++) entity_overrides[i] = invalid;
52 grfid_overrides = CallocT<uint32>(max_offset);
55 /**
56 * Destructor of the generic class.
57 * Frees allocated memory of constructor
59 OverrideManagerBase::~OverrideManagerBase()
61 free(mapping_ID);
62 free(entity_overrides);
63 free(grfid_overrides);
66 /**
67 * Since the entity IDs defined by the GRF file does not necessarily correlate
68 * to those used by the game, the IDs used for overriding old entities must be
69 * translated when the entity spec is set.
70 * @param local_id ID in grf file
71 * @param grfid ID of the grf file
72 * @param entity_type original entity type
74 void OverrideManagerBase::Add(uint8 local_id, uint32 grfid, uint entity_type)
76 assert(entity_type < max_offset);
77 /* An override can be set only once */
78 if (entity_overrides[entity_type] != invalid_ID) return;
79 entity_overrides[entity_type] = local_id;
80 grfid_overrides[entity_type] = grfid;
83 /** Resets the mapping, which is used while initializing game */
84 void OverrideManagerBase::ResetMapping()
86 memset(mapping_ID, 0, (max_new_entities - 1) * sizeof(EntityIDMapping));
89 /** Resets the override, which is used while initializing game */
90 void OverrideManagerBase::ResetOverride()
92 for (uint16 i = 0; i < max_offset; i++) {
93 entity_overrides[i] = invalid_ID;
94 grfid_overrides[i] = 0;
98 /**
99 * Return the ID (if ever available) of a previously inserted entity.
100 * @param grf_local_id ID of this entity within the grfID
101 * @param grfid ID of the grf file
102 * @return the ID of the candidate, of the Invalid flag item ID
104 uint16 OverrideManagerBase::GetID(uint8 grf_local_id, uint32 grfid) const
106 const EntityIDMapping *map;
108 for (uint16 id = 0; id < max_new_entities; id++) {
109 map = &mapping_ID[id];
110 if (map->entity_id == grf_local_id && map->grfid == grfid) {
111 return id;
115 return invalid_ID;
119 * Reserves a place in the mapping array for an entity to be installed
120 * @param grf_local_id is an arbitrary id given by the grf's author. Also known as setid
121 * @param grfid is the id of the grf file itself
122 * @param substitute_id is the original entity from which data is copied for the new one
123 * @return the proper usable slot id, or invalid marker if none is found
125 uint16 OverrideManagerBase::AddEntityID(byte grf_local_id, uint32 grfid, byte substitute_id)
127 uint16 id = this->GetID(grf_local_id, grfid);
128 EntityIDMapping *map;
130 /* Look to see if this entity has already been added. This is done
131 * separately from the loop below in case a GRF has been deleted, and there
132 * are any gaps in the array.
134 if (id != invalid_ID) {
135 return id;
138 /* This entity hasn't been defined before, so give it an ID now. */
139 for (id = max_offset; id < max_new_entities; id++) {
140 map = &mapping_ID[id];
142 if (CheckValidNewID(id) && map->entity_id == 0 && map->grfid == 0) {
143 map->entity_id = grf_local_id;
144 map->grfid = grfid;
145 map->substitute_id = substitute_id;
146 return id;
150 return invalid_ID;
154 * Gives the GRFID of the file the entity belongs to.
155 * @param entity_id ID of the entity being queried.
156 * @return GRFID.
158 uint32 OverrideManagerBase::GetGRFID(uint16 entity_id) const
160 return mapping_ID[entity_id].grfid;
164 * Gives the substitute of the entity, as specified by the grf file
165 * @param entity_id of the entity being queried
166 * @return mapped id
168 uint16 OverrideManagerBase::GetSubstituteID(uint16 entity_id) const
170 return mapping_ID[entity_id].substitute_id;
174 * Install the specs into the HouseSpecs array
175 * It will find itself the proper slot on which it will go
176 * @param hs HouseSpec read from the grf file, ready for inclusion
178 void HouseOverrideManager::SetEntitySpec(const HouseSpec *hs)
180 HouseID house_id = this->AddEntityID(hs->grf_prop.local_id, hs->grf_prop.grffile->grfid, hs->grf_prop.subst_id);
182 if (house_id == invalid_ID) {
183 grfmsg(1, "House.SetEntitySpec: Too many houses allocated. Ignoring.");
184 return;
187 MemCpyT(HouseSpec::Get(house_id), hs);
189 /* Now add the overrides. */
190 for (int i = 0; i != max_offset; i++) {
191 HouseSpec *overridden_hs = HouseSpec::Get(i);
193 if (entity_overrides[i] != hs->grf_prop.local_id || grfid_overrides[i] != hs->grf_prop.grffile->grfid) continue;
195 overridden_hs->grf_prop.override = house_id;
196 entity_overrides[i] = invalid_ID;
197 grfid_overrides[i] = 0;
202 * Return the ID (if ever available) of a previously inserted entity.
203 * @param grf_local_id ID of this entity within the grfID
204 * @param grfid ID of the grf file
205 * @return the ID of the candidate, of the Invalid flag item ID
207 uint16 IndustryOverrideManager::GetID(uint8 grf_local_id, uint32 grfid) const
209 uint16 id = OverrideManagerBase::GetID(grf_local_id, grfid);
210 if (id != invalid_ID) return id;
212 /* No mapping found, try the overrides */
213 for (id = 0; id < max_offset; id++) {
214 if (entity_overrides[id] == grf_local_id && grfid_overrides[id] == grfid) return id;
217 return invalid_ID;
221 * Method to find an entity ID and to mark it as reserved for the Industry to be included.
222 * @param grf_local_id ID used by the grf file for pre-installation work (equivalent of TTDPatch's setid
223 * @param grfid ID of the current grf file
224 * @param substitute_id industry from which data has been copied
225 * @return a free entity id (slotid) if ever one has been found, or Invalid_ID marker otherwise
227 uint16 IndustryOverrideManager::AddEntityID(byte grf_local_id, uint32 grfid, byte substitute_id)
229 /* This entity hasn't been defined before, so give it an ID now. */
230 for (uint16 id = 0; id < max_new_entities; id++) {
231 /* Skip overridden industries */
232 if (id < max_offset && entity_overrides[id] != invalid_ID) continue;
234 /* Get the real live industry */
235 const IndustrySpec *inds = GetIndustrySpec(id);
237 /* This industry must be one that is not available(enabled), mostly because of climate.
238 * And it must not already be used by a grf (grffile == NULL).
239 * So reserve this slot here, as it is the chosen one */
240 if (!inds->enabled && inds->grf_prop.grffile == NULL) {
241 EntityIDMapping *map = &mapping_ID[id];
243 if (map->entity_id == 0 && map->grfid == 0) {
244 /* winning slot, mark it as been used */
245 map->entity_id = grf_local_id;
246 map->grfid = grfid;
247 map->substitute_id = substitute_id;
248 return id;
253 return invalid_ID;
257 * Method to install the new industry data in its proper slot
258 * The slot assignment is internal of this method, since it requires
259 * checking what is available
260 * @param inds Industryspec that comes from the grf decoding process
262 void IndustryOverrideManager::SetEntitySpec(IndustrySpec *inds)
264 /* First step : We need to find if this industry is already specified in the savegame data. */
265 IndustryType ind_id = this->GetID(inds->grf_prop.local_id, inds->grf_prop.grffile->grfid);
267 if (ind_id == invalid_ID) {
268 /* Not found.
269 * Or it has already been overridden, so you've lost your place old boy.
270 * Or it is a simple substitute.
271 * We need to find a free available slot */
272 ind_id = this->AddEntityID(inds->grf_prop.local_id, inds->grf_prop.grffile->grfid, inds->grf_prop.subst_id);
273 inds->grf_prop.override = invalid_ID; // make sure it will not be detected as overridden
276 if (ind_id == invalid_ID) {
277 grfmsg(1, "Industry.SetEntitySpec: Too many industries allocated. Ignoring.");
278 return;
281 /* Now that we know we can use the given id, copy the spec to its final destination... */
282 memcpy(&_industry_specs[ind_id], inds, sizeof(*inds));
283 /* ... and mark it as usable*/
284 _industry_specs[ind_id].enabled = true;
287 void IndustryTileOverrideManager::SetEntitySpec(const IndustryTileSpec *its)
289 IndustryGfx indt_id = this->AddEntityID(its->grf_prop.local_id, its->grf_prop.grffile->grfid, its->grf_prop.subst_id);
291 if (indt_id == invalid_ID) {
292 grfmsg(1, "IndustryTile.SetEntitySpec: Too many industry tiles allocated. Ignoring.");
293 return;
296 memcpy(&_industry_tile_specs[indt_id], its, sizeof(*its));
298 /* Now add the overrides. */
299 for (int i = 0; i < max_offset; i++) {
300 IndustryTileSpec *overridden_its = &_industry_tile_specs[i];
302 if (entity_overrides[i] != its->grf_prop.local_id || grfid_overrides[i] != its->grf_prop.grffile->grfid) continue;
304 overridden_its->grf_prop.override = indt_id;
305 overridden_its->enabled = false;
306 entity_overrides[i] = invalid_ID;
307 grfid_overrides[i] = 0;
312 * Method to install the new object data in its proper slot
313 * The slot assignment is internal of this method, since it requires
314 * checking what is available
315 * @param spec ObjectSpec that comes from the grf decoding process
317 void ObjectOverrideManager::SetEntitySpec(ObjectSpec *spec)
319 /* First step : We need to find if this object is already specified in the savegame data. */
320 ObjectType type = this->GetID(spec->grf_prop.local_id, spec->grf_prop.grffile->grfid);
322 if (type == invalid_ID) {
323 /* Not found.
324 * Or it has already been overridden, so you've lost your place old boy.
325 * Or it is a simple substitute.
326 * We need to find a free available slot */
327 type = this->AddEntityID(spec->grf_prop.local_id, spec->grf_prop.grffile->grfid, OBJECT_TRANSMITTER);
330 if (type == invalid_ID) {
331 grfmsg(1, "Object.SetEntitySpec: Too many objects allocated. Ignoring.");
332 return;
335 extern ObjectSpec _object_specs[NUM_OBJECTS];
337 /* Now that we know we can use the given id, copy the spec to its final destination. */
338 memcpy(&_object_specs[type], spec, sizeof(*spec));
339 ObjectClass::Assign(&_object_specs[type]);
343 * Function used by houses (and soon industries) to get information
344 * on type of "terrain" the tile it is queries sits on.
345 * @param tile TileIndex of the tile been queried
346 * @param context The context of the tile.
347 * @return value corresponding to the grf expected format:
348 * Terrain type: 0 normal, 1 desert, 2 rainforest, 4 on or above snowline
350 uint32 GetTerrainType(TileIndex tile, TileContext context)
352 switch (_settings_game.game_creation.landscape) {
353 case LT_TROPIC: return GetTropicZone(tile);
354 case LT_ARCTIC: {
355 bool has_snow;
356 switch (GetTileType(tile)) {
357 case MP_CLEAR:
358 /* During map generation the snowstate may not be valid yet, as the tileloop may not have run yet. */
359 if (_generating_world) goto genworld;
360 has_snow = IsSnowTile(tile) && GetClearDensity(tile) >= 2;
361 break;
363 case MP_RAILWAY: {
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;
371 case MP_ROAD:
372 /* During map generation the snowstate may not be valid yet, as the tileloop may not have run yet. */
373 if (_generating_world) goto genworld; // we do not care about foundations here
374 has_snow = IsOnSnow(tile);
375 break;
377 case MP_TREES: {
378 /* During map generation the snowstate may not be valid yet, as the tileloop may not have run yet. */
379 if (_generating_world) goto genworld;
380 TreeGround ground = GetTreeGround(tile);
381 has_snow = (ground == TREE_GROUND_SNOW_DESERT || ground == TREE_GROUND_ROUGH_SNOW) && GetTreeDensity(tile) >= 2;
382 break;
385 case MP_TUNNELBRIDGE:
386 if (context == TCX_ON_BRIDGE) {
387 has_snow = (GetBridgeHeight(tile) > GetSnowLine());
388 } else {
389 /* During map generation the snowstate may not be valid yet, as the tileloop may not have run yet. */
390 if (_generating_world) goto genworld; // we do not care about foundations here
391 has_snow = HasTunnelBridgeSnowOrDesert(tile);
393 break;
395 case MP_STATION:
396 case MP_HOUSE:
397 case MP_INDUSTRY:
398 case MP_OBJECT:
399 /* These tiles usually have a levelling foundation. So use max Z */
400 has_snow = (GetTileMaxZ(tile) > GetSnowLine());
401 break;
403 case MP_VOID:
404 case MP_WATER:
405 genworld:
406 has_snow = (GetTileZ(tile) > GetSnowLine());
407 break;
409 default: NOT_REACHED();
411 return has_snow ? 4 : 0;
413 default: return 0;
418 * Get the tile at the given offset.
419 * @param parameter The NewGRF "encoded" offset.
420 * @param tile The tile to base the offset from.
421 * @param signed_offsets Whether the offsets are to be interpreted as signed or not.
422 * @param axis Axis of a railways station.
423 * @return The tile at the offset.
425 TileIndex GetNearbyTile(byte parameter, TileIndex tile, bool signed_offsets, Axis axis)
427 int8 x = GB(parameter, 0, 4);
428 int8 y = GB(parameter, 4, 4);
430 if (signed_offsets && x >= 8) x -= 16;
431 if (signed_offsets && y >= 8) y -= 16;
433 /* Swap width and height depending on axis for railway stations */
434 if (axis == INVALID_AXIS && HasStationTileRail(tile)) axis = GetRailStationAxis(tile);
435 if (axis == AXIS_Y) Swap(x, y);
437 /* Make sure we never roam outside of the map, better wrap in that case */
438 return TILE_MASK(tile + TileDiffXY(x, y));
442 * Common part of station var 0x67, house var 0x62, indtile var 0x60, industry var 0x62.
444 * @param tile the tile of interest.
445 * @param grf_version8 True, if we are dealing with a new NewGRF which uses GRF version >= 8.
446 * @return 0czzbbss: c = TileType; zz = TileZ; bb: 7-3 zero, 4-2 TerrainType, 1 water/shore, 0 zero; ss = TileSlope
448 uint32 GetNearbyTileInformation(TileIndex tile, bool grf_version8)
450 TileType tile_type = GetTileType(tile);
452 /* Fake tile type for trees on shore */
453 if (IsTileType(tile, MP_TREES) && GetTreeGround(tile) == TREE_GROUND_SHORE) tile_type = MP_WATER;
455 int z;
456 Slope tileh = GetTilePixelSlope(tile, &z);
457 /* Return 0 if the tile is a land tile */
458 byte terrain_type = (HasTileWaterClass(tile) ? (GetWaterClass(tile) + 1) & 3 : 0) << 5 | GetTerrainType(tile) << 2 | (tile_type == MP_WATER ? 1 : 0) << 1;
459 if (grf_version8) z /= TILE_HEIGHT;
460 return tile_type << 24 | Clamp(z, 0, 0xFF) << 16 | terrain_type << 8 | tileh;
464 * Returns company information like in vehicle var 43 or station var 43.
465 * @param owner Owner of the object.
466 * @param l Livery of the object; NULL to use default.
467 * @return NewGRF company information.
469 uint32 GetCompanyInfo(CompanyID owner, const Livery *l)
471 if (l == NULL && Company::IsValidID(owner)) l = &Company::Get(owner)->livery[LS_DEFAULT];
472 return owner | (Company::IsValidAiID(owner) ? 0x10000 : 0) | (l != NULL ? (l->colour1 << 24) | (l->colour2 << 28) : 0);
476 * Get the error message from a shape/location/slope check callback result.
477 * @param cb_res Callback result to translate. If bit 10 is set this is a standard error message, otherwise a NewGRF provided string.
478 * @param grffile NewGRF to use to resolve a custom error message.
479 * @param default_error Error message to use for the generic error.
480 * @return CommandCost indicating success or the error message.
482 CommandCost GetErrorMessageFromLocationCallbackResult(uint16 cb_res, const GRFFile *grffile, StringID default_error)
484 CommandCost res;
486 if (cb_res < 0x400) {
487 res = CommandCost(GetGRFStringID(grffile->grfid, 0xD000 + cb_res));
488 } else {
489 switch (cb_res) {
490 case 0x400: return res; // No error.
492 default: // unknown reason -> default error
493 case 0x401: res = CommandCost(default_error); break;
495 case 0x402: res = CommandCost(STR_ERROR_CAN_ONLY_BE_BUILT_IN_RAINFOREST); break;
496 case 0x403: res = CommandCost(STR_ERROR_CAN_ONLY_BE_BUILT_IN_DESERT); break;
497 case 0x404: res = CommandCost(STR_ERROR_CAN_ONLY_BE_BUILT_ABOVE_SNOW_LINE); break;
498 case 0x405: res = CommandCost(STR_ERROR_CAN_ONLY_BE_BUILT_BELOW_SNOW_LINE); break;
499 case 0x406: res = CommandCost(STR_ERROR_CAN_T_BUILD_ON_SEA); break;
500 case 0x407: res = CommandCost(STR_ERROR_CAN_T_BUILD_ON_CANAL); break;
501 case 0x408: res = CommandCost(STR_ERROR_CAN_T_BUILD_ON_RIVER); break;
505 /* Copy some parameters from the registers to the error message text ref. stack */
506 res.UseTextRefStack(grffile, 4);
508 return res;
512 * Record that a NewGRF returned an unknown/invalid callback result.
513 * Also show an error to the user.
514 * @param grfid ID of the NewGRF causing the problem.
515 * @param cbid Callback causing the problem.
516 * @param cb_res Invalid result returned by the callback.
518 void ErrorUnknownCallbackResult(uint32 grfid, uint16 cbid, uint16 cb_res)
520 GRFConfig *grfconfig = GetGRFConfig(grfid);
522 if (!HasBit(grfconfig->grf_bugs, GBUG_UNKNOWN_CB_RESULT)) {
523 SetBit(grfconfig->grf_bugs, GBUG_UNKNOWN_CB_RESULT);
524 SetDParamStr(0, grfconfig->GetName());
525 SetDParam(1, cbid);
526 SetDParam(2, cb_res);
527 ShowErrorMessage(STR_NEWGRF_BUGGY, STR_NEWGRF_BUGGY_UNKNOWN_CALLBACK_RESULT, WL_CRITICAL);
530 /* debug output */
531 char buffer[512];
533 SetDParamStr(0, grfconfig->GetName());
534 GetString(buffer, STR_NEWGRF_BUGGY, lastof(buffer));
535 DEBUG(grf, 0, "%s", buffer + 3);
537 SetDParam(1, cbid);
538 SetDParam(2, cb_res);
539 GetString(buffer, STR_NEWGRF_BUGGY_UNKNOWN_CALLBACK_RESULT, lastof(buffer));
540 DEBUG(grf, 0, "%s", buffer + 3);
544 * Converts a callback result into a boolean.
545 * For grf version < 8 the result is checked for zero or non-zero.
546 * For grf version >= 8 the callback result must be 0 or 1.
547 * @param grffile NewGRF returning the value.
548 * @param cbid Callback returning the value.
549 * @param cb_res Callback result.
550 * @return Boolean value. True if cb_res != 0.
552 bool ConvertBooleanCallback(const GRFFile *grffile, uint16 cbid, uint16 cb_res)
554 assert(cb_res != CALLBACK_FAILED); // We do not know what to return
556 if (grffile->grf_version < 8) return cb_res != 0;
558 if (cb_res > 1) ErrorUnknownCallbackResult(grffile->grfid, cbid, cb_res);
559 return cb_res != 0;
563 * Converts a callback result into a boolean.
564 * For grf version < 8 the first 8 bit of the result are checked for zero or non-zero.
565 * For grf version >= 8 the callback result must be 0 or 1.
566 * @param grffile NewGRF returning the value.
567 * @param cbid Callback returning the value.
568 * @param cb_res Callback result.
569 * @return Boolean value. True if cb_res != 0.
571 bool Convert8bitBooleanCallback(const GRFFile *grffile, uint16 cbid, uint16 cb_res)
573 assert(cb_res != CALLBACK_FAILED); // We do not know what to return
575 if (grffile->grf_version < 8) return GB(cb_res, 0, 8) != 0;
577 if (cb_res > 1) ErrorUnknownCallbackResult(grffile->grfid, cbid, cb_res);
578 return cb_res != 0;
582 /* static */ SmallVector<DrawTileSeqStruct, 8> NewGRFSpriteLayout::result_seq;
585 * Clone the building sprites of a spritelayout.
586 * @param source The building sprites to copy.
588 void NewGRFSpriteLayout::Clone(const DrawTileSeqStruct *source)
590 assert(this->seq == NULL);
591 assert(source != NULL);
593 size_t count = 1; // 1 for the terminator
594 const DrawTileSeqStruct *element;
595 foreach_draw_tile_seq(element, source) count++;
597 DrawTileSeqStruct *sprites = MallocT<DrawTileSeqStruct>(count);
598 MemCpyT(sprites, source, count);
599 this->seq = sprites;
603 * Clone a spritelayout.
604 * @param source The spritelayout to copy.
606 void NewGRFSpriteLayout::Clone(const NewGRFSpriteLayout *source)
608 this->Clone((const DrawTileSprites*)source);
610 if (source->registers != NULL) {
611 size_t count = 1; // 1 for the ground sprite
612 const DrawTileSeqStruct *element;
613 foreach_draw_tile_seq(element, source->seq) count++;
615 TileLayoutRegisters *regs = MallocT<TileLayoutRegisters>(count);
616 MemCpyT(regs, source->registers, count);
617 this->registers = regs;
623 * Allocate a spritelayout for \a num_sprites building sprites.
624 * @param num_sprites Number of building sprites to allocate memory for. (not counting the terminator)
626 void NewGRFSpriteLayout::Allocate(uint num_sprites)
628 assert(this->seq == NULL);
630 DrawTileSeqStruct *sprites = CallocT<DrawTileSeqStruct>(num_sprites + 1);
631 sprites[num_sprites].MakeTerminator();
632 this->seq = sprites;
636 * Allocate memory for register modifiers.
638 void NewGRFSpriteLayout::AllocateRegisters()
640 assert(this->seq != NULL);
641 assert(this->registers == NULL);
643 size_t count = 1; // 1 for the ground sprite
644 const DrawTileSeqStruct *element;
645 foreach_draw_tile_seq(element, this->seq) count++;
647 this->registers = CallocT<TileLayoutRegisters>(count);
651 * Prepares a sprite layout before resolving action-1-2-3 chains.
652 * Integrates offsets into the layout and determines which chains to resolve.
653 * @note The function uses statically allocated temporary storage, which is reused everytime when calling the function.
654 * That means, you have to use the sprite layout before calling #PrepareLayout() the next time.
655 * @param orig_offset Offset to apply to non-action-1 sprites.
656 * @param newgrf_ground_offset Offset to apply to action-1 ground sprites.
657 * @param newgrf_offset Offset to apply to action-1 non-ground sprites.
658 * @param constr_stage Construction stage (0-3) to apply to all action-1 sprites.
659 * @param separate_ground Whether the ground sprite shall be resolved by a separate action-1-2-3 chain by default.
660 * @return Bitmask of values for variable 10 to resolve action-1-2-3 chains for.
662 uint32 NewGRFSpriteLayout::PrepareLayout(uint32 orig_offset, uint32 newgrf_ground_offset, uint32 newgrf_offset, uint constr_stage, bool separate_ground) const
664 result_seq.Clear();
665 uint32 var10_values = 0;
667 /* Create a copy of the spritelayout, so we can modify some values.
668 * Also include the groundsprite into the sequence for easier processing. */
669 DrawTileSeqStruct *result = result_seq.Append();
670 result->image = ground;
671 result->delta_x = 0;
672 result->delta_y = 0;
673 result->delta_z = (int8)0x80;
675 const DrawTileSeqStruct *dtss;
676 foreach_draw_tile_seq(dtss, this->seq) {
677 *result_seq.Append() = *dtss;
679 result_seq.Append()->MakeTerminator();
681 /* Determine the var10 values the action-1-2-3 chains needs to be resolved for,
682 * and apply the default sprite offsets (unless disabled). */
683 const TileLayoutRegisters *regs = this->registers;
684 bool ground = true;
685 foreach_draw_tile_seq(result, result_seq.Begin()) {
686 TileLayoutFlags flags = TLF_NOTHING;
687 if (regs != NULL) flags = regs->flags;
689 /* Record var10 value for the sprite */
690 if (HasBit(result->image.sprite, SPRITE_MODIFIER_CUSTOM_SPRITE) || (flags & TLF_SPRITE_REG_FLAGS)) {
691 uint8 var10 = (flags & TLF_SPRITE_VAR10) ? regs->sprite_var10 : (ground && separate_ground ? 1 : 0);
692 SetBit(var10_values, var10);
695 /* Add default sprite offset, unless there is a custom one */
696 if (!(flags & TLF_SPRITE)) {
697 if (HasBit(result->image.sprite, SPRITE_MODIFIER_CUSTOM_SPRITE)) {
698 result->image.sprite += ground ? newgrf_ground_offset : newgrf_offset;
699 if (constr_stage > 0 && regs != NULL) result->image.sprite += GetConstructionStageOffset(constr_stage, regs->max_sprite_offset);
700 } else {
701 result->image.sprite += orig_offset;
705 /* Record var10 value for the palette */
706 if (HasBit(result->image.pal, SPRITE_MODIFIER_CUSTOM_SPRITE) || (flags & TLF_PALETTE_REG_FLAGS)) {
707 uint8 var10 = (flags & TLF_PALETTE_VAR10) ? regs->palette_var10 : (ground && separate_ground ? 1 : 0);
708 SetBit(var10_values, var10);
711 /* Add default palette offset, unless there is a custom one */
712 if (!(flags & TLF_PALETTE)) {
713 if (HasBit(result->image.pal, SPRITE_MODIFIER_CUSTOM_SPRITE)) {
714 result->image.sprite += ground ? newgrf_ground_offset : newgrf_offset;
715 if (constr_stage > 0 && regs != NULL) result->image.sprite += GetConstructionStageOffset(constr_stage, regs->max_palette_offset);
719 ground = false;
720 if (regs != NULL) regs++;
723 return var10_values;
727 * Evaluates the register modifiers and integrates them into the preprocessed sprite layout.
728 * @pre #PrepareLayout() needs calling first.
729 * @param resolved_var10 The value of var10 the action-1-2-3 chain was evaluated for.
730 * @param resolved_sprite Result sprite of the action-1-2-3 chain.
731 * @param separate_ground Whether the ground sprite is resolved by a separate action-1-2-3 chain.
732 * @return Resulting spritelayout after processing the registers.
734 void NewGRFSpriteLayout::ProcessRegisters(uint8 resolved_var10, uint32 resolved_sprite, bool separate_ground) const
736 DrawTileSeqStruct *result;
737 const TileLayoutRegisters *regs = this->registers;
738 bool ground = true;
739 foreach_draw_tile_seq(result, result_seq.Begin()) {
740 TileLayoutFlags flags = TLF_NOTHING;
741 if (regs != NULL) flags = regs->flags;
743 /* Is the sprite or bounding box affected by an action-1-2-3 chain? */
744 if (HasBit(result->image.sprite, SPRITE_MODIFIER_CUSTOM_SPRITE) || (flags & TLF_SPRITE_REG_FLAGS)) {
745 /* Does the var10 value apply to this sprite? */
746 uint8 var10 = (flags & TLF_SPRITE_VAR10) ? regs->sprite_var10 : (ground && separate_ground ? 1 : 0);
747 if (var10 == resolved_var10) {
748 /* Apply registers */
749 if ((flags & TLF_DODRAW) && GetRegister(regs->dodraw) == 0) {
750 result->image.sprite = 0;
751 } else {
752 if (HasBit(result->image.sprite, SPRITE_MODIFIER_CUSTOM_SPRITE)) result->image.sprite += resolved_sprite;
753 if (flags & TLF_SPRITE) {
754 int16 offset = (int16)GetRegister(regs->sprite); // mask to 16 bits to avoid trouble
755 if (!HasBit(result->image.sprite, SPRITE_MODIFIER_CUSTOM_SPRITE) || (offset >= 0 && offset < regs->max_sprite_offset)) {
756 result->image.sprite += offset;
757 } else {
758 result->image.sprite = SPR_IMG_QUERY;
762 if (result->IsParentSprite()) {
763 if (flags & TLF_BB_XY_OFFSET) {
764 result->delta_x += (int32)GetRegister(regs->delta.parent[0]);
765 result->delta_y += (int32)GetRegister(regs->delta.parent[1]);
767 if (flags & TLF_BB_Z_OFFSET) result->delta_z += (int32)GetRegister(regs->delta.parent[2]);
768 } else {
769 if (flags & TLF_CHILD_X_OFFSET) result->delta_x += (int32)GetRegister(regs->delta.child[0]);
770 if (flags & TLF_CHILD_Y_OFFSET) result->delta_y += (int32)GetRegister(regs->delta.child[1]);
776 /* Is the palette affected by an action-1-2-3 chain? */
777 if (result->image.sprite != 0 && (HasBit(result->image.pal, SPRITE_MODIFIER_CUSTOM_SPRITE) || (flags & TLF_PALETTE_REG_FLAGS))) {
778 /* Does the var10 value apply to this sprite? */
779 uint8 var10 = (flags & TLF_PALETTE_VAR10) ? regs->palette_var10 : (ground && separate_ground ? 1 : 0);
780 if (var10 == resolved_var10) {
781 /* Apply registers */
782 if (HasBit(result->image.pal, SPRITE_MODIFIER_CUSTOM_SPRITE)) result->image.pal += resolved_sprite;
783 if (flags & TLF_PALETTE) {
784 int16 offset = (int16)GetRegister(regs->palette); // mask to 16 bits to avoid trouble
785 if (!HasBit(result->image.pal, SPRITE_MODIFIER_CUSTOM_SPRITE) || (offset >= 0 && offset < regs->max_palette_offset)) {
786 result->image.pal += offset;
787 } else {
788 result->image.sprite = SPR_IMG_QUERY;
789 result->image.pal = PAL_NONE;
795 ground = false;
796 if (regs != NULL) regs++;