OpenTTD Source  14.0-beta1
object_cmd.cpp
Go to the documentation of this file.
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 
10 #include "stdafx.h"
11 #include "landscape.h"
12 #include "command_func.h"
13 #include "company_func.h"
14 #include "viewport_func.h"
15 #include "company_base.h"
16 #include "town.h"
17 #include "bridge_map.h"
18 #include "genworld.h"
19 #include "autoslope.h"
20 #include "clear_func.h"
21 #include "water.h"
22 #include "window_func.h"
23 #include "company_gui.h"
24 #include "cheat_type.h"
25 #include "object.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"
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"
40 
41 #include "table/strings.h"
42 #include "table/object_land.h"
43 
44 #include "safeguards.h"
45 
46 ObjectPool _object_pool("Object");
48 uint16_t Object::counts[NUM_OBJECTS];
49 
55 /* static */ Object *Object::GetByTile(TileIndex tile)
56 {
57  return Object::Get(GetObjectIndex(tile));
58 }
59 
67 {
68  assert(IsTileType(t, MP_OBJECT));
69  return Object::GetByTile(t)->type;
70 }
71 
74 {
76 }
77 
88 void BuildObject(ObjectType type, TileIndex tile, CompanyID owner, Town *town, uint8_t view)
89 {
90  const ObjectSpec *spec = ObjectSpec::Get(type);
91 
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();
94  o->type = type;
95  o->location = ta;
96  o->town = town == nullptr ? CalcClosestTownFromTile(tile) : town;
98  o->view = view;
99 
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();
104  } else {
105  const Livery *l = Company::Get(owner)->livery;
106  o->colour = l->colour1 + l->colour2 * 16;
107  }
108 
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;
111 
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);
117  }
118  }
119 
120  assert(o->town != nullptr);
121 
122  for (TileIndex t : ta) {
124  /* Update company infrastructure counts for objects build on canals owned by nobody. */
125  if (wc == WATER_CLASS_CANAL && owner != OWNER_NONE && (IsTileOwner(t, OWNER_NONE) || IsTileOwner(t, OWNER_WATER))) {
126  Company::Get(owner)->infrastructure.water++;
128  }
129  bool remove = IsDockingTile(t);
130  MakeObject(t, owner, o->index, wc, Random());
131  if (remove) RemoveDockingTile(t);
133  }
134 
135  Object::IncTypeCount(type);
137 }
138 
144 {
145  TileArea ta = Object::GetByTile(tile)->location;
146  for (TileIndex t : ta) {
149  }
150 }
151 
153 #define GetCompanyHQSize GetAnimationFrame
154 
155 #define IncreaseCompanyHQSize IncreaseAnimationStage
156 
162 void UpdateCompanyHQ(TileIndex tile, uint score)
163 {
164  if (tile == INVALID_TILE) return;
165 
166  byte val = 0;
167  if (score >= 170) val++;
168  if (score >= 350) val++;
169  if (score >= 520) val++;
170  if (score >= 720) val++;
171 
172  while (GetCompanyHQSize(tile) < val) {
173  IncreaseCompanyHQSize(tile);
174  }
175 }
176 
182 {
183  for (Object *obj : Object::Iterate()) {
184  Owner owner = GetTileOwner(obj->location.tile);
185  /* Not the current owner, so colour doesn't change. */
186  if (owner != c->index) continue;
187 
188  const ObjectSpec *spec = ObjectSpec::GetByTile(obj->location.tile);
189  /* Using the object colour callback, so not using company colour. */
190  if (HasBit(spec->callback_mask, CBM_OBJ_COLOUR)) continue;
191 
192  const Livery *l = c->livery;
193  obj->colour = ((spec->flags & OBJECT_FLAG_2CC_COLOUR) ? (l->colour2 * 16) : 0) + l->colour1;
194  }
195 }
196 
197 extern CommandCost CheckBuildableTile(TileIndex tile, uint invalid_dirs, int &allowed_z, bool allow_steep, bool check_bridge);
198 static CommandCost ClearTile_Object(TileIndex tile, DoCommandFlag flags);
199 
209 {
211 
212  if (type >= ObjectSpec::Count()) return CMD_ERROR;
213  const ObjectSpec *spec = ObjectSpec::Get(type);
214  if (_game_mode == GM_NORMAL && !spec->IsAvailable() && !_generating_world) return CMD_ERROR;
215  if ((_game_mode == GM_EDITOR || _generating_world) && !spec->WasEverAvailable()) return CMD_ERROR;
216 
217  if ((spec->flags & OBJECT_FLAG_ONLY_IN_SCENEDIT) != 0 && ((!_generating_world && _game_mode != GM_EDITOR) || _current_company != OWNER_NONE)) return CMD_ERROR;
218  if ((spec->flags & OBJECT_FLAG_ONLY_IN_GAME) != 0 && (_generating_world || _game_mode != GM_NORMAL || _current_company > MAX_COMPANIES)) return CMD_ERROR;
219  if (view >= spec->views) return CMD_ERROR;
220 
221  if (!Object::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_OBJECTS);
222  if (Town::GetNumItems() == 0) return_cmd_error(STR_ERROR_MUST_FOUND_TOWN_FIRST);
223 
224  int size_x = GB(spec->size, HasBit(view, 0) ? 4 : 0, 4);
225  int size_y = GB(spec->size, HasBit(view, 0) ? 0 : 4, 4);
226  TileArea ta(tile, size_x, size_y);
227  for (TileIndex t : ta) {
228  if (!IsValidTile(t)) return_cmd_error(STR_ERROR_TOO_CLOSE_TO_EDGE_OF_MAP_SUB); // Might be off the map
229  }
230 
231  if (type == OBJECT_OWNED_LAND) {
232  /* Owned land is special as it can be placed on any slope. */
233  cost.AddCost(Command<CMD_LANDSCAPE_CLEAR>::Do(flags, tile));
234  } else {
235  /* Check the surface to build on. At this time we can't actually execute the
236  * the CLEAR_TILE commands since the newgrf callback later on can check
237  * some information about the tiles. */
238  bool allow_water = (spec->flags & (OBJECT_FLAG_BUILT_ON_WATER | OBJECT_FLAG_NOT_ON_LAND)) != 0;
239  bool allow_ground = (spec->flags & OBJECT_FLAG_NOT_ON_LAND) == 0;
240  for (TileIndex t : ta) {
241  if (HasTileWaterGround(t)) {
242  if (!allow_water) return_cmd_error(STR_ERROR_CAN_T_BUILD_ON_WATER);
243  if (!IsWaterTile(t)) {
244  /* Normal water tiles don't have to be cleared. For all other tile types clear
245  * the tile but leave the water. */
247  } else {
248  /* Can't build on water owned by another company. */
249  Owner o = GetTileOwner(t);
250  if (o != OWNER_NONE && o != OWNER_WATER) cost.AddCost(CheckOwnership(o, t));
251 
252  /* However, the tile has to be clear of vehicles. */
254  }
255  } else {
256  if (!allow_ground) return_cmd_error(STR_ERROR_MUST_BE_BUILT_ON_WATER);
257  /* For non-water tiles, we'll have to clear it before building. */
258 
259  /* When relocating HQ, allow it to be relocated (partial) on itself. */
260  if (!(type == OBJECT_HQ &&
261  IsTileType(t, MP_OBJECT) &&
263  IsObjectType(t, OBJECT_HQ))) {
265  }
266  }
267  }
268 
269  /* So, now the surface is checked... check the slope of said surface. */
270  int allowed_z;
271  if (GetTileSlope(tile, &allowed_z) != SLOPE_FLAT) allowed_z++;
272 
273  for (TileIndex t : ta) {
274  uint16_t callback = CALLBACK_FAILED;
276  TileIndex diff = t - tile;
277  callback = GetObjectCallback(CBID_OBJECT_LAND_SLOPE_CHECK, GetTileSlope(t), TileY(diff) << 4 | TileX(diff), spec, nullptr, t, view);
278  }
279 
280  if (callback == CALLBACK_FAILED) {
281  cost.AddCost(CheckBuildableTile(t, 0, allowed_z, false, false));
282  } else {
283  /* The meaning of bit 10 is inverted for a grf version < 8. */
284  if (spec->grf_prop.grffile->grf_version < 8) ToggleBit(callback, 10);
285  CommandCost ret = GetErrorMessageFromLocationCallbackResult(callback, spec->grf_prop.grffile, STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION);
286  if (ret.Failed()) return ret;
287  }
288  }
289 
290  if (flags & DC_EXEC) {
291  /* This is basically a copy of the loop above with the exception that we now
292  * execute the commands and don't check for errors, since that's already done. */
293  for (TileIndex t : ta) {
294  if (HasTileWaterGround(t)) {
295  if (!IsWaterTile(t)) {
297  }
298  } else {
300  }
301  }
302  }
303  }
304  if (cost.Failed()) return cost;
305 
306  /* Finally do a check for bridges. */
307  for (TileIndex t : ta) {
308  if (IsBridgeAbove(t) && (
311  return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
312  }
313  }
314 
315  int hq_score = 0;
316  uint build_object_size = 1;
317  switch (type) {
318  case OBJECT_TRANSMITTER:
319  case OBJECT_LIGHTHOUSE:
320  if (!IsTileFlat(tile)) return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED);
321  break;
322 
323  case OBJECT_OWNED_LAND:
324  if (IsTileType(tile, MP_OBJECT) &&
325  IsTileOwner(tile, _current_company) &&
327  return_cmd_error(STR_ERROR_YOU_ALREADY_OWN_IT);
328  }
329  break;
330 
331  case OBJECT_HQ: {
333  if (c->location_of_HQ != INVALID_TILE) {
334  /* Don't relocate HQ on the same location. */
335  if (c->location_of_HQ == tile) return_cmd_error(STR_ERROR_ALREADY_BUILT);
336  /* We need to persuade a bit harder to remove the old HQ. */
338  cost.AddCost(ClearTile_Object(c->location_of_HQ, flags));
339  _current_company = c->index;
340  }
341 
342  if (flags & DC_EXEC) {
343  hq_score = UpdateCompanyRatingAndValue(c, false);
344  c->location_of_HQ = tile;
346  }
347  break;
348  }
349 
350  case OBJECT_STATUE:
351  /* This may never be constructed using this method. */
352  return CMD_ERROR;
353 
354  default: // i.e. NewGRF provided.
355  build_object_size = size_x * size_y;
356  break;
357  }
358 
359  /* Don't allow building more objects if the company has reached its limit. */
361  if (c != nullptr && GB(c->build_object_limit, 16, 16) < build_object_size) {
362  return_cmd_error(STR_ERROR_BUILD_OBJECT_LIMIT_REACHED);
363  }
364 
365  if (flags & DC_EXEC) {
366  BuildObject(type, tile, _current_company == OWNER_DEITY ? OWNER_NONE : _current_company, nullptr, view);
367  for (TileIndex t : ta) InvalidateWaterRegion(t);
368 
369  /* Make sure the HQ starts at the right size. */
370  if (type == OBJECT_HQ) UpdateCompanyHQ(tile, hq_score);
371 
372  /* Subtract the tile from the build limit. */
373  if (c != nullptr) c->build_object_limit -= build_object_size << 16;
374  }
375 
376  cost.AddCost(spec->GetBuildCost() * build_object_size);
377  return cost;
378 }
379 
390 CommandCost CmdBuildObjectArea(DoCommandFlag flags, TileIndex tile, TileIndex start_tile, ObjectType type, uint8_t view, bool diagonal)
391 {
392  if (start_tile >= Map::Size()) return CMD_ERROR;
393 
394  if (type >= ObjectSpec::Count()) return CMD_ERROR;
395  const ObjectSpec *spec = ObjectSpec::Get(type);
396  if (view >= spec->views) return CMD_ERROR;
397 
398  if (spec->size != OBJECT_SIZE_1X1) return CMD_ERROR;
399 
402  CommandCost last_error = CMD_ERROR;
403  bool had_success = false;
404 
406  int limit = (c == nullptr ? INT32_MAX : GB(c->build_object_limit, 16, 16));
407 
408  std::unique_ptr<TileIterator> iter = TileIterator::Create(tile, start_tile, diagonal);
409  for (; *iter != INVALID_TILE; ++(*iter)) {
410  TileIndex t = *iter;
411  CommandCost ret = Command<CMD_BUILD_OBJECT>::Do(flags & ~DC_EXEC, t, type, view);
412 
413  /* If we've reached the limit, stop building (or testing). */
414  if (c != nullptr && limit-- <= 0) break;
415 
416  if (ret.Failed()) {
417  last_error = ret;
418  continue;
419  }
420 
421  had_success = true;
422  if (flags & DC_EXEC) {
423  money -= ret.GetCost();
424 
425  /* If we run out of money, stop building. */
426  if (ret.GetCost() > 0 && money < 0) break;
427  Command<CMD_BUILD_OBJECT>::Do(flags, t, type, view);
428  }
429  cost.AddCost(ret);
430  }
431 
432  return had_success ? cost : last_error;
433 }
434 
435 static Foundation GetFoundation_Object(TileIndex tile, Slope tileh);
436 
437 static void DrawTile_Object(TileInfo *ti)
438 {
439  ObjectType type = GetObjectType(ti->tile);
440  const ObjectSpec *spec = ObjectSpec::Get(type);
441 
442  /* Fall back for when the object doesn't exist anymore. */
443  if (!spec->IsEnabled()) type = OBJECT_TRANSMITTER;
444 
445  if ((spec->flags & OBJECT_FLAG_HAS_NO_FOUNDATION) == 0) DrawFoundation(ti, GetFoundation_Object(ti->tile, ti->tileh));
446 
447  if (type < NEW_OBJECT_OFFSET) {
448  const DrawTileSprites *dts = nullptr;
449  Owner to = GetTileOwner(ti->tile);
450  PaletteID palette = to == OWNER_NONE ? PAL_NONE : COMPANY_SPRITE_COLOUR(to);
451 
452  if (type == OBJECT_HQ) {
453  TileIndex diff = ti->tile - Object::GetByTile(ti->tile)->location.tile;
454  dts = &_object_hq[GetCompanyHQSize(ti->tile) << 2 | TileY(diff) << 1 | TileX(diff)];
455  } else {
456  dts = &_objects[type];
457  }
458 
459  if (spec->flags & OBJECT_FLAG_HAS_NO_FOUNDATION) {
460  /* If an object has no foundation, but tries to draw a (flat) ground
461  * type... we have to be nice and convert that for them. */
462  switch (dts->ground.sprite) {
463  case SPR_FLAT_BARE_LAND: DrawClearLandTile(ti, 0); break;
464  case SPR_FLAT_1_THIRD_GRASS_TILE: DrawClearLandTile(ti, 1); break;
465  case SPR_FLAT_2_THIRD_GRASS_TILE: DrawClearLandTile(ti, 2); break;
466  case SPR_FLAT_GRASS_TILE: DrawClearLandTile(ti, 3); break;
467  default: DrawGroundSprite(dts->ground.sprite, palette); break;
468  }
469  } else {
470  DrawGroundSprite(dts->ground.sprite, palette);
471  }
472 
474  const DrawTileSeqStruct *dtss;
475  foreach_draw_tile_seq(dtss, dts->seq) {
477  dtss->image.sprite, palette,
478  ti->x + dtss->delta_x, ti->y + dtss->delta_y,
479  dtss->size_x, dtss->size_y,
480  dtss->size_z, ti->z + dtss->delta_z,
482  );
483  }
484  }
485  } else {
486  DrawNewObjectTile(ti, spec);
487  }
488 
489  DrawBridgeMiddle(ti);
490 }
491 
492 static int GetSlopePixelZ_Object(TileIndex tile, uint x, uint y, bool)
493 {
494  if (IsObjectType(tile, OBJECT_OWNED_LAND)) {
495  int z;
496  Slope tileh = GetTilePixelSlope(tile, &z);
497 
498  return z + GetPartialPixelZ(x & 0xF, y & 0xF, tileh);
499  } else {
500  return GetTileMaxPixelZ(tile);
501  }
502 }
503 
504 static Foundation GetFoundation_Object(TileIndex tile, Slope tileh)
505 {
507 }
508 
514 {
516  for (TileIndex tile_cur : o->location) {
517  DeleteNewGRFInspectWindow(GSF_OBJECTS, tile_cur.base());
518 
519  MakeWaterKeepingClass(tile_cur, GetTileOwner(tile_cur));
520  }
521  delete o;
522 }
523 
524 std::vector<ClearedObjectArea> _cleared_object_areas;
525 
532 {
533  TileArea ta = TileArea(tile, 1, 1);
534 
535  for (ClearedObjectArea &coa : _cleared_object_areas) {
536  if (coa.area.Intersects(ta)) return &coa;
537  }
538 
539  return nullptr;
540 }
541 
542 static CommandCost ClearTile_Object(TileIndex tile, DoCommandFlag flags)
543 {
544  /* Get to the northern most tile. */
545  Object *o = Object::GetByTile(tile);
546  TileArea ta = o->location;
547 
548  ObjectType type = o->type;
549  const ObjectSpec *spec = ObjectSpec::Get(type);
550 
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!
553 
554  /* Towns can't remove any objects. */
555  if (_current_company == OWNER_TOWN) return CMD_ERROR;
556 
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. */
576  if (type == OBJECT_HQ) return_cmd_error(STR_ERROR_COMPANY_HEADQUARTERS_IN);
577  return CMD_ERROR;
578  }
579 
580  /* Removing with the cheat costs more in TTDPatch / the specs. */
581  cost.MultiplyCost(25);
582  }
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. */
585  return CMD_ERROR;
586  }
587 
588  switch (type) {
589  case OBJECT_HQ: {
590  Company *c = Company::Get(GetTileOwner(tile));
591  if (flags & DC_EXEC) {
592  c->location_of_HQ = INVALID_TILE; // reset HQ position
595  }
596 
597  /* cost of relocating company is 1% of company value */
599  break;
600  }
601 
602  case OBJECT_STATUE:
603  if (flags & DC_EXEC) {
604  Town *town = o->town;
605  ClrBit(town->statues, GetTileOwner(tile));
607  }
608  break;
609 
610  default:
611  break;
612  }
613 
614  _cleared_object_areas.push_back({tile, ta});
615 
616  if (flags & DC_EXEC) ReallyClearObjectTile(o);
617 
618  return cost;
619 }
620 
621 static void AddAcceptedCargo_Object(TileIndex tile, CargoArray &acceptance, CargoTypes *always_accepted)
622 {
623  if (!IsObjectType(tile, OBJECT_HQ)) return;
624 
625  /* HQ accepts passenger and mail; but we have to divide the values
626  * between 4 tiles it occupies! */
627 
628  /* HQ level (depends on company performance) in the range 1..5. */
629  uint level = GetCompanyHQSize(tile) + 1;
630 
631  /* Top town building generates 10, so to make HQ interesting, the top
632  * type makes 20. */
633  acceptance[CT_PASSENGERS] += std::max(1U, level);
634  SetBit(*always_accepted, CT_PASSENGERS);
635 
636  /* Top town building generates 4, HQ can make up to 8. The
637  * proportion passengers:mail is different because such a huge
638  * commercial building generates unusually high amount of mail
639  * correspondence per physical visitor. */
640  acceptance[CT_MAIL] += std::max(1U, level / 2);
641  SetBit(*always_accepted, CT_MAIL);
642 }
643 
644 static void AddProducedCargo_Object(TileIndex tile, CargoArray &produced)
645 {
646  if (!IsObjectType(tile, OBJECT_HQ)) return;
647 
648  produced[CT_PASSENGERS]++;
649  produced[CT_MAIL]++;
650 }
651 
652 
653 static void GetTileDesc_Object(TileIndex tile, TileDesc *td)
654 {
655  const ObjectSpec *spec = ObjectSpec::GetByTile(tile);
656  td->str = spec->name;
657  td->owner[0] = GetTileOwner(tile);
659 
660  if (spec->grf_prop.grffile != nullptr) {
661  td->grf = GetGRFConfig(spec->grf_prop.grffile->grfid)->GetName();
662  }
663 }
664 
665 static void TileLoop_Object(TileIndex tile)
666 {
667  const ObjectSpec *spec = ObjectSpec::GetByTile(tile);
668  if (spec->flags & OBJECT_FLAG_ANIMATION) {
669  Object *o = Object::GetByTile(tile);
671  if (o->location.tile == tile) TriggerObjectAnimation(o, OAT_256_TICKS, spec);
672  }
673 
674  if (IsTileOnWater(tile)) TileLoop_Water(tile);
675 
676  if (!IsObjectType(tile, OBJECT_HQ)) return;
677 
678  /* HQ accepts passenger and mail; but we have to divide the values
679  * between 4 tiles it occupies! */
680 
681  /* HQ level (depends on company performance) in the range 1..5. */
682  uint level = GetCompanyHQSize(tile) + 1;
683  assert(level < 6);
684 
685  StationFinder stations(TileArea(tile, 2, 2));
686 
687  uint r = Random();
688  /* Top town buildings generate 250, so the top HQ type makes 256. */
689  if (GB(r, 0, 8) < (256 / 4 / (6 - level))) {
690  uint amt = GB(r, 0, 8) / 8 / 4 + 1;
691 
692  /* Production is halved during recessions. */
693  if (EconomyIsInRecession()) amt = (amt + 1) >> 1;
694 
695  /* Scale by cargo scale setting. */
696  amt = ScaleByCargoScale(amt, true);
697 
698  MoveGoodsToStation(CT_PASSENGERS, amt, SourceType::Headquarters, GetTileOwner(tile), stations.GetStations());
699  }
700 
701  /* Top town building generates 90, HQ can make up to 196. The
702  * proportion passengers:mail is about the same as in the acceptance
703  * equations. */
704  if (GB(r, 8, 8) < (196 / 4 / (6 - level))) {
705  uint amt = GB(r, 8, 8) / 8 / 4 + 1;
706 
707  /* Production is halved during recessions. */
708  if (EconomyIsInRecession()) amt = (amt + 1) >> 1;
709 
710  /* Scale by cargo scale setting. */
711  amt = ScaleByCargoScale(amt, true);
712 
713  MoveGoodsToStation(CT_MAIL, amt, SourceType::Headquarters, GetTileOwner(tile), stations.GetStations());
714  }
715 }
716 
717 
718 static TrackStatus GetTileTrackStatus_Object(TileIndex, TransportType, uint, DiagDirection)
719 {
720  return 0;
721 }
722 
723 static bool ClickTile_Object(TileIndex tile)
724 {
725  if (!IsObjectType(tile, OBJECT_HQ)) return false;
726 
727  ShowCompany(GetTileOwner(tile));
728  return true;
729 }
730 
731 static void AnimateTile_Object(TileIndex tile)
732 {
733  AnimateNewObjectTile(tile);
734 }
735 
741 static bool HasTransmitter(TileIndex tile, void *)
742 {
743  return IsObjectTypeTile(tile, OBJECT_TRANSMITTER);
744 }
745 
750 static bool TryBuildLightHouse()
751 {
752  uint maxx = Map::MaxX();
753  uint maxy = Map::MaxY();
754  uint r = Random();
755 
756  /* Scatter the lighthouses more evenly around the perimeter */
757  int perimeter = (GB(r, 16, 16) % (2 * (maxx + maxy))) - maxy;
758  DiagDirection dir;
759  for (dir = DIAGDIR_NE; perimeter > 0; dir++) {
760  perimeter -= (DiagDirToAxis(dir) == AXIS_X) ? maxx : maxy;
761  }
762 
763  TileIndex tile;
764  switch (dir) {
765  default:
766  case DIAGDIR_NE: tile = TileXY(maxx - 1, r % maxy); break;
767  case DIAGDIR_SE: tile = TileXY(r % maxx, 1); break;
768  case DIAGDIR_SW: tile = TileXY(1, r % maxy); break;
769  case DIAGDIR_NW: tile = TileXY(r % maxx, maxy - 1); break;
770  }
771 
772  /* Only build lighthouses at tiles where the border is sea. */
773  if (!IsTileType(tile, MP_WATER)) return false;
774 
775  for (int j = 0; j < 19; j++) {
776  int h;
777  if (IsTileType(tile, MP_CLEAR) && IsTileFlat(tile, &h) && h <= 2 && !IsBridgeAbove(tile)) {
779  assert(tile < Map::Size());
780  return true;
781  }
782  tile += TileOffsByDiagDir(dir);
783  if (!IsValidTile(tile)) return false;
784  }
785  return false;
786 }
787 
792 static bool TryBuildTransmitter()
793 {
794  TileIndex tile = RandomTile();
795  int h;
796  if (IsTileType(tile, MP_CLEAR) && IsTileFlat(tile, &h) && h >= 4 && !IsBridgeAbove(tile)) {
797  TileIndex t = tile;
798  if (CircularTileSearch(&t, 9, HasTransmitter, nullptr)) return false;
799 
801  return true;
802  }
803  return false;
804 }
805 
806 void GenerateObjects()
807 {
808  /* Set a guestimate on how much we progress */
809  SetGeneratingWorldProgress(GWP_OBJECT, (uint)ObjectSpec::Count());
810 
811  /* Determine number of water tiles at map border needed for freeform_edges */
812  uint num_water_tiles = 0;
814  for (uint x = 0; x < Map::MaxX(); x++) {
815  if (IsTileType(TileXY(x, 1), MP_WATER)) num_water_tiles++;
816  if (IsTileType(TileXY(x, Map::MaxY() - 1), MP_WATER)) num_water_tiles++;
817  }
818  for (uint y = 1; y < Map::MaxY() - 1; y++) {
819  if (IsTileType(TileXY(1, y), MP_WATER)) num_water_tiles++;
820  if (IsTileType(TileXY(Map::MaxX() - 1, y), MP_WATER)) num_water_tiles++;
821  }
822  }
823 
824  /* Iterate over all possible object types */
825  for (const auto &spec : ObjectSpec::Specs()) {
826 
827  /* Continue, if the object was never available till now or shall not be placed */
828  if (!spec.WasEverAvailable() || spec.generate_amount == 0) continue;
829 
830  uint16_t amount = spec.generate_amount;
831 
832  /* Scale by map size */
834  /* Scale the amount of lighthouses with the amount of land at the borders.
835  * The -6 is because the top borders are MP_VOID (-2) and all corners
836  * are counted twice (-4). */
837  amount = Map::ScaleBySize1D(amount * num_water_tiles) / (2 * Map::MaxY() + 2 * Map::MaxX() - 6);
838  } else if (spec.flags & OBJECT_FLAG_SCALE_BY_WATER) {
839  amount = Map::ScaleBySize1D(amount);
840  } else {
841  amount = Map::ScaleBySize(amount);
842  }
843 
844  /* Now try to place the requested amount of this object */
845  for (uint j = Map::ScaleBySize(1000); j != 0 && amount != 0 && Object::CanAllocateItem(); j--) {
846  switch (spec.Index()) {
847  case OBJECT_TRANSMITTER:
848  if (TryBuildTransmitter()) amount--;
849  break;
850 
851  case OBJECT_LIGHTHOUSE:
852  if (TryBuildLightHouse()) amount--;
853  break;
854 
855  default:
856  uint8_t view = RandomRange(spec.views);
858  break;
859  }
860  }
862  }
863 }
864 
865 static void ChangeTileOwner_Object(TileIndex tile, Owner old_owner, Owner new_owner)
866 {
867  if (!IsTileOwner(tile, old_owner)) return;
868 
869  bool do_clear = false;
870 
871  ObjectType type = GetObjectType(tile);
872  if ((type == OBJECT_OWNED_LAND || type >= NEW_OBJECT_OFFSET) && new_owner != INVALID_OWNER) {
873  SetTileOwner(tile, new_owner);
874  } else if (type == OBJECT_STATUE) {
875  Town *t = Object::GetByTile(tile)->town;
876  ClrBit(t->statues, old_owner);
877  if (new_owner != INVALID_OWNER && !HasBit(t->statues, new_owner)) {
878  /* Transfer ownership to the new company */
879  SetBit(t->statues, new_owner);
880  SetTileOwner(tile, new_owner);
881  } else {
882  do_clear = true;
883  }
884 
886  } else {
887  do_clear = true;
888  }
889 
890  if (do_clear) {
892  /* When clearing objects, they may turn into canal, which may require transferring ownership. */
893  ChangeTileOwner(tile, old_owner, new_owner);
894  }
895 }
896 
897 static CommandCost TerraformTile_Object(TileIndex tile, DoCommandFlag flags, int z_new, Slope tileh_new)
898 {
899  ObjectType type = GetObjectType(tile);
900 
901  if (type == OBJECT_OWNED_LAND) {
902  /* Owned land remains unsold */
903  CommandCost ret = CheckTileOwnership(tile);
904  if (ret.Succeeded()) return CommandCost();
905  } else if (AutoslopeEnabled() && type != OBJECT_TRANSMITTER && type != OBJECT_LIGHTHOUSE) {
906  /* Behaviour:
907  * - Both new and old slope must not be steep.
908  * - TileMaxZ must not be changed.
909  * - Allow autoslope by default.
910  * - Disallow autoslope if callback succeeds and returns non-zero.
911  */
912  Slope tileh_old = GetTileSlope(tile);
913  /* TileMaxZ must not be changed. Slopes must not be steep. */
914  if (!IsSteepSlope(tileh_old) && !IsSteepSlope(tileh_new) && (GetTileMaxZ(tile) == z_new + GetSlopeMaxZ(tileh_new))) {
915  const ObjectSpec *spec = ObjectSpec::Get(type);
916 
917  /* Call callback 'disable autosloping for objects'. */
918  if (HasBit(spec->callback_mask, CBM_OBJ_AUTOSLOPE)) {
919  /* If the callback fails, allow autoslope. */
920  uint16_t res = GetObjectCallback(CBID_OBJECT_AUTOSLOPE, 0, 0, spec, Object::GetByTile(tile), tile);
921  if (res == CALLBACK_FAILED || !ConvertBooleanCallback(spec->grf_prop.grffile, CBID_OBJECT_AUTOSLOPE, res)) return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
922  } else if (spec->IsEnabled()) {
923  /* allow autoslope */
924  return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
925  }
926  }
927  }
928 
929  return Command<CMD_LANDSCAPE_CLEAR>::Do(flags, tile);
930 }
931 
932 extern const TileTypeProcs _tile_type_object_procs = {
933  DrawTile_Object, // draw_tile_proc
934  GetSlopePixelZ_Object, // get_slope_z_proc
935  ClearTile_Object, // clear_tile_proc
936  AddAcceptedCargo_Object, // add_accepted_cargo_proc
937  GetTileDesc_Object, // get_tile_desc_proc
938  GetTileTrackStatus_Object, // get_tile_track_status_proc
939  ClickTile_Object, // click_tile_proc
940  AnimateTile_Object, // animate_tile_proc
941  TileLoop_Object, // tile_loop_proc
942  ChangeTileOwner_Object, // change_tile_owner_proc
943  AddProducedCargo_Object, // add_produced_cargo_proc
944  nullptr, // vehicle_enter_tile_proc
945  GetFoundation_Object, // get_foundation_proc
946  TerraformTile_Object, // terraform_tile_proc
947 };
TileY
static debug_inline uint TileY(TileIndex tile)
Get the Y component of a tile.
Definition: map_func.h:437
TileInfo::z
int z
Height.
Definition: tile_cmd.h:48
MP_CLEAR
@ MP_CLEAR
A tile without any structures, i.e. grass, rocks, farm fields etc.
Definition: tile_type.h:48
OBJECT_SIZE_1X1
static const uint8_t OBJECT_SIZE_1X1
The value of a NewGRF's size property when the object is 1x1 tiles: low nibble for X,...
Definition: newgrf_object.h:43
DeleteNewGRFInspectWindow
void DeleteNewGRFInspectWindow(GrfSpecFeature feature, uint index)
Delete inspect window for a given feature and index.
Definition: newgrf_debug_gui.cpp:739
IsTileFlat
bool IsTileFlat(TileIndex tile, int *h)
Check if a given tile is flat.
Definition: tile_map.cpp:100
DIAGDIR_SE
@ DIAGDIR_SE
Southeast.
Definition: direction_type.h:76
TileDesc::grf
const char * grf
newGRF used for the tile contents
Definition: tile_cmd.h:63
Object::colour
byte colour
Colour of the object, for display purpose.
Definition: object_base.h:28
CBID_OBJECT_COLOUR
@ CBID_OBJECT_COLOUR
Called to determine the colour of a town building.
Definition: newgrf_callbacks.h:266
Cheats::magic_bulldozer
Cheat magic_bulldozer
dynamite industries, objects
Definition: cheat_type.h:27
SetBit
constexpr T SetBit(T &x, const uint8_t y)
Set a bit in a variable.
Definition: bitmath_func.hpp:121
StationFinder
Structure contains cached list of stations nearby.
Definition: station_type.h:100
OAT_256_TICKS
@ OAT_256_TICKS
Triggered every 256 ticks (for all tiles at the same time).
Definition: newgrf_animation_type.h:59
Pool::PoolItem<&_object_pool >::Get
static Titem * Get(size_t index)
Returns Titem with given index.
Definition: pool_type.hpp:335
OBJECT_FLAG_CANNOT_REMOVE
@ OBJECT_FLAG_CANNOT_REMOVE
Object can not be removed.
Definition: newgrf_object.h:27
OBJECT_FLAG_2CC_COLOUR
@ OBJECT_FLAG_2CC_COLOUR
Object wants 2CC colour mapping.
Definition: newgrf_object.h:34
CBID_OBJECT_LAND_SLOPE_CHECK
@ CBID_OBJECT_LAND_SLOPE_CHECK
Callback done for each tile of an object to check the slope.
Definition: newgrf_callbacks.h:254
SetWindowDirty
void SetWindowDirty(WindowClass cls, WindowNumber number)
Mark window as dirty (in need of repainting)
Definition: window.cpp:3082
water.h
GetTileMaxZ
int GetTileMaxZ(TileIndex t)
Get top height of the tile inside the map.
Definition: tile_map.cpp:141
FindClearedObject
ClearedObjectArea * FindClearedObject(TileIndex tile)
Find the entry in _cleared_object_areas which occupies a certain tile.
Definition: object_cmd.cpp:531
Object::counts
static uint16_t counts[NUM_OBJECTS]
Number of objects per type ingame.
Definition: object_base.h:78
command_func.h
ObjectSpec
Allow incrementing of ObjectClassID variables.
Definition: newgrf_object.h:60
ObjectSpec::grf_prop
GRFFilePropsBase< 2 > grf_prop
Properties related the the grf file.
Definition: newgrf_object.h:62
GetObjectCallback
uint16_t GetObjectCallback(CallbackID callback, uint32_t param1, uint32_t param2, const ObjectSpec *spec, Object *o, TileIndex tile, uint8_t view)
Perform a callback for an object.
Definition: newgrf_object.cpp:431
Pool::PoolItem<&_company_pool >::GetIfValid
static Titem * GetIfValid(size_t index)
Returns Titem with given index.
Definition: pool_type.hpp:346
CMD_ERROR
static const CommandCost CMD_ERROR
Define a default return value for a failed command.
Definition: command_func.h:28
FlatteningFoundation
Foundation FlatteningFoundation(Slope s)
Returns the foundation needed to flatten a slope.
Definition: slope_func.h:369
TileInfo
Tile information, used while rendering the tile.
Definition: tile_cmd.h:43
GetWaterClass
WaterClass GetWaterClass(Tile t)
Get the water class at a tile.
Definition: water_map.h:115
Town::statues
CompanyMask statues
which companies have a statue?
Definition: town.h:66
Map::MaxX
static debug_inline uint MaxX()
Gets the maximum X coordinate within the map, including MP_VOID.
Definition: map_func.h:297
company_base.h
HasTransmitter
static bool HasTransmitter(TileIndex tile, void *)
Helper function for CircularTileSearch.
Definition: object_cmd.cpp:741
BuildObject
void BuildObject(ObjectType type, TileIndex tile, CompanyID owner, Town *town, uint8_t view)
Actually build the object.
Definition: object_cmd.cpp:88
timer_game_calendar.h
CommandCost::MultiplyCost
void MultiplyCost(int factor)
Multiplies the cost of the command by the given factor.
Definition: command_type.h:74
TileDesc::owner
Owner owner[4]
Name of the owner(s)
Definition: tile_cmd.h:55
company_gui.h
CargoPacket::InvalidateAllFrom
static void InvalidateAllFrom(SourceType src_type, SourceID src)
Invalidates (sets source_id to INVALID_SOURCE) all cargo packets from given source.
Definition: cargopacket.cpp:137
Object::location
TileArea location
Location of the object.
Definition: object_base.h:26
OBJECT_FLAG_SCALE_BY_WATER
@ OBJECT_FLAG_SCALE_BY_WATER
Object count is roughly scaled by water amount at edges.
Definition: newgrf_object.h:39
GB
constexpr static debug_inline uint GB(const T x, const uint8_t s, const uint8_t n)
Fetch n bits from x, started at bit s.
Definition: bitmath_func.hpp:32
OBJECT_FLAG_ALLOW_UNDER_BRIDGE
@ OBJECT_FLAG_ALLOW_UNDER_BRIDGE
Object can built under a bridge.
Definition: newgrf_object.h:37
Map::ScaleBySize1D
static uint ScaleBySize1D(uint n)
Scales the given value by the maps circumference, where the given value is for a 256 by 256 map.
Definition: map_func.h:341
AutoslopeEnabled
bool AutoslopeEnabled()
Tests if autoslope is enabled for _current_company.
Definition: autoslope.h:44
IsTransparencySet
bool IsTransparencySet(TransparencyOption to)
Check if the transparency option bit is set and if we aren't in the game menu (there's never transpar...
Definition: transparency.h:48
Pool::PoolItem::index
Tindex index
Index of this pool item.
Definition: pool_type.hpp:234
DiagDirToAxis
Axis DiagDirToAxis(DiagDirection d)
Convert a DiagDirection to the axis.
Definition: direction_func.h:214
Object::GetByTile
static Object * GetByTile(TileIndex tile)
Get the object associated with a tile.
Definition: object_cmd.cpp:55
ObjectSpec::IsAvailable
bool IsAvailable() const
Check whether the object is available at this time.
Definition: newgrf_object.cpp:93
GetCompanyHQSize
#define GetCompanyHQSize
We encode the company HQ size in the animation stage.
Definition: object_cmd.cpp:153
CargoArray
Class for storing amounts of cargo.
Definition: cargo_type.h:97
ObjectSpec::generate_amount
uint8_t generate_amount
Number of objects which are attempted to be generated per 256^2 map during world generation.
Definition: newgrf_object.h:77
PalSpriteID::sprite
SpriteID sprite
The 'real' sprite.
Definition: gfx_type.h:23
GetBridgeHeight
int GetBridgeHeight(TileIndex t)
Get the height ('z') of a bridge.
Definition: bridge_map.cpp:70
INVALID_TILE
constexpr TileIndex INVALID_TILE
The very nice invalid tile marker.
Definition: tile_type.h:95
TryBuildLightHouse
static bool TryBuildLightHouse()
Try to build a lighthouse.
Definition: object_cmd.cpp:750
TileIterator::Create
static std::unique_ptr< TileIterator > Create(TileIndex corner1, TileIndex corner2, bool diagonal)
Create either an OrthogonalTileIterator or DiagonalTileIterator given the diagonal parameter.
Definition: tilearea.cpp:291
TriggerObjectTileAnimation
void TriggerObjectTileAnimation(Object *o, TileIndex tile, ObjectAnimationTrigger trigger, const ObjectSpec *spec)
Trigger the update of animation on a single tile.
Definition: newgrf_object.cpp:562
ObjectSpec::height
uint8_t height
The height of this structure, in heightlevels; max MAX_TILE_HEIGHT.
Definition: newgrf_object.h:75
OBJECT_FLAG_ONLY_IN_GAME
@ OBJECT_FLAG_ONLY_IN_GAME
Object can only be built in game.
Definition: newgrf_object.h:33
IsSteepSlope
static constexpr bool IsSteepSlope(Slope s)
Checks if a slope is steep.
Definition: slope_func.h:36
OBJECT_STATUE
static const ObjectType OBJECT_STATUE
Statue in towns.
Definition: object_type.h:18
NUM_OBJECTS
static const ObjectType NUM_OBJECTS
Number of supported objects overall.
Definition: object_type.h:23
GetPartialPixelZ
uint GetPartialPixelZ(int x, int y, Slope corners)
Determines height at given coordinate of a slope.
Definition: landscape.cpp:224
DrawBridgeMiddle
void DrawBridgeMiddle(const TileInfo *ti)
Draw the middle bits of a bridge.
Definition: tunnelbridge_cmd.cpp:1544
Tile
Wrapper class to abstract away the way the tiles are stored.
Definition: map_func.h:25
DC_NO_WATER
@ DC_NO_WATER
don't allow building on water
Definition: command_type.h:374
newgrf_debug.h
town.h
GetGRFConfig
GRFConfig * GetGRFConfig(uint32_t grfid, uint32_t mask)
Retrieve a NewGRF from the current config by its grfid.
Definition: newgrf_config.cpp:716
TileInfo::y
int y
Y position of the tile in unit coordinates.
Definition: tile_cmd.h:45
StrongType::Typedef< uint32_t, struct TileIndexTag, StrongType::Compare, StrongType::Integer, StrongType::Compatible< int32_t >, StrongType::Compatible< int64_t > >
DIAGDIR_NW
@ DIAGDIR_NW
Northwest.
Definition: direction_type.h:78
DrawNewObjectTile
void DrawNewObjectTile(TileInfo *ti, const ObjectSpec *spec)
Draw an object on the map.
Definition: newgrf_object.cpp:469
WC_COMPANY
@ WC_COMPANY
Company view; Window numbers:
Definition: window_type.h:369
IsWaterTile
bool IsWaterTile(Tile t)
Is it a water tile with plain water?
Definition: water_map.h:193
CmdBuildObjectArea
CommandCost CmdBuildObjectArea(DoCommandFlag flags, TileIndex tile, TileIndex start_tile, ObjectType type, uint8_t view, bool diagonal)
Construct multiple objects in an area.
Definition: object_cmd.cpp:390
newgrf_config.h
Map::ScaleBySize
static uint ScaleBySize(uint n)
Scales the given value by the map size, where the given value is for a 256 by 256 map.
Definition: map_func.h:328
Owner
Owner
Enum for all companies/owners.
Definition: company_type.h:18
CalculateCompanyValue
Money CalculateCompanyValue(const Company *c, bool including_loan=true)
Calculate the value of the company.
Definition: economy.cpp:149
DC_EXEC
@ DC_EXEC
execute the given command
Definition: command_type.h:371
ObjectSpec::Get
static const ObjectSpec * Get(ObjectType index)
Get the specification associated with a specific ObjectType.
Definition: newgrf_object.cpp:50
PaletteID
uint32_t PaletteID
The number of the palette.
Definition: gfx_type.h:18
WATER_CLASS_INVALID
@ WATER_CLASS_INVALID
Used for industry tiles on land (also for oilrig if newgrf says so).
Definition: water_map.h:51
TileDesc
Tile description for the 'land area information' tool.
Definition: tile_cmd.h:52
DoCommandFlag
DoCommandFlag
List of flags for a command.
Definition: command_type.h:369
genworld.h
Foundation
Foundation
Enumeration for Foundations.
Definition: slope_type.h:93
TriggerObjectAnimation
void TriggerObjectAnimation(Object *o, ObjectAnimationTrigger trigger, const ObjectSpec *spec)
Trigger the update of animation on a whole object.
Definition: newgrf_object.cpp:575
OrthogonalTileArea::h
uint16_t h
The height of the area.
Definition: tilearea_type.h:21
EnsureNoVehicleOnGround
CommandCost EnsureNoVehicleOnGround(TileIndex tile)
Ensure there is no vehicle at the ground at the given position.
Definition: vehicle.cpp:546
Object::IncTypeCount
static void IncTypeCount(ObjectType type)
Increment the count of objects for this type.
Definition: object_base.h:43
IncreaseGeneratingWorldProgress
void IncreaseGeneratingWorldProgress(GenWorldProgress cls)
Increases the current stage of the world generation with one.
Definition: genworld_gui.cpp:1550
IncreaseAnimationStage
static void IncreaseAnimationStage(TileIndex tile)
Increase the animation stage of a whole structure.
Definition: object_cmd.cpp:143
ObjectSpec::GetClearCost
Money GetClearCost() const
Get the cost for clearing a structure of this type.
Definition: newgrf_object.h:95
CommandCost::Succeeded
bool Succeeded() const
Did this command succeed?
Definition: command_type.h:162
IncreaseCompanyHQSize
#define IncreaseCompanyHQSize
We encode the company HQ size in the animation stage.
Definition: object_cmd.cpp:155
object_base.h
RandomRange
static uint32_t RandomRange(uint32_t limit)
Pick a random number between 0 and limit - 1, inclusive.
Definition: random_func.hpp:81
ObjectSpec::callback_mask
uint16_t callback_mask
Bitmask of requested/allowed callbacks.
Definition: newgrf_object.h:74
TileInfo::tileh
Slope tileh
Slope of the tile.
Definition: tile_cmd.h:46
ReallyClearObjectTile
static void ReallyClearObjectTile(Object *o)
Perform the actual removal of the object from the map.
Definition: object_cmd.cpp:513
ChangeTileOwner
void ChangeTileOwner(TileIndex tile, Owner old_owner, Owner new_owner)
Change the owner of a tile.
Definition: landscape.cpp:567
NEW_OBJECT_OFFSET
static const ObjectType NEW_OBJECT_OFFSET
Offset for new objects.
Definition: object_type.h:22
ScaleByCargoScale
uint ScaleByCargoScale(uint num, bool town)
Scale a number by the cargo scale setting.
Definition: economy_func.h:77
IsInvisibilitySet
bool IsInvisibilitySet(TransparencyOption to)
Check if the invisibility option bit is set and if we aren't in the game menu (there's never transpar...
Definition: transparency.h:59
DrawTileSprites::ground
PalSpriteID ground
Palette and sprite for the ground.
Definition: sprite.h:59
TileDesc::build_date
TimerGameCalendar::Date build_date
Date of construction of tile contents.
Definition: tile_cmd.h:57
IsObjectType
bool IsObjectType(Tile t, ObjectType type)
Check whether the object on a tile is of a specific type.
Definition: object_map.h:25
Slope
Slope
Enumeration for the slope-type.
Definition: slope_type.h:48
ObjectSpec::size
uint8_t size
The size of this objects; low nibble for X, high nibble for Y.
Definition: newgrf_object.h:68
DIAGDIR_SW
@ DIAGDIR_SW
Southwest.
Definition: direction_type.h:77
landscape_cmd.h
CheckOwnership
CommandCost CheckOwnership(Owner owner, TileIndex tile)
Check whether the current owner owns something.
Definition: company_cmd.cpp:360
return_cmd_error
#define return_cmd_error(errcode)
Returns from a function with a specific StringID as error.
Definition: command_func.h:38
GetAvailableMoneyForCommand
Money GetAvailableMoneyForCommand()
This functions returns the money which can be used to execute a command.
Definition: company_cmd.cpp:227
EXPENSES_CONSTRUCTION
@ EXPENSES_CONSTRUCTION
Construction costs.
Definition: economy_type.h:173
CommandCost
Common return value for all commands.
Definition: command_type.h:23
WaterClass
WaterClass
classes of water (for WATER_TILE_CLEAR water tile type).
Definition: water_map.h:47
CircularTileSearch
bool CircularTileSearch(TileIndex *tile, uint size, TestTileOnSearchProc proc, void *user_data)
Function performing a search around a center tile and going outward, thus in circle.
Definition: map.cpp:260
clear_func.h
WC_TOWN_AUTHORITY
@ WC_TOWN_AUTHORITY
Town authority; Window numbers:
Definition: window_type.h:194
ObjectType
uint16_t ObjectType
Types of objects.
Definition: object_type.h:14
DirtyCompanyInfrastructureWindows
void DirtyCompanyInfrastructureWindows(CompanyID company)
Redraw all windows with company infrastructure counts.
Definition: company_gui.cpp:2651
GetSlopeMaxZ
static constexpr int GetSlopeMaxZ(Slope s)
Returns the height of the highest corner of a slope relative to TileZ (= minimal height)
Definition: slope_func.h:160
CalcClosestTownFromTile
Town * CalcClosestTownFromTile(TileIndex tile, uint threshold=UINT_MAX)
Return the town closest to the given tile within threshold.
Definition: town_cmd.cpp:3726
ObjectSpec::WasEverAvailable
bool WasEverAvailable() const
Check whether the object was available at some point in the past or present in this game with the cur...
Definition: newgrf_object.cpp:84
OBJECT_FLAG_ANIMATION
@ OBJECT_FLAG_ANIMATION
Object has animated tiles.
Definition: newgrf_object.h:32
OBJECT_FLAG_AUTOREMOVE
@ OBJECT_FLAG_AUTOREMOVE
Object get automatically removed (like "owned land").
Definition: newgrf_object.h:28
autoslope.h
MP_OBJECT
@ MP_OBJECT
Contains objects such as transmitters and owned land.
Definition: tile_type.h:58
TransportType
TransportType
Available types of transport.
Definition: transport_type.h:19
DrawTileSeqStruct::delta_z
int8_t delta_z
0x80 identifies child sprites
Definition: sprite.h:28
_cheats
Cheats _cheats
All the cheats.
Definition: cheat.cpp:16
Object::view
byte view
The view setting for this object.
Definition: object_base.h:29
INVALID_OWNER
@ INVALID_OWNER
An invalid owner.
Definition: company_type.h:29
MP_WATER
@ MP_WATER
Water tile.
Definition: tile_type.h:54
CommandCost::Failed
bool Failed() const
Did this command fail?
Definition: command_type.h:171
station_func.h
WATER_CLASS_CANAL
@ WATER_CLASS_CANAL
Canal.
Definition: water_map.h:49
Object
An object, such as transmitter, on the map.
Definition: object_base.h:23
OrthogonalTileArea
Represents the covered area of e.g.
Definition: tilearea_type.h:18
ObjectSpec::IsEnabled
bool IsEnabled() const
Test if this object is enabled.
Definition: newgrf_object.h:83
water_regions.h
foreach_draw_tile_seq
#define foreach_draw_tile_seq(idx, list)
Iterate through all DrawTileSeqStructs in DrawTileSprites.
Definition: sprite.h:79
_settings_game
GameSettings _settings_game
Game settings of a running game or the scenario editor.
Definition: settings.cpp:55
CBM_OBJ_COLOUR
@ CBM_OBJ_COLOUR
decide the colour of the building
Definition: newgrf_callbacks.h:401
IsTileOnWater
bool IsTileOnWater(Tile t)
Tests if the tile was built on water.
Definition: water_map.h:139
OBJECT_FLAG_CLEAR_INCOME
@ OBJECT_FLAG_CLEAR_INCOME
When object is cleared a positive income is generated instead of a cost.
Definition: newgrf_object.h:30
Object::type
ObjectType type
Type of the object.
Definition: object_base.h:24
MAX_COMPANIES
@ MAX_COMPANIES
Maximum number of companies.
Definition: company_type.h:23
safeguards.h
cargopacket.h
GWP_OBJECT
@ GWP_OBJECT
Generate objects (radio tower, light houses)
Definition: genworld.h:76
ConstructionSettings::freeform_edges
bool freeform_edges
allow terraforming the tiles at the map edges
Definition: settings_type.h:383
CommandCost::GetCost
Money GetCost() const
The costs as made up to this moment.
Definition: command_type.h:83
GetTileSlope
Slope GetTileSlope(TileIndex tile, int *h)
Return the slope of a given tile inside the map.
Definition: tile_map.cpp:59
UpdateCompanyRatingAndValue
int UpdateCompanyRatingAndValue(Company *c, bool update)
if update is set to true, the economy is updated with this score (also the house is updated,...
Definition: economy.cpp:201
CompanyProperties::location_of_HQ
TileIndex location_of_HQ
Northern tile of HQ; INVALID_TILE when there is none.
Definition: company_base.h:76
RandomTile
#define RandomTile()
Get a valid random tile.
Definition: map_func.h:657
DrawTileSprites
Ground palette sprite of a tile, together with its sprite layout.
Definition: sprite.h:58
DC_NO_TEST_TOWN_RATING
@ DC_NO_TEST_TOWN_RATING
town rating does not disallow you from building
Definition: command_type.h:376
GetTileOwner
Owner GetTileOwner(Tile tile)
Returns the owner of a tile.
Definition: tile_map.h:178
FOUNDATION_NONE
@ FOUNDATION_NONE
The tile has no foundation, the slope remains unchanged.
Definition: slope_type.h:94
GetSouthernBridgeEnd
TileIndex GetSouthernBridgeEnd(TileIndex t)
Finds the southern end of a bridge starting at a middle tile.
Definition: bridge_map.cpp:49
GetErrorMessageFromLocationCallbackResult
CommandCost GetErrorMessageFromLocationCallbackResult(uint16_t cb_res, const GRFFile *grffile, StringID default_error)
Get the error message from a shape/location/slope check callback result.
Definition: newgrf_commons.cpp:463
DiagDirection
DiagDirection
Enumeration for diagonal directions.
Definition: direction_type.h:73
CommandCost::AddCost
void AddCost(const Money &cost)
Adds the given cost to the cost of the command.
Definition: command_type.h:63
stdafx.h
landscape.h
TileTypeProcs
Set of callback functions for performing tile operations of a given tile type.
Definition: tile_cmd.h:158
SetAnimationFrame
void SetAnimationFrame(Tile t, byte frame)
Set a new animation frame.
Definition: tile_map.h:262
SetTileOwner
void SetTileOwner(Tile tile, Owner owner)
Sets the owner of a tile.
Definition: tile_map.h:198
Cheat::value
bool value
tells if the bool cheat is active or not
Definition: cheat_type.h:18
viewport_func.h
TileLoop_Water
void TileLoop_Water(TileIndex tile)
Let a water tile floods its diagonal adjoining tiles called from tunnelbridge_cmd,...
Definition: water_cmd.cpp:1230
bridge_map.h
OBJECT_FLAG_ONLY_IN_SCENEDIT
@ OBJECT_FLAG_ONLY_IN_SCENEDIT
Object can only be constructed in the scenario editor.
Definition: newgrf_object.h:26
object_cmd.h
CBID_OBJECT_AUTOSLOPE
@ CBID_OBJECT_AUTOSLOPE
Called to determine if one can alter the ground below an object tile.
Definition: newgrf_callbacks.h:272
AddSortableSpriteToDraw
void AddSortableSpriteToDraw(SpriteID image, PaletteID pal, int x, int y, int w, int h, int dz, int z, bool transparent, int bb_offset_x, int bb_offset_y, int bb_offset_z, const SubSprite *sub)
Draw a (transparent) sprite at given coordinates with a given bounding box.
Definition: viewport.cpp:673
IsValidTile
bool IsValidTile(Tile tile)
Checks if a tile is valid.
Definition: tile_map.h:161
OBJECT_FLAG_HAS_NO_FOUNDATION
@ OBJECT_FLAG_HAS_NO_FOUNDATION
Do not display foundations when on a slope.
Definition: newgrf_object.h:31
newgrf_object.h
ConvertBooleanCallback
bool ConvertBooleanCallback(const GRFFile *grffile, uint16_t cbid, uint16_t cb_res)
Converts a callback result into a boolean.
Definition: newgrf_commons.cpp:529
TileOffsByDiagDir
TileIndexDiff TileOffsByDiagDir(DiagDirection dir)
Convert a DiagDirection to a TileIndexDiff.
Definition: map_func.h:563
ObjectSpec::name
StringID name
The name for this object.
Definition: newgrf_object.h:65
object_map.h
DrawFoundation
void DrawFoundation(TileInfo *ti, Foundation f)
Draw foundation f at tile ti.
Definition: landscape.cpp:427
OBJECT_OWNED_LAND
static const ObjectType OBJECT_OWNED_LAND
Owned land 'flag'.
Definition: object_type.h:19
_generating_world
bool _generating_world
Whether we are generating the map or not.
Definition: genworld.cpp:62
GetObjectType
ObjectType GetObjectType(Tile t)
Gets the ObjectType of the given object tile.
Definition: object_cmd.cpp:66
CALLBACK_FAILED
static const uint CALLBACK_FAILED
Different values for Callback result evaluations.
Definition: newgrf_callbacks.h:420
ObjectSpec::Index
uint Index() const
Gets the index of this spec.
Definition: newgrf_object.cpp:103
object_land.h
_current_company
CompanyID _current_company
Company currently doing an action.
Definition: company_cmd.cpp:50
vehicle_func.h
OAT_BUILT
@ OAT_BUILT
Triggered when the object is built (for all tiles at the same time).
Definition: newgrf_animation_type.h:57
CBM_OBJ_SLOPE_CHECK
@ CBM_OBJ_SLOPE_CHECK
decides slope suitability
Definition: newgrf_callbacks.h:398
Pool::PoolItem<&_object_pool >::Iterate
static Pool::IterateWrapper< Titem > Iterate(size_t from=0)
Returns an iterable ensemble of all valid Titem.
Definition: pool_type.hpp:384
Map::MaxY
static uint MaxY()
Gets the maximum Y coordinate within the map, including MP_VOID.
Definition: map_func.h:306
Pool
Base class for all pools.
Definition: pool_type.hpp:80
TO_STRUCTURES
@ TO_STRUCTURES
other objects such as transmitters and lighthouses
Definition: transparency.h:29
OAT_TILELOOP
@ OAT_TILELOOP
Triggered in the periodic tile loop.
Definition: newgrf_animation_type.h:58
Pool::PoolItem<&_town_pool >::GetNumItems
static size_t GetNumItems()
Returns number of valid items in the pool.
Definition: pool_type.hpp:365
IsDockingTile
bool IsDockingTile(Tile t)
Checks whether the tile is marked as a dockling tile.
Definition: water_map.h:374
GetTilePixelSlope
Slope GetTilePixelSlope(TileIndex tile, int *h)
Return the slope of a given tile.
Definition: tile_map.h:280
TryBuildTransmitter
static bool TryBuildTransmitter()
Try to build a transmitter.
Definition: object_cmd.cpp:792
Map::Size
static debug_inline uint Size()
Get the size of the map.
Definition: map_func.h:288
CheckBuildableTile
CommandCost CheckBuildableTile(TileIndex tile, uint invalid_dirs, int &allowed_z, bool allow_steep, bool check_bridge)
Checks if the given tile is buildable, flat and has a certain height.
Definition: station_cmd.cpp:799
SetGeneratingWorldProgress
void SetGeneratingWorldProgress(GenWorldProgress cls, uint total)
Set the total of a stage of the world generation.
Definition: genworld_gui.cpp:1536
OrthogonalTileArea::tile
TileIndex tile
The base tile of the area.
Definition: tilearea_type.h:19
CBM_OBJ_AUTOSLOPE
@ CBM_OBJ_AUTOSLOPE
decides allowance of autosloping
Definition: newgrf_callbacks.h:403
cheat_type.h
Livery::colour1
Colours colour1
First colour, for all vehicles.
Definition: livery.h:80
MarkTileDirtyByTile
void MarkTileDirtyByTile(TileIndex tile, int bridge_level_offset, int tile_height_override)
Mark a tile given by its index dirty for repaint.
Definition: viewport.cpp:2051
ObjectSpec::GetByTile
static const ObjectSpec * GetByTile(TileIndex tile)
Get the specification associated with a tile.
Definition: newgrf_object.cpp:65
OWNER_NONE
@ OWNER_NONE
The tile has no ownership.
Definition: company_type.h:25
IsObjectTypeTile
bool IsObjectTypeTile(Tile t, ObjectType type)
Check whether a tile is a object tile of a specific type.
Definition: object_map.h:36
Pool::PoolItem<&_object_pool >::CanAllocateItem
static bool CanAllocateItem(size_t n=1)
Helper functions so we can use PoolItem::Function() instead of _poolitem_pool.Function()
Definition: pool_type.hpp:305
SourceType::Headquarters
@ Headquarters
Source/destination are company headquarters.
InvalidateWaterRegion
void InvalidateWaterRegion(TileIndex tile)
Marks the water region that tile is part of as invalid.
Definition: water_regions.cpp:279
OWNER_DEITY
@ OWNER_DEITY
The object is owned by a superuser / goal script.
Definition: company_type.h:27
IsBridgeAbove
bool IsBridgeAbove(Tile t)
checks if a bridge is set above the ground of this tile
Definition: bridge_map.h:45
TileDesc::str
StringID str
Description of the tile.
Definition: tile_cmd.h:53
DC_AUTO
@ DC_AUTO
don't allow building on structures
Definition: command_type.h:372
DC_NO_MODIFY_TOWN_RATING
@ DC_NO_MODIFY_TOWN_RATING
do not change town rating
Definition: command_type.h:381
InitializeObjects
void InitializeObjects()
Initialize/reset the objects.
Definition: object_cmd.cpp:73
company_func.h
Object::DecTypeCount
static void DecTypeCount(ObjectType type)
Decrement the count of objects for this type.
Definition: object_base.h:54
INSTANTIATE_POOL_METHODS
#define INSTANTIATE_POOL_METHODS(name)
Force instantiation of pool methods so we don't get linker errors.
Definition: pool_func.hpp:225
AXIS_X
@ AXIS_X
The X axis.
Definition: direction_type.h:117
OrthogonalTileArea::w
uint16_t w
The width of the area.
Definition: tilearea_type.h:20
ErrorUnknownCallbackResult
void ErrorUnknownCallbackResult(uint32_t grfid, uint16_t cbid, uint16_t cb_res)
Record that a NewGRF returned an unknown/invalid callback result.
Definition: newgrf_commons.cpp:499
TileArea
OrthogonalTileArea TileArea
Shorthand for the much more common orthogonal tile area.
Definition: tilearea_type.h:102
OBJECT_FLAG_BUILT_ON_WATER
@ OBJECT_FLAG_BUILT_ON_WATER
Object can be built on water (not required).
Definition: newgrf_object.h:29
Object::ResetTypeCounts
static void ResetTypeCounts()
Resets object counts.
Definition: object_base.h:72
CheckTileOwnership
CommandCost CheckTileOwnership(TileIndex tile)
Check whether the current owner owns the stuff on the given tile.
Definition: company_cmd.cpp:378
CommandHelper
Definition: command_func.h:93
DrawTileSprites::seq
const DrawTileSeqStruct * seq
Array of child sprites. Terminated with a terminator entry.
Definition: sprite.h:60
OBJECT_FLAG_NOT_ON_LAND
@ OBJECT_FLAG_NOT_ON_LAND
Object can not be on land, implicitly sets OBJECT_FLAG_BUILT_ON_WATER.
Definition: newgrf_object.h:35
window_func.h
Town
Town data structure.
Definition: town.h:50
GetAnimationFrame
byte GetAnimationFrame(Tile t)
Get the current animation frame.
Definition: tile_map.h:250
TileXY
static debug_inline TileIndex TileXY(uint x, uint y)
Returns the TileIndex of a coordinate.
Definition: map_func.h:385
UpdateCompanyHQ
void UpdateCompanyHQ(TileIndex tile, uint score)
Update the CompanyHQ to the state associated with the given score.
Definition: object_cmd.cpp:162
random_func.hpp
GetTileMaxPixelZ
int GetTileMaxPixelZ(TileIndex tile)
Get top height of the tile.
Definition: tile_map.h:304
GetObjectIndex
ObjectID GetObjectIndex(Tile t)
Get the index of which object this tile is attached to.
Definition: object_map.h:47
OverflowSafeInt< int64_t >
CompanyProperties::build_object_limit
uint32_t build_object_limit
Amount of tiles we can (still) build objects on (times 65536). Also applies to buying land.
Definition: company_base.h:89
AnimateNewObjectTile
void AnimateNewObjectTile(TileIndex tile)
Handle the animation of the object tile.
Definition: newgrf_object.cpp:547
TileInfo::x
int x
X position of the tile in unit coordinates.
Definition: tile_cmd.h:44
TimerGameCalendar::date
static Date date
Current date in days (day counter).
Definition: timer_game_calendar.h:34
TileInfo::tile
TileIndex tile
Tile index.
Definition: tile_cmd.h:47
GameSettings::construction
ConstructionSettings construction
construction of things in-game
Definition: settings_type.h:620
MakeObject
void MakeObject(Tile t, Owner o, ObjectID index, WaterClass wc, byte random)
Make an Object tile.
Definition: object_map.h:74
Object::build_date
TimerGameCalendar::Date build_date
Date of construction.
Definition: object_base.h:27
IsTileType
static debug_inline bool IsTileType(Tile tile, TileType type)
Checks if a tile is a given tiletype.
Definition: tile_map.h:150
EconomyIsInRecession
bool EconomyIsInRecession()
Is the economy in recession?
Definition: economy_func.h:49
ObjectSpec::GetBuildCost
Money GetBuildCost() const
Get the cost for building a structure of this type.
Definition: newgrf_object.h:89
GRFFilePropsBase::grffile
const struct GRFFile * grffile
grf file that introduced this entity
Definition: newgrf_commons.h:319
TileX
static debug_inline uint TileX(TileIndex tile)
Get the X component of a tile.
Definition: map_func.h:427
SLOPE_FLAT
@ SLOPE_FLAT
a flat tile
Definition: slope_type.h:49
pool_func.hpp
DrawTileSeqStruct::delta_x
int8_t delta_x
0x80 is sequence terminator
Definition: sprite.h:26
OBJECT_HQ
static const ObjectType OBJECT_HQ
HeadQuarter of a player.
Definition: object_type.h:20
OBJECT_TRANSMITTER
static const ObjectType OBJECT_TRANSMITTER
The large antenna.
Definition: object_type.h:16
OBJECT_LIGHTHOUSE
static const ObjectType OBJECT_LIGHTHOUSE
The nice lighthouse.
Definition: object_type.h:17
ShowCompany
void ShowCompany(CompanyID company)
Show the window with the overview of the company.
Definition: company_gui.cpp:2640
DIAGDIR_NE
@ DIAGDIR_NE
Northeast, upper right on your monitor.
Definition: direction_type.h:75
ClearedObjectArea
Keeps track of removed objects during execution/testruns of commands.
Definition: object_base.h:84
Company
Definition: company_base.h:116
Livery::colour2
Colours colour2
Second colour, for vehicles with 2CC support.
Definition: livery.h:81
ClrBit
constexpr T ClrBit(T &x, const uint8_t y)
Clears a bit in a variable.
Definition: bitmath_func.hpp:151
IsTileOwner
bool IsTileOwner(Tile tile, Owner owner)
Checks if a tile belongs to the given owner.
Definition: tile_map.h:214
OWNER_WATER
@ OWNER_WATER
The tile/execution is done by "water".
Definition: company_type.h:26
HasTileWaterGround
bool HasTileWaterGround(Tile t)
Checks whether the tile has water at the ground.
Definition: water_map.h:353
Livery
Information about a particular livery.
Definition: livery.h:78
Object::town
Town * town
Town the object is built in.
Definition: object_base.h:25
ToggleBit
constexpr T ToggleBit(T &x, const uint8_t y)
Toggles a bit in a variable.
Definition: bitmath_func.hpp:181
OWNER_TOWN
@ OWNER_TOWN
A town owns the tile, or a town is expanding.
Definition: company_type.h:24
UpdateObjectColours
void UpdateObjectColours(const Company *c)
Updates the colour of the object whenever a company changes.
Definition: object_cmd.cpp:181
DrawGroundSprite
void DrawGroundSprite(SpriteID image, PaletteID pal, const SubSprite *sub, int extra_offs_x, int extra_offs_y)
Draws a ground sprite for the current tile.
Definition: viewport.cpp:589
CmdBuildObject
CommandCost CmdBuildObject(DoCommandFlag flags, TileIndex tile, ObjectType type, uint8_t view)
Build an object object.
Definition: object_cmd.cpp:208
object.h
GRFConfig::GetName
const char * GetName() const
Get the name of this grf.
Definition: newgrf_config.cpp:98
DrawTileSeqStruct
A tile child sprite and palette to draw for stations etc, with 3D bounding box.
Definition: sprite.h:25
ObjectSpec::flags
ObjectFlags flags
Flags/settings related to the object.
Definition: newgrf_object.h:73
ObjectSpec::views
uint8_t views
The number of views.
Definition: newgrf_object.h:76
HasBit
constexpr debug_inline bool HasBit(const T x, const uint8_t y)
Checks if a bit in a value is set.
Definition: bitmath_func.hpp:103