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 object_cmd.cpp Handling of object tiles. */
11 #include "landscape.h"
12 #include "command_func.h"
13 #include "company_func.h"
14 #include "viewport_func.h"
15 #include "company_base.h"
17 #include "bridge_map.h"
19 #include "autoslope.h"
20 #include "clear_func.h"
22 #include "window_func.h"
23 #include "company_gui.h"
24 #include "cheat_type.h"
26 #include "cargopacket.h"
27 #include "core/random_func.hpp"
28 #include "core/pool_func.hpp"
29 #include "object_map.h"
30 #include "object_base.h"
31 #include "newgrf_config.h"
32 #include "newgrf_object.h"
33 #include "timer/timer_game_calendar.h"
34 #include "newgrf_debug.h"
35 #include "vehicle_func.h"
36 #include "station_func.h"
37 #include "object_cmd.h"
38 #include "landscape_cmd.h"
39 #include "pathfinder/water_regions.h"
41 #include "table/strings.h"
42 #include "table/object_land.h"
44 #include "safeguards.h"
46 ObjectPool
_object_pool("Object");
47 INSTANTIATE_POOL_METHODS(Object
)
48 uint16_t Object::counts
[NUM_OBJECTS
];
51 * Get the object associated with a tile.
52 * @param tile The tile to fetch the object for.
55 /* static */ Object
*Object::GetByTile(TileIndex tile
)
57 return Object::Get(GetObjectIndex(tile
));
61 * Gets the ObjectType of the given object tile
62 * @param t the tile to get the type from.
63 * @pre IsTileType(t, MP_OBJECT)
66 ObjectType
GetObjectType(Tile t
)
68 assert(IsTileType(t
, MP_OBJECT
));
69 return Object::GetByTile(t
)->type
;
72 /** Initialize/reset the objects. */
73 void InitializeObjects()
75 Object::ResetTypeCounts();
79 * Actually build the object.
80 * @param type The type of object to build.
81 * @param tile The tile to build the northern tile of the object on.
82 * @param owner The owner of the object.
83 * @param town Town the tile is related with.
84 * @param view The view for the object.
85 * @pre All preconditions for building the object at that location
86 * are met, e.g. slope and clearness of tiles are checked.
88 void BuildObject(ObjectType type
, TileIndex tile
, CompanyID owner
, Town
*town
, uint8_t view
)
90 const ObjectSpec
*spec
= ObjectSpec::Get(type
);
92 TileArea
ta(tile
, GB(spec
->size
, HasBit(view
, 0) ? 4 : 0, 4), GB(spec
->size
, HasBit(view
, 0) ? 0 : 4, 4));
93 Object
*o
= new Object();
96 o
->town
= town
== nullptr ? CalcClosestTownFromTile(tile
) : town
;
97 o
->build_date
= TimerGameCalendar::date
;
100 /* If nothing owns the object, the colour will be random. Otherwise
101 * get the colour from the company's livery settings. */
102 if (owner
== OWNER_NONE
) {
103 o
->colour
= Random();
105 const Livery
*l
= Company::Get(owner
)->livery
;
106 o
->colour
= l
->colour1
+ l
->colour2
* 16;
109 /* If the object wants only one colour, then give it that colour. */
110 if ((spec
->flags
& OBJECT_FLAG_2CC_COLOUR
) == 0) o
->colour
&= 0xF;
112 if (HasBit(spec
->callback_mask
, CBM_OBJ_COLOUR
)) {
113 uint16_t res
= GetObjectCallback(CBID_OBJECT_COLOUR
, o
->colour
, 0, spec
, o
, tile
);
114 if (res
!= CALLBACK_FAILED
) {
115 if (res
>= 0x100) ErrorUnknownCallbackResult(spec
->grf_prop
.grffile
->grfid
, CBID_OBJECT_COLOUR
, res
);
116 o
->colour
= GB(res
, 0, 8);
120 assert(o
->town
!= nullptr);
122 for (TileIndex t
: ta
) {
123 WaterClass wc
= (IsWaterTile(t
) ? GetWaterClass(t
) : WATER_CLASS_INVALID
);
124 /* Update company infrastructure counts for objects build on canals owned by nobody. */
125 if (wc
== WATER_CLASS_CANAL
&& owner
!= OWNER_NONE
&& (IsTileOwner(t
, OWNER_NONE
) || IsTileOwner(t
, OWNER_WATER
))) {
126 Company::Get(owner
)->infrastructure
.water
++;
127 DirtyCompanyInfrastructureWindows(owner
);
129 bool remove
= IsDockingTile(t
);
130 MakeObject(t
, owner
, o
->index
, wc
, Random());
131 if (remove
) RemoveDockingTile(t
);
132 MarkTileDirtyByTile(t
);
135 Object::IncTypeCount(type
);
136 if (spec
->flags
& OBJECT_FLAG_ANIMATION
) TriggerObjectAnimation(o
, OAT_BUILT
, spec
);
140 * Increase the animation stage of a whole structure.
141 * @param tile The tile of the structure.
143 static void IncreaseAnimationStage(TileIndex tile
)
145 TileArea ta
= Object::GetByTile(tile
)->location
;
146 for (TileIndex t
: ta
) {
147 SetAnimationFrame(t
, GetAnimationFrame(t
) + 1);
148 MarkTileDirtyByTile(t
);
152 /** We encode the company HQ size in the animation stage. */
153 #define GetCompanyHQSize GetAnimationFrame
154 /** We encode the company HQ size in the animation stage. */
155 #define IncreaseCompanyHQSize IncreaseAnimationStage
158 * Update the CompanyHQ to the state associated with the given score
159 * @param tile The (northern) tile of the company HQ, or INVALID_TILE.
160 * @param score The current (performance) score of the company.
162 void UpdateCompanyHQ(TileIndex tile
, uint score
)
164 if (tile
== INVALID_TILE
) return;
167 if (score
>= 170) val
++;
168 if (score
>= 350) val
++;
169 if (score
>= 520) val
++;
170 if (score
>= 720) val
++;
172 while (GetCompanyHQSize(tile
) < val
) {
173 IncreaseCompanyHQSize(tile
);
178 * Updates the colour of the object whenever a company changes.
179 * @param c The company the company colour changed of.
181 void UpdateObjectColours(const Company
*c
)
183 for (Object
*obj
: Object::Iterate()) {
184 Owner owner
= GetTileOwner(obj
->location
.tile
);
185 /* Not the current owner, so colour doesn't change. */
186 if (owner
!= c
->index
) continue;
188 const ObjectSpec
*spec
= ObjectSpec::GetByTile(obj
->location
.tile
);
189 /* Using the object colour callback, so not using company colour. */
190 if (HasBit(spec
->callback_mask
, CBM_OBJ_COLOUR
)) continue;
192 const Livery
*l
= c
->livery
;
193 obj
->colour
= ((spec
->flags
& OBJECT_FLAG_2CC_COLOUR
) ? (l
->colour2
* 16) : 0) + l
->colour1
;
197 extern CommandCost
CheckBuildableTile(TileIndex tile
, uint invalid_dirs
, int &allowed_z
, bool allow_steep
, bool check_bridge
);
198 static CommandCost
ClearTile_Object(TileIndex tile
, DoCommandFlag flags
);
201 * Build an object object
202 * @param flags type of operation
203 * @param tile tile where the object will be located
204 * @param type the object type to build
205 * @param view the view for the object
206 * @return the cost of this operation or an error
208 CommandCost
CmdBuildObject(DoCommandFlag flags
, TileIndex tile
, ObjectType type
, uint8_t view
)
210 CommandCost
cost(EXPENSES_CONSTRUCTION
);
212 if (type
>= ObjectSpec::Count()) return CMD_ERROR
;
213 const ObjectSpec
*spec
= ObjectSpec::Get(type
);
214 if (_game_mode
== GM_NORMAL
&& !spec
->IsAvailable() && !_generating_world
) return CMD_ERROR
;
215 if ((_game_mode
== GM_EDITOR
|| _generating_world
) && !spec
->WasEverAvailable()) return CMD_ERROR
;
217 if ((spec
->flags
& OBJECT_FLAG_ONLY_IN_SCENEDIT
) != 0 && ((!_generating_world
&& _game_mode
!= GM_EDITOR
) || _current_company
!= OWNER_NONE
)) return CMD_ERROR
;
218 if ((spec
->flags
& OBJECT_FLAG_ONLY_IN_GAME
) != 0 && (_generating_world
|| _game_mode
!= GM_NORMAL
|| _current_company
> MAX_COMPANIES
)) return CMD_ERROR
;
219 if (view
>= spec
->views
) return CMD_ERROR
;
221 if (!Object::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_OBJECTS
);
222 if (Town::GetNumItems() == 0) return_cmd_error(STR_ERROR_MUST_FOUND_TOWN_FIRST
);
224 int size_x
= GB(spec
->size
, HasBit(view
, 0) ? 4 : 0, 4);
225 int size_y
= GB(spec
->size
, HasBit(view
, 0) ? 0 : 4, 4);
226 TileArea
ta(tile
, size_x
, size_y
);
227 for (TileIndex t
: ta
) {
228 if (!IsValidTile(t
)) return_cmd_error(STR_ERROR_TOO_CLOSE_TO_EDGE_OF_MAP_SUB
); // Might be off the map
231 if (type
== OBJECT_OWNED_LAND
) {
232 /* Owned land is special as it can be placed on any slope. */
233 cost
.AddCost(Command
<CMD_LANDSCAPE_CLEAR
>::Do(flags
, tile
));
235 /* Check the surface to build on. At this time we can't actually execute the
236 * the CLEAR_TILE commands since the newgrf callback later on can check
237 * some information about the tiles. */
238 bool allow_water
= (spec
->flags
& (OBJECT_FLAG_BUILT_ON_WATER
| OBJECT_FLAG_NOT_ON_LAND
)) != 0;
239 bool allow_ground
= (spec
->flags
& OBJECT_FLAG_NOT_ON_LAND
) == 0;
240 for (TileIndex t
: ta
) {
241 if (HasTileWaterGround(t
)) {
242 if (!allow_water
) return_cmd_error(STR_ERROR_CAN_T_BUILD_ON_WATER
);
243 if (!IsWaterTile(t
)) {
244 /* Normal water tiles don't have to be cleared. For all other tile types clear
245 * the tile but leave the water. */
246 cost
.AddCost(Command
<CMD_LANDSCAPE_CLEAR
>::Do(flags
& ~DC_NO_WATER
& ~DC_EXEC
, t
));
248 /* Can't build on water owned by another company. */
249 Owner o
= GetTileOwner(t
);
250 if (o
!= OWNER_NONE
&& o
!= OWNER_WATER
) cost
.AddCost(CheckOwnership(o
, t
));
252 /* However, the tile has to be clear of vehicles. */
253 cost
.AddCost(EnsureNoVehicleOnGround(t
));
256 if (!allow_ground
) return_cmd_error(STR_ERROR_MUST_BE_BUILT_ON_WATER
);
257 /* For non-water tiles, we'll have to clear it before building. */
259 /* When relocating HQ, allow it to be relocated (partial) on itself. */
260 if (!(type
== OBJECT_HQ
&&
261 IsTileType(t
, MP_OBJECT
) &&
262 IsTileOwner(t
, _current_company
) &&
263 IsObjectType(t
, OBJECT_HQ
))) {
264 cost
.AddCost(Command
<CMD_LANDSCAPE_CLEAR
>::Do(flags
& ~DC_EXEC
, t
));
269 /* So, now the surface is checked... check the slope of said surface. */
270 auto [slope
, allowed_z
] = GetTileSlopeZ(tile
);
271 if (slope
!= SLOPE_FLAT
) allowed_z
++;
273 for (TileIndex t
: ta
) {
274 uint16_t callback
= CALLBACK_FAILED
;
275 if (HasBit(spec
->callback_mask
, CBM_OBJ_SLOPE_CHECK
)) {
276 TileIndex diff
= t
- tile
;
277 callback
= GetObjectCallback(CBID_OBJECT_LAND_SLOPE_CHECK
, GetTileSlope(t
), TileY(diff
) << 4 | TileX(diff
), spec
, nullptr, t
, view
);
280 if (callback
== CALLBACK_FAILED
) {
281 cost
.AddCost(CheckBuildableTile(t
, 0, allowed_z
, false, false));
283 /* The meaning of bit 10 is inverted for a grf version < 8. */
284 if (spec
->grf_prop
.grffile
->grf_version
< 8) ToggleBit(callback
, 10);
285 CommandCost ret
= GetErrorMessageFromLocationCallbackResult(callback
, spec
->grf_prop
.grffile
, STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION
);
286 if (ret
.Failed()) return ret
;
290 if (flags
& DC_EXEC
) {
291 /* This is basically a copy of the loop above with the exception that we now
292 * execute the commands and don't check for errors, since that's already done. */
293 for (TileIndex t
: ta
) {
294 if (HasTileWaterGround(t
)) {
295 if (!IsWaterTile(t
)) {
296 Command
<CMD_LANDSCAPE_CLEAR
>::Do((flags
& ~DC_NO_WATER
) | DC_NO_MODIFY_TOWN_RATING
, t
);
299 Command
<CMD_LANDSCAPE_CLEAR
>::Do(flags
| DC_NO_MODIFY_TOWN_RATING
, t
);
304 if (cost
.Failed()) return cost
;
306 /* Finally do a check for bridges. */
307 for (TileIndex t
: ta
) {
308 if (IsBridgeAbove(t
) && (
309 !(spec
->flags
& OBJECT_FLAG_ALLOW_UNDER_BRIDGE
) ||
310 (GetTileMaxZ(t
) + spec
->height
>= GetBridgeHeight(GetSouthernBridgeEnd(t
))))) {
311 return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST
);
316 uint build_object_size
= 1;
318 case OBJECT_TRANSMITTER
:
319 case OBJECT_LIGHTHOUSE
:
320 if (!IsTileFlat(tile
)) return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED
);
323 case OBJECT_OWNED_LAND
:
324 if (IsTileType(tile
, MP_OBJECT
) &&
325 IsTileOwner(tile
, _current_company
) &&
326 IsObjectType(tile
, OBJECT_OWNED_LAND
)) {
327 return_cmd_error(STR_ERROR_YOU_ALREADY_OWN_IT
);
332 Company
*c
= Company::Get(_current_company
);
333 if (c
->location_of_HQ
!= INVALID_TILE
) {
334 /* Don't relocate HQ on the same location. */
335 if (c
->location_of_HQ
== tile
) return_cmd_error(STR_ERROR_ALREADY_BUILT
);
336 /* We need to persuade a bit harder to remove the old HQ. */
337 _current_company
= OWNER_WATER
;
338 cost
.AddCost(ClearTile_Object(c
->location_of_HQ
, flags
));
339 _current_company
= c
->index
;
342 if (flags
& DC_EXEC
) {
343 hq_score
= UpdateCompanyRatingAndValue(c
, false);
344 c
->location_of_HQ
= tile
;
345 SetWindowDirty(WC_COMPANY
, c
->index
);
351 /* This may never be constructed using this method. */
354 default: // i.e. NewGRF provided.
355 build_object_size
= size_x
* size_y
;
359 /* Don't allow building more objects if the company has reached its limit. */
360 Company
*c
= Company::GetIfValid(_current_company
);
361 if (c
!= nullptr && GB(c
->build_object_limit
, 16, 16) < build_object_size
) {
362 return_cmd_error(STR_ERROR_BUILD_OBJECT_LIMIT_REACHED
);
365 if (flags
& DC_EXEC
) {
366 BuildObject(type
, tile
, _current_company
== OWNER_DEITY
? OWNER_NONE
: _current_company
, nullptr, view
);
367 for (TileIndex t
: ta
) InvalidateWaterRegion(t
);
369 /* Make sure the HQ starts at the right size. */
370 if (type
== OBJECT_HQ
) UpdateCompanyHQ(tile
, hq_score
);
372 /* Subtract the tile from the build limit. */
373 if (c
!= nullptr) c
->build_object_limit
-= build_object_size
<< 16;
376 cost
.AddCost(spec
->GetBuildCost() * build_object_size
);
381 * Construct multiple objects in an area
382 * @param flags of operation to conduct
383 * @param tile end tile of area dragging
384 * @param start_tile start tile of area dragging
385 * @param type the object type to build
386 * @param view the view for the object
387 * @param diagonal Whether to use the Orthogonal (0) or Diagonal (1) iterator.
388 * @return the cost of this operation or an error
390 CommandCost
CmdBuildObjectArea(DoCommandFlag flags
, TileIndex tile
, TileIndex start_tile
, ObjectType type
, uint8_t view
, bool diagonal
)
392 if (start_tile
>= Map::Size()) return CMD_ERROR
;
394 if (type
>= ObjectSpec::Count()) return CMD_ERROR
;
395 const ObjectSpec
*spec
= ObjectSpec::Get(type
);
396 if (view
>= spec
->views
) return CMD_ERROR
;
398 if (spec
->size
!= OBJECT_SIZE_1X1
) return CMD_ERROR
;
400 Money money
= GetAvailableMoneyForCommand();
401 CommandCost
cost(EXPENSES_CONSTRUCTION
);
402 CommandCost last_error
= CMD_ERROR
;
403 bool had_success
= false;
405 const Company
*c
= Company::GetIfValid(_current_company
);
406 int limit
= (c
== nullptr ? INT32_MAX
: GB(c
->build_object_limit
, 16, 16));
408 std::unique_ptr
<TileIterator
> iter
= TileIterator::Create(tile
, start_tile
, diagonal
);
409 for (; *iter
!= INVALID_TILE
; ++(*iter
)) {
411 CommandCost ret
= Command
<CMD_BUILD_OBJECT
>::Do(flags
& ~DC_EXEC
, t
, type
, view
);
413 /* If we've reached the limit, stop building (or testing). */
414 if (c
!= nullptr && limit
-- <= 0) break;
422 if (flags
& DC_EXEC
) {
423 money
-= ret
.GetCost();
425 /* If we run out of money, stop building. */
426 if (ret
.GetCost() > 0 && money
< 0) break;
427 Command
<CMD_BUILD_OBJECT
>::Do(flags
, t
, type
, view
);
432 return had_success
? cost
: last_error
;
435 static Foundation
GetFoundation_Object(TileIndex tile
, Slope tileh
);
437 static void DrawTile_Object(TileInfo
*ti
)
439 ObjectType type
= GetObjectType(ti
->tile
);
440 const ObjectSpec
*spec
= ObjectSpec::Get(type
);
442 /* Fall back for when the object doesn't exist anymore. */
443 if (!spec
->IsEnabled()) type
= OBJECT_TRANSMITTER
;
445 if ((spec
->flags
& OBJECT_FLAG_HAS_NO_FOUNDATION
) == 0) DrawFoundation(ti
, GetFoundation_Object(ti
->tile
, ti
->tileh
));
447 if (type
< NEW_OBJECT_OFFSET
) {
448 const DrawTileSprites
*dts
= nullptr;
449 Owner to
= GetTileOwner(ti
->tile
);
450 PaletteID palette
= to
== OWNER_NONE
? PAL_NONE
: COMPANY_SPRITE_COLOUR(to
);
452 if (type
== OBJECT_HQ
) {
453 TileIndex diff
= ti
->tile
- Object::GetByTile(ti
->tile
)->location
.tile
;
454 dts
= &_object_hq
[GetCompanyHQSize(ti
->tile
) << 2 | TileY(diff
) << 1 | TileX(diff
)];
456 dts
= &_objects
[type
];
459 if (spec
->flags
& OBJECT_FLAG_HAS_NO_FOUNDATION
) {
460 /* If an object has no foundation, but tries to draw a (flat) ground
461 * type... we have to be nice and convert that for them. */
462 switch (dts
->ground
.sprite
) {
463 case SPR_FLAT_BARE_LAND
: DrawClearLandTile(ti
, 0); break;
464 case SPR_FLAT_1_THIRD_GRASS_TILE
: DrawClearLandTile(ti
, 1); break;
465 case SPR_FLAT_2_THIRD_GRASS_TILE
: DrawClearLandTile(ti
, 2); break;
466 case SPR_FLAT_GRASS_TILE
: DrawClearLandTile(ti
, 3); break;
467 default: DrawGroundSprite(dts
->ground
.sprite
, palette
); break;
470 DrawGroundSprite(dts
->ground
.sprite
, palette
);
473 if (!IsInvisibilitySet(TO_STRUCTURES
)) {
474 const DrawTileSeqStruct
*dtss
;
475 foreach_draw_tile_seq(dtss
, dts
->seq
) {
476 AddSortableSpriteToDraw(
477 dtss
->image
.sprite
, palette
,
478 ti
->x
+ dtss
->delta_x
, ti
->y
+ dtss
->delta_y
,
479 dtss
->size_x
, dtss
->size_y
,
480 dtss
->size_z
, ti
->z
+ dtss
->delta_z
,
481 IsTransparencySet(TO_STRUCTURES
)
486 DrawNewObjectTile(ti
, spec
);
489 DrawBridgeMiddle(ti
);
492 static int GetSlopePixelZ_Object(TileIndex tile
, uint x
, uint y
, bool)
494 if (IsObjectType(tile
, OBJECT_OWNED_LAND
)) {
495 auto [tileh
, z
] = GetTilePixelSlope(tile
);
497 return z
+ GetPartialPixelZ(x
& 0xF, y
& 0xF, tileh
);
499 return GetTileMaxPixelZ(tile
);
503 static Foundation
GetFoundation_Object(TileIndex tile
, Slope tileh
)
505 return IsObjectType(tile
, OBJECT_OWNED_LAND
) ? FOUNDATION_NONE
: FlatteningFoundation(tileh
);
509 * Perform the actual removal of the object from the map.
510 * @param o The object to really clear.
512 static void ReallyClearObjectTile(Object
*o
)
514 Object::DecTypeCount(o
->type
);
515 for (TileIndex tile_cur
: o
->location
) {
516 DeleteNewGRFInspectWindow(GSF_OBJECTS
, tile_cur
.base());
518 MakeWaterKeepingClass(tile_cur
, GetTileOwner(tile_cur
));
523 std::vector
<ClearedObjectArea
> _cleared_object_areas
;
526 * Find the entry in _cleared_object_areas which occupies a certain tile.
527 * @param tile Tile of interest
528 * @return Occupying entry, or nullptr if none
530 ClearedObjectArea
*FindClearedObject(TileIndex tile
)
532 TileArea ta
= TileArea(tile
, 1, 1);
534 for (ClearedObjectArea
&coa
: _cleared_object_areas
) {
535 if (coa
.area
.Intersects(ta
)) return &coa
;
541 static CommandCost
ClearTile_Object(TileIndex tile
, DoCommandFlag flags
)
543 /* Get to the northern most tile. */
544 Object
*o
= Object::GetByTile(tile
);
545 TileArea ta
= o
->location
;
547 ObjectType type
= o
->type
;
548 const ObjectSpec
*spec
= ObjectSpec::Get(type
);
550 CommandCost
cost(EXPENSES_CONSTRUCTION
, spec
->GetClearCost() * ta
.w
* ta
.h
/ 5);
551 if (spec
->flags
& OBJECT_FLAG_CLEAR_INCOME
) cost
.MultiplyCost(-1); // They get an income!
553 /* Towns can't remove any objects. */
554 if (_current_company
== OWNER_TOWN
) return CMD_ERROR
;
556 /* Water can remove everything! */
557 if (_current_company
!= OWNER_WATER
) {
558 if ((flags
& DC_NO_WATER
) && IsTileOnWater(tile
)) {
559 /* There is water under the object, treat it as water tile. */
560 return_cmd_error(STR_ERROR_CAN_T_BUILD_ON_WATER
);
561 } else if (!(spec
->flags
& OBJECT_FLAG_AUTOREMOVE
) && (flags
& DC_AUTO
)) {
562 /* No automatic removal by overbuilding stuff. */
563 return_cmd_error(type
== OBJECT_HQ
? STR_ERROR_COMPANY_HEADQUARTERS_IN
: STR_ERROR_OBJECT_IN_THE_WAY
);
564 } else if (_game_mode
== GM_EDITOR
) {
565 /* No further limitations for the editor. */
566 } else if (GetTileOwner(tile
) == OWNER_NONE
) {
567 /* Owned by nobody and unremovable, so we can only remove it with brute force! */
568 if (!_cheats
.magic_bulldozer
.value
&& (spec
->flags
& OBJECT_FLAG_CANNOT_REMOVE
) != 0) return CMD_ERROR
;
569 } else if (CheckTileOwnership(tile
).Failed()) {
570 /* We don't own it!. */
571 return_cmd_error(STR_ERROR_OWNED_BY
);
572 } else if ((spec
->flags
& OBJECT_FLAG_CANNOT_REMOVE
) != 0 && (spec
->flags
& OBJECT_FLAG_AUTOREMOVE
) == 0) {
573 /* In the game editor or with cheats we can remove, otherwise we can't. */
574 if (!_cheats
.magic_bulldozer
.value
) {
575 if (type
== OBJECT_HQ
) return_cmd_error(STR_ERROR_COMPANY_HEADQUARTERS_IN
);
579 /* Removing with the cheat costs more in TTDPatch / the specs. */
580 cost
.MultiplyCost(25);
582 } else if ((spec
->flags
& (OBJECT_FLAG_BUILT_ON_WATER
| OBJECT_FLAG_NOT_ON_LAND
)) != 0) {
583 /* Water can't remove objects that are buildable on water. */
589 Company
*c
= Company::Get(GetTileOwner(tile
));
590 if (flags
& DC_EXEC
) {
591 c
->location_of_HQ
= INVALID_TILE
; // reset HQ position
592 SetWindowDirty(WC_COMPANY
, c
->index
);
593 CargoPacket::InvalidateAllFrom(SourceType::Headquarters
, c
->index
);
596 /* cost of relocating company is 1% of company value */
597 cost
= CommandCost(EXPENSES_CONSTRUCTION
, CalculateCompanyValue(c
) / 100);
602 if (flags
& DC_EXEC
) {
603 Town
*town
= o
->town
;
604 ClrBit(town
->statues
, GetTileOwner(tile
));
605 SetWindowDirty(WC_TOWN_AUTHORITY
, town
->index
);
613 _cleared_object_areas
.push_back({tile
, ta
});
615 if (flags
& DC_EXEC
) ReallyClearObjectTile(o
);
620 static void AddAcceptedCargo_Object(TileIndex tile
, CargoArray
&acceptance
, CargoTypes
&always_accepted
)
622 if (!IsObjectType(tile
, OBJECT_HQ
)) return;
624 /* HQ accepts passenger and mail; but we have to divide the values
625 * between 4 tiles it occupies! */
627 /* HQ level (depends on company performance) in the range 1..5. */
628 uint level
= GetCompanyHQSize(tile
) + 1;
630 /* Top town building generates 10, so to make HQ interesting, the top
632 CargoID pass
= GetCargoIDByLabel(CT_PASSENGERS
);
633 if (IsValidCargoID(pass
)) {
634 acceptance
[pass
] += std::max(1U, level
);
635 SetBit(always_accepted
, pass
);
638 /* Top town building generates 4, HQ can make up to 8. The
639 * proportion passengers:mail is different because such a huge
640 * commercial building generates unusually high amount of mail
641 * correspondence per physical visitor. */
642 CargoID mail
= GetCargoIDByLabel(CT_MAIL
);
643 if (IsValidCargoID(mail
)) {
644 acceptance
[mail
] += std::max(1U, level
/ 2);
645 SetBit(always_accepted
, mail
);
649 static void AddProducedCargo_Object(TileIndex tile
, CargoArray
&produced
)
651 if (!IsObjectType(tile
, OBJECT_HQ
)) return;
653 CargoID pass
= GetCargoIDByLabel(CT_PASSENGERS
);
654 if (IsValidCargoID(pass
)) produced
[pass
]++;
655 CargoID mail
= GetCargoIDByLabel(CT_MAIL
);
656 if (IsValidCargoID(mail
)) produced
[mail
]++;
660 static void GetTileDesc_Object(TileIndex tile
, TileDesc
*td
)
662 const ObjectSpec
*spec
= ObjectSpec::GetByTile(tile
);
663 td
->str
= spec
->name
;
664 td
->owner
[0] = GetTileOwner(tile
);
665 td
->build_date
= Object::GetByTile(tile
)->build_date
;
667 if (spec
->grf_prop
.grffile
!= nullptr) {
668 td
->grf
= GetGRFConfig(spec
->grf_prop
.grffile
->grfid
)->GetName();
672 static void TileLoop_Object(TileIndex tile
)
674 const ObjectSpec
*spec
= ObjectSpec::GetByTile(tile
);
675 if (spec
->flags
& OBJECT_FLAG_ANIMATION
) {
676 Object
*o
= Object::GetByTile(tile
);
677 TriggerObjectTileAnimation(o
, tile
, OAT_TILELOOP
, spec
);
678 if (o
->location
.tile
== tile
) TriggerObjectAnimation(o
, OAT_256_TICKS
, spec
);
681 if (IsTileOnWater(tile
)) TileLoop_Water(tile
);
683 if (!IsObjectType(tile
, OBJECT_HQ
)) return;
685 /* HQ accepts passenger and mail; but we have to divide the values
686 * between 4 tiles it occupies! */
688 /* HQ level (depends on company performance) in the range 1..5. */
689 uint level
= GetCompanyHQSize(tile
) + 1;
692 StationFinder
stations(TileArea(tile
, 2, 2));
695 /* Top town buildings generate 250, so the top HQ type makes 256. */
696 CargoID pass
= GetCargoIDByLabel(CT_PASSENGERS
);
697 if (IsValidCargoID(pass
) && GB(r
, 0, 8) < (256 / 4 / (6 - level
))) {
698 uint amt
= GB(r
, 0, 8) / 8 / 4 + 1;
700 /* Production is halved during recessions. */
701 if (EconomyIsInRecession()) amt
= (amt
+ 1) >> 1;
703 /* Scale by cargo scale setting. */
704 amt
= ScaleByCargoScale(amt
, true);
706 MoveGoodsToStation(pass
, amt
, SourceType::Headquarters
, GetTileOwner(tile
), stations
.GetStations());
709 /* Top town building generates 90, HQ can make up to 196. The
710 * proportion passengers:mail is about the same as in the acceptance
712 CargoID mail
= GetCargoIDByLabel(CT_MAIL
);
713 if (IsValidCargoID(mail
) && GB(r
, 8, 8) < (196 / 4 / (6 - level
))) {
714 uint amt
= GB(r
, 8, 8) / 8 / 4 + 1;
716 /* Production is halved during recessions. */
717 if (EconomyIsInRecession()) amt
= (amt
+ 1) >> 1;
719 /* Scale by cargo scale setting. */
720 amt
= ScaleByCargoScale(amt
, true);
722 MoveGoodsToStation(mail
, amt
, SourceType::Headquarters
, GetTileOwner(tile
), stations
.GetStations());
727 static TrackStatus
GetTileTrackStatus_Object(TileIndex
, TransportType
, uint
, DiagDirection
)
732 static bool ClickTile_Object(TileIndex tile
)
734 if (!IsObjectType(tile
, OBJECT_HQ
)) return false;
736 ShowCompany(GetTileOwner(tile
));
740 static void AnimateTile_Object(TileIndex tile
)
742 AnimateNewObjectTile(tile
);
746 * Helper function for \c CircularTileSearch.
747 * @param tile The tile to check.
748 * @return True iff the tile has a radio tower.
750 static bool HasTransmitter(TileIndex tile
, void *)
752 return IsObjectTypeTile(tile
, OBJECT_TRANSMITTER
);
756 * Try to build a lighthouse.
757 * @return True iff building a lighthouse succeeded.
759 static bool TryBuildLightHouse()
761 uint maxx
= Map::MaxX();
762 uint maxy
= Map::MaxY();
765 /* Scatter the lighthouses more evenly around the perimeter */
766 int perimeter
= (GB(r
, 16, 16) % (2 * (maxx
+ maxy
))) - maxy
;
768 for (dir
= DIAGDIR_NE
; perimeter
> 0; dir
++) {
769 perimeter
-= (DiagDirToAxis(dir
) == AXIS_X
) ? maxx
: maxy
;
775 case DIAGDIR_NE
: tile
= TileXY(maxx
- 1, r
% maxy
); break;
776 case DIAGDIR_SE
: tile
= TileXY(r
% maxx
, 1); break;
777 case DIAGDIR_SW
: tile
= TileXY(1, r
% maxy
); break;
778 case DIAGDIR_NW
: tile
= TileXY(r
% maxx
, maxy
- 1); break;
781 /* Only build lighthouses at tiles where the border is sea. */
782 if (!IsTileType(tile
, MP_WATER
)) return false;
784 for (int j
= 0; j
< 19; j
++) {
786 if (IsTileType(tile
, MP_CLEAR
) && IsTileFlat(tile
, &h
) && h
<= 2 && !IsBridgeAbove(tile
)) {
787 BuildObject(OBJECT_LIGHTHOUSE
, tile
);
788 assert(tile
< Map::Size());
791 tile
+= TileOffsByDiagDir(dir
);
792 if (!IsValidTile(tile
)) return false;
798 * Try to build a transmitter.
799 * @return True iff a transmitter was built.
801 static bool TryBuildTransmitter()
803 TileIndex tile
= RandomTile();
805 if (IsTileType(tile
, MP_CLEAR
) && IsTileFlat(tile
, &h
) && h
>= 4 && !IsBridgeAbove(tile
)) {
807 if (CircularTileSearch(&t
, 9, HasTransmitter
, nullptr)) return false;
809 BuildObject(OBJECT_TRANSMITTER
, tile
);
815 void GenerateObjects()
817 /* Set a guestimate on how much we progress */
818 SetGeneratingWorldProgress(GWP_OBJECT
, (uint
)ObjectSpec::Count());
820 /* Determine number of water tiles at map border needed for freeform_edges */
821 uint num_water_tiles
= 0;
822 if (_settings_game
.construction
.freeform_edges
) {
823 for (uint x
= 0; x
< Map::MaxX(); x
++) {
824 if (IsTileType(TileXY(x
, 1), MP_WATER
)) num_water_tiles
++;
825 if (IsTileType(TileXY(x
, Map::MaxY() - 1), MP_WATER
)) num_water_tiles
++;
827 for (uint y
= 1; y
< Map::MaxY() - 1; y
++) {
828 if (IsTileType(TileXY(1, y
), MP_WATER
)) num_water_tiles
++;
829 if (IsTileType(TileXY(Map::MaxX() - 1, y
), MP_WATER
)) num_water_tiles
++;
833 /* Iterate over all possible object types */
834 for (const auto &spec
: ObjectSpec::Specs()) {
836 /* Continue, if the object was never available till now or shall not be placed */
837 if (!spec
.WasEverAvailable() || spec
.generate_amount
== 0) continue;
839 uint16_t amount
= spec
.generate_amount
;
841 /* Scale by map size */
842 if ((spec
.flags
& OBJECT_FLAG_SCALE_BY_WATER
) && _settings_game
.construction
.freeform_edges
) {
843 /* Scale the amount of lighthouses with the amount of land at the borders.
844 * The -6 is because the top borders are MP_VOID (-2) and all corners
845 * are counted twice (-4). */
846 amount
= Map::ScaleBySize1D(amount
* num_water_tiles
) / (2 * Map::MaxY() + 2 * Map::MaxX() - 6);
847 } else if (spec
.flags
& OBJECT_FLAG_SCALE_BY_WATER
) {
848 amount
= Map::ScaleBySize1D(amount
);
850 amount
= Map::ScaleBySize(amount
);
853 /* Now try to place the requested amount of this object */
854 for (uint j
= Map::ScaleBySize(1000); j
!= 0 && amount
!= 0 && Object::CanAllocateItem(); j
--) {
855 switch (spec
.Index()) {
856 case OBJECT_TRANSMITTER
:
857 if (TryBuildTransmitter()) amount
--;
860 case OBJECT_LIGHTHOUSE
:
861 if (TryBuildLightHouse()) amount
--;
865 uint8_t view
= RandomRange(spec
.views
);
866 if (CmdBuildObject(DC_EXEC
| DC_AUTO
| DC_NO_TEST_TOWN_RATING
| DC_NO_MODIFY_TOWN_RATING
, RandomTile(), spec
.Index(), view
).Succeeded()) amount
--;
870 IncreaseGeneratingWorldProgress(GWP_OBJECT
);
874 static void ChangeTileOwner_Object(TileIndex tile
, Owner old_owner
, Owner new_owner
)
876 if (!IsTileOwner(tile
, old_owner
)) return;
878 bool do_clear
= false;
880 ObjectType type
= GetObjectType(tile
);
881 if ((type
== OBJECT_OWNED_LAND
|| type
>= NEW_OBJECT_OFFSET
) && new_owner
!= INVALID_OWNER
) {
882 SetTileOwner(tile
, new_owner
);
883 if (GetWaterClass(tile
) == WATER_CLASS_CANAL
) {
884 Company::Get(old_owner
)->infrastructure
.water
--;
885 Company::Get(new_owner
)->infrastructure
.water
++;
887 } else if (type
== OBJECT_STATUE
) {
888 Town
*t
= Object::GetByTile(tile
)->town
;
889 ClrBit(t
->statues
, old_owner
);
890 if (new_owner
!= INVALID_OWNER
&& !HasBit(t
->statues
, new_owner
)) {
891 /* Transfer ownership to the new company */
892 SetBit(t
->statues
, new_owner
);
893 SetTileOwner(tile
, new_owner
);
898 SetWindowDirty(WC_TOWN_AUTHORITY
, t
->index
);
904 ReallyClearObjectTile(Object::GetByTile(tile
));
905 /* When clearing objects, they may turn into canal, which may require transferring ownership. */
906 ChangeTileOwner(tile
, old_owner
, new_owner
);
910 static CommandCost
TerraformTile_Object(TileIndex tile
, DoCommandFlag flags
, int z_new
, Slope tileh_new
)
912 ObjectType type
= GetObjectType(tile
);
914 if (type
== OBJECT_OWNED_LAND
) {
915 /* Owned land remains unsold */
916 CommandCost ret
= CheckTileOwnership(tile
);
917 if (ret
.Succeeded()) return CommandCost();
918 } else if (AutoslopeEnabled() && type
!= OBJECT_TRANSMITTER
&& type
!= OBJECT_LIGHTHOUSE
) {
920 * - Both new and old slope must not be steep.
921 * - TileMaxZ must not be changed.
922 * - Allow autoslope by default.
923 * - Disallow autoslope if callback succeeds and returns non-zero.
925 Slope tileh_old
= GetTileSlope(tile
);
926 /* TileMaxZ must not be changed. Slopes must not be steep. */
927 if (!IsSteepSlope(tileh_old
) && !IsSteepSlope(tileh_new
) && (GetTileMaxZ(tile
) == z_new
+ GetSlopeMaxZ(tileh_new
))) {
928 const ObjectSpec
*spec
= ObjectSpec::Get(type
);
930 /* Call callback 'disable autosloping for objects'. */
931 if (HasBit(spec
->callback_mask
, CBM_OBJ_AUTOSLOPE
)) {
932 /* If the callback fails, allow autoslope. */
933 uint16_t res
= GetObjectCallback(CBID_OBJECT_AUTOSLOPE
, 0, 0, spec
, Object::GetByTile(tile
), tile
);
934 if (res
== CALLBACK_FAILED
|| !ConvertBooleanCallback(spec
->grf_prop
.grffile
, CBID_OBJECT_AUTOSLOPE
, res
)) return CommandCost(EXPENSES_CONSTRUCTION
, _price
[PR_BUILD_FOUNDATION
]);
935 } else if (spec
->IsEnabled()) {
936 /* allow autoslope */
937 return CommandCost(EXPENSES_CONSTRUCTION
, _price
[PR_BUILD_FOUNDATION
]);
942 return Command
<CMD_LANDSCAPE_CLEAR
>::Do(flags
, tile
);
945 extern const TileTypeProcs _tile_type_object_procs
= {
946 DrawTile_Object
, // draw_tile_proc
947 GetSlopePixelZ_Object
, // get_slope_z_proc
948 ClearTile_Object
, // clear_tile_proc
949 AddAcceptedCargo_Object
, // add_accepted_cargo_proc
950 GetTileDesc_Object
, // get_tile_desc_proc
951 GetTileTrackStatus_Object
, // get_tile_track_status_proc
952 ClickTile_Object
, // click_tile_proc
953 AnimateTile_Object
, // animate_tile_proc
954 TileLoop_Object
, // tile_loop_proc
955 ChangeTileOwner_Object
, // change_tile_owner_proc
956 AddProducedCargo_Object
, // add_produced_cargo_proc
957 nullptr, // vehicle_enter_tile_proc
958 GetFoundation_Object
, // get_foundation_proc
959 TerraformTile_Object
, // terraform_tile_proc