15 #include "3rdparty/nlohmann/json.hpp"
47 void GenerateClearTile();
49 void GenerateObjects();
52 void StartupEconomy();
54 void StartupDisasters();
56 void InitializeGame(uint size_x, uint size_y,
bool reset_date,
bool reset_settings);
103 ScriptObject::InitializeRandomizers();
115 bool landscape_generated =
false;
122 if (!landscape_generated) {
134 ConvertGroundTilesIntoWaterTiles();
142 if (_game_mode != GM_EDITOR) {
167 for (i = 0; i < 0x500; i++) {
173 if (_game_mode != GM_EDITOR) {
179 for (i = 0; i < 2500; i++) {
192 _cur_company.
Trash();
209 if (_debug_desync_level > 0) {
221 Debug(net, 0,
"Generating map failed; closing server");
304 uint estimated_height = 0;
313 estimated_height = 0;
366 TownID
id = std::get<TownID>(result);
369 if (
id == INVALID_TOWN)
return false;
385 if (!f.has_value()) {
390 std::string text(filesize,
'\0');
391 size_t len = fread(text.data(), filesize, 1, *f);
399 nlohmann::json town_data;
401 town_data = nlohmann::json::parse(text);
402 }
catch (nlohmann::json::exception &) {
408 if (!town_data.is_array()) {
413 std::vector<std::pair<Town *, uint> > towns;
414 uint failed_towns = 0;
417 for (
auto &feature : town_data) {
421 if (!feature.is_object()) {
428 if (!feature.contains(
"name") || !feature.at(
"name").is_string()) {
434 if (!feature.contains(
"population") || !feature.at(
"population").is_number() ||
435 !feature.contains(
"city") || !feature.at(
"city").is_boolean() ||
436 !feature.contains(
"x") || !feature.at(
"x").is_number() ||
437 !feature.contains(
"y") || !feature.at(
"y").is_number()) {
438 feature.at(
"name").get_to(town.
name);
445 feature.at(
"name").get_to(town.
name);
446 feature.at(
"population").get_to(town.
population);
447 feature.at(
"city").get_to(town.
is_city);
471 default: NOT_REACHED();
491 if (failed_towns > 0) {
497 for (
const auto &item : towns) {
498 Town *t = item.first;
499 uint population = item.second;
503 int try_limit = 1000;
510 const int HOUSES_TO_GROW = 10;
516 }
while (fail_limit > 0 && try_limit-- > 0 && t->
cache.
population < population);
Class for backupping variables and making sure they are restored later.
static void StartNew()
Start up a new GameScript.
static class GameInstance * GetInstance()
Get the current active instance.
static void GameLoop()
Called every game-tick to let Game do something.
static Date date
Current date in days (day counter).
static TickCounter counter
Monotonic counter, in ticks, since start of game.
@ DC_EXEC
execute the given command
CompanyID _local_company
Company controlled by the human player at this client. Can also be COMPANY_SPECTATOR.
void SetLocalCompany(CompanyID new_company)
Sets the local company and updates the settings that are set on a per-company basis to reflect the co...
CompanyID _current_company
Company currently doing an action.
Functions related to companies.
@ COMPANY_SPECTATOR
The client is spectating.
@ OWNER_NONE
The tile has no ownership.
#define Debug(category, level, format_string,...)
Ouptut a line of debugging information.
void StartupEngines()
Start/initialise all our engines.
Functions related to engines.
Functions related to errors.
void UnshowCriticalError()
Unshow the critical error.
void ShowErrorMessage(StringID summary_msg, int x, int y, CommandCost cc)
Display an error message in a window.
void ShowFirstError()
Show the first error of the queue.
@ WL_WARNING
Other information.
@ WL_ERROR
Errors (eg. saving/loading failed)
std::optional< FileHandle > FioFOpenFile(const std::string &filename, const char *mode, Subdirectory subdir, size_t *filesize)
Opens a OpenTTD file somewhere in a personal or global directory.
@ SLO_SAVE
File is being saved.
@ DFT_GAME_FILE
Save game or scenario file.
@ HEIGHTMAP_DIR
Subdirectory of scenario for heightmaps.
@ AUTOSAVE_DIR
Subdirectory of save for autosaves.
Base functions for all Games.
The GameInstance tracks games.
bool _generating_world
Whether we are generating the map or not.
void GenerateWorldSetCallback(GWDoneProc *proc)
Set here the function, if any, that you want to be called when landscape generation is done.
void GenerateWorldSetAbortCallback(GWAbortProc *proc)
Set here the function, if any, that you want to be called when landscape generation is aborted.
void HandleGeneratingWorldAbortion()
Really handle the abortion, i.e.
GenWorldInfo _gw
Please only use this variable in genworld.h and genworld.cpp and nowhere else.
void GenerateTrees()
Place new trees.
static void _GenerateWorld()
The internal, real, generate function.
static bool TryFoundTownNearby(TileIndex tile, void *user_data)
Helper for CircularTileSearch to found a town on or near a given tile.
void GenerateIndustries()
This function will create random industries during game creation.
static void CleanupGeneration()
Generation is done; show windows again and delete the progress window.
void GenerateWorld(GenWorldMode mode, uint size_x, uint size_y, bool reset_settings)
Generate a world.
void AbortGeneratingWorld()
Initializes the abortion process.
bool IsGeneratingWorldAborted()
Is the generation being aborted?
void LoadTownData()
Load town data from _file_to_saveload, place towns at the appropriate locations, and expand them to t...
void StartupCompanies()
Start of a new game.
Functions related to world/map generation.
void GWAbortProc()
Called when genworld is aborted.
void IncreaseGeneratingWorldProgress(GenWorldProgress cls)
Increases the current stage of the world generation with one.
static const uint MAP_HEIGHT_LIMIT_AUTO_MINIMUM
When map height limit is auto, make this the lowest possible map height limit.
void ShowGenerateWorldProgress()
Show the window where a user can follow the process of the map generation.
GenWorldMode
Modes for GenerateWorld.
@ GWM_HEIGHTMAP
Generate a newgame from a heightmap.
@ GWM_EMPTY
Generate an empty map (sea-level)
@ GWP_OBJECT
Generate objects (radio tower, light houses)
@ GWP_MAP_INIT
Initialize/allocate the map, start economy.
@ GWP_RUNSCRIPT
Runs the game script at most 2500 times, or when ever the script sleeps.
@ GWP_GAME_START
Really prepare to start the game.
@ GWP_GAME_INIT
Initialize the game.
@ GWP_RUNTILELOOP
Runs the tile loop 1280 times to make snow etc.
void GWDoneProc()
Procedure called when the genworld process finishes.
static const uint MAP_HEIGHT_LIMIT_AUTO_CEILING_ROOM
When map height limit is auto, the map height limit will be the higest peak plus this value.
static const uint32_t GENERATE_NEW_SEED
Create a new random seed.
void SetGeneratingWorldProgress(GenWorldProgress cls, uint total)
Set the total of a stage of the world generation.
void PrepareGenerateWorldProgress()
Initializes the progress counters to the starting point.
@ LG_TERRAGENESIS
TerraGenesis Perlin landscape generator.
void SetMouseCursorBusy(bool busy)
Set or unset the ZZZ cursor.
void LoadStringWidthTable(bool monospace)
Initialize _stringwidth_table cache.
SwitchMode _switch_mode
The next mainloop command.
void GfxLoadSprites()
Initialise and load all the sprites.
Functions related to the graphics initialization.
void MarkWholeScreenDirty()
This function mark the whole screen as dirty.
void FlatEmptyWorld(uint8_t tile_height)
Make an empty world where all tiles are of height 'tile_height'.
Functions related to creating heightmaps from files.
@ HM_CLOCKWISE
Rotate the map clockwise 45 degrees.
@ HM_COUNTER_CLOCKWISE
Rotate the map counter clockwise 45 degrees.
void RunTileLoop()
Gradually iterate over all tiles on the map, calling their TileLoopProcs once every TILE_UPDATE_FREQU...
bool GenerateLandscape(uint8_t mode)
Functions related to OTTD's landscape.
void ShowVitalWindows()
Show the vital in-game windows.
void SetupColoursAndInitialWindow()
Initialise the default colours (remaps and the likes), and load the main windows.
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.
static debug_inline TileIndex TileXY(uint x, uint y)
Returns the TileIndex of a coordinate.
bool _network_dedicated
are we a dedicated server?
Basic functions/variables used all over the place.
Base for the NewGRF implementation.
void ShowNewGRFError()
Show the first NewGRF error we can find.
void InitializeBuildingCounts(Town *t)
Initialise building counts for a town.
Functions related to NewGRF houses.
@ PSM_ENTER_GAMELOOP
Enter the gameloop, changes will be permanent.
@ PSM_LEAVE_GAMELOOP
Leave the gameloop, changes will be temporary.
@ SM_MENU
Switch to game intro menu.
@ SM_EDITOR
Switch to scenario editor.
void SetModalProgress(bool state)
Set the modal progress state.
Functions related to modal progress.
bool HasModalProgress()
Check if we are currently in a modal progress state.
Randomizer _random
Random used in the game state calculations.
Pseudo random number generator.
A number of safeguards to prevent using unsafe methods.
SaveOrLoadResult SaveOrLoad(const std::string &filename, SaveLoadOperation fop, DetailedFileType dft, Subdirectory sb, bool threaded)
Main Save or Load function where the high-level saveload functions are handled.
FileToSaveLoad _file_to_saveload
File to save or load in the openttd loop.
Functions/types related to saving and loading games.
GameSettings _settings_game
Game settings of a running game or the scenario editor.
Command definitions related to signs.
Definition of base types and functions in a cross-platform compatible way.
Functions related to low-level strings.
void SetDParam(size_t n, uint64_t v)
Set a string parameter v at index n in the global string parameter array.
void SetDParamStr(size_t n, const char *str)
This function is used to "bind" a C string to a OpenTTD dparam slot.
Functions related to OTTD's strings.
static const StringID INVALID_STRING_ID
Constant representing an invalid string (16bit in case it is used in savegames)
Class to backup a specific variable and restore it later.
bool IsValid() const
Checks whether the variable was already restored.
void Trash()
Trash the backup.
void Restore()
Restore the variable.
static void SwitchMode(PersistentStorageMode mode, bool ignore_prev_mode=false)
Clear temporary changes made since the last call to SwitchMode, and set whether subsequent changes sh...
bool freeform_edges
allow terraforming the tiles at the map edges
uint8_t map_height_limit
the maximum allowed heightlevel
TownLayout town_layout
select town layout,
Town data imported from JSON files and used to place towns.
std::string name
The name of the town.
bool is_city
Should it be created as a city in OpenTTD? If input is blank, defaults to false.
uint population
The target population of the town when created in OpenTTD. If input is blank, defaults to 0.
float x_proportion
The X coordinate of the town, as a proportion 0..1 of the maximum X coordinate.
TownID town_id
The TownID of the town in OpenTTD. Not imported, but set during the founding proceess and stored here...
float y_proportion
The Y coordinate of the town, as a proportion 0..1 of the maximum Y coordinate.
std::string name
Name of the file.
uint8_t snow_line_height
the configured snow line height (deduced from "snow_coverage")
uint8_t land_generator
the landscape generator
uint8_t se_flat_world_height
land height a flat world gets in SE
uint8_t heightmap_rotation
rotation director for the heightmap
uint32_t generation_seed
noise seed for world generation
uint8_t heightmap_height
highest mountain for heightmap (towards what it scales)
EconomySettings economy
settings to change the economy
ConstructionSettings construction
construction of things in-game
GameCreationSettings game_creation
settings used during the creation of a game (map)
Properties of current genworld process.
GWDoneProc * proc
Proc that is called when done (can be nullptr)
CompanyID lc
The local_company before generating.
uint size_x
X-size of the map.
uint size_y
Y-size of the map.
bool abort
Whether to abort the thread ASAP.
GWAbortProc * abortp
Proc that is called when aborting (can be nullptr)
GenWorldMode mode
What mode are we making a world in.
static uint SizeY()
Get the size of the map along the Y.
static debug_inline uint SizeX()
Get the size of the map along the X.
static uint MaxY()
Gets the maximum Y coordinate within the map, including MP_VOID.
static debug_inline uint MaxX()
Gets the maximum X coordinate within the map, including MP_VOID.
Tindex index
Index of this pool item.
static Titem * Get(size_t index)
Returns Titem with given index.
void SetSeed(uint32_t seed)
(Re)set the state of the random number generator.
uint32_t population
Current population of people.
uint32_t num_houses
Amount of houses.
TownCache cache
Container for all cacheable data.
uint GetEstimationTGPMapHeight()
Get an overestimation of the highest peak TGP wants to generate.
Functions for the Perlin noise enhanced map generator.
static const uint DEF_SNOWLINE_HEIGHT
Default snowline height.
static const uint MAX_MAP_HEIGHT_LIMIT
Upper bound of maximum allowed heightlevel (in the construction settings)
Functions related to tile highlights.
void ResetObjectToPlace()
Reset the cursor and mouse mode handling back to default (normal cursor, only clicking in windows).
void SetObjectToPlace(CursorID icon, PaletteID pal, HighLightStyle mode, WindowClass window_class, WindowNumber window_num)
Change the cursor and mouse click/drag handling to a mode for performing special operations like tile...
Definition of the game-calendar-timer.
Definition of the tick-based game-timer.
bool CheckTownRoadTypes()
Check if towns are able to build road.
bool GenerateTowns(TownLayout layout)
Generate a number of towns with a given layout.
Command definitions related to towns.
Base of all video drivers.
bool ScrollMainWindowToTile(TileIndex tile, bool instant)
Scrolls the viewport of the main window to a given location.
Functions related to (drawing on) viewports.
Map accessors for void tiles.
void MakeVoid(Tile t)
Make a nice void tile ;)
Functions related to water (management)
void CloseWindowByClass(WindowClass cls, int data)
Close all windows of a given class.
void ResetWindowSystem()
Reset the windowing system, by means of shutting it down followed by re-initialization.
void HideVitalWindows()
Close all always on-top windows to get an empty screen.
void CloseAllNonVitalWindows()
It is possible that a stickied window gets to a position where the 'close' button is outside the gami...
Window functions not directly related to making/drawing windows.
@ WC_MAIN_WINDOW
Main window; Window numbers:
@ WC_MODAL_PROGRESS
Progress report of landscape generation; Window numbers: