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  */
7 
8 /** @file object_cmd.cpp Handling of object tiles. */
9 
10 #include "stdafx.h"
11 #include "landscape.h"
12 #include "command_func.h"
13 #include "viewport_func.h"
14 #include "company_base.h"
15 #include "town.h"
16 #include "bridge_map.h"
17 #include "genworld.h"
18 #include "autoslope.h"
19 #include "clear_func.h"
20 #include "water.h"
21 #include "window_func.h"
22 #include "company_gui.h"
23 #include "cheat_type.h"
24 #include "object.h"
25 #include "cargopacket.h"
26 #include "core/random_func.hpp"
27 #include "core/pool_func.hpp"
28 #include "object_map.h"
29 #include "object_base.h"
30 #include "newgrf_config.h"
31 #include "newgrf_object.h"
32 #include "date_func.h"
33 #include "newgrf_debug.h"
34 #include "vehicle_func.h"
35 #include "station_func.h"
36 
37 #include "table/strings.h"
38 #include "table/object_land.h"
39 
40 #include "safeguards.h"
41 
42 ObjectPool _object_pool("Object");
43 INSTANTIATE_POOL_METHODS(Object)
44 uint16 Object::counts[NUM_OBJECTS];
45 
46 /**
47  * Get the object associated with a tile.
48  * @param tile The tile to fetch the object for.
49  * @return The object.
50  */
GetByTile(TileIndex tile)51 /* static */ Object *Object::GetByTile(TileIndex tile)
52 {
53 	return Object::Get(GetObjectIndex(tile));
54 }
55 
56 /**
57  * Gets the ObjectType of the given object tile
58  * @param t the tile to get the type from.
59  * @pre IsTileType(t, MP_OBJECT)
60  * @return the type.
61  */
GetObjectType(TileIndex t)62 ObjectType GetObjectType(TileIndex t)
63 {
64 	assert(IsTileType(t, MP_OBJECT));
65 	return Object::GetByTile(t)->type;
66 }
67 
68 /** Initialize/reset the objects. */
InitializeObjects()69 void InitializeObjects()
70 {
71 	Object::ResetTypeCounts();
72 }
73 
74 /**
75  * Actually build the object.
76  * @param type  The type of object to build.
77  * @param tile  The tile to build the northern tile of the object on.
78  * @param owner The owner of the object.
79  * @param town  Town the tile is related with.
80  * @param view  The view for the object.
81  * @pre All preconditions for building the object at that location
82  *      are met, e.g. slope and clearness of tiles are checked.
83  */
BuildObject(ObjectType type,TileIndex tile,CompanyID owner,Town * town,uint8 view)84 void BuildObject(ObjectType type, TileIndex tile, CompanyID owner, Town *town, uint8 view)
85 {
86 	const ObjectSpec *spec = ObjectSpec::Get(type);
87 
88 	TileArea ta(tile, GB(spec->size, HasBit(view, 0) ? 4 : 0, 4), GB(spec->size, HasBit(view, 0) ? 0 : 4, 4));
89 	Object *o = new Object();
90 	o->type          = type;
91 	o->location      = ta;
92 	o->town          = town == nullptr ? CalcClosestTownFromTile(tile) : town;
93 	o->build_date    = _date;
94 	o->view          = view;
95 
96 	/* If nothing owns the object, the colour will be random. Otherwise
97 	 * get the colour from the company's livery settings. */
98 	if (owner == OWNER_NONE) {
99 		o->colour = Random();
100 	} else {
101 		const Livery *l = Company::Get(owner)->livery;
102 		o->colour = l->colour1 + l->colour2 * 16;
103 	}
104 
105 	/* If the object wants only one colour, then give it that colour. */
106 	if ((spec->flags & OBJECT_FLAG_2CC_COLOUR) == 0) o->colour &= 0xF;
107 
108 	if (HasBit(spec->callback_mask, CBM_OBJ_COLOUR)) {
109 		uint16 res = GetObjectCallback(CBID_OBJECT_COLOUR, o->colour, 0, spec, o, tile);
110 		if (res != CALLBACK_FAILED) {
111 			if (res >= 0x100) ErrorUnknownCallbackResult(spec->grf_prop.grffile->grfid, CBID_OBJECT_COLOUR, res);
112 			o->colour = GB(res, 0, 8);
113 		}
114 	}
115 
116 	assert(o->town != nullptr);
117 
118 	for (TileIndex t : ta) {
119 		WaterClass wc = (IsWaterTile(t) ? GetWaterClass(t) : WATER_CLASS_INVALID);
120 		/* Update company infrastructure counts for objects build on canals owned by nobody. */
121 		if (wc == WATER_CLASS_CANAL && owner != OWNER_NONE && (IsTileOwner(tile, OWNER_NONE) || IsTileOwner(tile, OWNER_WATER))) {
122 			Company::Get(owner)->infrastructure.water++;
123 			DirtyCompanyInfrastructureWindows(owner);
124 		}
125 		bool remove = IsDockingTile(t);
126 		MakeObject(t, owner, o->index, wc, Random());
127 		if (remove) RemoveDockingTile(t);
128 		MarkTileDirtyByTile(t);
129 	}
130 
131 	Object::IncTypeCount(type);
132 	if (spec->flags & OBJECT_FLAG_ANIMATION) TriggerObjectAnimation(o, OAT_BUILT, spec);
133 }
134 
135 /**
136  * Increase the animation stage of a whole structure.
137  * @param tile The tile of the structure.
138  */
IncreaseAnimationStage(TileIndex tile)139 static void IncreaseAnimationStage(TileIndex tile)
140 {
141 	TileArea ta = Object::GetByTile(tile)->location;
142 	for (TileIndex t : ta) {
143 		SetAnimationFrame(t, GetAnimationFrame(t) + 1);
144 		MarkTileDirtyByTile(t);
145 	}
146 }
147 
148 /** We encode the company HQ size in the animation stage. */
149 #define GetCompanyHQSize GetAnimationFrame
150 /** We encode the company HQ size in the animation stage. */
151 #define IncreaseCompanyHQSize IncreaseAnimationStage
152 
153 /**
154  * Update the CompanyHQ to the state associated with the given score
155  * @param tile  The (northern) tile of the company HQ, or INVALID_TILE.
156  * @param score The current (performance) score of the company.
157  */
UpdateCompanyHQ(TileIndex tile,uint score)158 void UpdateCompanyHQ(TileIndex tile, uint score)
159 {
160 	if (tile == INVALID_TILE) return;
161 
162 	byte val = 0;
163 	if (score >= 170) val++;
164 	if (score >= 350) val++;
165 	if (score >= 520) val++;
166 	if (score >= 720) val++;
167 
168 	while (GetCompanyHQSize(tile) < val) {
169 		IncreaseCompanyHQSize(tile);
170 	}
171 }
172 
173 /**
174  * Updates the colour of the object whenever a company changes.
175  * @param c The company the company colour changed of.
176  */
UpdateObjectColours(const Company * c)177 void UpdateObjectColours(const Company *c)
178 {
179 	for (Object *obj : Object::Iterate()) {
180 		Owner owner = GetTileOwner(obj->location.tile);
181 		/* Not the current owner, so colour doesn't change. */
182 		if (owner != c->index) continue;
183 
184 		const ObjectSpec *spec = ObjectSpec::GetByTile(obj->location.tile);
185 		/* Using the object colour callback, so not using company colour. */
186 		if (HasBit(spec->callback_mask, CBM_OBJ_COLOUR)) continue;
187 
188 		const Livery *l = c->livery;
189 		obj->colour = ((spec->flags & OBJECT_FLAG_2CC_COLOUR) ? (l->colour2 * 16) : 0) + l->colour1;
190 	}
191 }
192 
193 extern CommandCost CheckBuildableTile(TileIndex tile, uint invalid_dirs, int &allowed_z, bool allow_steep, bool check_bridge);
194 static CommandCost ClearTile_Object(TileIndex tile, DoCommandFlag flags);
195 
196 /**
197  * Build an object object
198  * @param tile tile where the object will be located
199  * @param flags type of operation
200  * @param p1 the object type to build
201  * @param p2 the view for the object
202  * @param text unused
203  * @return the cost of this operation or an error
204  */
CmdBuildObject(TileIndex tile,DoCommandFlag flags,uint32 p1,uint32 p2,const std::string & text)205 CommandCost CmdBuildObject(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text)
206 {
207 	CommandCost cost(EXPENSES_CONSTRUCTION);
208 
209 	ObjectType type = (ObjectType)GB(p1, 0, 16);
210 	if (type >= NUM_OBJECTS) return CMD_ERROR;
211 	uint8 view = GB(p2, 0, 2);
212 	const ObjectSpec *spec = ObjectSpec::Get(type);
213 	if (_game_mode == GM_NORMAL && !spec->IsAvailable() && !_generating_world) return CMD_ERROR;
214 	if ((_game_mode == GM_EDITOR || _generating_world) && !spec->WasEverAvailable()) return CMD_ERROR;
215 
216 	if ((spec->flags & OBJECT_FLAG_ONLY_IN_SCENEDIT) != 0 && ((!_generating_world && _game_mode != GM_EDITOR) || _current_company != OWNER_NONE)) return CMD_ERROR;
217 	if ((spec->flags & OBJECT_FLAG_ONLY_IN_GAME) != 0 && (_generating_world || _game_mode != GM_NORMAL || _current_company > MAX_COMPANIES)) return CMD_ERROR;
218 	if (view >= spec->views) return CMD_ERROR;
219 
220 	if (!Object::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_OBJECTS);
221 	if (Town::GetNumItems() == 0) return_cmd_error(STR_ERROR_MUST_FOUND_TOWN_FIRST);
222 
223 	int size_x = GB(spec->size, HasBit(view, 0) ? 4 : 0, 4);
224 	int size_y = GB(spec->size, HasBit(view, 0) ? 0 : 4, 4);
225 	TileArea ta(tile, size_x, size_y);
226 	for (TileIndex t : ta) {
227 		if (!IsValidTile(t)) return_cmd_error(STR_ERROR_TOO_CLOSE_TO_EDGE_OF_MAP_SUB); // Might be off the map
228 	}
229 
230 	if (type == OBJECT_OWNED_LAND) {
231 		/* Owned land is special as it can be placed on any slope. */
232 		cost.AddCost(DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR));
233 	} else {
234 		/* Check the surface to build on. At this time we can't actually execute the
235 		 * the CLEAR_TILE commands since the newgrf callback later on can check
236 		 * some information about the tiles. */
237 		bool allow_water = (spec->flags & (OBJECT_FLAG_BUILT_ON_WATER | OBJECT_FLAG_NOT_ON_LAND)) != 0;
238 		bool allow_ground = (spec->flags & OBJECT_FLAG_NOT_ON_LAND) == 0;
239 		for (TileIndex t : ta) {
240 			if (HasTileWaterGround(t)) {
241 				if (!allow_water) return_cmd_error(STR_ERROR_CAN_T_BUILD_ON_WATER);
242 				if (!IsWaterTile(t)) {
243 					/* Normal water tiles don't have to be cleared. For all other tile types clear
244 					 * the tile but leave the water. */
245 					cost.AddCost(DoCommand(t, 0, 0, flags & ~DC_NO_WATER & ~DC_EXEC, CMD_LANDSCAPE_CLEAR));
246 				} else {
247 					/* Can't build on water owned by another company. */
248 					Owner o = GetTileOwner(t);
249 					if (o != OWNER_NONE && o != OWNER_WATER) cost.AddCost(CheckOwnership(o, t));
250 
251 					/* However, the tile has to be clear of vehicles. */
252 					cost.AddCost(EnsureNoVehicleOnGround(t));
253 				}
254 			} else {
255 				if (!allow_ground) return_cmd_error(STR_ERROR_MUST_BE_BUILT_ON_WATER);
256 				/* For non-water tiles, we'll have to clear it before building. */
257 
258 				/* When relocating HQ, allow it to be relocated (partial) on itself. */
259 				if (!(type == OBJECT_HQ &&
260 						IsTileType(t, MP_OBJECT) &&
261 						IsTileOwner(t, _current_company) &&
262 						IsObjectType(t, OBJECT_HQ))) {
263 					cost.AddCost(DoCommand(t, 0, 0, flags & ~DC_EXEC, CMD_LANDSCAPE_CLEAR));
264 				}
265 			}
266 		}
267 
268 		/* So, now the surface is checked... check the slope of said surface. */
269 		int allowed_z;
270 		if (GetTileSlope(tile, &allowed_z) != SLOPE_FLAT) allowed_z++;
271 
272 		for (TileIndex t : ta) {
273 			uint16 callback = CALLBACK_FAILED;
274 			if (HasBit(spec->callback_mask, CBM_OBJ_SLOPE_CHECK)) {
275 				TileIndex diff = t - tile;
276 				callback = GetObjectCallback(CBID_OBJECT_LAND_SLOPE_CHECK, GetTileSlope(t), TileY(diff) << 4 | TileX(diff), spec, nullptr, t, view);
277 			}
278 
279 			if (callback == CALLBACK_FAILED) {
280 				cost.AddCost(CheckBuildableTile(t, 0, allowed_z, false, false));
281 			} else {
282 				/* The meaning of bit 10 is inverted for a grf version < 8. */
283 				if (spec->grf_prop.grffile->grf_version < 8) ToggleBit(callback, 10);
284 				CommandCost ret = GetErrorMessageFromLocationCallbackResult(callback, spec->grf_prop.grffile, STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION);
285 				if (ret.Failed()) return ret;
286 			}
287 		}
288 
289 		if (flags & DC_EXEC) {
290 			/* This is basically a copy of the loop above with the exception that we now
291 			 * execute the commands and don't check for errors, since that's already done. */
292 			for (TileIndex t : ta) {
293 				if (HasTileWaterGround(t)) {
294 					if (!IsWaterTile(t)) {
295 						DoCommand(t, 0, 0, (flags & ~DC_NO_WATER) | DC_NO_MODIFY_TOWN_RATING, CMD_LANDSCAPE_CLEAR);
296 					}
297 				} else {
298 					DoCommand(t, 0, 0, flags | DC_NO_MODIFY_TOWN_RATING, CMD_LANDSCAPE_CLEAR);
299 				}
300 			}
301 		}
302 	}
303 	if (cost.Failed()) return cost;
304 
305 	/* Finally do a check for bridges. */
306 	for (TileIndex t : ta) {
307 		if (IsBridgeAbove(t) && (
308 				!(spec->flags & OBJECT_FLAG_ALLOW_UNDER_BRIDGE) ||
309 				(GetTileMaxZ(t) + spec->height >= GetBridgeHeight(GetSouthernBridgeEnd(t))))) {
310 			return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
311 		}
312 	}
313 
314 	int hq_score = 0;
315 	switch (type) {
316 		case OBJECT_TRANSMITTER:
317 		case OBJECT_LIGHTHOUSE:
318 			if (!IsTileFlat(tile)) return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED);
319 			break;
320 
321 		case OBJECT_OWNED_LAND:
322 			if (IsTileType(tile, MP_OBJECT) &&
323 					IsTileOwner(tile, _current_company) &&
324 					IsObjectType(tile, OBJECT_OWNED_LAND)) {
325 				return_cmd_error(STR_ERROR_YOU_ALREADY_OWN_IT);
326 			}
327 			break;
328 
329 		case OBJECT_HQ: {
330 			Company *c = Company::Get(_current_company);
331 			if (c->location_of_HQ != INVALID_TILE) {
332 				/* We need to persuade a bit harder to remove the old HQ. */
333 				_current_company = OWNER_WATER;
334 				cost.AddCost(ClearTile_Object(c->location_of_HQ, flags));
335 				_current_company = c->index;
336 			}
337 
338 			if (flags & DC_EXEC) {
339 				hq_score = UpdateCompanyRatingAndValue(c, false);
340 				c->location_of_HQ = tile;
341 				SetWindowDirty(WC_COMPANY, c->index);
342 			}
343 			break;
344 		}
345 
346 		case OBJECT_STATUE:
347 			/* This may never be constructed using this method. */
348 			return CMD_ERROR;
349 
350 		default: // i.e. NewGRF provided.
351 			break;
352 	}
353 
354 	if (flags & DC_EXEC) {
355 		BuildObject(type, tile, _current_company == OWNER_DEITY ? OWNER_NONE : _current_company, nullptr, view);
356 
357 		/* Make sure the HQ starts at the right size. */
358 		if (type == OBJECT_HQ) UpdateCompanyHQ(tile, hq_score);
359 	}
360 
361 	cost.AddCost(ObjectSpec::Get(type)->GetBuildCost() * size_x * size_y);
362 	return cost;
363 }
364 
365 
366 static Foundation GetFoundation_Object(TileIndex tile, Slope tileh);
367 
DrawTile_Object(TileInfo * ti)368 static void DrawTile_Object(TileInfo *ti)
369 {
370 	ObjectType type = GetObjectType(ti->tile);
371 	const ObjectSpec *spec = ObjectSpec::Get(type);
372 
373 	/* Fall back for when the object doesn't exist anymore. */
374 	if (!spec->enabled) type = OBJECT_TRANSMITTER;
375 
376 	if ((spec->flags & OBJECT_FLAG_HAS_NO_FOUNDATION) == 0) DrawFoundation(ti, GetFoundation_Object(ti->tile, ti->tileh));
377 
378 	if (type < NEW_OBJECT_OFFSET) {
379 		const DrawTileSprites *dts = nullptr;
380 		Owner to = GetTileOwner(ti->tile);
381 		PaletteID palette = to == OWNER_NONE ? PAL_NONE : COMPANY_SPRITE_COLOUR(to);
382 
383 		if (type == OBJECT_HQ) {
384 			TileIndex diff = ti->tile - Object::GetByTile(ti->tile)->location.tile;
385 			dts = &_object_hq[GetCompanyHQSize(ti->tile) << 2 | TileY(diff) << 1 | TileX(diff)];
386 		} else {
387 			dts = &_objects[type];
388 		}
389 
390 		if (spec->flags & OBJECT_FLAG_HAS_NO_FOUNDATION) {
391 			/* If an object has no foundation, but tries to draw a (flat) ground
392 			 * type... we have to be nice and convert that for them. */
393 			switch (dts->ground.sprite) {
394 				case SPR_FLAT_BARE_LAND:          DrawClearLandTile(ti, 0); break;
395 				case SPR_FLAT_1_THIRD_GRASS_TILE: DrawClearLandTile(ti, 1); break;
396 				case SPR_FLAT_2_THIRD_GRASS_TILE: DrawClearLandTile(ti, 2); break;
397 				case SPR_FLAT_GRASS_TILE:         DrawClearLandTile(ti, 3); break;
398 				default: DrawGroundSprite(dts->ground.sprite, palette);     break;
399 			}
400 		} else {
401 			DrawGroundSprite(dts->ground.sprite, palette);
402 		}
403 
404 		if (!IsInvisibilitySet(TO_STRUCTURES)) {
405 			const DrawTileSeqStruct *dtss;
406 			foreach_draw_tile_seq(dtss, dts->seq) {
407 				AddSortableSpriteToDraw(
408 					dtss->image.sprite, palette,
409 					ti->x + dtss->delta_x, ti->y + dtss->delta_y,
410 					dtss->size_x, dtss->size_y,
411 					dtss->size_z, ti->z + dtss->delta_z,
412 					IsTransparencySet(TO_STRUCTURES)
413 				);
414 			}
415 		}
416 	} else {
417 		DrawNewObjectTile(ti, spec);
418 	}
419 
420 	DrawBridgeMiddle(ti);
421 }
422 
GetSlopePixelZ_Object(TileIndex tile,uint x,uint y)423 static int GetSlopePixelZ_Object(TileIndex tile, uint x, uint y)
424 {
425 	if (IsObjectType(tile, OBJECT_OWNED_LAND)) {
426 		int z;
427 		Slope tileh = GetTilePixelSlope(tile, &z);
428 
429 		return z + GetPartialPixelZ(x & 0xF, y & 0xF, tileh);
430 	} else {
431 		return GetTileMaxPixelZ(tile);
432 	}
433 }
434 
GetFoundation_Object(TileIndex tile,Slope tileh)435 static Foundation GetFoundation_Object(TileIndex tile, Slope tileh)
436 {
437 	return IsObjectType(tile, OBJECT_OWNED_LAND) ? FOUNDATION_NONE : FlatteningFoundation(tileh);
438 }
439 
440 /**
441  * Perform the actual removal of the object from the map.
442  * @param o The object to really clear.
443  */
ReallyClearObjectTile(Object * o)444 static void ReallyClearObjectTile(Object *o)
445 {
446 	Object::DecTypeCount(o->type);
447 	for (TileIndex tile_cur : o->location) {
448 		DeleteNewGRFInspectWindow(GSF_OBJECTS, tile_cur);
449 
450 		MakeWaterKeepingClass(tile_cur, GetTileOwner(tile_cur));
451 	}
452 	delete o;
453 }
454 
455 std::vector<ClearedObjectArea> _cleared_object_areas;
456 
457 /**
458  * Find the entry in _cleared_object_areas which occupies a certain tile.
459  * @param tile Tile of interest
460  * @return Occupying entry, or nullptr if none
461  */
FindClearedObject(TileIndex tile)462 ClearedObjectArea *FindClearedObject(TileIndex tile)
463 {
464 	TileArea ta = TileArea(tile, 1, 1);
465 
466 	for (ClearedObjectArea &coa : _cleared_object_areas) {
467 		if (coa.area.Intersects(ta)) return &coa;
468 	}
469 
470 	return nullptr;
471 }
472 
ClearTile_Object(TileIndex tile,DoCommandFlag flags)473 static CommandCost ClearTile_Object(TileIndex tile, DoCommandFlag flags)
474 {
475 	/* Get to the northern most tile. */
476 	Object *o = Object::GetByTile(tile);
477 	TileArea ta = o->location;
478 
479 	ObjectType type = o->type;
480 	const ObjectSpec *spec = ObjectSpec::Get(type);
481 
482 	CommandCost cost(EXPENSES_CONSTRUCTION, spec->GetClearCost() * ta.w * ta.h / 5);
483 	if (spec->flags & OBJECT_FLAG_CLEAR_INCOME) cost.MultiplyCost(-1); // They get an income!
484 
485 	/* Towns can't remove any objects. */
486 	if (_current_company == OWNER_TOWN) return CMD_ERROR;
487 
488 	/* Water can remove everything! */
489 	if (_current_company != OWNER_WATER) {
490 		if ((flags & DC_NO_WATER) && IsTileOnWater(tile)) {
491 			/* There is water under the object, treat it as water tile. */
492 			return_cmd_error(STR_ERROR_CAN_T_BUILD_ON_WATER);
493 		} else if (!(spec->flags & OBJECT_FLAG_AUTOREMOVE) && (flags & DC_AUTO)) {
494 			/* No automatic removal by overbuilding stuff. */
495 			return_cmd_error(type == OBJECT_HQ ? STR_ERROR_COMPANY_HEADQUARTERS_IN : STR_ERROR_OBJECT_IN_THE_WAY);
496 		} else if (_game_mode == GM_EDITOR) {
497 			/* No further limitations for the editor. */
498 		} else if (GetTileOwner(tile) == OWNER_NONE) {
499 			/* Owned by nobody and unremovable, so we can only remove it with brute force! */
500 			if (!_cheats.magic_bulldozer.value && (spec->flags & OBJECT_FLAG_CANNOT_REMOVE) != 0) return CMD_ERROR;
501 		} else if (CheckTileOwnership(tile).Failed()) {
502 			/* We don't own it!. */
503 			return_cmd_error(STR_ERROR_OWNED_BY);
504 		} else if ((spec->flags & OBJECT_FLAG_CANNOT_REMOVE) != 0 && (spec->flags & OBJECT_FLAG_AUTOREMOVE) == 0) {
505 			/* In the game editor or with cheats we can remove, otherwise we can't. */
506 			if (!_cheats.magic_bulldozer.value) {
507 				if (type == OBJECT_HQ) return_cmd_error(STR_ERROR_COMPANY_HEADQUARTERS_IN);
508 				return CMD_ERROR;
509 			}
510 
511 			/* Removing with the cheat costs more in TTDPatch / the specs. */
512 			cost.MultiplyCost(25);
513 		}
514 	} else if ((spec->flags & (OBJECT_FLAG_BUILT_ON_WATER | OBJECT_FLAG_NOT_ON_LAND)) != 0) {
515 		/* Water can't remove objects that are buildable on water. */
516 		return CMD_ERROR;
517 	}
518 
519 	switch (type) {
520 		case OBJECT_HQ: {
521 			Company *c = Company::Get(GetTileOwner(tile));
522 			if (flags & DC_EXEC) {
523 				c->location_of_HQ = INVALID_TILE; // reset HQ position
524 				SetWindowDirty(WC_COMPANY, c->index);
525 				CargoPacket::InvalidateAllFrom(ST_HEADQUARTERS, c->index);
526 			}
527 
528 			/* cost of relocating company is 1% of company value */
529 			cost = CommandCost(EXPENSES_CONSTRUCTION, CalculateCompanyValue(c) / 100);
530 			break;
531 		}
532 
533 		case OBJECT_STATUE:
534 			if (flags & DC_EXEC) {
535 				Town *town = o->town;
536 				ClrBit(town->statues, GetTileOwner(tile));
537 				SetWindowDirty(WC_TOWN_AUTHORITY, town->index);
538 			}
539 			break;
540 
541 		default:
542 			break;
543 	}
544 
545 	_cleared_object_areas.push_back({tile, ta});
546 
547 	if (flags & DC_EXEC) ReallyClearObjectTile(o);
548 
549 	return cost;
550 }
551 
AddAcceptedCargo_Object(TileIndex tile,CargoArray & acceptance,CargoTypes * always_accepted)552 static void AddAcceptedCargo_Object(TileIndex tile, CargoArray &acceptance, CargoTypes *always_accepted)
553 {
554 	if (!IsObjectType(tile, OBJECT_HQ)) return;
555 
556 	/* HQ accepts passenger and mail; but we have to divide the values
557 	 * between 4 tiles it occupies! */
558 
559 	/* HQ level (depends on company performance) in the range 1..5. */
560 	uint level = GetCompanyHQSize(tile) + 1;
561 
562 	/* Top town building generates 10, so to make HQ interesting, the top
563 	 * type makes 20. */
564 	acceptance[CT_PASSENGERS] += std::max(1U, level);
565 	SetBit(*always_accepted, CT_PASSENGERS);
566 
567 	/* Top town building generates 4, HQ can make up to 8. The
568 	 * proportion passengers:mail is different because such a huge
569 	 * commercial building generates unusually high amount of mail
570 	 * correspondence per physical visitor. */
571 	acceptance[CT_MAIL] += std::max(1U, level / 2);
572 	SetBit(*always_accepted, CT_MAIL);
573 }
574 
AddProducedCargo_Object(TileIndex tile,CargoArray & produced)575 static void AddProducedCargo_Object(TileIndex tile, CargoArray &produced)
576 {
577 	if (!IsObjectType(tile, OBJECT_HQ)) return;
578 
579 	produced[CT_PASSENGERS]++;
580 	produced[CT_MAIL]++;
581 }
582 
583 
GetTileDesc_Object(TileIndex tile,TileDesc * td)584 static void GetTileDesc_Object(TileIndex tile, TileDesc *td)
585 {
586 	const ObjectSpec *spec = ObjectSpec::GetByTile(tile);
587 	td->str = spec->name;
588 	td->owner[0] = GetTileOwner(tile);
589 	td->build_date = Object::GetByTile(tile)->build_date;
590 
591 	if (spec->grf_prop.grffile != nullptr) {
592 		td->grf = GetGRFConfig(spec->grf_prop.grffile->grfid)->GetName();
593 	}
594 }
595 
TileLoop_Object(TileIndex tile)596 static void TileLoop_Object(TileIndex tile)
597 {
598 	const ObjectSpec *spec = ObjectSpec::GetByTile(tile);
599 	if (spec->flags & OBJECT_FLAG_ANIMATION) {
600 		Object *o = Object::GetByTile(tile);
601 		TriggerObjectTileAnimation(o, tile, OAT_TILELOOP, spec);
602 		if (o->location.tile == tile) TriggerObjectAnimation(o, OAT_256_TICKS, spec);
603 	}
604 
605 	if (IsTileOnWater(tile)) TileLoop_Water(tile);
606 
607 	if (!IsObjectType(tile, OBJECT_HQ)) return;
608 
609 	/* HQ accepts passenger and mail; but we have to divide the values
610 	 * between 4 tiles it occupies! */
611 
612 	/* HQ level (depends on company performance) in the range 1..5. */
613 	uint level = GetCompanyHQSize(tile) + 1;
614 	assert(level < 6);
615 
616 	StationFinder stations(TileArea(tile, 2, 2));
617 
618 	uint r = Random();
619 	/* Top town buildings generate 250, so the top HQ type makes 256. */
620 	if (GB(r, 0, 8) < (256 / 4 / (6 - level))) {
621 		uint amt = GB(r, 0, 8) / 8 / 4 + 1;
622 		if (EconomyIsInRecession()) amt = (amt + 1) >> 1;
623 		MoveGoodsToStation(CT_PASSENGERS, amt, ST_HEADQUARTERS, GetTileOwner(tile), stations.GetStations());
624 	}
625 
626 	/* Top town building generates 90, HQ can make up to 196. The
627 	 * proportion passengers:mail is about the same as in the acceptance
628 	 * equations. */
629 	if (GB(r, 8, 8) < (196 / 4 / (6 - level))) {
630 		uint amt = GB(r, 8, 8) / 8 / 4 + 1;
631 		if (EconomyIsInRecession()) amt = (amt + 1) >> 1;
632 		MoveGoodsToStation(CT_MAIL, amt, ST_HEADQUARTERS, GetTileOwner(tile), stations.GetStations());
633 	}
634 }
635 
636 
GetTileTrackStatus_Object(TileIndex tile,TransportType mode,uint sub_mode,DiagDirection side)637 static TrackStatus GetTileTrackStatus_Object(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
638 {
639 	return 0;
640 }
641 
ClickTile_Object(TileIndex tile)642 static bool ClickTile_Object(TileIndex tile)
643 {
644 	if (!IsObjectType(tile, OBJECT_HQ)) return false;
645 
646 	ShowCompany(GetTileOwner(tile));
647 	return true;
648 }
649 
AnimateTile_Object(TileIndex tile)650 static void AnimateTile_Object(TileIndex tile)
651 {
652 	AnimateNewObjectTile(tile);
653 }
654 
655 /**
656  * Helper function for \c CircularTileSearch.
657  * @param tile The tile to check.
658  * @param user Ignored.
659  * @return True iff the tile has a radio tower.
660  */
HasTransmitter(TileIndex tile,void * user)661 static bool HasTransmitter(TileIndex tile, void *user)
662 {
663 	return IsObjectTypeTile(tile, OBJECT_TRANSMITTER);
664 }
665 
666 /**
667  * Try to build a lighthouse.
668  * @return True iff building a lighthouse succeeded.
669  */
TryBuildLightHouse()670 static bool TryBuildLightHouse()
671 {
672 	uint maxx = MapMaxX();
673 	uint maxy = MapMaxY();
674 	uint r = Random();
675 
676 	/* Scatter the lighthouses more evenly around the perimeter */
677 	int perimeter = (GB(r, 16, 16) % (2 * (maxx + maxy))) - maxy;
678 	DiagDirection dir;
679 	for (dir = DIAGDIR_NE; perimeter > 0; dir++) {
680 		perimeter -= (DiagDirToAxis(dir) == AXIS_X) ? maxx : maxy;
681 	}
682 
683 	TileIndex tile;
684 	switch (dir) {
685 		default:
686 		case DIAGDIR_NE: tile = TileXY(maxx - 1, r % maxy); break;
687 		case DIAGDIR_SE: tile = TileXY(r % maxx, 1); break;
688 		case DIAGDIR_SW: tile = TileXY(1,        r % maxy); break;
689 		case DIAGDIR_NW: tile = TileXY(r % maxx, maxy - 1); break;
690 	}
691 
692 	/* Only build lighthouses at tiles where the border is sea. */
693 	if (!IsTileType(tile, MP_WATER)) return false;
694 
695 	for (int j = 0; j < 19; j++) {
696 		int h;
697 		if (IsTileType(tile, MP_CLEAR) && IsTileFlat(tile, &h) && h <= 2 && !IsBridgeAbove(tile)) {
698 			BuildObject(OBJECT_LIGHTHOUSE, tile);
699 			assert(tile < MapSize());
700 			return true;
701 		}
702 		tile += TileOffsByDiagDir(dir);
703 		if (!IsValidTile(tile)) return false;
704 	}
705 	return false;
706 }
707 
708 /**
709  * Try to build a transmitter.
710  * @return True iff a transmitter was built.
711  */
TryBuildTransmitter()712 static bool TryBuildTransmitter()
713 {
714 	TileIndex tile = RandomTile();
715 	int h;
716 	if (IsTileType(tile, MP_CLEAR) && IsTileFlat(tile, &h) && h >= 4 && !IsBridgeAbove(tile)) {
717 		TileIndex t = tile;
718 		if (CircularTileSearch(&t, 9, HasTransmitter, nullptr)) return false;
719 
720 		BuildObject(OBJECT_TRANSMITTER, tile);
721 		return true;
722 	}
723 	return false;
724 }
725 
GenerateObjects()726 void GenerateObjects()
727 {
728 	/* Set a guestimate on how much we progress */
729 	SetGeneratingWorldProgress(GWP_OBJECT, NUM_OBJECTS);
730 
731 	/* Determine number of water tiles at map border needed for freeform_edges */
732 	uint num_water_tiles = 0;
733 	if (_settings_game.construction.freeform_edges) {
734 		for (uint x = 0; x < MapMaxX(); x++) {
735 			if (IsTileType(TileXY(x, 1), MP_WATER)) num_water_tiles++;
736 			if (IsTileType(TileXY(x, MapMaxY() - 1), MP_WATER)) num_water_tiles++;
737 		}
738 		for (uint y = 1; y < MapMaxY() - 1; y++) {
739 			if (IsTileType(TileXY(1, y), MP_WATER)) num_water_tiles++;
740 			if (IsTileType(TileXY(MapMaxX() - 1, y), MP_WATER)) num_water_tiles++;
741 		}
742 	}
743 
744 	/* Iterate over all possible object types */
745 	for (uint i = 0; i < NUM_OBJECTS; i++) {
746 		const ObjectSpec *spec = ObjectSpec::Get(i);
747 
748 		/* Continue, if the object was never available till now or shall not be placed */
749 		if (!spec->WasEverAvailable() || spec->generate_amount == 0) continue;
750 
751 		uint16 amount = spec->generate_amount;
752 
753 		/* Scale by map size */
754 		if ((spec->flags & OBJECT_FLAG_SCALE_BY_WATER) && _settings_game.construction.freeform_edges) {
755 			/* Scale the amount of lighthouses with the amount of land at the borders.
756 			 * The -6 is because the top borders are MP_VOID (-2) and all corners
757 			 * are counted twice (-4). */
758 			amount = ScaleByMapSize1D(amount * num_water_tiles) / (2 * MapMaxY() + 2 * MapMaxX() - 6);
759 		} else if (spec->flags & OBJECT_FLAG_SCALE_BY_WATER) {
760 			amount = ScaleByMapSize1D(amount);
761 		} else {
762 			amount = ScaleByMapSize(amount);
763 		}
764 
765 		/* Now try to place the requested amount of this object */
766 		for (uint j = ScaleByMapSize(1000); j != 0 && amount != 0 && Object::CanAllocateItem(); j--) {
767 			switch (i) {
768 				case OBJECT_TRANSMITTER:
769 					if (TryBuildTransmitter()) amount--;
770 					break;
771 
772 				case OBJECT_LIGHTHOUSE:
773 					if (TryBuildLightHouse()) amount--;
774 					break;
775 
776 				default:
777 					uint8 view = RandomRange(spec->views);
778 					if (CmdBuildObject(RandomTile(), DC_EXEC | DC_AUTO | DC_NO_TEST_TOWN_RATING | DC_NO_MODIFY_TOWN_RATING, i, view, {}).Succeeded()) amount--;
779 					break;
780 			}
781 		}
782 		IncreaseGeneratingWorldProgress(GWP_OBJECT);
783 	}
784 }
785 
ChangeTileOwner_Object(TileIndex tile,Owner old_owner,Owner new_owner)786 static void ChangeTileOwner_Object(TileIndex tile, Owner old_owner, Owner new_owner)
787 {
788 	if (!IsTileOwner(tile, old_owner)) return;
789 
790 	bool do_clear = false;
791 
792 	ObjectType type = GetObjectType(tile);
793 	if ((type == OBJECT_OWNED_LAND || type >= NEW_OBJECT_OFFSET) && new_owner != INVALID_OWNER) {
794 		SetTileOwner(tile, new_owner);
795 	} else if (type == OBJECT_STATUE) {
796 		Town *t = Object::GetByTile(tile)->town;
797 		ClrBit(t->statues, old_owner);
798 		if (new_owner != INVALID_OWNER && !HasBit(t->statues, new_owner)) {
799 			/* Transfer ownership to the new company */
800 			SetBit(t->statues, new_owner);
801 			SetTileOwner(tile, new_owner);
802 		} else {
803 			do_clear = true;
804 		}
805 
806 		SetWindowDirty(WC_TOWN_AUTHORITY, t->index);
807 	} else {
808 		do_clear = true;
809 	}
810 
811 	if (do_clear) {
812 		ReallyClearObjectTile(Object::GetByTile(tile));
813 		/* When clearing objects, they may turn into canal, which may require transferring ownership. */
814 		ChangeTileOwner(tile, old_owner, new_owner);
815 	}
816 }
817 
TerraformTile_Object(TileIndex tile,DoCommandFlag flags,int z_new,Slope tileh_new)818 static CommandCost TerraformTile_Object(TileIndex tile, DoCommandFlag flags, int z_new, Slope tileh_new)
819 {
820 	ObjectType type = GetObjectType(tile);
821 
822 	if (type == OBJECT_OWNED_LAND) {
823 		/* Owned land remains unsold */
824 		CommandCost ret = CheckTileOwnership(tile);
825 		if (ret.Succeeded()) return CommandCost();
826 	} else if (AutoslopeEnabled() && type != OBJECT_TRANSMITTER && type != OBJECT_LIGHTHOUSE) {
827 		/* Behaviour:
828 		 *  - Both new and old slope must not be steep.
829 		 *  - TileMaxZ must not be changed.
830 		 *  - Allow autoslope by default.
831 		 *  - Disallow autoslope if callback succeeds and returns non-zero.
832 		 */
833 		Slope tileh_old = GetTileSlope(tile);
834 		/* TileMaxZ must not be changed. Slopes must not be steep. */
835 		if (!IsSteepSlope(tileh_old) && !IsSteepSlope(tileh_new) && (GetTileMaxZ(tile) == z_new + GetSlopeMaxZ(tileh_new))) {
836 			const ObjectSpec *spec = ObjectSpec::Get(type);
837 
838 			/* Call callback 'disable autosloping for objects'. */
839 			if (HasBit(spec->callback_mask, CBM_OBJ_AUTOSLOPE)) {
840 				/* If the callback fails, allow autoslope. */
841 				uint16 res = GetObjectCallback(CBID_OBJECT_AUTOSLOPE, 0, 0, spec, Object::GetByTile(tile), tile);
842 				if (res == CALLBACK_FAILED || !ConvertBooleanCallback(spec->grf_prop.grffile, CBID_OBJECT_AUTOSLOPE, res)) return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
843 			} else if (spec->enabled) {
844 				/* allow autoslope */
845 				return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
846 			}
847 		}
848 	}
849 
850 	return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
851 }
852 
853 extern const TileTypeProcs _tile_type_object_procs = {
854 	DrawTile_Object,             // draw_tile_proc
855 	GetSlopePixelZ_Object,       // get_slope_z_proc
856 	ClearTile_Object,            // clear_tile_proc
857 	AddAcceptedCargo_Object,     // add_accepted_cargo_proc
858 	GetTileDesc_Object,          // get_tile_desc_proc
859 	GetTileTrackStatus_Object,   // get_tile_track_status_proc
860 	ClickTile_Object,            // click_tile_proc
861 	AnimateTile_Object,          // animate_tile_proc
862 	TileLoop_Object,             // tile_loop_proc
863 	ChangeTileOwner_Object,      // change_tile_owner_proc
864 	AddProducedCargo_Object,     // add_produced_cargo_proc
865 	nullptr,                        // vehicle_enter_tile_proc
866 	GetFoundation_Object,        // get_foundation_proc
867 	TerraformTile_Object,        // terraform_tile_proc
868 };
869