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/>.
8 /** @file newgrf_object.cpp Handling of object NewGRFs. */
11 #include "company_base.h"
12 #include "company_func.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"
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()
40 size_t ObjectSpec::Count()
42 return _object_specs
.size();
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
];
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
));
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;
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
;
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);
100 * Gets the index of this spec.
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
.cls_id
!= INVALID_OBJECT_CLASS
) {
115 ObjectClass::Assign(&spec
);
120 /** This function initialize the spec arrays of objects. */
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
].cls_id
= ObjectClass::Allocate('LTHS');
136 _object_specs
[OBJECT_TRANSMITTER
].cls_id
= ObjectClass::Allocate('TRNS');
139 template <typename Tspec
, typename Tid
, Tid Tmax
>
140 /* static */ void NewGRFClass
<Tspec
, Tid
, Tmax
>::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 <typename Tspec
, typename Tid
, Tid Tmax
>
147 bool NewGRFClass
<Tspec
, Tid
, Tmax
>::IsUIAvailable(uint index
) const
149 return this->GetSpec(index
)->IsEverAvailable();
152 INSTANTIATE_NEWGRF_CLASS_METHODS(ObjectClass
, ObjectSpec
, ObjectClassID
, OBJECT_CLASS_MAX
)
154 /* virtual */ uint32_t ObjectScopeResolver::GetRandomBits() const
156 return IsValidTile(this->tile
) && IsTileType(this->tile
, MP_OBJECT
) ? GetObjectRandomBits(this->tile
) : 0;
160 * Make an analysis of a tile and get the object type.
161 * @param tile TileIndex of the tile to query
162 * @param cur_grfid GRFID of the current callback chain
163 * @return value encoded as per NFO specs
165 static uint32_t GetObjectIDAtOffset(TileIndex tile
, uint32_t cur_grfid
)
167 if (!IsTileType(tile
, MP_OBJECT
)) {
171 const Object
*o
= Object::GetByTile(tile
);
172 const ObjectSpec
*spec
= ObjectSpec::Get(o
->type
);
174 /* Default objects have no associated NewGRF file */
175 if (spec
->grf_prop
.grffile
== nullptr) {
176 return 0xFFFE; // Defined in another grf file
179 if (spec
->grf_prop
.grffile
->grfid
== cur_grfid
) { // same object, same grf ?
180 return spec
->grf_prop
.local_id
| o
->view
<< 16;
183 return 0xFFFE; // Defined in another grf file
187 * Based on newhouses equivalent, but adapted for newobjects
188 * @param parameter from callback. It's in fact a pair of coordinates
189 * @param tile TileIndex from which the callback was initiated
190 * @param index of the object been queried for
191 * @param grf_version8 True, if we are dealing with a new NewGRF which uses GRF version >= 8.
192 * @return a construction of bits obeying the newgrf format
194 static uint32_t GetNearbyObjectTileInformation(byte parameter
, TileIndex tile
, ObjectID index
, bool grf_version8
)
196 if (parameter
!= 0) tile
= GetNearbyTile(parameter
, tile
); // only perform if it is required
197 bool is_same_object
= (IsTileType(tile
, MP_OBJECT
) && GetObjectIndex(tile
) == index
);
199 return GetNearbyTileInformation(tile
, grf_version8
) | (is_same_object
? 1 : 0) << 8;
203 * Get the closest object of a given type.
204 * @param tile The tile to start searching from.
205 * @param type The type of the object to search for.
206 * @param current The current object (to ignore).
207 * @return The distance to the closest object.
209 static uint32_t GetClosestObject(TileIndex tile
, ObjectType type
, const Object
*current
)
211 uint32_t best_dist
= UINT32_MAX
;
212 for (const Object
*o
: Object::Iterate()) {
213 if (o
->type
!= type
|| o
== current
) continue;
215 best_dist
= std::min(best_dist
, DistanceManhattan(tile
, o
->location
.tile
));
222 * Implementation of var 65
223 * @param local_id Parameter given to the callback, which is the set id, or the local id, in our terminology.
224 * @param grfid The object's GRFID.
225 * @param tile The tile to look from.
226 * @param current Object for which the inquiry is made
227 * @return The formatted answer to the callback : rr(reserved) cc(count) dddd(manhattan distance of closest sister)
229 static uint32_t GetCountAndDistanceOfClosestInstance(byte local_id
, uint32_t grfid
, TileIndex tile
, const Object
*current
)
231 uint32_t grf_id
= GetRegister(0x100); // Get the GRFID of the definition to look for in register 100h
234 /* Determine what will be the object type to look for */
236 case 0: // this is a default object type
240 case 0xFFFFFFFF: // current grf
244 default: // use the grfid specified in register 100h
245 idx
= _object_mngr
.GetID(local_id
, grf_id
);
249 /* If the object type is invalid, there is none and the closest is far away. */
250 if (idx
>= NUM_OBJECTS
) return 0 | 0xFFFF;
252 return Object::GetTypeCount(idx
) << 16 | ClampTo
<uint16_t>(GetClosestObject(tile
, idx
, current
));
255 /** Used by the resolver to get values for feature 0F deterministic spritegroups. */
256 /* virtual */ uint32_t ObjectScopeResolver::GetVariable(byte variable
, [[maybe_unused
]] uint32_t parameter
, bool *available
) const
258 /* We get the town from the object, or we calculate the closest
259 * town if we need to when there's no object. */
260 const Town
*t
= nullptr;
262 if (this->obj
== nullptr) {
264 /* Allow these when there's no object. */
272 /* Allow these, but find the closest town. */
275 if (!IsValidTile(this->tile
)) goto unhandled
;
276 t
= ClosestTownFromTile(this->tile
, UINT_MAX
);
279 /* Construction date */
280 case 0x42: return TimerGameCalendar::date
.base();
282 /* Object founder information */
283 case 0x44: return _current_company
;
286 case 0x48: return this->view
;
290 * 0x40: Relative position is passed as parameter during construction.
291 * 0x43: Animation counter is only for actual tiles.
292 * 0x47: Object colour is only valid when its built.
293 * 0x63: Animation counter of nearby tile, see above.
299 /* If there's an invalid tile, then we don't have enough information at all. */
300 if (!IsValidTile(this->tile
)) goto unhandled
;
306 /* Relative position. */
308 TileIndex offset
= this->tile
- this->obj
->location
.tile
;
309 uint offset_x
= TileX(offset
);
310 uint offset_y
= TileY(offset
);
311 return offset_y
<< 20 | offset_x
<< 16 | offset_y
<< 8 | offset_x
;
314 /* Tile information. */
315 case 0x41: return GetTileSlope(this->tile
) << 8 | GetTerrainType(this->tile
);
317 /* Construction date */
318 case 0x42: return this->obj
->build_date
.base();
320 /* Animation counter */
321 case 0x43: return GetAnimationFrame(this->tile
);
323 /* Object founder information */
324 case 0x44: return GetTileOwner(this->tile
);
326 /* Get town zone and Manhattan distance of closest town */
327 case 0x45: return GetTownRadiusGroup(t
, this->tile
) << 16 | ClampTo
<uint16_t>(DistanceManhattan(this->tile
, t
->xy
));
329 /* Get square of Euclidian distance of closest town */
330 case 0x46: return DistanceSquare(this->tile
, t
->xy
);
333 case 0x47: return this->obj
->colour
;
336 case 0x48: return this->obj
->view
;
338 /* Get object ID at offset param */
339 case 0x60: return GetObjectIDAtOffset(GetNearbyTile(parameter
, this->tile
), this->ro
.grffile
->grfid
);
341 /* Get random tile bits at offset param */
343 TileIndex tile
= GetNearbyTile(parameter
, this->tile
);
344 return (IsTileType(tile
, MP_OBJECT
) && Object::GetByTile(tile
) == this->obj
) ? GetObjectRandomBits(tile
) : 0;
347 /* Land info of nearby tiles */
348 case 0x62: return GetNearbyObjectTileInformation(parameter
, this->tile
, this->obj
== nullptr ? INVALID_OBJECT
: this->obj
->index
, this->ro
.grffile
->grf_version
>= 8);
350 /* Animation counter of nearby tile */
352 TileIndex tile
= GetNearbyTile(parameter
, this->tile
);
353 return (IsTileType(tile
, MP_OBJECT
) && Object::GetByTile(tile
) == this->obj
) ? GetAnimationFrame(tile
) : 0;
356 /* Count of object, distance of closest instance */
357 case 0x64: return GetCountAndDistanceOfClosestInstance(parameter
, this->ro
.grffile
->grfid
, this->tile
, this->obj
);
361 Debug(grf
, 1, "Unhandled object variable 0x{:X}", variable
);
368 * Constructor of the object resolver.
369 * @param obj Object being resolved.
370 * @param tile %Tile of the object.
371 * @param view View of the object.
372 * @param callback Callback ID.
373 * @param param1 First parameter (var 10) of the callback.
374 * @param param2 Second parameter (var 18) of the callback.
376 ObjectResolverObject::ObjectResolverObject(const ObjectSpec
*spec
, Object
*obj
, TileIndex tile
, uint8_t view
,
377 CallbackID callback
, uint32_t param1
, uint32_t param2
)
378 : ResolverObject(spec
->grf_prop
.grffile
, callback
, param1
, param2
), object_scope(*this, obj
, spec
, tile
, view
)
380 this->town_scope
= nullptr;
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
];
385 ObjectResolverObject::~ObjectResolverObject()
387 delete this->town_scope
;
391 * Get the town resolver scope that belongs to this object resolver.
392 * On the first call, the town scope is created (if possible).
393 * @return Town scope, if available.
395 TownScopeResolver
*ObjectResolverObject::GetTown()
397 if (this->town_scope
== nullptr) {
399 if (this->object_scope
.obj
!= nullptr) {
400 t
= this->object_scope
.obj
->town
;
402 t
= ClosestTownFromTile(this->object_scope
.tile
, UINT_MAX
);
404 if (t
== nullptr) return nullptr;
405 this->town_scope
= new TownScopeResolver(*this, t
, this->object_scope
.obj
== nullptr);
407 return this->town_scope
;
410 GrfSpecFeature
ObjectResolverObject::GetFeature() const
415 uint32_t ObjectResolverObject::GetDebugID() const
417 return this->object_scope
.spec
->grf_prop
.local_id
;
421 * Perform a callback for an object.
422 * @param callback The callback to perform.
423 * @param param1 The first parameter to pass to the NewGRF.
424 * @param param2 The second parameter to pass to the NewGRF.
425 * @param spec The specification of the object / the entry point.
426 * @param o The object to call the callback for.
427 * @param tile The tile the callback is called for.
428 * @param view The view of the object (only used when o == nullptr).
429 * @return The result of the callback.
431 uint16_t GetObjectCallback(CallbackID callback
, uint32_t param1
, uint32_t param2
, const ObjectSpec
*spec
, Object
*o
, TileIndex tile
, uint8_t view
)
433 ObjectResolverObject
object(spec
, o
, tile
, view
, callback
, param1
, param2
);
434 return object
.ResolveCallback();
438 * Draw an group of sprites on the map.
439 * @param ti Information about the tile to draw on.
440 * @param group The group of sprites to draw.
441 * @param spec Object spec to draw.
443 static void DrawTileLayout(const TileInfo
*ti
, const TileLayoutSpriteGroup
*group
, const ObjectSpec
*spec
)
445 const DrawTileSprites
*dts
= group
->ProcessRegisters(nullptr);
446 PaletteID palette
= ((spec
->flags
& OBJECT_FLAG_2CC_COLOUR
) ? SPR_2CCMAP_BASE
: PALETTE_RECOLOUR_START
) + Object::GetByTile(ti
->tile
)->colour
;
448 SpriteID image
= dts
->ground
.sprite
;
449 PaletteID pal
= dts
->ground
.pal
;
451 if (GB(image
, 0, SPRITE_WIDTH
) != 0) {
452 /* If the ground sprite is the default flat water sprite, draw also canal/river borders
453 * Do not do this if the tile's WaterClass is 'land'. */
454 if ((image
== SPR_FLAT_WATER_TILE
|| spec
->flags
& OBJECT_FLAG_DRAW_WATER
) && IsTileOnWater(ti
->tile
)) {
455 DrawWaterClassGround(ti
);
457 DrawGroundSprite(image
, GroundSpritePaletteTransform(image
, pal
, palette
));
461 DrawNewGRFTileSeq(ti
, dts
, TO_STRUCTURES
, 0, palette
);
465 * Draw an object on the map.
466 * @param ti Information about the tile to draw on.
467 * @param spec Object spec to draw.
469 void DrawNewObjectTile(TileInfo
*ti
, const ObjectSpec
*spec
)
471 Object
*o
= Object::GetByTile(ti
->tile
);
472 ObjectResolverObject
object(spec
, o
, ti
->tile
);
474 const SpriteGroup
*group
= object
.Resolve();
475 if (group
== nullptr || group
->type
!= SGT_TILELAYOUT
) return;
477 DrawTileLayout(ti
, (const TileLayoutSpriteGroup
*)group
, spec
);
481 * Draw representation of an object (tile) for GUI purposes.
482 * @param x Position x of image.
483 * @param y Position y of image.
484 * @param spec Object spec to draw.
485 * @param view The object's view.
487 void DrawNewObjectTileInGUI(int x
, int y
, const ObjectSpec
*spec
, uint8_t view
)
489 ObjectResolverObject
object(spec
, nullptr, INVALID_TILE
, view
);
490 const SpriteGroup
*group
= object
.Resolve();
491 if (group
== nullptr || group
->type
!= SGT_TILELAYOUT
) return;
493 const DrawTileSprites
*dts
= ((const TileLayoutSpriteGroup
*)group
)->ProcessRegisters(nullptr);
496 if (Company::IsValidID(_local_company
)) {
497 /* Get the colours of our company! */
498 if (spec
->flags
& OBJECT_FLAG_2CC_COLOUR
) {
499 const Livery
*l
= Company::Get(_local_company
)->livery
;
500 palette
= SPR_2CCMAP_BASE
+ l
->colour1
+ l
->colour2
* 16;
502 palette
= COMPANY_SPRITE_COLOUR(_local_company
);
505 /* There's no company, so just take the base palette. */
506 palette
= (spec
->flags
& OBJECT_FLAG_2CC_COLOUR
) ? SPR_2CCMAP_BASE
: PALETTE_RECOLOUR_START
;
509 SpriteID image
= dts
->ground
.sprite
;
510 PaletteID pal
= dts
->ground
.pal
;
512 if (GB(image
, 0, SPRITE_WIDTH
) != 0) {
513 DrawSprite(image
, GroundSpritePaletteTransform(image
, pal
, palette
), x
, y
);
516 DrawNewGRFTileSeqInGUI(x
, y
, dts
, 0, palette
);
520 * Perform a callback for an object.
521 * @param callback The callback to perform.
522 * @param param1 The first parameter to pass to the NewGRF.
523 * @param param2 The second parameter to pass to the NewGRF.
524 * @param spec The specification of the object / the entry point.
525 * @param o The object to call the callback for.
526 * @param tile The tile the callback is called for.
527 * @return The result of the callback.
529 uint16_t StubGetObjectCallback(CallbackID callback
, uint32_t param1
, uint32_t param2
, const ObjectSpec
*spec
, Object
*o
, TileIndex tile
, int)
531 return GetObjectCallback(callback
, param1
, param2
, spec
, o
, tile
);
534 /** Helper class for animation control. */
535 struct ObjectAnimationBase
: public AnimationBase
<ObjectAnimationBase
, ObjectSpec
, Object
, int, StubGetObjectCallback
, TileAnimationFrameAnimationHelper
<Object
> > {
536 static const CallbackID cb_animation_speed
= CBID_OBJECT_ANIMATION_SPEED
;
537 static const CallbackID cb_animation_next_frame
= CBID_OBJECT_ANIMATION_NEXT_FRAME
;
539 static const ObjectCallbackMask cbm_animation_speed
= CBM_OBJ_ANIMATION_SPEED
;
540 static const ObjectCallbackMask cbm_animation_next_frame
= CBM_OBJ_ANIMATION_NEXT_FRAME
;
544 * Handle the animation of the object tile.
545 * @param tile The tile to animate.
547 void AnimateNewObjectTile(TileIndex tile
)
549 const ObjectSpec
*spec
= ObjectSpec::GetByTile(tile
);
550 if (spec
== nullptr || !(spec
->flags
& OBJECT_FLAG_ANIMATION
)) return;
552 ObjectAnimationBase::AnimateTile(spec
, Object::GetByTile(tile
), tile
, (spec
->flags
& OBJECT_FLAG_ANIM_RANDOM_BITS
) != 0);
556 * Trigger the update of animation on a single tile.
557 * @param o The object that got triggered.
558 * @param tile The location of the triggered tile.
559 * @param trigger The trigger that is triggered.
560 * @param spec The spec associated with the object.
562 void TriggerObjectTileAnimation(Object
*o
, TileIndex tile
, ObjectAnimationTrigger trigger
, const ObjectSpec
*spec
)
564 if (!HasBit(spec
->animation
.triggers
, trigger
)) return;
566 ObjectAnimationBase::ChangeAnimationFrame(CBID_OBJECT_ANIMATION_START_STOP
, spec
, o
, tile
, Random(), trigger
);
570 * Trigger the update of animation on a whole object.
571 * @param o The object that got triggered.
572 * @param trigger The trigger that is triggered.
573 * @param spec The spec associated with the object.
575 void TriggerObjectAnimation(Object
*o
, ObjectAnimationTrigger trigger
, const ObjectSpec
*spec
)
577 if (!HasBit(spec
->animation
.triggers
, trigger
)) return;
579 for (TileIndex tile
: o
->location
) {
580 TriggerObjectTileAnimation(o
, tile
, trigger
, spec
);