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 if (IsWaterTile(t
)) ClearNeighbourNonFloodingStates(t
);
124 if (HasTileWaterGround(t
)) InvalidateWaterRegion(t
);
125 WaterClass wc
= (IsWaterTile(t
) ? GetWaterClass(t
) : WATER_CLASS_INVALID
);
126 /* Update company infrastructure counts for objects build on canals owned by nobody. */
127 if (wc
== WATER_CLASS_CANAL
&& owner
!= OWNER_NONE
&& (IsTileOwner(t
, OWNER_NONE
) || IsTileOwner(t
, OWNER_WATER
))) {
128 Company::Get(owner
)->infrastructure
.water
++;
129 DirtyCompanyInfrastructureWindows(owner
);
131 bool remove
= IsDockingTile(t
);
132 MakeObject(t
, owner
, o
->index
, wc
, Random());
133 if (remove
) RemoveDockingTile(t
);
134 MarkTileDirtyByTile(t
);
137 Object::IncTypeCount(type
);
138 if (spec
->flags
& OBJECT_FLAG_ANIMATION
) TriggerObjectAnimation(o
, OAT_BUILT
, spec
);
142 * Increase the animation stage of a whole structure.
143 * @param tile The tile of the structure.
145 static void IncreaseAnimationStage(TileIndex tile
)
147 TileArea ta
= Object::GetByTile(tile
)->location
;
148 for (TileIndex t
: ta
) {
149 SetAnimationFrame(t
, GetAnimationFrame(t
) + 1);
150 MarkTileDirtyByTile(t
);
154 /** We encode the company HQ size in the animation stage. */
155 #define GetCompanyHQSize GetAnimationFrame
156 /** We encode the company HQ size in the animation stage. */
157 #define IncreaseCompanyHQSize IncreaseAnimationStage
160 * Update the CompanyHQ to the state associated with the given score
161 * @param tile The (northern) tile of the company HQ, or INVALID_TILE.
162 * @param score The current (performance) score of the company.
164 void UpdateCompanyHQ(TileIndex tile
, uint score
)
166 if (tile
== INVALID_TILE
) return;
169 if (score
>= 170) val
++;
170 if (score
>= 350) val
++;
171 if (score
>= 520) val
++;
172 if (score
>= 720) val
++;
174 while (GetCompanyHQSize(tile
) < val
) {
175 IncreaseCompanyHQSize(tile
);
180 * Updates the colour of the object whenever a company changes.
181 * @param c The company the company colour changed of.
183 void UpdateObjectColours(const Company
*c
)
185 for (Object
*obj
: Object::Iterate()) {
186 Owner owner
= GetTileOwner(obj
->location
.tile
);
187 /* Not the current owner, so colour doesn't change. */
188 if (owner
!= c
->index
) continue;
190 const ObjectSpec
*spec
= ObjectSpec::GetByTile(obj
->location
.tile
);
191 /* Using the object colour callback, so not using company colour. */
192 if (HasBit(spec
->callback_mask
, CBM_OBJ_COLOUR
)) continue;
194 const Livery
*l
= c
->livery
;
195 obj
->colour
= ((spec
->flags
& OBJECT_FLAG_2CC_COLOUR
) ? (l
->colour2
* 16) : 0) + l
->colour1
;
199 extern CommandCost
CheckBuildableTile(TileIndex tile
, uint invalid_dirs
, int &allowed_z
, bool allow_steep
, bool check_bridge
);
200 static CommandCost
ClearTile_Object(TileIndex tile
, DoCommandFlag flags
);
203 * Build an object object
204 * @param flags type of operation
205 * @param tile tile where the object will be located
206 * @param type the object type to build
207 * @param view the view for the object
208 * @return the cost of this operation or an error
210 CommandCost
CmdBuildObject(DoCommandFlag flags
, TileIndex tile
, ObjectType type
, uint8_t view
)
212 CommandCost
cost(EXPENSES_CONSTRUCTION
);
214 if (type
>= ObjectSpec::Count()) return CMD_ERROR
;
215 const ObjectSpec
*spec
= ObjectSpec::Get(type
);
216 if (_game_mode
== GM_NORMAL
&& !spec
->IsAvailable() && !_generating_world
) return CMD_ERROR
;
217 if ((_game_mode
== GM_EDITOR
|| _generating_world
) && !spec
->WasEverAvailable()) return CMD_ERROR
;
219 if ((spec
->flags
& OBJECT_FLAG_ONLY_IN_SCENEDIT
) != 0 && ((!_generating_world
&& _game_mode
!= GM_EDITOR
) || _current_company
!= OWNER_NONE
)) return CMD_ERROR
;
220 if ((spec
->flags
& OBJECT_FLAG_ONLY_IN_GAME
) != 0 && (_generating_world
|| _game_mode
!= GM_NORMAL
|| _current_company
> MAX_COMPANIES
)) return CMD_ERROR
;
221 if (view
>= spec
->views
) return CMD_ERROR
;
223 if (!Object::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_OBJECTS
);
224 if (Town::GetNumItems() == 0) return_cmd_error(STR_ERROR_MUST_FOUND_TOWN_FIRST
);
226 int size_x
= GB(spec
->size
, HasBit(view
, 0) ? 4 : 0, 4);
227 int size_y
= GB(spec
->size
, HasBit(view
, 0) ? 0 : 4, 4);
228 TileArea
ta(tile
, size_x
, size_y
);
229 for (TileIndex t
: ta
) {
230 if (!IsValidTile(t
)) return_cmd_error(STR_ERROR_TOO_CLOSE_TO_EDGE_OF_MAP_SUB
); // Might be off the map
233 if (type
== OBJECT_OWNED_LAND
) {
234 /* Owned land is special as it can be placed on any slope. */
235 cost
.AddCost(Command
<CMD_LANDSCAPE_CLEAR
>::Do(flags
, tile
));
237 /* Check the surface to build on. At this time we can't actually execute the
238 * the CLEAR_TILE commands since the newgrf callback later on can check
239 * some information about the tiles. */
240 bool allow_water
= (spec
->flags
& (OBJECT_FLAG_BUILT_ON_WATER
| OBJECT_FLAG_NOT_ON_LAND
)) != 0;
241 bool allow_ground
= (spec
->flags
& OBJECT_FLAG_NOT_ON_LAND
) == 0;
242 for (TileIndex t
: ta
) {
243 if (HasTileWaterGround(t
)) {
244 if (!allow_water
) return_cmd_error(STR_ERROR_CAN_T_BUILD_ON_WATER
);
245 if (!IsWaterTile(t
)) {
246 /* Normal water tiles don't have to be cleared. For all other tile types clear
247 * the tile but leave the water. */
248 cost
.AddCost(Command
<CMD_LANDSCAPE_CLEAR
>::Do(flags
& ~DC_NO_WATER
& ~DC_EXEC
, t
));
250 /* Can't build on water owned by another company. */
251 Owner o
= GetTileOwner(t
);
252 if (o
!= OWNER_NONE
&& o
!= OWNER_WATER
) cost
.AddCost(CheckOwnership(o
, t
));
254 /* However, the tile has to be clear of vehicles. */
255 cost
.AddCost(EnsureNoVehicleOnGround(t
));
258 if (!allow_ground
) return_cmd_error(STR_ERROR_MUST_BE_BUILT_ON_WATER
);
259 /* For non-water tiles, we'll have to clear it before building. */
261 /* When relocating HQ, allow it to be relocated (partial) on itself. */
262 if (!(type
== OBJECT_HQ
&&
263 IsTileType(t
, MP_OBJECT
) &&
264 IsTileOwner(t
, _current_company
) &&
265 IsObjectType(t
, OBJECT_HQ
))) {
266 cost
.AddCost(Command
<CMD_LANDSCAPE_CLEAR
>::Do(flags
& ~DC_EXEC
, t
));
271 /* So, now the surface is checked... check the slope of said surface. */
272 auto [slope
, allowed_z
] = GetTileSlopeZ(tile
);
273 if (slope
!= SLOPE_FLAT
) allowed_z
++;
275 for (TileIndex t
: ta
) {
276 uint16_t callback
= CALLBACK_FAILED
;
277 if (HasBit(spec
->callback_mask
, CBM_OBJ_SLOPE_CHECK
)) {
278 TileIndex diff
= t
- tile
;
279 callback
= GetObjectCallback(CBID_OBJECT_LAND_SLOPE_CHECK
, GetTileSlope(t
), TileY(diff
) << 4 | TileX(diff
), spec
, nullptr, t
, view
);
282 if (callback
== CALLBACK_FAILED
) {
283 cost
.AddCost(CheckBuildableTile(t
, 0, allowed_z
, false, false));
285 /* The meaning of bit 10 is inverted for a grf version < 8. */
286 if (spec
->grf_prop
.grffile
->grf_version
< 8) ToggleBit(callback
, 10);
287 CommandCost ret
= GetErrorMessageFromLocationCallbackResult(callback
, spec
->grf_prop
.grffile
, STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION
);
288 if (ret
.Failed()) return ret
;
292 if (flags
& DC_EXEC
) {
293 /* This is basically a copy of the loop above with the exception that we now
294 * execute the commands and don't check for errors, since that's already done. */
295 for (TileIndex t
: ta
) {
296 if (HasTileWaterGround(t
)) {
297 if (!IsWaterTile(t
)) {
298 Command
<CMD_LANDSCAPE_CLEAR
>::Do((flags
& ~DC_NO_WATER
) | DC_NO_MODIFY_TOWN_RATING
, t
);
301 Command
<CMD_LANDSCAPE_CLEAR
>::Do(flags
| DC_NO_MODIFY_TOWN_RATING
, t
);
306 if (cost
.Failed()) return cost
;
308 /* Finally do a check for bridges. */
309 for (TileIndex t
: ta
) {
310 if (IsBridgeAbove(t
) && (
311 !(spec
->flags
& OBJECT_FLAG_ALLOW_UNDER_BRIDGE
) ||
312 (GetTileMaxZ(t
) + spec
->height
>= GetBridgeHeight(GetSouthernBridgeEnd(t
))))) {
313 return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST
);
318 uint build_object_size
= 1;
320 case OBJECT_TRANSMITTER
:
321 case OBJECT_LIGHTHOUSE
:
322 if (!IsTileFlat(tile
)) return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED
);
325 case OBJECT_OWNED_LAND
:
326 if (IsTileType(tile
, MP_OBJECT
) &&
327 IsTileOwner(tile
, _current_company
) &&
328 IsObjectType(tile
, OBJECT_OWNED_LAND
)) {
329 return_cmd_error(STR_ERROR_YOU_ALREADY_OWN_IT
);
334 Company
*c
= Company::Get(_current_company
);
335 if (c
->location_of_HQ
!= INVALID_TILE
) {
336 /* Don't relocate HQ on the same location. */
337 if (c
->location_of_HQ
== tile
) return_cmd_error(STR_ERROR_ALREADY_BUILT
);
338 /* We need to persuade a bit harder to remove the old HQ. */
339 _current_company
= OWNER_WATER
;
340 cost
.AddCost(ClearTile_Object(c
->location_of_HQ
, flags
));
341 _current_company
= c
->index
;
344 if (flags
& DC_EXEC
) {
345 hq_score
= UpdateCompanyRatingAndValue(c
, false);
346 c
->location_of_HQ
= tile
;
347 SetWindowDirty(WC_COMPANY
, c
->index
);
353 /* This may never be constructed using this method. */
356 default: // i.e. NewGRF provided.
357 build_object_size
= size_x
* size_y
;
361 /* Don't allow building more objects if the company has reached its limit. */
362 Company
*c
= Company::GetIfValid(_current_company
);
363 if (c
!= nullptr && GB(c
->build_object_limit
, 16, 16) < build_object_size
) {
364 return_cmd_error(STR_ERROR_BUILD_OBJECT_LIMIT_REACHED
);
367 if (flags
& DC_EXEC
) {
368 BuildObject(type
, tile
, _current_company
== OWNER_DEITY
? OWNER_NONE
: _current_company
, nullptr, view
);
370 /* Make sure the HQ starts at the right size. */
371 if (type
== OBJECT_HQ
) UpdateCompanyHQ(tile
, hq_score
);
373 /* Subtract the tile from the build limit. */
374 if (c
!= nullptr) c
->build_object_limit
-= build_object_size
<< 16;
377 cost
.AddCost(spec
->GetBuildCost() * build_object_size
);
382 * Construct multiple objects in an area
383 * @param flags of operation to conduct
384 * @param tile end tile of area dragging
385 * @param start_tile start tile of area dragging
386 * @param type the object type to build
387 * @param view the view for the object
388 * @param diagonal Whether to use the Orthogonal (0) or Diagonal (1) iterator.
389 * @return the cost of this operation or an error
391 CommandCost
CmdBuildObjectArea(DoCommandFlag flags
, TileIndex tile
, TileIndex start_tile
, ObjectType type
, uint8_t view
, bool diagonal
)
393 if (start_tile
>= Map::Size()) return CMD_ERROR
;
395 if (type
>= ObjectSpec::Count()) return CMD_ERROR
;
396 const ObjectSpec
*spec
= ObjectSpec::Get(type
);
397 if (view
>= spec
->views
) return CMD_ERROR
;
399 if (spec
->size
!= OBJECT_SIZE_1X1
) return CMD_ERROR
;
401 Money money
= GetAvailableMoneyForCommand();
402 CommandCost
cost(EXPENSES_CONSTRUCTION
);
403 CommandCost last_error
= CMD_ERROR
;
404 bool had_success
= false;
406 const Company
*c
= Company::GetIfValid(_current_company
);
407 int limit
= (c
== nullptr ? INT32_MAX
: GB(c
->build_object_limit
, 16, 16));
409 std::unique_ptr
<TileIterator
> iter
= TileIterator::Create(tile
, start_tile
, diagonal
);
410 for (; *iter
!= INVALID_TILE
; ++(*iter
)) {
412 CommandCost ret
= Command
<CMD_BUILD_OBJECT
>::Do(flags
& ~DC_EXEC
, t
, type
, view
);
414 /* If we've reached the limit, stop building (or testing). */
415 if (c
!= nullptr && limit
-- <= 0) break;
423 if (flags
& DC_EXEC
) {
424 money
-= ret
.GetCost();
426 /* If we run out of money, stop building. */
427 if (ret
.GetCost() > 0 && money
< 0) break;
428 Command
<CMD_BUILD_OBJECT
>::Do(flags
, t
, type
, view
);
433 return had_success
? cost
: last_error
;
436 static Foundation
GetFoundation_Object(TileIndex tile
, Slope tileh
);
438 static void DrawTile_Object(TileInfo
*ti
)
440 ObjectType type
= GetObjectType(ti
->tile
);
441 const ObjectSpec
*spec
= ObjectSpec::Get(type
);
443 /* Fall back for when the object doesn't exist anymore. */
444 if (!spec
->IsEnabled()) type
= OBJECT_TRANSMITTER
;
446 if ((spec
->flags
& OBJECT_FLAG_HAS_NO_FOUNDATION
) == 0) DrawFoundation(ti
, GetFoundation_Object(ti
->tile
, ti
->tileh
));
448 if (type
< NEW_OBJECT_OFFSET
) {
449 const DrawTileSprites
*dts
= nullptr;
450 Owner to
= GetTileOwner(ti
->tile
);
451 PaletteID palette
= to
== OWNER_NONE
? PAL_NONE
: COMPANY_SPRITE_COLOUR(to
);
453 if (type
== OBJECT_HQ
) {
454 TileIndex diff
= ti
->tile
- Object::GetByTile(ti
->tile
)->location
.tile
;
455 dts
= &_object_hq
[GetCompanyHQSize(ti
->tile
) << 2 | TileY(diff
) << 1 | TileX(diff
)];
457 dts
= &_objects
[type
];
460 if (spec
->flags
& OBJECT_FLAG_HAS_NO_FOUNDATION
) {
461 /* If an object has no foundation, but tries to draw a (flat) ground
462 * type... we have to be nice and convert that for them. */
463 switch (dts
->ground
.sprite
) {
464 case SPR_FLAT_BARE_LAND
: DrawClearLandTile(ti
, 0); break;
465 case SPR_FLAT_1_THIRD_GRASS_TILE
: DrawClearLandTile(ti
, 1); break;
466 case SPR_FLAT_2_THIRD_GRASS_TILE
: DrawClearLandTile(ti
, 2); break;
467 case SPR_FLAT_GRASS_TILE
: DrawClearLandTile(ti
, 3); break;
468 default: DrawGroundSprite(dts
->ground
.sprite
, palette
); break;
471 DrawGroundSprite(dts
->ground
.sprite
, palette
);
474 if (!IsInvisibilitySet(TO_STRUCTURES
)) {
475 const DrawTileSeqStruct
*dtss
;
476 foreach_draw_tile_seq(dtss
, dts
->seq
) {
477 AddSortableSpriteToDraw(
478 dtss
->image
.sprite
, palette
,
479 ti
->x
+ dtss
->delta_x
, ti
->y
+ dtss
->delta_y
,
480 dtss
->size_x
, dtss
->size_y
,
481 dtss
->size_z
, ti
->z
+ dtss
->delta_z
,
482 IsTransparencySet(TO_STRUCTURES
)
487 DrawNewObjectTile(ti
, spec
);
490 DrawBridgeMiddle(ti
);
493 static int GetSlopePixelZ_Object(TileIndex tile
, uint x
, uint y
, bool)
495 if (IsObjectType(tile
, OBJECT_OWNED_LAND
)) {
496 auto [tileh
, z
] = GetTilePixelSlope(tile
);
498 return z
+ GetPartialPixelZ(x
& 0xF, y
& 0xF, tileh
);
500 return GetTileMaxPixelZ(tile
);
504 static Foundation
GetFoundation_Object(TileIndex tile
, Slope tileh
)
506 return IsObjectType(tile
, OBJECT_OWNED_LAND
) ? FOUNDATION_NONE
: FlatteningFoundation(tileh
);
510 * Perform the actual removal of the object from the map.
511 * @param o The object to really clear.
513 static void ReallyClearObjectTile(Object
*o
)
515 Object::DecTypeCount(o
->type
);
516 for (TileIndex tile_cur
: o
->location
) {
517 DeleteNewGRFInspectWindow(GSF_OBJECTS
, tile_cur
.base());
519 MakeWaterKeepingClass(tile_cur
, GetTileOwner(tile_cur
));
524 std::vector
<ClearedObjectArea
> _cleared_object_areas
;
527 * Find the entry in _cleared_object_areas which occupies a certain tile.
528 * @param tile Tile of interest
529 * @return Occupying entry, or nullptr if none
531 ClearedObjectArea
*FindClearedObject(TileIndex tile
)
533 TileArea ta
= TileArea(tile
, 1, 1);
535 for (ClearedObjectArea
&coa
: _cleared_object_areas
) {
536 if (coa
.area
.Intersects(ta
)) return &coa
;
542 static CommandCost
ClearTile_Object(TileIndex tile
, DoCommandFlag flags
)
544 /* Get to the northern most tile. */
545 Object
*o
= Object::GetByTile(tile
);
546 TileArea ta
= o
->location
;
548 ObjectType type
= o
->type
;
549 const ObjectSpec
*spec
= ObjectSpec::Get(type
);
551 CommandCost
cost(EXPENSES_CONSTRUCTION
, spec
->GetClearCost() * ta
.w
* ta
.h
/ 5);
552 if (spec
->flags
& OBJECT_FLAG_CLEAR_INCOME
) cost
.MultiplyCost(-1); // They get an income!
554 /* Towns can't remove any objects. */
555 if (_current_company
== OWNER_TOWN
) return CMD_ERROR
;
557 /* Water can remove everything! */
558 if (_current_company
!= OWNER_WATER
) {
559 if ((flags
& DC_NO_WATER
) && IsTileOnWater(tile
)) {
560 /* There is water under the object, treat it as water tile. */
561 return_cmd_error(STR_ERROR_CAN_T_BUILD_ON_WATER
);
562 } else if (!(spec
->flags
& OBJECT_FLAG_AUTOREMOVE
) && (flags
& DC_AUTO
)) {
563 /* No automatic removal by overbuilding stuff. */
564 return_cmd_error(type
== OBJECT_HQ
? STR_ERROR_COMPANY_HEADQUARTERS_IN
: STR_ERROR_OBJECT_IN_THE_WAY
);
565 } else if (_game_mode
== GM_EDITOR
) {
566 /* No further limitations for the editor. */
567 } else if (GetTileOwner(tile
) == OWNER_NONE
) {
568 /* Owned by nobody and unremovable, so we can only remove it with brute force! */
569 if (!_cheats
.magic_bulldozer
.value
&& (spec
->flags
& OBJECT_FLAG_CANNOT_REMOVE
) != 0) return CMD_ERROR
;
570 } else if (CheckTileOwnership(tile
).Failed()) {
571 /* We don't own it!. */
572 return_cmd_error(STR_ERROR_OWNED_BY
);
573 } else if ((spec
->flags
& OBJECT_FLAG_CANNOT_REMOVE
) != 0 && (spec
->flags
& OBJECT_FLAG_AUTOREMOVE
) == 0) {
574 /* In the game editor or with cheats we can remove, otherwise we can't. */
575 if (!_cheats
.magic_bulldozer
.value
) {
576 if (type
== OBJECT_HQ
) return_cmd_error(STR_ERROR_COMPANY_HEADQUARTERS_IN
);
580 /* Removing with the cheat costs more in TTDPatch / the specs. */
581 cost
.MultiplyCost(25);
583 } else if ((spec
->flags
& (OBJECT_FLAG_BUILT_ON_WATER
| OBJECT_FLAG_NOT_ON_LAND
)) != 0) {
584 /* Water can't remove objects that are buildable on water. */
590 Company
*c
= Company::Get(GetTileOwner(tile
));
591 if (flags
& DC_EXEC
) {
592 c
->location_of_HQ
= INVALID_TILE
; // reset HQ position
593 SetWindowDirty(WC_COMPANY
, c
->index
);
594 CargoPacket::InvalidateAllFrom(SourceType::Headquarters
, c
->index
);
597 /* cost of relocating company is 1% of company value */
598 cost
= CommandCost(EXPENSES_CONSTRUCTION
, CalculateCompanyValue(c
) / 100);
603 if (flags
& DC_EXEC
) {
604 Town
*town
= o
->town
;
605 ClrBit(town
->statues
, GetTileOwner(tile
));
606 SetWindowDirty(WC_TOWN_AUTHORITY
, town
->index
);
614 _cleared_object_areas
.push_back({tile
, ta
});
616 if (flags
& DC_EXEC
) ReallyClearObjectTile(o
);
621 static void AddAcceptedCargo_Object(TileIndex tile
, CargoArray
&acceptance
, CargoTypes
&always_accepted
)
623 if (!IsObjectType(tile
, OBJECT_HQ
)) return;
625 /* HQ accepts passenger and mail; but we have to divide the values
626 * between 4 tiles it occupies! */
628 /* HQ level (depends on company performance) in the range 1..5. */
629 uint level
= GetCompanyHQSize(tile
) + 1;
631 /* Top town building generates 10, so to make HQ interesting, the top
633 CargoID pass
= GetCargoIDByLabel(CT_PASSENGERS
);
634 if (IsValidCargoID(pass
)) {
635 acceptance
[pass
] += std::max(1U, level
);
636 SetBit(always_accepted
, pass
);
639 /* Top town building generates 4, HQ can make up to 8. The
640 * proportion passengers:mail is different because such a huge
641 * commercial building generates unusually high amount of mail
642 * correspondence per physical visitor. */
643 CargoID mail
= GetCargoIDByLabel(CT_MAIL
);
644 if (IsValidCargoID(mail
)) {
645 acceptance
[mail
] += std::max(1U, level
/ 2);
646 SetBit(always_accepted
, mail
);
650 static void AddProducedCargo_Object(TileIndex tile
, CargoArray
&produced
)
652 if (!IsObjectType(tile
, OBJECT_HQ
)) return;
654 CargoID pass
= GetCargoIDByLabel(CT_PASSENGERS
);
655 if (IsValidCargoID(pass
)) produced
[pass
]++;
656 CargoID mail
= GetCargoIDByLabel(CT_MAIL
);
657 if (IsValidCargoID(mail
)) produced
[mail
]++;
661 static void GetTileDesc_Object(TileIndex tile
, TileDesc
*td
)
663 const ObjectSpec
*spec
= ObjectSpec::GetByTile(tile
);
664 td
->str
= spec
->name
;
665 td
->owner
[0] = GetTileOwner(tile
);
666 td
->build_date
= Object::GetByTile(tile
)->build_date
;
668 if (spec
->grf_prop
.grffile
!= nullptr) {
669 td
->grf
= GetGRFConfig(spec
->grf_prop
.grffile
->grfid
)->GetName();
673 static void TileLoop_Object(TileIndex tile
)
675 const ObjectSpec
*spec
= ObjectSpec::GetByTile(tile
);
676 if (spec
->flags
& OBJECT_FLAG_ANIMATION
) {
677 Object
*o
= Object::GetByTile(tile
);
678 TriggerObjectTileAnimation(o
, tile
, OAT_TILELOOP
, spec
);
679 if (o
->location
.tile
== tile
) TriggerObjectAnimation(o
, OAT_256_TICKS
, spec
);
682 if (IsTileOnWater(tile
)) TileLoop_Water(tile
);
684 if (!IsObjectType(tile
, OBJECT_HQ
)) return;
686 /* HQ accepts passenger and mail; but we have to divide the values
687 * between 4 tiles it occupies! */
689 /* HQ level (depends on company performance) in the range 1..5. */
690 uint level
= GetCompanyHQSize(tile
) + 1;
693 StationFinder
stations(TileArea(tile
, 2, 2));
696 /* Top town buildings generate 250, so the top HQ type makes 256. */
697 CargoID pass
= GetCargoIDByLabel(CT_PASSENGERS
);
698 if (IsValidCargoID(pass
) && GB(r
, 0, 8) < (256 / 4 / (6 - level
))) {
699 uint amt
= GB(r
, 0, 8) / 8 / 4 + 1;
701 /* Production is halved during recessions. */
702 if (EconomyIsInRecession()) amt
= (amt
+ 1) >> 1;
704 /* Scale by cargo scale setting. */
705 amt
= ScaleByCargoScale(amt
, true);
707 MoveGoodsToStation(pass
, amt
, SourceType::Headquarters
, GetTileOwner(tile
), stations
.GetStations());
710 /* Top town building generates 90, HQ can make up to 196. The
711 * proportion passengers:mail is about the same as in the acceptance
713 CargoID mail
= GetCargoIDByLabel(CT_MAIL
);
714 if (IsValidCargoID(mail
) && GB(r
, 8, 8) < (196 / 4 / (6 - level
))) {
715 uint amt
= GB(r
, 8, 8) / 8 / 4 + 1;
717 /* Production is halved during recessions. */
718 if (EconomyIsInRecession()) amt
= (amt
+ 1) >> 1;
720 /* Scale by cargo scale setting. */
721 amt
= ScaleByCargoScale(amt
, true);
723 MoveGoodsToStation(mail
, amt
, SourceType::Headquarters
, GetTileOwner(tile
), stations
.GetStations());
728 static TrackStatus
GetTileTrackStatus_Object(TileIndex
, TransportType
, uint
, DiagDirection
)
733 static bool ClickTile_Object(TileIndex tile
)
735 if (!IsObjectType(tile
, OBJECT_HQ
)) return false;
737 ShowCompany(GetTileOwner(tile
));
741 static void AnimateTile_Object(TileIndex tile
)
743 AnimateNewObjectTile(tile
);
747 * Helper function for \c CircularTileSearch.
748 * @param tile The tile to check.
749 * @return True iff the tile has a radio tower.
751 static bool HasTransmitter(TileIndex tile
, void *)
753 return IsObjectTypeTile(tile
, OBJECT_TRANSMITTER
);
757 * Try to build a lighthouse.
758 * @return True iff building a lighthouse succeeded.
760 static bool TryBuildLightHouse()
762 uint maxx
= Map::MaxX();
763 uint maxy
= Map::MaxY();
766 /* Scatter the lighthouses more evenly around the perimeter */
767 int perimeter
= (GB(r
, 16, 16) % (2 * (maxx
+ maxy
))) - maxy
;
769 for (dir
= DIAGDIR_NE
; perimeter
> 0; dir
++) {
770 perimeter
-= (DiagDirToAxis(dir
) == AXIS_X
) ? maxx
: maxy
;
776 case DIAGDIR_NE
: tile
= TileXY(maxx
- 1, r
% maxy
); break;
777 case DIAGDIR_SE
: tile
= TileXY(r
% maxx
, 1); break;
778 case DIAGDIR_SW
: tile
= TileXY(1, r
% maxy
); break;
779 case DIAGDIR_NW
: tile
= TileXY(r
% maxx
, maxy
- 1); break;
782 /* Only build lighthouses at tiles where the border is sea. */
783 if (!IsTileType(tile
, MP_WATER
)) return false;
785 for (int j
= 0; j
< 19; j
++) {
787 if (IsTileType(tile
, MP_CLEAR
) && IsTileFlat(tile
, &h
) && h
<= 2 && !IsBridgeAbove(tile
)) {
788 BuildObject(OBJECT_LIGHTHOUSE
, tile
);
789 assert(tile
< Map::Size());
792 tile
+= TileOffsByDiagDir(dir
);
793 if (!IsValidTile(tile
)) return false;
799 * Try to build a transmitter.
800 * @return True iff a transmitter was built.
802 static bool TryBuildTransmitter()
804 TileIndex tile
= RandomTile();
806 if (IsTileType(tile
, MP_CLEAR
) && IsTileFlat(tile
, &h
) && h
>= 4 && !IsBridgeAbove(tile
)) {
808 if (CircularTileSearch(&t
, 9, HasTransmitter
, nullptr)) return false;
810 BuildObject(OBJECT_TRANSMITTER
, tile
);
816 void GenerateObjects()
818 /* Set a guestimate on how much we progress */
819 SetGeneratingWorldProgress(GWP_OBJECT
, (uint
)ObjectSpec::Count());
821 /* Determine number of water tiles at map border needed for freeform_edges */
822 uint num_water_tiles
= 0;
823 if (_settings_game
.construction
.freeform_edges
) {
824 for (uint x
= 0; x
< Map::MaxX(); x
++) {
825 if (IsTileType(TileXY(x
, 1), MP_WATER
)) num_water_tiles
++;
826 if (IsTileType(TileXY(x
, Map::MaxY() - 1), MP_WATER
)) num_water_tiles
++;
828 for (uint y
= 1; y
< Map::MaxY() - 1; y
++) {
829 if (IsTileType(TileXY(1, y
), MP_WATER
)) num_water_tiles
++;
830 if (IsTileType(TileXY(Map::MaxX() - 1, y
), MP_WATER
)) num_water_tiles
++;
834 /* Iterate over all possible object types */
835 for (const auto &spec
: ObjectSpec::Specs()) {
837 /* Continue, if the object was never available till now or shall not be placed */
838 if (!spec
.WasEverAvailable() || spec
.generate_amount
== 0) continue;
840 uint16_t amount
= spec
.generate_amount
;
842 /* Scale by map size */
843 if ((spec
.flags
& OBJECT_FLAG_SCALE_BY_WATER
) && _settings_game
.construction
.freeform_edges
) {
844 /* Scale the amount of lighthouses with the amount of land at the borders.
845 * The -6 is because the top borders are MP_VOID (-2) and all corners
846 * are counted twice (-4). */
847 amount
= Map::ScaleBySize1D(amount
* num_water_tiles
) / (2 * Map::MaxY() + 2 * Map::MaxX() - 6);
848 } else if (spec
.flags
& OBJECT_FLAG_SCALE_BY_WATER
) {
849 amount
= Map::ScaleBySize1D(amount
);
851 amount
= Map::ScaleBySize(amount
);
854 /* Now try to place the requested amount of this object */
855 for (uint j
= Map::ScaleBySize(1000); j
!= 0 && amount
!= 0 && Object::CanAllocateItem(); j
--) {
856 switch (spec
.Index()) {
857 case OBJECT_TRANSMITTER
:
858 if (TryBuildTransmitter()) amount
--;
861 case OBJECT_LIGHTHOUSE
:
862 if (TryBuildLightHouse()) amount
--;
866 uint8_t view
= RandomRange(spec
.views
);
867 if (CmdBuildObject(DC_EXEC
| DC_AUTO
| DC_NO_TEST_TOWN_RATING
| DC_NO_MODIFY_TOWN_RATING
, RandomTile(), spec
.Index(), view
).Succeeded()) amount
--;
871 IncreaseGeneratingWorldProgress(GWP_OBJECT
);
875 static void ChangeTileOwner_Object(TileIndex tile
, Owner old_owner
, Owner new_owner
)
877 if (!IsTileOwner(tile
, old_owner
)) return;
879 bool do_clear
= false;
881 ObjectType type
= GetObjectType(tile
);
882 if ((type
== OBJECT_OWNED_LAND
|| type
>= NEW_OBJECT_OFFSET
) && new_owner
!= INVALID_OWNER
) {
883 SetTileOwner(tile
, new_owner
);
884 if (GetWaterClass(tile
) == WATER_CLASS_CANAL
) {
885 Company::Get(old_owner
)->infrastructure
.water
--;
886 Company::Get(new_owner
)->infrastructure
.water
++;
888 } else if (type
== OBJECT_STATUE
) {
889 Town
*t
= Object::GetByTile(tile
)->town
;
890 ClrBit(t
->statues
, old_owner
);
891 if (new_owner
!= INVALID_OWNER
&& !HasBit(t
->statues
, new_owner
)) {
892 /* Transfer ownership to the new company */
893 SetBit(t
->statues
, new_owner
);
894 SetTileOwner(tile
, new_owner
);
899 SetWindowDirty(WC_TOWN_AUTHORITY
, t
->index
);
905 ReallyClearObjectTile(Object::GetByTile(tile
));
906 /* When clearing objects, they may turn into canal, which may require transferring ownership. */
907 ChangeTileOwner(tile
, old_owner
, new_owner
);
911 static CommandCost
TerraformTile_Object(TileIndex tile
, DoCommandFlag flags
, int z_new
, Slope tileh_new
)
913 ObjectType type
= GetObjectType(tile
);
915 if (type
== OBJECT_OWNED_LAND
) {
916 /* Owned land remains unsold */
917 CommandCost ret
= CheckTileOwnership(tile
);
918 if (ret
.Succeeded()) return CommandCost();
919 } else if (AutoslopeEnabled() && type
!= OBJECT_TRANSMITTER
&& type
!= OBJECT_LIGHTHOUSE
) {
921 * - Both new and old slope must not be steep.
922 * - TileMaxZ must not be changed.
923 * - Allow autoslope by default.
924 * - Disallow autoslope if callback succeeds and returns non-zero.
926 Slope tileh_old
= GetTileSlope(tile
);
927 /* TileMaxZ must not be changed. Slopes must not be steep. */
928 if (!IsSteepSlope(tileh_old
) && !IsSteepSlope(tileh_new
) && (GetTileMaxZ(tile
) == z_new
+ GetSlopeMaxZ(tileh_new
))) {
929 const ObjectSpec
*spec
= ObjectSpec::Get(type
);
931 /* Call callback 'disable autosloping for objects'. */
932 if (HasBit(spec
->callback_mask
, CBM_OBJ_AUTOSLOPE
)) {
933 /* If the callback fails, allow autoslope. */
934 uint16_t res
= GetObjectCallback(CBID_OBJECT_AUTOSLOPE
, 0, 0, spec
, Object::GetByTile(tile
), tile
);
935 if (res
== CALLBACK_FAILED
|| !ConvertBooleanCallback(spec
->grf_prop
.grffile
, CBID_OBJECT_AUTOSLOPE
, res
)) return CommandCost(EXPENSES_CONSTRUCTION
, _price
[PR_BUILD_FOUNDATION
]);
936 } else if (spec
->IsEnabled()) {
937 /* allow autoslope */
938 return CommandCost(EXPENSES_CONSTRUCTION
, _price
[PR_BUILD_FOUNDATION
]);
943 return Command
<CMD_LANDSCAPE_CLEAR
>::Do(flags
, tile
);
946 extern const TileTypeProcs _tile_type_object_procs
= {
947 DrawTile_Object
, // draw_tile_proc
948 GetSlopePixelZ_Object
, // get_slope_z_proc
949 ClearTile_Object
, // clear_tile_proc
950 AddAcceptedCargo_Object
, // add_accepted_cargo_proc
951 GetTileDesc_Object
, // get_tile_desc_proc
952 GetTileTrackStatus_Object
, // get_tile_track_status_proc
953 ClickTile_Object
, // click_tile_proc
954 AnimateTile_Object
, // animate_tile_proc
955 TileLoop_Object
, // tile_loop_proc
956 ChangeTileOwner_Object
, // change_tile_owner_proc
957 AddProducedCargo_Object
, // add_produced_cargo_proc
958 nullptr, // vehicle_enter_tile_proc
959 GetFoundation_Object
, // get_foundation_proc
960 TerraformTile_Object
, // terraform_tile_proc