(svn r25652) -Fix: Improve text caret movement for complex scripts.
[openttd/fttd.git] / src / object_cmd.cpp
blob9ba2ba83c7b2aab1c54251eb221cd1eb93f909fc
1 /* $Id$ */
3 /*
4 * This file is part of OpenTTD.
5 * 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.
6 * 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.
7 * 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 */
10 /** @file object_cmd.cpp Handling of object tiles. */
12 #include "stdafx.h"
13 #include "landscape.h"
14 #include "command_func.h"
15 #include "viewport_func.h"
16 #include "company_base.h"
17 #include "town.h"
18 #include "bridge_map.h"
19 #include "genworld.h"
20 #include "autoslope.h"
21 #include "clear_func.h"
22 #include "water.h"
23 #include "window_func.h"
24 #include "company_gui.h"
25 #include "cheat_type.h"
26 #include "object.h"
27 #include "cargopacket.h"
28 #include "core/random_func.hpp"
29 #include "core/pool_func.hpp"
30 #include "object_map.h"
31 #include "object_base.h"
32 #include "newgrf_config.h"
33 #include "newgrf_object.h"
34 #include "date_func.h"
35 #include "newgrf_debug.h"
36 #include "vehicle_func.h"
38 #include "table/strings.h"
39 #include "table/object_land.h"
41 ObjectPool _object_pool("Object");
42 INSTANTIATE_POOL_METHODS(Object)
43 uint16 Object::counts[NUM_OBJECTS];
45 /**
46 * Get the object associated with a tile.
47 * @param tile The tile to fetch the object for.
48 * @return The object.
50 /* static */ Object *Object::GetByTile(TileIndex tile)
52 return Object::Get(GetObjectIndex(tile));
55 /** Initialize/reset the objects. */
56 void InitializeObjects()
58 Object::ResetTypeCounts();
61 /**
62 * Actually build the object.
63 * @param type The type of object to build.
64 * @param tile The tile to build the northern tile of the object on.
65 * @param owner The owner of the object.
66 * @param town Town the tile is related with.
67 * @param view The view for the object.
68 * @pre All preconditions for building the object at that location
69 * are met, e.g. slope and clearness of tiles are checked.
71 void BuildObject(ObjectType type, TileIndex tile, CompanyID owner, Town *town, uint8 view)
73 const ObjectSpec *spec = ObjectSpec::Get(type);
75 TileArea ta(tile, GB(spec->size, HasBit(view, 0) ? 4 : 0, 4), GB(spec->size, HasBit(view, 0) ? 0 : 4, 4));
76 Object *o = new Object();
77 o->location = ta;
78 o->town = town == NULL ? CalcClosestTownFromTile(tile) : town;
79 o->build_date = _date;
80 o->view = view;
82 /* If nothing owns the object, the colour will be random. Otherwise
83 * get the colour from the company's livery settings. */
84 if (owner == OWNER_NONE) {
85 o->colour = Random();
86 } else {
87 const Livery *l = Company::Get(owner)->livery;
88 o->colour = l->colour1 + l->colour2 * 16;
91 /* If the object wants only one colour, then give it that colour. */
92 if ((spec->flags & OBJECT_FLAG_2CC_COLOUR) == 0) o->colour &= 0xF;
94 if (HasBit(spec->callback_mask, CBM_OBJ_COLOUR)) {
95 uint16 res = GetObjectCallback(CBID_OBJECT_COLOUR, o->colour, 0, spec, o, tile);
96 if (res != CALLBACK_FAILED) {
97 if (res >= 0x100) ErrorUnknownCallbackResult(spec->grf_prop.grffile->grfid, CBID_OBJECT_COLOUR, res);
98 o->colour = GB(res, 0, 8);
102 assert(o->town != NULL);
104 TILE_AREA_LOOP(t, ta) {
105 WaterClass wc = (IsWaterTile(t) ? GetWaterClass(t) : WATER_CLASS_INVALID);
106 /* Update company infrastructure counts for objects build on canals owned by nobody. */
107 if (wc == WATER_CLASS_CANAL && owner != OWNER_NONE && (IsTileOwner(tile, OWNER_NONE) || IsTileOwner(tile, OWNER_WATER))) {
108 Company::Get(owner)->infrastructure.water++;
109 DirtyCompanyInfrastructureWindows(owner);
111 MakeObject(t, type, owner, o->index, wc, Random());
112 MarkTileDirtyByTile(t);
115 Object::IncTypeCount(type);
116 if (spec->flags & OBJECT_FLAG_ANIMATION) TriggerObjectAnimation(o, OAT_BUILT, spec);
120 * Increase the animation stage of a whole structure.
121 * @param tile The tile of the structure.
123 static void IncreaseAnimationStage(TileIndex tile)
125 TileArea ta = Object::GetByTile(tile)->location;
126 TILE_AREA_LOOP(t, ta) {
127 SetAnimationFrame(t, GetAnimationFrame(t) + 1);
128 MarkTileDirtyByTile(t);
132 /** We encode the company HQ size in the animation stage. */
133 #define GetCompanyHQSize GetAnimationFrame
134 /** We encode the company HQ size in the animation stage. */
135 #define IncreaseCompanyHQSize IncreaseAnimationStage
138 * Update the CompanyHQ to the state associated with the given score
139 * @param tile The (northern) tile of the company HQ, or INVALID_TILE.
140 * @param score The current (performance) score of the company.
142 void UpdateCompanyHQ(TileIndex tile, uint score)
144 if (tile == INVALID_TILE) return;
146 byte val;
147 (val = 0, score < 170) ||
148 (val++, score < 350) ||
149 (val++, score < 520) ||
150 (val++, score < 720) ||
151 (val++, true);
153 while (GetCompanyHQSize(tile) < val) {
154 IncreaseCompanyHQSize(tile);
159 * Updates the colour of the object whenever a company changes.
160 * @param c The company the company colour changed of.
162 void UpdateObjectColours(const Company *c)
164 Object *obj;
165 FOR_ALL_OBJECTS(obj) {
166 Owner owner = GetTileOwner(obj->location.tile);
167 /* Not the current owner, so colour doesn't change. */
168 if (owner != c->index) continue;
170 const ObjectSpec *spec = ObjectSpec::GetByTile(obj->location.tile);
171 /* Using the object colour callback, so not using company colour. */
172 if (HasBit(spec->callback_mask, CBM_OBJ_COLOUR)) continue;
174 const Livery *l = c->livery;
175 obj->colour = ((spec->flags & OBJECT_FLAG_2CC_COLOUR) ? (l->colour2 * 16) : 0) + l->colour1;
179 extern CommandCost CheckBuildableTile(TileIndex tile, uint invalid_dirs, int &allowed_z, bool allow_steep, bool check_bridge);
180 static CommandCost ClearTile_Object(TileIndex tile, DoCommandFlag flags);
183 * Build an object object
184 * @param tile tile where the object will be located
185 * @param flags type of operation
186 * @param p1 the object type to build
187 * @param p2 the view for the object
188 * @param text unused
189 * @return the cost of this operation or an error
191 CommandCost CmdBuildObject(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
193 CommandCost cost(EXPENSES_PROPERTY);
195 ObjectType type = (ObjectType)GB(p1, 0, 8);
196 uint8 view = GB(p2, 0, 2);
197 const ObjectSpec *spec = ObjectSpec::Get(type);
198 if (!spec->IsAvailable()) return CMD_ERROR;
200 if (spec->flags & OBJECT_FLAG_ONLY_IN_SCENEDIT && (_game_mode != GM_EDITOR || _current_company != OWNER_NONE)) return CMD_ERROR;
201 if (spec->flags & OBJECT_FLAG_ONLY_IN_GAME && (_game_mode != GM_NORMAL || _current_company > MAX_COMPANIES)) return CMD_ERROR;
202 if (view >= spec->views) return CMD_ERROR;
204 if (!Object::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_OBJECTS);
205 if (Town::GetNumItems() == 0) return_cmd_error(STR_ERROR_MUST_FOUND_TOWN_FIRST);
207 int size_x = GB(spec->size, HasBit(view, 0) ? 4 : 0, 4);
208 int size_y = GB(spec->size, HasBit(view, 0) ? 0 : 4, 4);
209 TileArea ta(tile, size_x, size_y);
211 if (type == OBJECT_OWNED_LAND) {
212 /* Owned land is special as it can be placed on any slope. */
213 cost.AddCost(DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR));
214 } else {
215 /* Check the surface to build on. At this time we can't actually execute the
216 * the CLEAR_TILE commands since the newgrf callback later on can check
217 * some information about the tiles. */
218 bool allow_water = (spec->flags & (OBJECT_FLAG_BUILT_ON_WATER | OBJECT_FLAG_NOT_ON_LAND)) != 0;
219 bool allow_ground = (spec->flags & OBJECT_FLAG_NOT_ON_LAND) == 0;
220 TILE_AREA_LOOP(t, ta) {
221 if (HasTileWaterGround(t)) {
222 if (!allow_water) return_cmd_error(STR_ERROR_CAN_T_BUILD_ON_WATER);
223 if (!IsWaterTile(t)) {
224 /* Normal water tiles don't have to be cleared. For all other tile types clear
225 * the tile but leave the water. */
226 cost.AddCost(DoCommand(t, 0, 0, flags & ~DC_NO_WATER & ~DC_EXEC, CMD_LANDSCAPE_CLEAR));
227 } else {
228 /* Can't build on water owned by another company. */
229 Owner o = GetTileOwner(t);
230 if (o != OWNER_NONE && o != OWNER_WATER) cost.AddCost(CheckOwnership(o, t));
232 /* However, the tile has to be clear of vehicles. */
233 cost.AddCost(EnsureNoVehicleOnGround(t));
235 } else {
236 if (!allow_ground) return_cmd_error(STR_ERROR_MUST_BE_BUILT_ON_WATER);
237 /* For non-water tiles, we'll have to clear it before building. */
238 cost.AddCost(DoCommand(t, 0, 0, flags & ~DC_EXEC, CMD_LANDSCAPE_CLEAR));
242 /* So, now the surface is checked... check the slope of said surface. */
243 int allowed_z;
244 if (GetTileSlope(tile, &allowed_z) != SLOPE_FLAT) allowed_z++;
246 TILE_AREA_LOOP(t, ta) {
247 uint16 callback = CALLBACK_FAILED;
248 if (HasBit(spec->callback_mask, CBM_OBJ_SLOPE_CHECK)) {
249 TileIndex diff = t - tile;
250 callback = GetObjectCallback(CBID_OBJECT_LAND_SLOPE_CHECK, GetTileSlope(t), TileY(diff) << 4 | TileX(diff), spec, NULL, t, view);
253 if (callback == CALLBACK_FAILED) {
254 cost.AddCost(CheckBuildableTile(t, 0, allowed_z, false, false));
255 } else {
256 /* The meaning of bit 10 is inverted for a grf version < 8. */
257 if (spec->grf_prop.grffile->grf_version < 8) ToggleBit(callback, 10);
258 CommandCost ret = GetErrorMessageFromLocationCallbackResult(callback, spec->grf_prop.grffile->grfid, STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION);
259 if (ret.Failed()) return ret;
263 if (flags & DC_EXEC) {
264 /* This is basically a copy of the loop above with the exception that we now
265 * execute the commands and don't check for errors, since that's already done. */
266 TILE_AREA_LOOP(t, ta) {
267 if (HasTileWaterGround(t)) {
268 if (!IsWaterTile(t)) {
269 DoCommand(t, 0, 0, (flags & ~DC_NO_WATER) | DC_NO_MODIFY_TOWN_RATING, CMD_LANDSCAPE_CLEAR);
271 } else {
272 DoCommand(t, 0, 0, flags | DC_NO_MODIFY_TOWN_RATING, CMD_LANDSCAPE_CLEAR);
277 if (cost.Failed()) return cost;
279 /* Finally do a check for bridges. */
280 TILE_AREA_LOOP(t, ta) {
281 if (MayHaveBridgeAbove(t) && IsBridgeAbove(t) && (
282 !(spec->flags & OBJECT_FLAG_ALLOW_UNDER_BRIDGE) ||
283 (GetTileMaxZ(t) + spec->height >= GetBridgeHeight(GetSouthernBridgeEnd(t))))) {
284 return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
288 int hq_score = 0;
289 switch (type) {
290 case OBJECT_TRANSMITTER:
291 case OBJECT_LIGHTHOUSE:
292 if (GetTileSlope(tile) != SLOPE_FLAT) return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED);
293 break;
295 case OBJECT_OWNED_LAND:
296 if (IsTileType(tile, MP_OBJECT) &&
297 IsTileOwner(tile, _current_company) &&
298 IsOwnedLand(tile)) {
299 return_cmd_error(STR_ERROR_YOU_ALREADY_OWN_IT);
301 break;
303 case OBJECT_HQ: {
304 Company *c = Company::Get(_current_company);
305 if (c->location_of_HQ != INVALID_TILE) {
306 /* We need to persuade a bit harder to remove the old HQ. */
307 _current_company = OWNER_WATER;
308 cost.AddCost(ClearTile_Object(c->location_of_HQ, flags));
309 _current_company = c->index;
312 if (flags & DC_EXEC) {
313 hq_score = UpdateCompanyRatingAndValue(c, false);
314 c->location_of_HQ = tile;
315 SetWindowDirty(WC_COMPANY, c->index);
317 break;
320 case OBJECT_STATUE:
321 /* This may never be constructed using this method. */
322 return CMD_ERROR;
324 default: // i.e. NewGRF provided.
325 break;
328 if (flags & DC_EXEC) {
329 BuildObject(type, tile, _current_company, NULL, view);
331 /* Make sure the HQ starts at the right size. */
332 if (type == OBJECT_HQ) UpdateCompanyHQ(tile, hq_score);
335 cost.AddCost(ObjectSpec::Get(type)->GetBuildCost() * size_x * size_y);
336 return cost;
340 static Foundation GetFoundation_Object(TileIndex tile, Slope tileh);
342 static void DrawTile_Object(TileInfo *ti)
344 ObjectType type = GetObjectType(ti->tile);
345 const ObjectSpec *spec = ObjectSpec::Get(type);
347 /* Fall back for when the object doesn't exist anymore. */
348 if (!spec->enabled) type = OBJECT_TRANSMITTER;
350 if ((spec->flags & OBJECT_FLAG_HAS_NO_FOUNDATION) == 0) DrawFoundation(ti, GetFoundation_Object(ti->tile, ti->tileh));
352 if (type < NEW_OBJECT_OFFSET) {
353 const DrawTileSprites *dts = NULL;
354 Owner to = GetTileOwner(ti->tile);
355 PaletteID palette = to == OWNER_NONE ? PAL_NONE : COMPANY_SPRITE_COLOUR(to);
357 if (type == OBJECT_HQ) {
358 TileIndex diff = ti->tile - Object::GetByTile(ti->tile)->location.tile;
359 dts = &_object_hq[GetCompanyHQSize(ti->tile) << 2 | TileY(diff) << 1 | TileX(diff)];
360 } else {
361 dts = &_objects[type];
364 if (spec->flags & OBJECT_FLAG_HAS_NO_FOUNDATION) {
365 /* If an object has no foundation, but tries to draw a (flat) ground
366 * type... we have to be nice and convert that for them. */
367 switch (dts->ground.sprite) {
368 case SPR_FLAT_BARE_LAND: DrawClearLandTile(ti, 0); break;
369 case SPR_FLAT_1_THIRD_GRASS_TILE: DrawClearLandTile(ti, 1); break;
370 case SPR_FLAT_2_THIRD_GRASS_TILE: DrawClearLandTile(ti, 2); break;
371 case SPR_FLAT_GRASS_TILE: DrawClearLandTile(ti, 3); break;
372 default: DrawGroundSprite(dts->ground.sprite, palette); break;
374 } else {
375 DrawGroundSprite(dts->ground.sprite, palette);
378 if (!IsInvisibilitySet(TO_STRUCTURES)) {
379 const DrawTileSeqStruct *dtss;
380 foreach_draw_tile_seq(dtss, dts->seq) {
381 AddSortableSpriteToDraw(
382 dtss->image.sprite, palette,
383 ti->x + dtss->delta_x, ti->y + dtss->delta_y,
384 dtss->size_x, dtss->size_y,
385 dtss->size_z, ti->z + dtss->delta_z,
386 IsTransparencySet(TO_STRUCTURES)
390 } else {
391 DrawNewObjectTile(ti, spec);
394 if (spec->flags & OBJECT_FLAG_ALLOW_UNDER_BRIDGE) DrawBridgeMiddle(ti);
397 static int GetSlopePixelZ_Object(TileIndex tile, uint x, uint y)
399 if (IsOwnedLand(tile)) {
400 int z;
401 Slope tileh = GetTilePixelSlope(tile, &z);
403 return z + GetPartialPixelZ(x & 0xF, y & 0xF, tileh);
404 } else {
405 return GetTileMaxPixelZ(tile);
409 static Foundation GetFoundation_Object(TileIndex tile, Slope tileh)
411 return IsOwnedLand(tile) ? FOUNDATION_NONE : FlatteningFoundation(tileh);
415 * Perform the actual removal of the object from the map.
416 * @param o The object to really clear.
418 static void ReallyClearObjectTile(Object *o)
420 Object::DecTypeCount(GetObjectType(o->location.tile));
421 TILE_AREA_LOOP(tile_cur, o->location) {
422 DeleteNewGRFInspectWindow(GSF_OBJECTS, tile_cur);
424 MakeWaterKeepingClass(tile_cur, GetTileOwner(tile_cur));
426 delete o;
429 SmallVector<ClearedObjectArea, 4> _cleared_object_areas;
432 * Find the entry in _cleared_object_areas which occupies a certain tile.
433 * @param tile Tile of interest
434 * @return Occupying entry, or NULL if none
436 ClearedObjectArea *FindClearedObject(TileIndex tile)
438 TileArea ta = TileArea(tile, 1, 1);
440 const ClearedObjectArea *end = _cleared_object_areas.End();
441 for (ClearedObjectArea *coa = _cleared_object_areas.Begin(); coa != end; coa++) {
442 if (coa->area.Intersects(ta)) return coa;
445 return NULL;
448 static CommandCost ClearTile_Object(TileIndex tile, DoCommandFlag flags)
450 ObjectType type = GetObjectType(tile);
451 const ObjectSpec *spec = ObjectSpec::Get(type);
453 /* Get to the northern most tile. */
454 Object *o = Object::GetByTile(tile);
455 TileArea ta = o->location;
457 CommandCost cost(EXPENSES_CONSTRUCTION, spec->GetClearCost() * ta.w * ta.h / 5);
458 if (spec->flags & OBJECT_FLAG_CLEAR_INCOME) cost.MultiplyCost(-1); // They get an income!
460 /* Towns can't remove any objects. */
461 if (_current_company == OWNER_TOWN) return CMD_ERROR;
463 /* Water can remove everything! */
464 if (_current_company != OWNER_WATER) {
465 if ((flags & DC_NO_WATER) && IsTileOnWater(tile)) {
466 /* There is water under the object, treat it as water tile. */
467 return_cmd_error(STR_ERROR_CAN_T_BUILD_ON_WATER);
468 } else if (!(spec->flags & OBJECT_FLAG_AUTOREMOVE) && (flags & DC_AUTO)) {
469 /* No automatic removal by overbuilding stuff. */
470 return_cmd_error(type == OBJECT_HQ ? STR_ERROR_COMPANY_HEADQUARTERS_IN : STR_ERROR_OBJECT_IN_THE_WAY);
471 } else if (_game_mode == GM_EDITOR) {
472 /* No further limitations for the editor. */
473 } else if (GetTileOwner(tile) == OWNER_NONE) {
474 /* Owned by nobody, so we can only remove it with brute force! */
475 if (!_cheats.magic_bulldozer.value) return CMD_ERROR;
476 } else if (CheckTileOwnership(tile).Failed()) {
477 /* We don't own it!. */
478 return_cmd_error(STR_ERROR_OWNED_BY);
479 } else if ((spec->flags & OBJECT_FLAG_CANNOT_REMOVE) != 0 && (spec->flags & OBJECT_FLAG_AUTOREMOVE) == 0) {
480 /* In the game editor or with cheats we can remove, otherwise we can't. */
481 if (!_cheats.magic_bulldozer.value) return CMD_ERROR;
483 /* Removing with the cheat costs more in TTDPatch / the specs. */
484 cost.MultiplyCost(25);
486 } else if ((spec->flags & (OBJECT_FLAG_BUILT_ON_WATER | OBJECT_FLAG_NOT_ON_LAND)) != 0) {
487 /* Water can't remove objects that are buildable on water. */
488 return CMD_ERROR;
491 switch (type) {
492 case OBJECT_HQ: {
493 Company *c = Company::Get(GetTileOwner(tile));
494 if (flags & DC_EXEC) {
495 c->location_of_HQ = INVALID_TILE; // reset HQ position
496 SetWindowDirty(WC_COMPANY, c->index);
497 CargoPacket::InvalidateAllFrom(ST_HEADQUARTERS, c->index);
500 /* cost of relocating company is 1% of company value */
501 cost = CommandCost(EXPENSES_PROPERTY, CalculateCompanyValue(c) / 100);
502 break;
505 case OBJECT_STATUE:
506 if (flags & DC_EXEC) {
507 Town *town = o->town;
508 ClrBit(town->statues, GetTileOwner(tile));
509 SetWindowDirty(WC_TOWN_AUTHORITY, town->index);
511 break;
513 default:
514 break;
517 ClearedObjectArea *cleared_area = _cleared_object_areas.Append();
518 cleared_area->first_tile = tile;
519 cleared_area->area = ta;
521 if (flags & DC_EXEC) ReallyClearObjectTile(o);
523 return cost;
526 static void AddAcceptedCargo_Object(TileIndex tile, CargoArray &acceptance, uint32 *always_accepted)
528 if (!IsCompanyHQ(tile)) return;
530 /* HQ accepts passenger and mail; but we have to divide the values
531 * between 4 tiles it occupies! */
533 /* HQ level (depends on company performance) in the range 1..5. */
534 uint level = GetCompanyHQSize(tile) + 1;
536 /* Top town building generates 10, so to make HQ interesting, the top
537 * type makes 20. */
538 acceptance[CT_PASSENGERS] += max(1U, level);
539 SetBit(*always_accepted, CT_PASSENGERS);
541 /* Top town building generates 4, HQ can make up to 8. The
542 * proportion passengers:mail is different because such a huge
543 * commercial building generates unusually high amount of mail
544 * correspondence per physical visitor. */
545 acceptance[CT_MAIL] += max(1U, level / 2);
546 SetBit(*always_accepted, CT_MAIL);
550 static void GetTileDesc_Object(TileIndex tile, TileDesc *td)
552 const ObjectSpec *spec = ObjectSpec::GetByTile(tile);
553 td->str = spec->name;
554 td->owner[0] = GetTileOwner(tile);
555 td->build_date = Object::GetByTile(tile)->build_date;
557 if (spec->grf_prop.grffile != NULL) {
558 td->grf = GetGRFConfig(spec->grf_prop.grffile->grfid)->GetName();
562 static void TileLoop_Object(TileIndex tile)
564 const ObjectSpec *spec = ObjectSpec::GetByTile(tile);
565 if (spec->flags & OBJECT_FLAG_ANIMATION) {
566 Object *o = Object::GetByTile(tile);
567 TriggerObjectTileAnimation(o, tile, OAT_TILELOOP, spec);
568 if (o->location.tile == tile) TriggerObjectAnimation(o, OAT_256_TICKS, spec);
571 if (IsTileOnWater(tile)) TileLoop_Water(tile);
573 if (!IsCompanyHQ(tile)) return;
575 /* HQ accepts passenger and mail; but we have to divide the values
576 * between 4 tiles it occupies! */
578 /* HQ level (depends on company performance) in the range 1..5. */
579 uint level = GetCompanyHQSize(tile) + 1;
580 assert(level < 6);
582 StationFinder stations(TileArea(tile, 2, 2));
584 uint r = Random();
585 /* Top town buildings generate 250, so the top HQ type makes 256. */
586 if (GB(r, 0, 8) < (256 / 4 / (6 - level))) {
587 uint amt = GB(r, 0, 8) / 8 / 4 + 1;
588 if (EconomyIsInRecession()) amt = (amt + 1) >> 1;
589 MoveGoodsToStation(CT_PASSENGERS, amt, ST_HEADQUARTERS, GetTileOwner(tile), stations.GetStations());
592 /* Top town building generates 90, HQ can make up to 196. The
593 * proportion passengers:mail is about the same as in the acceptance
594 * equations. */
595 if (GB(r, 8, 8) < (196 / 4 / (6 - level))) {
596 uint amt = GB(r, 8, 8) / 8 / 4 + 1;
597 if (EconomyIsInRecession()) amt = (amt + 1) >> 1;
598 MoveGoodsToStation(CT_MAIL, amt, ST_HEADQUARTERS, GetTileOwner(tile), stations.GetStations());
603 static TrackStatus GetTileTrackStatus_Object(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
605 return 0;
608 static bool ClickTile_Object(TileIndex tile)
610 if (!IsCompanyHQ(tile)) return false;
612 ShowCompany(GetTileOwner(tile));
613 return true;
616 static void AnimateTile_Object(TileIndex tile)
618 AnimateNewObjectTile(tile);
622 * Helper function for \c CircularTileSearch.
623 * @param tile The tile to check.
624 * @param user Ignored.
625 * @return True iff the tile has a radio tower.
627 static bool HasTransmitter(TileIndex tile, void *user)
629 return IsTransmitterTile(tile);
632 void GenerateObjects()
634 if (_settings_game.game_creation.landscape == LT_TOYLAND) return;
636 /* add radio tower */
637 int radiotower_to_build = ScaleByMapSize(15); // maximum number of radio towers on the map
638 int lighthouses_to_build = _settings_game.game_creation.landscape == LT_TROPIC ? 0 : ScaleByMapSize1D((Random() & 3) + 7);
640 /* Scale the amount of lighthouses with the amount of land at the borders. */
641 if (_settings_game.construction.freeform_edges && lighthouses_to_build != 0) {
642 uint num_water_tiles = 0;
643 for (uint x = 0; x < MapMaxX(); x++) {
644 if (IsTileType(TileXY(x, 1), MP_WATER)) num_water_tiles++;
645 if (IsTileType(TileXY(x, MapMaxY() - 1), MP_WATER)) num_water_tiles++;
647 for (uint y = 1; y < MapMaxY() - 1; y++) {
648 if (IsTileType(TileXY(1, y), MP_WATER)) num_water_tiles++;
649 if (IsTileType(TileXY(MapMaxX() - 1, y), MP_WATER)) num_water_tiles++;
651 /* The -6 is because the top borders are MP_VOID (-2) and all corners
652 * are counted twice (-4). */
653 lighthouses_to_build = lighthouses_to_build * num_water_tiles / (2 * MapMaxY() + 2 * MapMaxX() - 6);
656 SetGeneratingWorldProgress(GWP_OBJECT, radiotower_to_build + lighthouses_to_build);
658 for (uint i = ScaleByMapSize(1000); i != 0 && Object::CanAllocateItem(); i--) {
659 TileIndex tile = RandomTile();
661 int h;
662 if (IsTileType(tile, MP_CLEAR) && GetTileSlope(tile, &h) == SLOPE_FLAT && h >= 4 && !IsBridgeAbove(tile)) {
663 TileIndex t = tile;
664 if (CircularTileSearch(&t, 9, HasTransmitter, NULL)) continue;
666 BuildObject(OBJECT_TRANSMITTER, tile);
667 IncreaseGeneratingWorldProgress(GWP_OBJECT);
668 if (--radiotower_to_build == 0) break;
672 /* add lighthouses */
673 uint maxx = MapMaxX();
674 uint maxy = MapMaxY();
675 for (int loop_count = 0; loop_count < 1000 && lighthouses_to_build != 0 && Object::CanAllocateItem(); loop_count++) {
676 uint r = Random();
678 /* Scatter the lighthouses more evenly around the perimeter */
679 int perimeter = (GB(r, 16, 16) % (2 * (maxx + maxy))) - maxy;
680 DiagDirection dir;
681 for (dir = DIAGDIR_NE; perimeter > 0; dir++) {
682 perimeter -= (DiagDirToAxis(dir) == AXIS_X) ? maxx : maxy;
685 TileIndex tile;
686 switch (dir) {
687 default:
688 case DIAGDIR_NE: tile = TileXY(maxx - 1, r % maxy); break;
689 case DIAGDIR_SE: tile = TileXY(r % maxx, 1); break;
690 case DIAGDIR_SW: tile = TileXY(1, r % maxy); break;
691 case DIAGDIR_NW: tile = TileXY(r % maxx, maxy - 1); break;
694 /* Only build lighthouses at tiles where the border is sea. */
695 if (!IsTileType(tile, MP_WATER)) continue;
697 for (int j = 0; j < 19; j++) {
698 int h;
699 if (IsTileType(tile, MP_CLEAR) && GetTileSlope(tile, &h) == SLOPE_FLAT && h <= 2 && !IsBridgeAbove(tile)) {
700 BuildObject(OBJECT_LIGHTHOUSE, tile);
701 IncreaseGeneratingWorldProgress(GWP_OBJECT);
702 lighthouses_to_build--;
703 assert(tile < MapSize());
704 break;
706 tile += TileOffsByDiagDir(dir);
707 if (!IsValidTile(tile)) break;
712 static void ChangeTileOwner_Object(TileIndex tile, Owner old_owner, Owner new_owner)
714 if (!IsTileOwner(tile, old_owner)) return;
716 if (IsOwnedLand(tile) && new_owner != INVALID_OWNER) {
717 SetTileOwner(tile, new_owner);
718 } else if (IsStatueTile(tile)) {
719 Town *t = Object::GetByTile(tile)->town;
720 ClrBit(t->statues, old_owner);
721 if (new_owner != INVALID_OWNER && !HasBit(t->statues, new_owner)) {
722 /* Transfer ownership to the new company */
723 SetBit(t->statues, new_owner);
724 SetTileOwner(tile, new_owner);
725 } else {
726 ReallyClearObjectTile(Object::GetByTile(tile));
729 SetWindowDirty(WC_TOWN_AUTHORITY, t->index);
730 } else {
731 ReallyClearObjectTile(Object::GetByTile(tile));
735 static CommandCost TerraformTile_Object(TileIndex tile, DoCommandFlag flags, int z_new, Slope tileh_new)
737 ObjectType type = GetObjectType(tile);
739 if (type == OBJECT_OWNED_LAND) {
740 /* Owned land remains unsold */
741 CommandCost ret = CheckTileOwnership(tile);
742 if (ret.Succeeded()) return CommandCost();
743 } else if (AutoslopeEnabled() && type != OBJECT_TRANSMITTER && type != OBJECT_LIGHTHOUSE) {
744 /* Behaviour:
745 * - Both new and old slope must not be steep.
746 * - TileMaxZ must not be changed.
747 * - Allow autoslope by default.
748 * - Disallow autoslope if callback succeeds and returns non-zero.
750 Slope tileh_old = GetTileSlope(tile);
751 /* TileMaxZ must not be changed. Slopes must not be steep. */
752 if (!IsSteepSlope(tileh_old) && !IsSteepSlope(tileh_new) && (GetTileMaxZ(tile) == z_new + GetSlopeMaxZ(tileh_new))) {
753 const ObjectSpec *spec = ObjectSpec::Get(type);
755 /* Call callback 'disable autosloping for objects'. */
756 if (HasBit(spec->callback_mask, CBM_OBJ_AUTOSLOPE)) {
757 /* If the callback fails, allow autoslope. */
758 uint16 res = GetObjectCallback(CBID_OBJECT_AUTOSLOPE, 0, 0, spec, Object::GetByTile(tile), tile);
759 if (res == CALLBACK_FAILED || !ConvertBooleanCallback(spec->grf_prop.grffile, CBID_OBJECT_AUTOSLOPE, res)) return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
760 } else if (spec->enabled) {
761 /* allow autoslope */
762 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
767 return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
770 extern const TileTypeProcs _tile_type_object_procs = {
771 DrawTile_Object, // draw_tile_proc
772 GetSlopePixelZ_Object, // get_slope_z_proc
773 ClearTile_Object, // clear_tile_proc
774 AddAcceptedCargo_Object, // add_accepted_cargo_proc
775 GetTileDesc_Object, // get_tile_desc_proc
776 GetTileTrackStatus_Object, // get_tile_track_status_proc
777 ClickTile_Object, // click_tile_proc
778 AnimateTile_Object, // animate_tile_proc
779 TileLoop_Object, // tile_loop_proc
780 ChangeTileOwner_Object, // change_tile_owner_proc
781 NULL, // add_produced_cargo_proc
782 NULL, // vehicle_enter_tile_proc
783 GetFoundation_Object, // get_foundation_proc
784 TerraformTile_Object, // terraform_tile_proc