Update: Translations from eints
[openttd-github.git] / src / newgrf_object.cpp
blob14046a469b14cb363f7e69a582d8c355bbb1d8a5
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 */
8 /** @file newgrf_object.cpp Handling of object NewGRFs. */
10 #include "stdafx.h"
11 #include "company_base.h"
12 #include "company_func.h"
13 #include "debug.h"
14 #include "genworld.h"
15 #include "newgrf_object.h"
16 #include "newgrf_class_func.h"
17 #include "newgrf_sound.h"
18 #include "object_base.h"
19 #include "object_map.h"
20 #include "timer/timer_game_calendar.h"
21 #include "tile_cmd.h"
22 #include "town.h"
23 #include "water.h"
24 #include "newgrf_animation_base.h"
26 #include "safeguards.h"
28 /** The override manager for our objects. */
29 ObjectOverrideManager _object_mngr(NEW_OBJECT_OFFSET, NUM_OBJECTS, INVALID_OBJECT_TYPE);
31 extern const ObjectSpec _original_objects[NEW_OBJECT_OFFSET];
32 /** All the object specifications. */
33 std::vector<ObjectSpec> _object_specs;
35 const std::vector<ObjectSpec> &ObjectSpec::Specs()
37 return _object_specs;
40 size_t ObjectSpec::Count()
42 return _object_specs.size();
45 /**
46 * Get the specification associated with a specific ObjectType.
47 * @param index The object type to fetch.
48 * @return The specification.
50 /* static */ const ObjectSpec *ObjectSpec::Get(ObjectType index)
52 /* Empty object if index is out of range -- this might happen if NewGRFs are changed. */
53 static ObjectSpec empty = {};
55 assert(index < NUM_OBJECTS);
56 if (index >= _object_specs.size()) return &empty;
57 return &_object_specs[index];
60 /**
61 * Get the specification associated with a tile.
62 * @param tile The tile to fetch the data for.
63 * @return The specification.
65 /* static */ const ObjectSpec *ObjectSpec::GetByTile(TileIndex tile)
67 return ObjectSpec::Get(GetObjectType(tile));
70 /**
71 * Check whether the object might be available at some point in this game with the current game mode.
72 * @return true if it might be available.
74 bool ObjectSpec::IsEverAvailable() const
76 return this->IsEnabled() && HasBit(this->climate, _settings_game.game_creation.landscape) &&
77 (this->flags & ((_game_mode != GM_EDITOR && !_generating_world) ? OBJECT_FLAG_ONLY_IN_SCENEDIT : OBJECT_FLAG_ONLY_IN_GAME)) == 0;
80 /**
81 * Check whether the object was available at some point in the past or present in this game with the current game mode.
82 * @return true if it was ever or is available.
84 bool ObjectSpec::WasEverAvailable() const
86 return this->IsEverAvailable() && TimerGameCalendar::date > this->introduction_date;
89 /**
90 * Check whether the object is available at this time.
91 * @return true if it is available.
93 bool ObjectSpec::IsAvailable() const
95 return this->WasEverAvailable() &&
96 (TimerGameCalendar::date < this->end_of_life_date || this->end_of_life_date < this->introduction_date + 365);
99 /**
100 * Gets the index of this spec.
101 * @return The index.
103 uint ObjectSpec::Index() const
105 return this - _object_specs.data();
109 * Tie all ObjectSpecs to their class.
111 /* static */ void ObjectSpec::BindToClasses()
113 for (auto &spec : _object_specs) {
114 if (spec.IsEnabled() && spec.class_index != INVALID_OBJECT_CLASS) {
115 ObjectClass::Assign(&spec);
120 /** This function initialize the spec arrays of objects. */
121 void ResetObjects()
123 /* Clean the pool. */
124 _object_specs.clear();
126 /* And add our originals. */
127 _object_specs.reserve(lengthof(_original_objects));
129 for (uint16_t i = 0; i < lengthof(_original_objects); i++) {
130 ObjectSpec &spec = _object_specs.emplace_back(_original_objects[i]);
131 spec.grf_prop.local_id = i;
134 /* Set class for originals. */
135 _object_specs[OBJECT_LIGHTHOUSE].class_index = ObjectClass::Allocate('LTHS');
136 _object_specs[OBJECT_TRANSMITTER].class_index = ObjectClass::Allocate('TRNS');
139 template <>
140 /* static */ void ObjectClass::InsertDefaults()
142 ObjectClass::Get(ObjectClass::Allocate('LTHS'))->name = STR_OBJECT_CLASS_LTHS;
143 ObjectClass::Get(ObjectClass::Allocate('TRNS'))->name = STR_OBJECT_CLASS_TRNS;
146 template <>
147 bool ObjectClass::IsUIAvailable(uint index) const
149 return this->GetSpec(index)->IsEverAvailable();
152 /* Instantiate ObjectClass. */
153 template class NewGRFClass<ObjectSpec, ObjectClassID, OBJECT_CLASS_MAX>;
155 /* virtual */ uint32_t ObjectScopeResolver::GetRandomBits() const
157 return IsValidTile(this->tile) && IsTileType(this->tile, MP_OBJECT) ? GetObjectRandomBits(this->tile) : 0;
161 * Make an analysis of a tile and get the object type.
162 * @param tile TileIndex of the tile to query
163 * @param cur_grfid GRFID of the current callback chain
164 * @return value encoded as per NFO specs
166 static uint32_t GetObjectIDAtOffset(TileIndex tile, uint32_t cur_grfid)
168 if (!IsTileType(tile, MP_OBJECT)) {
169 return 0xFFFF;
172 const Object *o = Object::GetByTile(tile);
173 const ObjectSpec *spec = ObjectSpec::Get(o->type);
175 /* Default objects have no associated NewGRF file */
176 if (spec->grf_prop.grffile == nullptr) {
177 return 0xFFFE; // Defined in another grf file
180 if (spec->grf_prop.grffile->grfid == cur_grfid) { // same object, same grf ?
181 return spec->grf_prop.local_id | o->view << 16;
184 return 0xFFFE; // Defined in another grf file
188 * Based on newhouses equivalent, but adapted for newobjects
189 * @param parameter from callback. It's in fact a pair of coordinates
190 * @param tile TileIndex from which the callback was initiated
191 * @param index of the object been queried for
192 * @param grf_version8 True, if we are dealing with a new NewGRF which uses GRF version >= 8.
193 * @return a construction of bits obeying the newgrf format
195 static uint32_t GetNearbyObjectTileInformation(uint8_t parameter, TileIndex tile, ObjectID index, bool grf_version8)
197 if (parameter != 0) tile = GetNearbyTile(parameter, tile); // only perform if it is required
198 bool is_same_object = (IsTileType(tile, MP_OBJECT) && GetObjectIndex(tile) == index);
200 return GetNearbyTileInformation(tile, grf_version8) | (is_same_object ? 1 : 0) << 8;
204 * Get the closest object of a given type.
205 * @param tile The tile to start searching from.
206 * @param type The type of the object to search for.
207 * @param current The current object (to ignore).
208 * @return The distance to the closest object.
210 static uint32_t GetClosestObject(TileIndex tile, ObjectType type, const Object *current)
212 uint32_t best_dist = UINT32_MAX;
213 for (const Object *o : Object::Iterate()) {
214 if (o->type != type || o == current) continue;
216 best_dist = std::min(best_dist, DistanceManhattan(tile, o->location.tile));
219 return best_dist;
223 * Implementation of var 65
224 * @param local_id Parameter given to the callback, which is the set id, or the local id, in our terminology.
225 * @param grfid The object's GRFID.
226 * @param tile The tile to look from.
227 * @param current Object for which the inquiry is made
228 * @return The formatted answer to the callback : rr(reserved) cc(count) dddd(manhattan distance of closest sister)
230 static uint32_t GetCountAndDistanceOfClosestInstance(uint8_t local_id, uint32_t grfid, TileIndex tile, const Object *current)
232 uint32_t grf_id = GetRegister(0x100); // Get the GRFID of the definition to look for in register 100h
233 uint32_t idx;
235 /* Determine what will be the object type to look for */
236 switch (grf_id) {
237 case 0: // this is a default object type
238 idx = local_id;
239 break;
241 case 0xFFFFFFFF: // current grf
242 grf_id = grfid;
243 [[fallthrough]];
245 default: // use the grfid specified in register 100h
246 idx = _object_mngr.GetID(local_id, grf_id);
247 break;
250 /* If the object type is invalid, there is none and the closest is far away. */
251 if (idx >= NUM_OBJECTS) return 0 | 0xFFFF;
253 return Object::GetTypeCount(idx) << 16 | ClampTo<uint16_t>(GetClosestObject(tile, idx, current));
256 /** Used by the resolver to get values for feature 0F deterministic spritegroups. */
257 /* virtual */ uint32_t ObjectScopeResolver::GetVariable(uint8_t variable, [[maybe_unused]] uint32_t parameter, bool &available) const
259 /* We get the town from the object, or we calculate the closest
260 * town if we need to when there's no object. */
261 const Town *t = nullptr;
263 if (this->obj == nullptr) {
264 switch (variable) {
265 /* Allow these when there's no object. */
266 case 0x41:
267 case 0x60:
268 case 0x61:
269 case 0x62:
270 case 0x64:
271 break;
273 /* Allow these, but find the closest town. */
274 case 0x45:
275 case 0x46:
276 if (!IsValidTile(this->tile)) goto unhandled;
277 t = ClosestTownFromTile(this->tile, UINT_MAX);
278 break;
280 /* Construction date */
281 case 0x42: return TimerGameCalendar::date.base();
283 /* Object founder information */
284 case 0x44: return _current_company;
286 /* Object view */
287 case 0x48: return this->view;
290 * Disallow the rest:
291 * 0x40: Relative position is passed as parameter during construction.
292 * 0x43: Animation counter is only for actual tiles.
293 * 0x47: Object colour is only valid when its built.
294 * 0x63: Animation counter of nearby tile, see above.
296 default:
297 goto unhandled;
300 /* If there's an invalid tile, then we don't have enough information at all. */
301 if (!IsValidTile(this->tile)) goto unhandled;
302 } else {
303 t = this->obj->town;
306 switch (variable) {
307 /* Relative position. */
308 case 0x40: {
309 TileIndex offset = this->tile - this->obj->location.tile;
310 uint offset_x = TileX(offset);
311 uint offset_y = TileY(offset);
312 return offset_y << 20 | offset_x << 16 | offset_y << 8 | offset_x;
315 /* Tile information. */
316 case 0x41: return GetTileSlope(this->tile) << 8 | GetTerrainType(this->tile);
318 /* Construction date */
319 case 0x42: return this->obj->build_date.base();
321 /* Animation counter */
322 case 0x43: return GetAnimationFrame(this->tile);
324 /* Object founder information */
325 case 0x44: return GetTileOwner(this->tile);
327 /* Get town zone and Manhattan distance of closest town */
328 case 0x45: return GetTownRadiusGroup(t, this->tile) << 16 | ClampTo<uint16_t>(DistanceManhattan(this->tile, t->xy));
330 /* Get square of Euclidian distance of closest town */
331 case 0x46: return DistanceSquare(this->tile, t->xy);
333 /* Object colour */
334 case 0x47: return this->obj->colour;
336 /* Object view */
337 case 0x48: return this->obj->view;
339 /* Get object ID at offset param */
340 case 0x60: return GetObjectIDAtOffset(GetNearbyTile(parameter, this->tile), this->ro.grffile->grfid);
342 /* Get random tile bits at offset param */
343 case 0x61: {
344 TileIndex tile = GetNearbyTile(parameter, this->tile);
345 return (IsTileType(tile, MP_OBJECT) && Object::GetByTile(tile) == this->obj) ? GetObjectRandomBits(tile) : 0;
348 /* Land info of nearby tiles */
349 case 0x62: return GetNearbyObjectTileInformation(parameter, this->tile, this->obj == nullptr ? INVALID_OBJECT : this->obj->index, this->ro.grffile->grf_version >= 8);
351 /* Animation counter of nearby tile */
352 case 0x63: {
353 TileIndex tile = GetNearbyTile(parameter, this->tile);
354 return (IsTileType(tile, MP_OBJECT) && Object::GetByTile(tile) == this->obj) ? GetAnimationFrame(tile) : 0;
357 /* Count of object, distance of closest instance */
358 case 0x64: return GetCountAndDistanceOfClosestInstance(parameter, this->ro.grffile->grfid, this->tile, this->obj);
361 unhandled:
362 Debug(grf, 1, "Unhandled object variable 0x{:X}", variable);
364 available = false;
365 return UINT_MAX;
369 * Constructor of the object resolver.
370 * @param obj Object being resolved.
371 * @param tile %Tile of the object.
372 * @param view View of the object.
373 * @param callback Callback ID.
374 * @param param1 First parameter (var 10) of the callback.
375 * @param param2 Second parameter (var 18) of the callback.
377 ObjectResolverObject::ObjectResolverObject(const ObjectSpec *spec, Object *obj, TileIndex tile, uint8_t view,
378 CallbackID callback, uint32_t param1, uint32_t param2)
379 : ResolverObject(spec->grf_prop.grffile, callback, param1, param2), object_scope(*this, obj, spec, tile, view)
381 this->root_spritegroup = (obj == nullptr && spec->grf_prop.spritegroup[OBJECT_SPRITE_GROUP_PURCHASE] != nullptr) ?
382 spec->grf_prop.spritegroup[OBJECT_SPRITE_GROUP_PURCHASE] : spec->grf_prop.spritegroup[OBJECT_SPRITE_GROUP_DEFAULT];
386 * Get the town resolver scope that belongs to this object resolver.
387 * On the first call, the town scope is created (if possible).
388 * @return Town scope, if available.
390 TownScopeResolver *ObjectResolverObject::GetTown()
392 if (!this->town_scope.has_value()) {
393 Town *t;
394 if (this->object_scope.obj != nullptr) {
395 t = this->object_scope.obj->town;
396 } else {
397 t = ClosestTownFromTile(this->object_scope.tile, UINT_MAX);
399 if (t == nullptr) return nullptr;
400 this->town_scope.emplace(*this, t, this->object_scope.obj == nullptr);
402 return &*this->town_scope;
405 GrfSpecFeature ObjectResolverObject::GetFeature() const
407 return GSF_OBJECTS;
410 uint32_t ObjectResolverObject::GetDebugID() const
412 return this->object_scope.spec->grf_prop.local_id;
416 * Perform a callback for an object.
417 * @param callback The callback to perform.
418 * @param param1 The first parameter to pass to the NewGRF.
419 * @param param2 The second parameter to pass to the NewGRF.
420 * @param spec The specification of the object / the entry point.
421 * @param o The object to call the callback for.
422 * @param tile The tile the callback is called for.
423 * @param view The view of the object (only used when o == nullptr).
424 * @return The result of the callback.
426 uint16_t GetObjectCallback(CallbackID callback, uint32_t param1, uint32_t param2, const ObjectSpec *spec, Object *o, TileIndex tile, uint8_t view)
428 ObjectResolverObject object(spec, o, tile, view, callback, param1, param2);
429 return object.ResolveCallback();
433 * Draw an group of sprites on the map.
434 * @param ti Information about the tile to draw on.
435 * @param group The group of sprites to draw.
436 * @param spec Object spec to draw.
438 static void DrawTileLayout(const TileInfo *ti, const TileLayoutSpriteGroup *group, const ObjectSpec *spec)
440 const DrawTileSprites *dts = group->ProcessRegisters(nullptr);
441 PaletteID palette = ((spec->flags & OBJECT_FLAG_2CC_COLOUR) ? SPR_2CCMAP_BASE : PALETTE_RECOLOUR_START) + Object::GetByTile(ti->tile)->colour;
443 SpriteID image = dts->ground.sprite;
444 PaletteID pal = dts->ground.pal;
446 if (GB(image, 0, SPRITE_WIDTH) != 0) {
447 /* If the ground sprite is the default flat water sprite, draw also canal/river borders
448 * Do not do this if the tile's WaterClass is 'land'. */
449 if ((image == SPR_FLAT_WATER_TILE || spec->flags & OBJECT_FLAG_DRAW_WATER) && IsTileOnWater(ti->tile)) {
450 DrawWaterClassGround(ti);
451 } else {
452 DrawGroundSprite(image, GroundSpritePaletteTransform(image, pal, palette));
456 DrawNewGRFTileSeq(ti, dts, TO_STRUCTURES, 0, palette);
460 * Draw an object on the map.
461 * @param ti Information about the tile to draw on.
462 * @param spec Object spec to draw.
464 void DrawNewObjectTile(TileInfo *ti, const ObjectSpec *spec)
466 Object *o = Object::GetByTile(ti->tile);
467 ObjectResolverObject object(spec, o, ti->tile);
469 const SpriteGroup *group = object.Resolve();
470 if (group == nullptr || group->type != SGT_TILELAYOUT) return;
472 DrawTileLayout(ti, (const TileLayoutSpriteGroup *)group, spec);
476 * Draw representation of an object (tile) for GUI purposes.
477 * @param x Position x of image.
478 * @param y Position y of image.
479 * @param spec Object spec to draw.
480 * @param view The object's view.
482 void DrawNewObjectTileInGUI(int x, int y, const ObjectSpec *spec, uint8_t view)
484 ObjectResolverObject object(spec, nullptr, INVALID_TILE, view);
485 const SpriteGroup *group = object.Resolve();
486 if (group == nullptr || group->type != SGT_TILELAYOUT) return;
488 const DrawTileSprites *dts = ((const TileLayoutSpriteGroup *)group)->ProcessRegisters(nullptr);
490 PaletteID palette;
491 if (Company::IsValidID(_local_company)) {
492 /* Get the colours of our company! */
493 if (spec->flags & OBJECT_FLAG_2CC_COLOUR) {
494 const Livery *l = Company::Get(_local_company)->livery;
495 palette = SPR_2CCMAP_BASE + l->colour1 + l->colour2 * 16;
496 } else {
497 palette = COMPANY_SPRITE_COLOUR(_local_company);
499 } else {
500 /* There's no company, so just take the base palette. */
501 palette = (spec->flags & OBJECT_FLAG_2CC_COLOUR) ? SPR_2CCMAP_BASE : PALETTE_RECOLOUR_START;
504 SpriteID image = dts->ground.sprite;
505 PaletteID pal = dts->ground.pal;
507 if (GB(image, 0, SPRITE_WIDTH) != 0) {
508 DrawSprite(image, GroundSpritePaletteTransform(image, pal, palette), x, y);
511 DrawNewGRFTileSeqInGUI(x, y, dts, 0, palette);
515 * Perform a callback for an object.
516 * @param callback The callback to perform.
517 * @param param1 The first parameter to pass to the NewGRF.
518 * @param param2 The second parameter to pass to the NewGRF.
519 * @param spec The specification of the object / the entry point.
520 * @param o The object to call the callback for.
521 * @param tile The tile the callback is called for.
522 * @return The result of the callback.
524 uint16_t StubGetObjectCallback(CallbackID callback, uint32_t param1, uint32_t param2, const ObjectSpec *spec, Object *o, TileIndex tile, int)
526 return GetObjectCallback(callback, param1, param2, spec, o, tile);
529 /** Helper class for animation control. */
530 struct ObjectAnimationBase : public AnimationBase<ObjectAnimationBase, ObjectSpec, Object, int, StubGetObjectCallback, TileAnimationFrameAnimationHelper<Object> > {
531 static const CallbackID cb_animation_speed = CBID_OBJECT_ANIMATION_SPEED;
532 static const CallbackID cb_animation_next_frame = CBID_OBJECT_ANIMATION_NEXT_FRAME;
534 static const ObjectCallbackMask cbm_animation_speed = CBM_OBJ_ANIMATION_SPEED;
535 static const ObjectCallbackMask cbm_animation_next_frame = CBM_OBJ_ANIMATION_NEXT_FRAME;
539 * Handle the animation of the object tile.
540 * @param tile The tile to animate.
542 void AnimateNewObjectTile(TileIndex tile)
544 const ObjectSpec *spec = ObjectSpec::GetByTile(tile);
545 if (spec == nullptr || !(spec->flags & OBJECT_FLAG_ANIMATION)) return;
547 ObjectAnimationBase::AnimateTile(spec, Object::GetByTile(tile), tile, (spec->flags & OBJECT_FLAG_ANIM_RANDOM_BITS) != 0);
551 * Trigger the update of animation on a single tile.
552 * @param o The object that got triggered.
553 * @param tile The location of the triggered tile.
554 * @param trigger The trigger that is triggered.
555 * @param spec The spec associated with the object.
557 void TriggerObjectTileAnimation(Object *o, TileIndex tile, ObjectAnimationTrigger trigger, const ObjectSpec *spec)
559 if (!HasBit(spec->animation.triggers, trigger)) return;
561 ObjectAnimationBase::ChangeAnimationFrame(CBID_OBJECT_ANIMATION_START_STOP, spec, o, tile, Random(), trigger);
565 * Trigger the update of animation on a whole object.
566 * @param o The object that got triggered.
567 * @param trigger The trigger that is triggered.
568 * @param spec The spec associated with the object.
570 void TriggerObjectAnimation(Object *o, ObjectAnimationTrigger trigger, const ObjectSpec *spec)
572 if (!HasBit(spec->animation.triggers, trigger)) return;
574 for (TileIndex tile : o->location) {
575 TriggerObjectTileAnimation(o, tile, trigger, spec);