Skip to content

Instantly share code, notes, and snippets.

@Wolfolo
Last active August 22, 2017 22:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Wolfolo/d7cfc9f2018339453d14f62a9e6e26d6 to your computer and use it in GitHub Desktop.
Save Wolfolo/d7cfc9f2018339453d14f62a9e6e26d6 to your computer and use it in GitHub Desktop.
Game state handling with singleton
diff --git a/projects/openttd_vs100.vcxproj b/projects/openttd_vs100.vcxproj
index 9c3b107..df8c58b 100644
--- a/projects/openttd_vs100.vcxproj
+++ b/projects/openttd_vs100.vcxproj
@@ -334,6 +334,7 @@
<ClCompile Include="..\src\fontcache.cpp" />
<ClCompile Include="..\src\fontdetection.cpp" />
<ClCompile Include="..\src\base_consist.cpp" />
+ <ClCompile Include="..\src\game_state.cpp" />
<ClCompile Include="..\src\gamelog.cpp" />
<ClCompile Include="..\src\genworld.cpp" />
<ClCompile Include="..\src\gfx.cpp" />
@@ -470,6 +471,7 @@
<ClInclude Include="..\src\fontcache.h" />
<ClInclude Include="..\src\fontdetection.h" />
<ClInclude Include="..\src\base_consist.h" />
+ <ClInclude Include="..\src\game_state.h" />
<ClInclude Include="..\src\gamelog.h" />
<ClInclude Include="..\src\gamelog_internal.h" />
<ClInclude Include="..\src\genworld.h" />
diff --git a/projects/openttd_vs100.vcxproj.filters b/projects/openttd_vs100.vcxproj.filters
index 06800ff..4001a5f 100644
--- a/projects/openttd_vs100.vcxproj.filters
+++ b/projects/openttd_vs100.vcxproj.filters
@@ -195,6 +195,9 @@
<ClCompile Include="..\src\base_consist.cpp">
<Filter>Source Files</Filter>
</ClCompile>
+ <ClCompile Include="..\src\game_state.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
<ClCompile Include="..\src\gamelog.cpp">
<Filter>Source Files</Filter>
</ClCompile>
@@ -603,6 +606,9 @@
<ClInclude Include="..\src\base_consist.h">
<Filter>Header Files</Filter>
</ClInclude>
+ <ClInclude Include="..\src\game_state.h">
+ <Filter>Header Files</Filter>
+ </ClInclude>
<ClInclude Include="..\src\gamelog.h">
<Filter>Header Files</Filter>
</ClInclude>
diff --git a/projects/openttd_vs140.vcxproj b/projects/openttd_vs140.vcxproj
index eb84941..32e1905 100644
--- a/projects/openttd_vs140.vcxproj
+++ b/projects/openttd_vs140.vcxproj
@@ -351,6 +351,7 @@
<ClCompile Include="..\src\fontcache.cpp" />
<ClCompile Include="..\src\fontdetection.cpp" />
<ClCompile Include="..\src\base_consist.cpp" />
+ <ClCompile Include="..\src\game_state.cpp" />
<ClCompile Include="..\src\gamelog.cpp" />
<ClCompile Include="..\src\genworld.cpp" />
<ClCompile Include="..\src\gfx.cpp" />
@@ -487,6 +488,7 @@
<ClInclude Include="..\src\fontcache.h" />
<ClInclude Include="..\src\fontdetection.h" />
<ClInclude Include="..\src\base_consist.h" />
+ <ClInclude Include="..\src\game_state.h" />
<ClInclude Include="..\src\gamelog.h" />
<ClInclude Include="..\src\gamelog_internal.h" />
<ClInclude Include="..\src\genworld.h" />
diff --git a/projects/openttd_vs140.vcxproj.filters b/projects/openttd_vs140.vcxproj.filters
index 06800ff..4001a5f 100644
--- a/projects/openttd_vs140.vcxproj.filters
+++ b/projects/openttd_vs140.vcxproj.filters
@@ -195,6 +195,9 @@
<ClCompile Include="..\src\base_consist.cpp">
<Filter>Source Files</Filter>
</ClCompile>
+ <ClCompile Include="..\src\game_state.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
<ClCompile Include="..\src\gamelog.cpp">
<Filter>Source Files</Filter>
</ClCompile>
@@ -603,6 +606,9 @@
<ClInclude Include="..\src\base_consist.h">
<Filter>Header Files</Filter>
</ClInclude>
+ <ClInclude Include="..\src\game_state.h">
+ <Filter>Header Files</Filter>
+ </ClInclude>
<ClInclude Include="..\src\gamelog.h">
<Filter>Header Files</Filter>
</ClInclude>
diff --git a/projects/openttd_vs80.vcproj b/projects/openttd_vs80.vcproj
index 70dcab2..2d8ec0e 100644
--- a/projects/openttd_vs80.vcproj
+++ b/projects/openttd_vs80.vcproj
@@ -559,6 +559,10 @@
>
</File>
<File
+ RelativePath=".\..\src\game_state.cpp"
+ >
+ </File>
+ <File
RelativePath=".\..\src\gamelog.cpp"
>
</File>
@@ -1107,6 +1111,10 @@
>
</File>
<File
+ RelativePath=".\..\src\game_state.h"
+ >
+ </File>
+ <File
RelativePath=".\..\src\gamelog.h"
>
</File>
diff --git a/projects/openttd_vs90.vcproj b/projects/openttd_vs90.vcproj
index dd722d0..caee008 100644
--- a/projects/openttd_vs90.vcproj
+++ b/projects/openttd_vs90.vcproj
@@ -556,6 +556,10 @@
>
</File>
<File
+ RelativePath=".\..\src\game_state.cpp"
+ >
+ </File>
+ <File
RelativePath=".\..\src\gamelog.cpp"
>
</File>
@@ -1104,6 +1108,10 @@
>
</File>
<File
+ RelativePath=".\..\src\game_state.h"
+ >
+ </File>
+ <File
RelativePath=".\..\src\gamelog.h"
>
</File>
diff --git a/source.list b/source.list
index df35cdd..67afd98 100644
--- a/source.list
+++ b/source.list
@@ -30,6 +30,7 @@ fios.cpp
fontcache.cpp
fontdetection.cpp
base_consist.cpp
+game_state.cpp
gamelog.cpp
genworld.cpp
gfx.cpp
@@ -197,6 +198,7 @@ fios.h
fontcache.h
fontdetection.h
base_consist.h
+game_state.h
gamelog.h
gamelog_internal.h
genworld.h
diff --git a/src/ai/ai_config.cpp b/src/ai/ai_config.cpp
index f920d31..b5d1283 100644
--- a/src/ai/ai_config.cpp
+++ b/src/ai/ai_config.cpp
@@ -38,7 +38,7 @@ ScriptConfigItem _start_date_config = {
/* static */ AIConfig *AIConfig::GetConfig(CompanyID company, ScriptSettingSource source)
{
AIConfig **config;
- if (source == SSS_FORCE_NEWGAME || (source == SSS_DEFAULT && _game_mode == GM_MENU)) {
+ if (source == SSS_FORCE_NEWGAME || (source == SSS_DEFAULT && GameState::GetInstance()->IsGameMode(GM_MENU))) {
config = &_settings_newgame.ai_config[company];
} else {
config = &_settings_game.ai_config[company];
diff --git a/src/ai/ai_gui.cpp b/src/ai/ai_gui.cpp
index 101a97d..5e39898 100644
--- a/src/ai/ai_gui.cpp
+++ b/src/ai/ai_gui.cpp
@@ -222,7 +222,7 @@ struct AIListWindow : public Window {
*/
virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
{
- if (_game_mode == GM_NORMAL && Company::IsValidID(this->slot)) {
+ if (GameState::GetInstance()->IsGameMode(GM_NORMAL) && Company::IsValidID(this->slot)) {
delete this;
return;
}
@@ -292,6 +292,7 @@ struct AISettingsWindow : public Window {
Scrollbar *vscroll; ///< Cache of the vertical scrollbar.
typedef std::vector<const ScriptConfigItem *> VisibleSettingsList;
VisibleSettingsList visible_settings; ///< List of visible AI settings
+ GameState *gs;
/**
* Constructor for the window.
@@ -305,13 +306,14 @@ struct AISettingsWindow : public Window {
closing_dropdown(false),
timeout(0)
{
+ this->gs = GameState::GetInstance();
this->ai_config = GetConfig(slot);
this->CreateNestedTree();
this->vscroll = this->GetScrollbar(WID_AIS_SCROLLBAR);
this->FinishInitNested(slot); // Initializes 'this->line_height' as side effect.
- this->SetWidgetDisabledState(WID_AIS_RESET, _game_mode != GM_MENU && Company::IsValidID(this->slot));
+ this->SetWidgetDisabledState(WID_AIS_RESET, !this->gs->IsGameMode(GM_MENU) && Company::IsValidID(this->slot));
this->RebuildVisibleSettings();
}
@@ -377,7 +379,7 @@ struct AISettingsWindow : public Window {
for (; this->vscroll->IsVisible(i) && it != visible_settings.end(); i++, it++) {
const ScriptConfigItem &config_item = **it;
int current_value = config->GetSetting((config_item).name);
- bool editable = _game_mode == GM_MENU || ((this->slot != OWNER_DEITY) && !Company::IsValidID(this->slot)) || (config_item.flags & SCRIPTCONFIG_INGAME) != 0;
+ bool editable = this->gs->IsGameMode(GM_MENU) || ((this->slot != OWNER_DEITY) && !Company::IsValidID(this->slot)) || (config_item.flags & SCRIPTCONFIG_INGAME) != 0;
StringID str;
TextColour colour;
@@ -440,7 +442,7 @@ struct AISettingsWindow : public Window {
VisibleSettingsList::const_iterator it = this->visible_settings.begin();
for (int i = 0; i < num; i++) it++;
const ScriptConfigItem config_item = **it;
- if (_game_mode == GM_NORMAL && ((this->slot == OWNER_DEITY) || Company::IsValidID(this->slot)) && (config_item.flags & SCRIPTCONFIG_INGAME) == 0) return;
+ if (this->gs->IsGameMode(GM_NORMAL) && ((this->slot == OWNER_DEITY) || Company::IsValidID(this->slot)) && (config_item.flags & SCRIPTCONFIG_INGAME) == 0) return;
if (this->clicked_row != num) {
DeleteChildWindows(WC_QUERY_STRING);
@@ -521,7 +523,7 @@ struct AISettingsWindow : public Window {
break;
case WID_AIS_RESET:
- if (_game_mode == GM_MENU || !Company::IsValidID(this->slot)) {
+ if (this->gs->IsGameMode(GM_MENU) || !Company::IsValidID(this->slot)) {
this->ai_config->ResetSettings();
this->SetDirty();
}
@@ -535,7 +537,7 @@ struct AISettingsWindow : public Window {
VisibleSettingsList::const_iterator it = this->visible_settings.begin();
for (int i = 0; i < this->clicked_row; i++) it++;
const ScriptConfigItem config_item = **it;
- if (_game_mode == GM_NORMAL && ((this->slot == OWNER_DEITY) || Company::IsValidID(this->slot)) && (config_item.flags & SCRIPTCONFIG_INGAME) == 0) return;
+ if (this->gs->IsGameMode(GM_NORMAL) && ((this->slot == OWNER_DEITY) || Company::IsValidID(this->slot)) && (config_item.flags & SCRIPTCONFIG_INGAME) == 0) return;
int32 value = atoi(str);
this->ai_config->SetSetting(config_item.name, value);
this->SetDirty();
@@ -547,7 +549,7 @@ struct AISettingsWindow : public Window {
VisibleSettingsList::const_iterator it = this->visible_settings.begin();
for (int i = 0; i < this->clicked_row; i++) it++;
const ScriptConfigItem config_item = **it;
- if (_game_mode == GM_NORMAL && ((this->slot == OWNER_DEITY) || Company::IsValidID(this->slot)) && (config_item.flags & SCRIPTCONFIG_INGAME) == 0) return;
+ if (this->gs->IsGameMode(GM_NORMAL) && ((this->slot == OWNER_DEITY) || Company::IsValidID(this->slot)) && (config_item.flags & SCRIPTCONFIG_INGAME) == 0) return;
this->ai_config->SetSetting(config_item.name, index);
this->SetDirty();
}
@@ -716,9 +718,11 @@ struct AIConfigWindow : public Window {
CompanyID selected_slot; ///< The currently selected AI slot or \c INVALID_COMPANY.
int line_height; ///< Height of a single AI-name line.
Scrollbar *vscroll; ///< Cache of the vertical scrollbar.
+ GameState *gs;
AIConfigWindow() : Window(&_ai_config_desc)
{
+ this->gs = GameState::GetInstance();
this->InitNested(WN_GAME_OPTIONS_AI); // Initializes 'this->line_height' as a side effect.
this->vscroll = this->GetScrollbar(WID_AIC_SCROLLBAR);
this->selected_slot = INVALID_COMPANY;
@@ -796,9 +800,11 @@ struct AIConfigWindow : public Window {
*/
static bool IsEditable(CompanyID slot)
{
- if (slot == OWNER_DEITY) return _game_mode != GM_NORMAL || Game::GetInstance() != NULL;
+ GameState *gs = GameState::GetInstance();
- if (_game_mode != GM_NORMAL) {
+ if (slot == OWNER_DEITY) return !gs->IsGameMode(GM_NORMAL) || Game::GetInstance() != NULL;
+
+ if (!gs->IsGameMode(GM_NORMAL)) {
return slot > 0 && slot <= GetGameSettings().difficulty.max_no_competitors;
}
if (Company::IsValidID(slot) || slot < 0) return false;
@@ -832,7 +838,7 @@ struct AIConfigWindow : public Window {
for (int i = this->vscroll->GetPosition(); this->vscroll->IsVisible(i) && i < MAX_COMPANIES; i++) {
StringID text;
- if ((_game_mode != GM_NORMAL && i == 0) || (_game_mode == GM_NORMAL && Company::IsValidHumanID(i))) {
+ if ((!this->gs->IsGameMode(GM_NORMAL) && i == 0) || (this->gs->IsGameMode(GM_NORMAL) && Company::IsValidHumanID(i))) {
text = STR_AI_CONFIG_HUMAN_PLAYER;
} else if (AIConfig::GetConfig((CompanyID)i)->GetInfo() != NULL) {
SetDParamStr(0, AIConfig::GetConfig((CompanyID)i)->GetInfo()->GetName());
@@ -875,7 +881,7 @@ struct AIConfigWindow : public Window {
case WID_AIC_GAMELIST: {
this->selected_slot = OWNER_DEITY;
this->InvalidateData();
- if (click_count > 1 && this->selected_slot != INVALID_COMPANY && _game_mode != GM_NORMAL) ShowAIListWindow((CompanyID)this->selected_slot);
+ if (click_count > 1 && this->selected_slot != INVALID_COMPANY && !this->gs->IsGameMode(GM_NORMAL)) ShowAIListWindow((CompanyID)this->selected_slot);
break;
}
@@ -943,7 +949,7 @@ struct AIConfigWindow : public Window {
this->SetWidgetDisabledState(WID_AIC_DECREASE, GetGameSettings().difficulty.max_no_competitors == 0);
this->SetWidgetDisabledState(WID_AIC_INCREASE, GetGameSettings().difficulty.max_no_competitors == MAX_COMPANIES - 1);
- this->SetWidgetDisabledState(WID_AIC_CHANGE, (this->selected_slot == OWNER_DEITY && _game_mode == GM_NORMAL) || this->selected_slot == INVALID_COMPANY);
+ this->SetWidgetDisabledState(WID_AIC_CHANGE, (this->selected_slot == OWNER_DEITY && this->gs->IsGameMode(GM_NORMAL)) || this->selected_slot == INVALID_COMPANY);
this->SetWidgetDisabledState(WID_AIC_CONFIGURE, this->selected_slot == INVALID_COMPANY || GetConfig(this->selected_slot)->GetConfigList()->size() == 0);
this->SetWidgetDisabledState(WID_AIC_MOVE_UP, this->selected_slot == OWNER_DEITY || this->selected_slot == INVALID_COMPANY || !IsEditable((CompanyID)(this->selected_slot - 1)));
this->SetWidgetDisabledState(WID_AIC_MOVE_DOWN, this->selected_slot == OWNER_DEITY || this->selected_slot == INVALID_COMPANY || !IsEditable((CompanyID)(this->selected_slot + 1)));
@@ -1429,7 +1435,7 @@ NWidgetBase *MakeCompanyButtonRowsAIDebug(int *biggest_index)
*/
static EventState AIDebugGlobalHotkeys(int hotkey)
{
- if (_game_mode != GM_NORMAL) return ES_NOT_HANDLED;
+ if (!GameState::GetInstance()->IsGameMode(GM_NORMAL)) return ES_NOT_HANDLED;
Window *w = ShowAIDebugWindow(INVALID_COMPANY);
if (w == NULL) return ES_NOT_HANDLED;
return w->OnHotkey(hotkey);
diff --git a/src/airport_gui.cpp b/src/airport_gui.cpp
index 6437f23..4aceff4 100644
--- a/src/airport_gui.cpp
+++ b/src/airport_gui.cpp
@@ -159,7 +159,7 @@ struct BuildAirToolbarWindow : Window {
*/
static EventState AirportToolbarGlobalHotkeys(int hotkey)
{
- if (_game_mode != GM_NORMAL || !CanBuildVehicleInfrastructure(VEH_AIRCRAFT)) return ES_NOT_HANDLED;
+ if (!GameState::GetInstance()->IsGameMode(GM_NORMAL) || !CanBuildVehicleInfrastructure(VEH_AIRCRAFT)) return ES_NOT_HANDLED;
Window *w = ShowBuildAirToolbar();
if (w == NULL) return ES_NOT_HANDLED;
return w->OnHotkey(hotkey);
diff --git a/src/autoslope.h b/src/autoslope.h
index e504610..bdf23e4 100644
--- a/src/autoslope.h
+++ b/src/autoslope.h
@@ -47,7 +47,7 @@ static inline bool AutoslopeEnabled()
{
return (_settings_game.construction.autoslope &&
(_current_company < MAX_COMPANIES ||
- (_current_company == OWNER_NONE && _game_mode == GM_EDITOR)));
+ (_current_company == OWNER_NONE && GameState::GetInstance()->IsGameMode(GM_EDITOR))));
}
#endif /* AUTOSLOPE_H */
diff --git a/src/bootstrap_gui.cpp b/src/bootstrap_gui.cpp
index 7abc385..ee2f28b 100644
--- a/src/bootstrap_gui.cpp
+++ b/src/bootstrap_gui.cpp
@@ -21,6 +21,7 @@
#include "network/network.h"
#include "network/network_content_gui.h"
#include "openttd.h"
+#include "game_state.h"
#include "strings_func.h"
#include "video/video_driver.hpp"
#include "window_func.h"
@@ -93,11 +94,13 @@ public:
/* We have completed downloading. We can trigger finding the right set now. */
BaseGraphics::FindSets();
+ GameState *gs = GameState::GetInstance();
+
/* And continue going into the menu. */
- _game_mode = GM_MENU;
+ gs->SetGameMode(GM_MENU);
/* _exit_game is used to break out of the outer video driver's MainLoop. */
- _exit_game = true;
+ gs->ExitGame(true);
delete this;
}
};
@@ -181,7 +184,7 @@ public:
break;
case WID_BAFD_NO:
- _exit_game = true;
+ GameState::GetInstance()->ExitGame(true);
break;
default:
@@ -224,7 +227,8 @@ bool HandleBootstrap()
if (!_network_available) goto failure;
/* First tell the game we're bootstrapping. */
- _game_mode = GM_BOOTSTRAP;
+ GameState *gs = GameState::GetInstance();
+ gs->SetGameMode(GM_BOOTSTRAP);
/* Initialise the freetype font code. */
InitializeUnicodeGlyphMap();
@@ -251,14 +255,14 @@ bool HandleBootstrap()
/* _exit_game is used to get out of the video driver's main loop.
* In case GM_BOOTSTRAP is still set we did not exit it via the
* "download complete" event, so it was a manual exit. Obey it. */
- _exit_game = _game_mode == GM_BOOTSTRAP;
- if (_exit_game) return false;
+ gs->ExitGame(gs->IsGameMode(GM_BOOTSTRAP));
+ if (gs->ExitGame()) return false;
/* Try to probe the graphics. Should work this time. */
if (!BaseGraphics::SetSet(NULL)) goto failure;
/* Finally we can continue heading for the menu. */
- _game_mode = GM_MENU;
+ gs->SetGameMode(GM_MENU);
return true;
#endif
diff --git a/src/bridge_gui.cpp b/src/bridge_gui.cpp
index 797ead1..3ce2758 100644
--- a/src/bridge_gui.cpp
+++ b/src/bridge_gui.cpp
@@ -193,7 +193,7 @@ public:
SetDParam(2, this->bridges->Get(i)->cost);
SetDParam(1, b->speed);
SetDParam(0, b->material);
- text_dim = maxdim(text_dim, GetStringBoundingBox(_game_mode == GM_EDITOR ? STR_SELECT_BRIDGE_SCENEDIT_INFO : STR_SELECT_BRIDGE_INFO));
+ text_dim = maxdim(text_dim, GetStringBoundingBox(GameState::GetInstance()->IsGameMode(GM_EDITOR) ? STR_SELECT_BRIDGE_SCENEDIT_INFO : STR_SELECT_BRIDGE_INFO));
}
sprite_dim.height++; // Sprite is rendered one pixel down in the matrix field.
text_dim.height++; // Allowing the bottom row pixels to be rendered on the edge of the matrix field.
@@ -235,7 +235,7 @@ public:
DrawSprite(b->sprite, b->pal, r.left + WD_MATRIX_LEFT, y + this->resize.step_height - 1 - GetSpriteSize(b->sprite).height);
DrawStringMultiLine(r.left + this->bridgetext_offset, r.right, y + 2, y + this->resize.step_height,
- _game_mode == GM_EDITOR ? STR_SELECT_BRIDGE_SCENEDIT_INFO : STR_SELECT_BRIDGE_INFO);
+ GameState::GetInstance()->IsGameMode(GM_EDITOR) ? STR_SELECT_BRIDGE_SCENEDIT_INFO : STR_SELECT_BRIDGE_INFO);
y += this->resize.step_height;
}
break;
diff --git a/src/clear_cmd.cpp b/src/clear_cmd.cpp
index f9eb88d..ac58364 100644
--- a/src/clear_cmd.cpp
+++ b/src/clear_cmd.cpp
@@ -264,11 +264,13 @@ static void TileLoop_Clear(TileIndex tile)
case LT_ARCTIC: TileLoopClearAlps(tile); break;
}
+ GameState *gs = GameState::GetInstance();
+
switch (GetClearGround(tile)) {
case CLEAR_GRASS:
if (GetClearDensity(tile) == 3) return;
- if (_game_mode != GM_EDITOR) {
+ if (!gs->IsGameMode(GM_EDITOR)) {
if (GetClearCounter(tile) < 7) {
AddClearCounter(tile, 1);
return;
@@ -284,7 +286,7 @@ static void TileLoop_Clear(TileIndex tile)
case CLEAR_FIELDS:
UpdateFences(tile);
- if (_game_mode == GM_EDITOR) return;
+ if (gs->IsGameMode(GM_EDITOR)) return;
if (GetClearCounter(tile) < 7) {
AddClearCounter(tile, 1);
diff --git a/src/command.cpp b/src/command.cpp
index 959610c..666eb11 100644
--- a/src/command.cpp
+++ b/src/command.cpp
@@ -419,7 +419,7 @@ bool IsCommandAllowedWhilePaused(uint32 cmd)
assert_compile(lengthof(command_type_lookup) == CMDT_END);
assert(IsValidCommand(cmd));
- return _game_mode == GM_EDITOR || command_type_lookup[_command_proc_table[cmd & CMD_ID_MASK].type] <= _settings_game.construction.command_pause_level;
+ return GameState::GetInstance()->IsGameMode(GM_EDITOR) || command_type_lookup[_command_proc_table[cmd & CMD_ID_MASK].type] <= _settings_game.construction.command_pause_level;
}
@@ -583,7 +583,7 @@ bool DoCommandP(TileIndex tile, uint32 p1, uint32 p2, uint32 cmd, CommandCallbac
}
} else if (estimate_only) {
ShowEstimatedCostOrIncome(res.GetCost(), x, y);
- } else if (!only_sending && res.GetCost() != 0 && tile != 0 && IsLocalCompany() && _game_mode != GM_EDITOR) {
+ } else if (!only_sending && res.GetCost() != 0 && tile != 0 && IsLocalCompany() && !GameState::GetInstance()->IsGameMode(GM_EDITOR)) {
/* Only show the cost animation when we did actually
* execute the command, i.e. we're not sending it to
* the server, when it has cost the local company
@@ -657,7 +657,7 @@ CommandCost DoCommandPInternal(TileIndex tile, uint32 p1, uint32 p2, uint32 cmd,
/* If the company isn't valid it may only do server command or start a new company!
* The server will ditch any server commands a client sends to it, so effectively
* this guards the server from executing functions for an invalid company. */
- if (_game_mode == GM_NORMAL && !exec_as_spectator && !Company::IsValidID(_current_company) && !(_current_company == OWNER_DEITY && (cmd_flags & CMD_DEITY) != 0)) {
+ if (GameState::GetInstance()->IsGameMode(GM_NORMAL) && !exec_as_spectator && !Company::IsValidID(_current_company) && !(_current_company == OWNER_DEITY && (cmd_flags & CMD_DEITY) != 0)) {
return_dcpi(CMD_ERROR);
}
diff --git a/src/company_cmd.cpp b/src/company_cmd.cpp
index ee2ed13..9a6924e 100644
--- a/src/company_cmd.cpp
+++ b/src/company_cmd.cpp
@@ -696,7 +696,9 @@ static void HandleBankruptcyTakeover(Company *c)
/** Called every tick for updating some company info. */
void OnTick_Companies()
{
- if (_game_mode == GM_EDITOR) return;
+ GameState *gs = GameState::GetInstance();
+
+ if (gs->IsGameMode(GM_EDITOR)) return;
Company *c = Company::GetIfValid(_cur_company_tick_index);
if (c != NULL) {
@@ -708,7 +710,7 @@ void OnTick_Companies()
_next_competitor_start = AI::GetStartNextTime() * DAY_TICKS;
}
- if (AI::CanStartNew() && _game_mode != GM_MENU && --_next_competitor_start == 0) {
+ if (AI::CanStartNew() && !gs->IsGameMode(GM_MENU) && --_next_competitor_start == 0) {
MaybeStartNewCompany();
}
diff --git a/src/console_cmds.cpp b/src/console_cmds.cpp
index 9cfc8e8..fa44dc9 100644
--- a/src/console_cmds.cpp
+++ b/src/console_cmds.cpp
@@ -166,7 +166,7 @@ DEF_CONSOLE_HOOK(ConHookNoNetwork)
DEF_CONSOLE_HOOK(ConHookNewGRFDeveloperTool)
{
if (_settings_client.gui.newgrf_developer_tools) {
- if (_game_mode == GM_MENU) {
+ if (GameState::GetInstance()->IsGameMode(GM_MENU)) {
if (echo) IConsoleError("This command is only available in game and editor.");
return CHR_DISALLOW;
}
@@ -215,7 +215,7 @@ DEF_CONSOLE_CMD(ConResetEnginePool)
return true;
}
- if (_game_mode == GM_MENU) {
+ if (GameState::GetInstance()->IsGameMode(GM_MENU)) {
IConsoleError("This command is only available in game and editor.");
return true;
}
@@ -361,7 +361,7 @@ DEF_CONSOLE_CMD(ConLoad)
const FiosItem *item = _console_file_list.FindItem(file);
if (item != NULL) {
if (GetAbstractFileType(item->type) == FT_SAVEGAME) {
- _switch_mode = SM_LOAD_GAME;
+ GameState::GetInstance()->SetSwitchMode(SM_LOAD_GAME);
_file_to_saveload.SetMode(item->type);
_file_to_saveload.SetName(FiosBrowseTo(item));
_file_to_saveload.SetTitle(item->title);
@@ -1056,7 +1056,7 @@ DEF_CONSOLE_CMD(ConRestart)
/* Don't copy the _newgame pointers to the real pointers, so call SwitchToMode directly */
_settings_game.game_creation.map_x = MapLogX();
_settings_game.game_creation.map_y = FindFirstBit(MapSizeY());
- _switch_mode = SM_RESTARTGAME;
+ GameState::GetInstance()->SetSwitchMode(SM_RESTARTGAME);
return true;
}
@@ -1127,7 +1127,7 @@ DEF_CONSOLE_CMD(ConStartAI)
return true;
}
- if (_game_mode != GM_NORMAL) {
+ if (!GameState::GetInstance()->IsGameMode(GM_NORMAL)) {
IConsoleWarning("AIs can only be managed in a game.");
return true;
}
@@ -1184,7 +1184,7 @@ DEF_CONSOLE_CMD(ConReloadAI)
return true;
}
- if (_game_mode != GM_NORMAL) {
+ if (!GameState::GetInstance()->IsGameMode(GM_NORMAL)) {
IConsoleWarning("AIs can only be managed in a game.");
return true;
}
@@ -1221,7 +1221,7 @@ DEF_CONSOLE_CMD(ConStopAI)
return true;
}
- if (_game_mode != GM_NORMAL) {
+ if (!GameState::GetInstance()->IsGameMode(GM_NORMAL)) {
IConsoleWarning("AIs can only be managed in a game.");
return true;
}
@@ -1432,9 +1432,11 @@ DEF_CONSOLE_CMD(ConExit)
return true;
}
- if (_game_mode == GM_NORMAL && _settings_client.gui.autosave_on_exit) DoExitSave();
+ GameState *gs = GameState::GetInstance();
- _exit_game = true;
+ if (gs->IsGameMode(GM_NORMAL) && _settings_client.gui.autosave_on_exit) DoExitSave();
+
+ gs->ExitGame(true);
return true;
}
@@ -1445,9 +1447,11 @@ DEF_CONSOLE_CMD(ConPart)
return true;
}
- if (_game_mode != GM_NORMAL) return false;
+ GameState *gs = GameState::GetInstance();
+
+ if (!gs->IsGameMode(GM_NORMAL)) return false;
- _switch_mode = SM_MENU;
+ gs->SetSwitchMode(SM_MENU);
return true;
}
diff --git a/src/date.cpp b/src/date.cpp
index 9c25af4..0f1ee10 100644
--- a/src/date.cpp
+++ b/src/date.cpp
@@ -277,7 +277,7 @@ void IncreaseDate()
/* increase day, and check if a new day is there? */
_tick_counter++;
- if (_game_mode == GM_MENU) return;
+ if (GameState::GetInstance()->IsGameMode(GM_MENU)) return;
_date_fract++;
if (_date_fract < DAY_TICKS) return;
diff --git a/src/dock_gui.cpp b/src/dock_gui.cpp
index 79eaa89..935ae29 100644
--- a/src/dock_gui.cpp
+++ b/src/dock_gui.cpp
@@ -94,9 +94,11 @@ static TileIndex GetOtherAqueductEnd(TileIndex tile_from, TileIndex *tile_to = N
/** Toolbar window for constructing water infrastructure. */
struct BuildDocksToolbarWindow : Window {
DockToolbarWidgets last_clicked_widget; ///< Contains the last widget that has been clicked on this toolbar.
+ GameState *gs;
BuildDocksToolbarWindow(WindowDesc *desc, WindowNumber window_number) : Window(desc)
{
+ this->gs = GameState::GetInstance();
this->last_clicked_widget = WID_DT_INVALID;
this->InitNested(window_number);
this->OnInvalidateData();
@@ -160,7 +162,7 @@ struct BuildDocksToolbarWindow : Window {
break;
case WID_DT_RIVER: // Build river button (in scenario editor)
- if (_game_mode != GM_EDITOR) return;
+ if (!this->gs->IsGameMode(GM_EDITOR)) return;
HandlePlacePushButton(this, WID_DT_RIVER, SPR_CURSOR_RIVER, HT_RECT);
break;
@@ -177,7 +179,7 @@ struct BuildDocksToolbarWindow : Window {
{
switch (this->last_clicked_widget) {
case WID_DT_CANAL: // Build canal button
- VpStartPlaceSizing(tile, (_game_mode == GM_EDITOR) ? VPM_X_AND_Y : VPM_X_OR_Y, DDSP_CREATE_WATER);
+ VpStartPlaceSizing(tile, (this->gs->IsGameMode(GM_EDITOR)) ? VPM_X_AND_Y : VPM_X_OR_Y, DDSP_CREATE_WATER);
break;
case WID_DT_LOCK: // Build lock button
@@ -235,7 +237,7 @@ struct BuildDocksToolbarWindow : Window {
GUIPlaceProcDragXY(select_proc, start_tile, end_tile);
break;
case DDSP_CREATE_WATER:
- DoCommandP(end_tile, start_tile, (_game_mode == GM_EDITOR && _ctrl_pressed) ? WATER_CLASS_SEA : WATER_CLASS_CANAL, CMD_BUILD_CANAL | CMD_MSG(STR_ERROR_CAN_T_BUILD_CANALS), CcPlaySound_SPLAT_WATER);
+ DoCommandP(end_tile, start_tile, (this->gs->IsGameMode(GM_EDITOR) && _ctrl_pressed) ? WATER_CLASS_SEA : WATER_CLASS_CANAL, CMD_BUILD_CANAL | CMD_MSG(STR_ERROR_CAN_T_BUILD_CANALS), CcPlaySound_SPLAT_WATER);
break;
case DDSP_CREATE_RIVER:
DoCommandP(end_tile, start_tile, WATER_CLASS_RIVER, CMD_BUILD_CANAL | CMD_MSG(STR_ERROR_CAN_T_PLACE_RIVERS), CcPlaySound_SPLAT_WATER);
@@ -285,7 +287,7 @@ struct BuildDocksToolbarWindow : Window {
*/
static EventState DockToolbarGlobalHotkeys(int hotkey)
{
- if (_game_mode != GM_NORMAL) return ES_NOT_HANDLED;
+ if (!GameState::GetInstance()->IsGameMode(GM_NORMAL)) return ES_NOT_HANDLED;
Window *w = ShowBuildDocksToolbar();
if (w == NULL) return ES_NOT_HANDLED;
return w->OnHotkey(hotkey);
diff --git a/src/economy.cpp b/src/economy.cpp
index 0106e87..efd8645 100644
--- a/src/economy.cpp
+++ b/src/economy.cpp
@@ -1863,7 +1863,7 @@ static void LoadUnloadVehicle(Vehicle *front)
* if _settings_client.gui.loading_indicators == 1, _local_company must be the owner or must be a spectator to show ind., so 1 > 0
* if _settings_client.gui.loading_indicators == 0, do not display indicators ... 0 is never greater than anything
*/
- if (_game_mode != GM_MENU && (_settings_client.gui.loading_indicators > (uint)(front->owner != _local_company && _local_company != COMPANY_SPECTATOR))) {
+ if (!GameState::GetInstance()->IsGameMode(GM_MENU) && (_settings_client.gui.loading_indicators > (uint)(front->owner != _local_company && _local_company != COMPANY_SPECTATOR))) {
StringID percent_up_down = STR_NULL;
int percent = CalcPercentVehicleFilled(front, &percent_up_down);
if (front->fill_percent_te_id == INVALID_TE_ID) {
diff --git a/src/fios.cpp b/src/fios.cpp
index 5e78fb1..f1c8695 100644
--- a/src/fios.cpp
+++ b/src/fios.cpp
@@ -242,7 +242,7 @@ static void FiosMakeFilename(char *buf, const char *path, const char *name, cons
*/
void FiosMakeSavegameName(char *buf, const char *name, const char *last)
{
- const char *extension = (_game_mode == GM_EDITOR) ? ".scn" : ".sav";
+ const char *extension = (GameState::GetInstance()->IsGameMode(GM_EDITOR)) ? ".scn" : ".sav";
FiosMakeFilename(buf, _fios_path, name, extension, last);
}
diff --git a/src/fios_gui.cpp b/src/fios_gui.cpp
index f20cfd7..b35756f 100644
--- a/src/fios_gui.cpp
+++ b/src/fios_gui.cpp
@@ -10,6 +10,7 @@
/** @file fios_gui.cpp GUIs for loading/saving games, scenarios, heightmaps, ... */
#include "stdafx.h"
+#include "game_state.h"
#include "saveload/saveload.h"
#include "error.h"
#include "gui.h"
@@ -234,6 +235,7 @@ private:
FiosItem o_dir;
const FiosItem *selected; ///< Selected game in #fios_items, or \c NULL.
Scrollbar *vscroll;
+ GameState *gs;
public:
/** Generate a default save filename. */
@@ -248,6 +250,8 @@ public:
{
assert(this->fop == SLO_SAVE || this->fop == SLO_LOAD);
+ this->gs = GameState::GetInstance();
+
/* For saving, construct an initial file name. */
if (this->fop == SLO_SAVE) {
switch (this->abstract_filetype) {
@@ -299,7 +303,7 @@ public:
/* pause is only used in single-player, non-editor mode, non-menu mode. It
* will be unpaused in the WE_DESTROY event handler. */
- if (_game_mode != GM_MENU && !_networking && _game_mode != GM_EDITOR) {
+ if (!this->gs->IsGameMode(GM_MENU) && !_networking && !this->gs->IsGameMode(GM_EDITOR)) {
DoCommandP(0, PM_PAUSED_SAVELOAD, 1, CMD_PAUSE);
}
SetObjectToPlace(SPR_CURSOR_ZZZ, PAL_NONE, HT_NONE, WC_MAIN_WINDOW, 0);
@@ -334,7 +338,7 @@ public:
virtual ~SaveLoadWindow()
{
/* pause is only used in single-player, non-editor mode, non menu mode */
- if (!_networking && _game_mode != GM_EDITOR && _game_mode != GM_MENU) {
+ if (!_networking && !this->gs->IsGameMode(GM_EDITOR) && !this->gs->IsGameMode(GM_MENU)) {
DoCommandP(0, PM_PAUSED_SAVELOAD, 0, CMD_PAUSE);
}
}
@@ -545,7 +549,7 @@ public:
ShowHeightmapLoad();
} else if (!_load_check_data.HasNewGrfs() || _load_check_data.grf_compatibility != GLC_NOT_FOUND || _settings_client.gui.UserIsAllowedToChangeNewGRFs()) {
- _switch_mode = (_game_mode == GM_EDITOR) ? SM_LOAD_SCENARIO : SM_LOAD_GAME;
+ this->gs->SetSwitchMode(this->gs->IsGameMode(GM_EDITOR) ? SM_LOAD_SCENARIO : SM_LOAD_GAME);
ClearErrorMessages();
delete this;
}
@@ -666,15 +670,15 @@ public:
}
} else if (this->IsWidgetLowered(WID_SL_SAVE_GAME)) { // Save button clicked
if (this->abstract_filetype == FT_SAVEGAME || this->abstract_filetype == FT_SCENARIO) {
- _switch_mode = SM_SAVE_GAME;
+ this->gs->SetSwitchMode(SM_SAVE_GAME);
FiosMakeSavegameName(_file_to_saveload.name, this->filename_editbox.text.buf, lastof(_file_to_saveload.name));
} else {
- _switch_mode = SM_SAVE_HEIGHTMAP;
+ this->gs->SetSwitchMode(SM_SAVE_HEIGHTMAP);
FiosMakeHeightmapName(_file_to_saveload.name, this->filename_editbox.text.buf, lastof(_file_to_saveload.name));
}
/* In the editor set up the vehicle engines correctly (date might have changed) */
- if (_game_mode == GM_EDITOR) StartupEngines();
+ if (this->gs->IsGameMode(GM_EDITOR)) StartupEngines();
}
}
diff --git a/src/game/game_config.cpp b/src/game/game_config.cpp
index 50cd5da..ecc36e7 100644
--- a/src/game/game_config.cpp
+++ b/src/game/game_config.cpp
@@ -20,7 +20,7 @@
/* static */ GameConfig *GameConfig::GetConfig(ScriptSettingSource source)
{
GameConfig **config;
- if (source == SSS_FORCE_NEWGAME || (source == SSS_DEFAULT && _game_mode == GM_MENU)) {
+ if (source == SSS_FORCE_NEWGAME || (source == SSS_DEFAULT && GameState::GetInstance()->IsGameMode(GM_MENU))) {
config = &_settings_newgame.game_config;
} else {
config = &_settings_game.game_config;
diff --git a/src/game_state.cpp b/src/game_state.cpp
new file mode 100644
index 0000000..566da09
--- /dev/null
+++ b/src/game_state.cpp
@@ -0,0 +1,277 @@
+/* $Id$ */
+
+/*
+ * This file is part of OpenTTD.
+ * 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.
+ * 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.
+ * 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/>.
+ */
+
+/** @file game_state.cpp Functions related to the game state. */
+
+#include "stdafx.h"
+#include "game_state.h"
+
+#include "ai/ai.hpp"
+#include "base_media_base.h"
+#include "command_func.h"
+#include "company_func.h"
+#include "console_func.h"
+#include "date_func.h"
+#include "engine_base.h"
+#include "error.h"
+#include "genworld.h"
+#include "network/network.h"
+#include "network/network_func.h"
+#include "openttd.h"
+#include "saveload/saveload.h"
+#include "screenshot.h"
+#include "settings_func.h"
+#include "settings_type.h"
+#include "string_func.h"
+#include "window_func.h"
+
+extern void LoadIntroGame(bool load_newgrfs = false);
+extern void MakeNewGame(bool from_heightmap, bool reset_settings);
+extern void MakeNewgameSettingsLive();
+extern void MakeNewEditorWorld();
+extern bool SafeLoad(const char *filename, SaveLoadOperation fop, DetailedFileType dft, GameMode newgm, Subdirectory subdir, struct LoadFilter *lf = NULL);
+
+/* static */ GameState *GameState::instance;
+
+/**
+ * Checks the current game mode.
+ * @param mode the game mode to check
+ * @return True if the mode matches
+ */
+bool GameState::IsGameMode(GameMode mode)
+{
+ return this->game_mode == mode;
+}
+
+/**
+ * Restores the backed up game mode.
+ */
+void GameState::RestoreGameMode()
+{
+ this->game_mode = this->old_game_mode;
+}
+
+/**
+ * Sets the new game mode. Back ups the current game mode.
+ * @param new_mode the new mode to set
+ */
+void GameState::SetGameMode(GameMode new_mode)
+{
+ this->old_game_mode = this->game_mode;
+ this->game_mode = new_mode;
+}
+
+/**
+ * Returns the current game mode.
+ * @return GameMode
+ */
+GameMode GameState::GetGameMode()
+{
+ return this->game_mode;
+}
+
+/**
+ * Returns the backed up game mode.
+ * @return GameMode
+ */
+GameMode GameState::GetOldGameMode()
+{
+ return this->old_game_mode;
+}
+
+/**
+ * Checks the current switch mode.
+ * @param mode the switch mode to check
+ * @return True if the mode matches
+ */
+bool GameState::IsSwitchMode(SwitchMode mode)
+{
+ return this->switch_mode == mode;
+}
+
+/**
+ * Prepare the game to switch mode in the next mainloop.
+ * @param new_mode the the mode to switch to
+ */
+void GameState::SetSwitchMode(SwitchMode new_mode)
+{
+ this->switch_mode = new_mode;
+}
+
+/**
+ * Returns the current switch mode.
+ * @return SwitchMode
+ */
+SwitchMode GameState::GetSwitchMode()
+{
+ return this->switch_mode;
+}
+
+/**
+ * Execute the switch to the new mode.
+ * @param new_mode the new game mode to switch to
+ */
+void GameState::SwitchToMode(SwitchMode new_mode)
+{
+#ifdef ENABLE_NETWORK
+ /* If we are saving something, the network stays in his current state */
+ if (new_mode != SM_SAVE_GAME) {
+ /* If the network is active, make it not-active */
+ if (_networking) {
+ if (_network_server && (new_mode == SM_LOAD_GAME || new_mode == SM_NEWGAME || new_mode == SM_RESTARTGAME)) {
+ NetworkReboot();
+ } else {
+ NetworkDisconnect();
+ }
+ }
+
+ /* If we are a server, we restart the server */
+ if (_is_network_server) {
+ /* But not if we are going to the menu */
+ if (new_mode != SM_MENU) {
+ /* check if we should reload the config */
+ if (_settings_client.network.reload_cfg) {
+ LoadFromConfig();
+ MakeNewgameSettingsLive();
+ ResetGRFConfig(false);
+ }
+ NetworkServerStart();
+ } else {
+ /* This client no longer wants to be a network-server */
+ _is_network_server = false;
+ }
+ }
+ }
+#endif /* ENABLE_NETWORK */
+ /* Make sure all AI controllers are gone at quitting game */
+ if (new_mode != SM_SAVE_GAME) AI::KillAll();
+
+ switch (new_mode) {
+ case SM_EDITOR: // Switch to scenario editor
+ MakeNewEditorWorld();
+ break;
+
+ case SM_RESTARTGAME: // Restart --> 'Random game' with current settings
+ case SM_NEWGAME: // New Game --> 'Random game'
+#ifdef ENABLE_NETWORK
+ if (_network_server) {
+ seprintf(_network_game_info.map_name, lastof(_network_game_info.map_name), "Random Map");
+ }
+#endif /* ENABLE_NETWORK */
+ MakeNewGame(false, new_mode == SM_NEWGAME);
+ break;
+
+ case SM_LOAD_GAME: { // Load game, Play Scenario
+ ResetGRFConfig(true);
+ ResetWindowSystem();
+
+ if (!SafeLoad(_file_to_saveload.name, _file_to_saveload.file_op, _file_to_saveload.detail_ftype, GM_NORMAL, NO_DIRECTORY)) {
+ SetDParamStr(0, GetSaveLoadErrorString());
+ ShowErrorMessage(STR_JUST_RAW_STRING, INVALID_STRING_ID, WL_ERROR);
+ } else {
+ if (_file_to_saveload.abstract_ftype == FT_SCENARIO) {
+ /* Reset engine pool to simplify changing engine NewGRFs in scenario editor. */
+ EngineOverrideManager::ResetToCurrentNewGRFConfig();
+ }
+ /* Update the local company for a loaded game. It is either always
+ * company #1 (eg 0) or in the case of a dedicated server a spectator */
+ SetLocalCompany(_network_dedicated ? COMPANY_SPECTATOR : COMPANY_FIRST);
+ /* Execute the game-start script */
+ IConsoleCmdExec("exec scripts/game_start.scr 0");
+ /* Decrease pause counter (was increased from opening load dialog) */
+ DoCommandP(0, PM_PAUSED_SAVELOAD, 0, CMD_PAUSE);
+#ifdef ENABLE_NETWORK
+ if (_network_server) {
+ seprintf(_network_game_info.map_name, lastof(_network_game_info.map_name), "%s (Loaded game)", _file_to_saveload.title);
+ }
+#endif /* ENABLE_NETWORK */
+ }
+ break;
+ }
+
+ case SM_START_HEIGHTMAP: // Load a heightmap and start a new game from it
+#ifdef ENABLE_NETWORK
+ if (_network_server) {
+ seprintf(_network_game_info.map_name, lastof(_network_game_info.map_name), "%s (Heightmap)", _file_to_saveload.title);
+ }
+#endif /* ENABLE_NETWORK */
+ MakeNewGame(true, true);
+ break;
+
+ case SM_LOAD_HEIGHTMAP: // Load heightmap from scenario editor
+ SetLocalCompany(OWNER_NONE);
+
+ GenerateWorld(GWM_HEIGHTMAP, 1 << _settings_game.game_creation.map_x, 1 << _settings_game.game_creation.map_y);
+ MarkWholeScreenDirty();
+ break;
+
+ case SM_LOAD_SCENARIO: { // Load scenario from scenario editor
+ if (SafeLoad(_file_to_saveload.name, _file_to_saveload.file_op, _file_to_saveload.detail_ftype, GM_EDITOR, NO_DIRECTORY)) {
+ SetLocalCompany(OWNER_NONE);
+ _settings_newgame.game_creation.starting_year = _cur_year;
+ /* Cancel the saveload pausing */
+ DoCommandP(0, PM_PAUSED_SAVELOAD, 0, CMD_PAUSE);
+ } else {
+ SetDParamStr(0, GetSaveLoadErrorString());
+ ShowErrorMessage(STR_JUST_RAW_STRING, INVALID_STRING_ID, WL_ERROR);
+ }
+ break;
+ }
+
+ case SM_MENU: // Switch to game intro menu
+ LoadIntroGame();
+ if (BaseSounds::ini_set == NULL && BaseSounds::GetUsedSet()->fallback) {
+ ShowErrorMessage(STR_WARNING_FALLBACK_SOUNDSET, INVALID_STRING_ID, WL_CRITICAL);
+ BaseSounds::ini_set = stredup(BaseSounds::GetUsedSet()->name);
+ }
+ break;
+
+ case SM_SAVE_GAME: // Save game.
+ /* Make network saved games on pause compatible to singleplayer */
+ if (SaveOrLoad(_file_to_saveload.name, SLO_SAVE, DFT_GAME_FILE, NO_DIRECTORY) != SL_OK) {
+ SetDParamStr(0, GetSaveLoadErrorString());
+ ShowErrorMessage(STR_JUST_RAW_STRING, INVALID_STRING_ID, WL_ERROR);
+ } else {
+ DeleteWindowById(WC_SAVELOAD, 0);
+ }
+ break;
+
+ case SM_SAVE_HEIGHTMAP: // Save heightmap.
+ MakeHeightmapScreenshot(_file_to_saveload.name);
+ DeleteWindowById(WC_SAVELOAD, 0);
+ break;
+
+ case SM_GENRANDLAND: // Generate random land within scenario editor
+ SetLocalCompany(OWNER_NONE);
+ GenerateWorld(GWM_RANDOM, 1 << _settings_game.game_creation.map_x, 1 << _settings_game.game_creation.map_y);
+ /* XXX: set date */
+ MarkWholeScreenDirty();
+ break;
+
+ default: NOT_REACHED();
+ }
+}
+
+/**
+ * Returns whether we are exiting the game.
+ * @return True if we are exiting the game
+ */
+bool GameState::ExitGame()
+{
+ return this->exit_game;
+}
+
+/**
+ * Sets whether we are exiting the game.
+ * @param bool exit the game
+ */
+void GameState::ExitGame(bool exit)
+{
+ this->exit_game = exit;
+}
diff --git a/src/game_state.h b/src/game_state.h
new file mode 100644
index 0000000..f1809fa
--- /dev/null
+++ b/src/game_state.h
@@ -0,0 +1,90 @@
+/* $Id$ */
+
+/*
+ * This file is part of OpenTTD.
+ * 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.
+ * 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.
+ * 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/>.
+ */
+
+/** @file game_state.h class for handling the game state variables. */
+
+#ifndef GAME_STATE_H
+#define GAME_STATE_H
+
+/** Mode which defines the state of the game. */
+enum GameMode {
+ GM_MENU,
+ GM_NORMAL,
+ GM_EDITOR,
+ GM_BOOTSTRAP
+};
+
+/** Mode which defines what mode we're switching to. */
+enum SwitchMode {
+ SM_NONE,
+ SM_NEWGAME, ///< New Game --> 'Random game'.
+ SM_RESTARTGAME, ///< Restart --> 'Random game' with current settings.
+ SM_EDITOR, ///< Switch to scenario editor.
+ SM_LOAD_GAME, ///< Load game, Play Scenario.
+ SM_MENU, ///< Switch to game intro menu.
+ SM_SAVE_GAME, ///< Save game.
+ SM_SAVE_HEIGHTMAP, ///< Save heightmap.
+ SM_GENRANDLAND, ///< Generate random land within scenario editor.
+ SM_LOAD_SCENARIO, ///< Load scenario from scenario editor.
+ SM_START_HEIGHTMAP, ///< Load a heightmap and start a new game from it.
+ SM_LOAD_HEIGHTMAP, ///< Load heightmap from scenario editor.
+};
+
+/**
+ * Singleton class for handling the current state of the game
+ */
+class GameState {
+public:
+ static GameState *GetInstance()
+ {
+ if (!instance) {
+ instance = new GameState();
+ }
+
+ return instance;
+ }
+
+ virtual ~GameState()
+ {
+ delete instance;
+ }
+
+ /* Public accessors */
+ virtual bool IsGameMode(GameMode mode);
+ virtual void SetGameMode(GameMode new_mode);
+ virtual void RestoreGameMode();
+ virtual GameMode GetGameMode();
+ virtual GameMode GetOldGameMode();
+
+ virtual bool IsSwitchMode(SwitchMode mode);
+ virtual void SetSwitchMode(SwitchMode new_mode);
+ virtual void SwitchToMode(SwitchMode new_mode);
+ virtual SwitchMode GetSwitchMode();
+
+ virtual void ExitGame(bool exit);
+ virtual bool ExitGame();
+
+private:
+ static GameState *instance;
+
+ GameState() {}
+ GameState(GameState const&);
+ GameState &operator=(const GameState&);
+
+ GameMode game_mode = GM_BOOTSTRAP;
+ GameMode old_game_mode = GM_BOOTSTRAP;
+ SwitchMode switch_mode = SM_NONE;
+
+ bool exit_game = false;
+};
+
+extern GameState *_game_state;
+
+
+#endif /* GAME_STATE_H */
diff --git a/src/gamelog.cpp b/src/gamelog.cpp
index 400c0d2..da09b8b 100644
--- a/src/gamelog.cpp
+++ b/src/gamelog.cpp
@@ -431,7 +431,7 @@ void GamelogMode()
LoggedChange *lc = GamelogChange(GLCT_MODE);
if (lc == NULL) return;
- lc->mode.mode = _game_mode;
+ lc->mode.mode = GameState::GetInstance()->GetGameMode();
lc->mode.landscape = _settings_game.game_creation.landscape;
}
@@ -507,7 +507,7 @@ void GamelogTestMode()
}
}
- if (mode == NULL || mode->mode.mode != _game_mode || mode->mode.landscape != _settings_game.game_creation.landscape) GamelogMode();
+ if (mode == NULL || mode->mode.mode != GameState::GetInstance()->GetGameMode() || mode->mode.landscape != _settings_game.game_creation.landscape) GamelogMode();
}
diff --git a/src/genworld.cpp b/src/genworld.cpp
index 5cdb129..ab47fe0 100644
--- a/src/genworld.cpp
+++ b/src/genworld.cpp
@@ -79,7 +79,7 @@ static void CleanupGeneration()
SetMouseCursorBusy(false);
/* Show all vital windows again, because we have hidden them */
- if (_gw.threaded && _game_mode != GM_MENU) ShowVitalWindows();
+ if (_gw.threaded && !GameState::GetInstance()->IsGameMode(GM_MENU)) ShowVitalWindows();
SetModalProgress(false);
_gw.proc = NULL;
_gw.abortp = NULL;
@@ -114,6 +114,8 @@ static void _GenerateWorld(void *)
/* Must start economy early because of the costs. */
StartupEconomy();
+ GameState *gs = GameState::GetInstance();
+
/* Don't generate landscape items when in the scenario editor. */
if (_gw.mode == GWM_EMPTY) {
SetGeneratingWorldProgress(GWP_OBJECT, 1);
@@ -125,7 +127,7 @@ static void _GenerateWorld(void *)
}
/* Make the map the height of the setting */
- if (_game_mode != GM_MENU) FlatEmptyWorld(_settings_game.game_creation.se_flat_world_height);
+ if (!gs->IsGameMode(GM_MENU)) FlatEmptyWorld(_settings_game.game_creation.se_flat_world_height);
ConvertGroundTilesIntoWaterTiles();
IncreaseGeneratingWorldProgress(GWP_OBJECT);
@@ -134,7 +136,7 @@ static void _GenerateWorld(void *)
GenerateClearTile();
/* only generate towns, tree and industries in newgame mode. */
- if (_game_mode != GM_EDITOR) {
+ if (!gs->IsGameMode(GM_EDITOR)) {
if (!GenerateTowns(_settings_game.economy.town_layout)) {
_cur_company.Restore();
HandleGeneratingWorldAbortion();
@@ -166,7 +168,7 @@ static void _GenerateWorld(void *)
IncreaseGeneratingWorldProgress(GWP_RUNTILELOOP);
}
- if (_game_mode != GM_EDITOR) {
+ if (!gs->IsGameMode(GM_EDITOR)) {
Game::StartNew();
if (Game::GetInstance() != NULL) {
@@ -276,8 +278,10 @@ bool IsGeneratingWorldAborted()
*/
void HandleGeneratingWorldAbortion()
{
+ GameState *gs = GameState::GetInstance();
+
/* Clean up - in SE create an empty map, otherwise, go to intro menu */
- _switch_mode = (_game_mode == GM_EDITOR) ? SM_EDITOR : SM_MENU;
+ gs->SetSwitchMode(gs->IsGameMode(GM_EDITOR) ? SM_EDITOR : SM_MENU);
if (_gw.abortp != NULL) _gw.abortp();
@@ -285,7 +289,7 @@ void HandleGeneratingWorldAbortion()
if (_gw.thread != NULL) _gw.thread->Exit();
- SwitchToMode(_switch_mode);
+ gs->SwitchToMode(gs->GetSwitchMode());
}
/**
diff --git a/src/genworld_gui.cpp b/src/genworld_gui.cpp
index 359709e..213c335 100644
--- a/src/genworld_gui.cpp
+++ b/src/genworld_gui.cpp
@@ -268,11 +268,13 @@ static void StartGeneratingLandscape(GenerateLandscapeWindowMode mode)
MakeNewgameSettingsLive();
ResetGRFConfig(true);
+ GameState *gs = GameState::GetInstance();
+
if (_settings_client.sound.confirm) SndPlayFx(SND_15_BEEP);
switch (mode) {
- case GLWM_GENERATE: _switch_mode = (_game_mode == GM_EDITOR) ? SM_GENRANDLAND : SM_NEWGAME; break;
- case GLWM_HEIGHTMAP: _switch_mode = (_game_mode == GM_EDITOR) ? SM_LOAD_HEIGHTMAP : SM_START_HEIGHTMAP; break;
- case GLWM_SCENARIO: _switch_mode = SM_EDITOR; break;
+ case GLWM_GENERATE: gs->SetSwitchMode((gs->IsGameMode(GM_EDITOR)) ? SM_GENRANDLAND : SM_NEWGAME); break;
+ case GLWM_HEIGHTMAP: gs->SetSwitchMode((gs->IsGameMode(GM_EDITOR)) ? SM_LOAD_HEIGHTMAP : SM_START_HEIGHTMAP); break;
+ case GLWM_SCENARIO: gs->SetSwitchMode(SM_EDITOR); break;
default: NOT_REACHED();
}
}
@@ -314,9 +316,11 @@ struct GenerateLandscapeWindow : public Window {
uint y;
char name[64];
GenerateLandscapeWindowMode mode;
+ GameState *gs;
GenerateLandscapeWindow(WindowDesc *desc, WindowNumber number = 0) : Window(desc)
{
+ this->gs = GameState::GetInstance();
this->InitNested(number);
this->LowerWidget(_settings_newgame.game_creation.landscape + WID_GL_TEMPERATE);
@@ -324,9 +328,9 @@ struct GenerateLandscapeWindow : public Window {
this->mode = (GenerateLandscapeWindowMode)this->window_number;
/* Disable town, industry and trees in SE */
- this->SetWidgetDisabledState(WID_GL_TOWN_PULLDOWN, _game_mode == GM_EDITOR);
- this->SetWidgetDisabledState(WID_GL_INDUSTRY_PULLDOWN, _game_mode == GM_EDITOR);
- this->SetWidgetDisabledState(WID_GL_TREE_PULLDOWN, _game_mode == GM_EDITOR);
+ this->SetWidgetDisabledState(WID_GL_TOWN_PULLDOWN, gs->IsGameMode(GM_EDITOR));
+ this->SetWidgetDisabledState(WID_GL_INDUSTRY_PULLDOWN, gs->IsGameMode(GM_EDITOR));
+ this->SetWidgetDisabledState(WID_GL_TREE_PULLDOWN, gs->IsGameMode(GM_EDITOR));
this->OnInvalidateData();
}
@@ -342,7 +346,7 @@ struct GenerateLandscapeWindow : public Window {
case WID_GL_SNOW_LEVEL_TEXT: SetDParam(0, _settings_newgame.game_creation.snow_line_height); break;
case WID_GL_TOWN_PULLDOWN:
- if (_game_mode == GM_EDITOR) {
+ if (gs->IsGameMode(GM_EDITOR)) {
SetDParam(0, STR_CONFIG_SETTING_OFF);
} else if (_settings_newgame.difficulty.number_towns == CUSTOM_TOWN_NUMBER_DIFFICULTY) {
SetDParam(0, STR_NUM_CUSTOM_NUMBER);
@@ -352,7 +356,7 @@ struct GenerateLandscapeWindow : public Window {
}
break;
- case WID_GL_INDUSTRY_PULLDOWN: SetDParam(0, _game_mode == GM_EDITOR ? STR_CONFIG_SETTING_OFF : _num_inds[_settings_newgame.difficulty.industry_density]); break;
+ case WID_GL_INDUSTRY_PULLDOWN: SetDParam(0, gs->IsGameMode(GM_EDITOR) ? STR_CONFIG_SETTING_OFF : _num_inds[_settings_newgame.difficulty.industry_density]); break;
case WID_GL_LANDSCAPE_PULLDOWN: SetDParam(0, _landscape[_settings_newgame.game_creation.land_generator]); break;
case WID_GL_TREE_PULLDOWN: SetDParam(0, _tree_placer[_settings_newgame.game_creation.tree_placer]); break;
case WID_GL_TERRAIN_PULLDOWN: SetDParam(0, _elevations[_settings_newgame.difficulty.terrain_type]); break;
diff --git a/src/gfx.cpp b/src/gfx.cpp
index 7195051..101d27b 100644
--- a/src/gfx.cpp
+++ b/src/gfx.cpp
@@ -10,6 +10,7 @@
/** @file gfx.cpp Handling of drawing text and other gfx related stuff. */
#include "stdafx.h"
+#include "game_state.h"
#include "gfx_layout.h"
#include "progress.h"
#include "zoom_func.h"
@@ -42,9 +43,6 @@ bool _right_button_down; ///< Is right mouse button pressed?
bool _right_button_clicked; ///< Is right mouse button clicked?
DrawPixelInfo _screen;
bool _screen_disable_anim = false; ///< Disable palette animation (important for 32bpp-anim blitter during giant screenshot)
-bool _exit_game;
-GameMode _game_mode;
-SwitchMode _switch_mode; ///< The next mainloop command.
PauseModeByte _pause_mode;
Palette _cur_palette;
@@ -1328,7 +1326,7 @@ void DrawDirtyBlocks()
* Simply let the next run do so, otherwise we would be loading
* the new state (and possibly change the blitter) when we hold
* the drawing lock, which we must not do. */
- if (_switch_mode != SM_NONE && !HasModalProgress()) return;
+ if (!GameState::GetInstance()->IsSwitchMode(SM_NONE) && !HasModalProgress()) return;
}
y = 0;
diff --git a/src/highscore_gui.cpp b/src/highscore_gui.cpp
index c67aaa1..eb952f7 100644
--- a/src/highscore_gui.cpp
+++ b/src/highscore_gui.cpp
@@ -154,15 +154,18 @@ struct EndGameWindow : EndGameHighScoreBaseWindow {
struct HighScoreWindow : EndGameHighScoreBaseWindow {
bool game_paused_by_player; ///< True if the game was paused by the player when the highscore window was opened.
+ GameState *gs;
HighScoreWindow(WindowDesc *desc, int difficulty, int8 ranking) : EndGameHighScoreBaseWindow(desc)
{
+ this->gs = GameState::GetInstance();
+
/* pause game to show the chart */
this->game_paused_by_player = _pause_mode == PM_PAUSED_NORMAL;
if (!_networking && !this->game_paused_by_player) DoCommandP(0, PM_PAUSED_NORMAL, 1, CMD_PAUSE);
/* Close all always on-top windows to get a clean screen */
- if (_game_mode != GM_MENU) HideVitalWindows();
+ if (!gs->IsGameMode(GM_MENU)) HideVitalWindows();
MarkWholeScreenDirty();
this->window_number = difficulty; // show highscore chart for difficulty...
@@ -172,7 +175,7 @@ struct HighScoreWindow : EndGameHighScoreBaseWindow {
~HighScoreWindow()
{
- if (_game_mode != GM_MENU) ShowVitalWindows();
+ if (!gs->IsGameMode(GM_MENU)) ShowVitalWindows();
if (!_networking && !this->game_paused_by_player) DoCommandP(0, PM_PAUSED_NORMAL, 0, CMD_PAUSE); // unpause
}
diff --git a/src/hotkeys.cpp b/src/hotkeys.cpp
index 870e2cb..165a29b 100644
--- a/src/hotkeys.cpp
+++ b/src/hotkeys.cpp
@@ -11,6 +11,7 @@
#include "stdafx.h"
#include "openttd.h"
+#include "game_state.h"
#include "hotkeys.h"
#include "ini_type.h"
#include "string_func.h"
diff --git a/src/industry_cmd.cpp b/src/industry_cmd.cpp
index 8fea695..d2c5649 100644
--- a/src/industry_cmd.cpp
+++ b/src/industry_cmd.cpp
@@ -473,7 +473,7 @@ static CommandCost ClearTile_Industry(TileIndex tile, DoCommandFlag flags)
* with magic_bulldozer cheat you can destroy industries
* (area around OILRIG is water, so water shouldn't flood it
*/
- if ((_current_company != OWNER_WATER && _game_mode != GM_EDITOR &&
+ if ((_current_company != OWNER_WATER && !GameState::GetInstance()->IsGameMode(GM_EDITOR) &&
!_cheats.magic_bulldozer.value) ||
((flags & DC_AUTO) != 0) ||
(_current_company == OWNER_WATER &&
@@ -808,7 +808,7 @@ static void TileLoop_Industry(TileIndex tile)
return;
}
- if (_game_mode == GM_EDITOR) return;
+ if (GameState::GetInstance()->IsGameMode(GM_EDITOR)) return;
TransportIndustryGoods(tile);
@@ -1164,7 +1164,7 @@ void OnTick_Industry()
}
}
- if (_game_mode == GM_EDITOR) return;
+ if (GameState::GetInstance()->IsGameMode(GM_EDITOR)) return;
Industry *i;
FOR_ALL_INDUSTRIES(i) {
@@ -1204,7 +1204,7 @@ static CommandCost CheckNewIndustry_Forest(TileIndex tile)
*/
static CommandCost CheckNewIndustry_OilRefinery(TileIndex tile)
{
- if (_game_mode == GM_EDITOR) return CommandCost();
+ if (GameState::GetInstance()->IsGameMode(GM_EDITOR)) return CommandCost();
if (DistanceFromEdge(TILE_ADDXY(tile, 1, 1)) < _settings_game.game_creation.oil_refinery_limit) return CommandCost();
return_cmd_error(STR_ERROR_CAN_ONLY_BE_POSITIONED);
@@ -1219,7 +1219,7 @@ extern bool _ignore_restrictions;
*/
static CommandCost CheckNewIndustry_OilRig(TileIndex tile)
{
- if (_game_mode == GM_EDITOR && _ignore_restrictions) return CommandCost();
+ if (GameState::GetInstance()->IsGameMode(GM_EDITOR) && _ignore_restrictions) return CommandCost();
if (TileHeight(tile) == 0 &&
DistanceFromEdge(TILE_ADDXY(tile, 1, 1)) < _settings_game.game_creation.oil_refinery_limit) return CommandCost();
@@ -1681,7 +1681,7 @@ static void DoCreateNewIndustry(Industry *i, TileIndex tile, IndustryType type,
i->founder = founder;
i->construction_date = _date;
- i->construction_type = (_game_mode == GM_EDITOR) ? ICT_SCENARIO_EDITOR :
+ i->construction_type = (GameState::GetInstance()->IsGameMode(GM_EDITOR)) ? ICT_SCENARIO_EDITOR :
(_generating_world ? ICT_MAP_GENERATION : ICT_NORMAL_GAMEPLAY);
/* Adding 1 here makes it conform to specs of var44 of varaction2 for industries
@@ -1865,13 +1865,15 @@ CommandCost CmdBuildIndustry(TileIndex tile, DoCommandFlag flags, uint32 p1, uin
/* Check if the to-be built/founded industry is available for this climate. */
if (!indspec->enabled || indspec->num_table == 0) return CMD_ERROR;
+ GameState *gs = GameState::GetInstance();
+
/* If the setting for raw-material industries is not on, you cannot build raw-material industries.
* Raw material industries are industries that do not accept cargo (at least for now) */
- if (_game_mode != GM_EDITOR && _current_company != OWNER_DEITY && _settings_game.construction.raw_industry_construction == 0 && indspec->IsRawIndustry()) {
+ if (!gs->IsGameMode(GM_EDITOR) && _current_company != OWNER_DEITY && _settings_game.construction.raw_industry_construction == 0 && indspec->IsRawIndustry()) {
return CMD_ERROR;
}
- if (_game_mode != GM_EDITOR && GetIndustryProbabilityCallback(it, _current_company == OWNER_DEITY ? IACT_RANDOMCREATION : IACT_USERCREATION, 1) == 0) {
+ if (!gs->IsGameMode(GM_EDITOR) && GetIndustryProbabilityCallback(it, _current_company == OWNER_DEITY ? IACT_RANDOMCREATION : IACT_USERCREATION, 1) == 0) {
return CMD_ERROR;
}
@@ -1884,7 +1886,7 @@ CommandCost CmdBuildIndustry(TileIndex tile, DoCommandFlag flags, uint32 p1, uin
const bool deity_prospect = _current_company == OWNER_DEITY && !HasBit(p1, 16);
Industry *ind = NULL;
- if (deity_prospect || (_game_mode != GM_EDITOR && _current_company != OWNER_DEITY && _settings_game.construction.raw_industry_construction == 2 && indspec->IsRawIndustry())) {
+ if (deity_prospect || (!gs->IsGameMode(GM_EDITOR) && _current_company != OWNER_DEITY && _settings_game.construction.raw_industry_construction == 2 && indspec->IsRawIndustry())) {
if (flags & DC_EXEC) {
/* Prospected industries are build as OWNER_TOWN to not e.g. be build on owned land of the founder */
Backup<CompanyByte> cur_company(_current_company, OWNER_TOWN, FILE_LINE);
@@ -1925,7 +1927,7 @@ CommandCost CmdBuildIndustry(TileIndex tile, DoCommandFlag flags, uint32 p1, uin
if (ret.Failed()) return ret;
}
- if ((flags & DC_EXEC) && ind != NULL && _game_mode != GM_EDITOR) {
+ if ((flags & DC_EXEC) && ind != NULL && !gs->IsGameMode(GM_EDITOR)) {
AdvertiseIndustryOpening(ind);
}
@@ -1960,10 +1962,11 @@ static Industry *CreateNewIndustry(TileIndex tile, IndustryType type, IndustryAv
*/
static uint32 GetScaledIndustryGenerationProbability(IndustryType it, bool *force_at_least_one)
{
+ GameState *gs = GameState::GetInstance();
const IndustrySpec *ind_spc = GetIndustrySpec(it);
uint32 chance = ind_spc->appear_creation[_settings_game.game_creation.landscape] * 16; // * 16 to increase precision
if (!ind_spc->enabled || ind_spc->num_table == 0 ||
- (_game_mode != GM_EDITOR && _settings_game.difficulty.industry_density == ID_FUND_ONLY) ||
+ (!gs->IsGameMode(GM_EDITOR) && _settings_game.difficulty.industry_density == ID_FUND_ONLY) ||
(chance = GetIndustryProbabilityCallback(it, IACT_MAPGENERATION, chance)) == 0) {
*force_at_least_one = false;
return 0;
@@ -1972,7 +1975,7 @@ static uint32 GetScaledIndustryGenerationProbability(IndustryType it, bool *forc
* For simplicity we scale in both cases, though scaling the probabilities of all industries has no effect. */
chance = (ind_spc->check_proc == CHECK_REFINERY || ind_spc->check_proc == CHECK_OIL_RIG) ? ScaleByMapSize1D(chance) : ScaleByMapSize(chance);
- *force_at_least_one = (chance > 0) && !(ind_spc->behaviour & INDUSTRYBEH_NOBUILT_MAPCREATION) && (_game_mode != GM_EDITOR);
+ *force_at_least_one = (chance > 0) && !(ind_spc->behaviour & INDUSTRYBEH_NOBUILT_MAPCREATION) && (!gs->IsGameMode(GM_EDITOR));
return chance;
}
}
@@ -2020,7 +2023,7 @@ static uint GetNumberOfIndustries()
};
assert(lengthof(numof_industry_table) == ID_END);
- uint difficulty = (_game_mode != GM_EDITOR) ? _settings_game.difficulty.industry_density : (uint)ID_VERY_LOW;
+ uint difficulty = (!GameState::GetInstance()->IsGameMode(GM_EDITOR)) ? _settings_game.difficulty.industry_density : (uint)ID_VERY_LOW;
return min(IndustryPool::MAX_SIZE, ScaleByMapSize(numof_industry_table[difficulty]));
}
@@ -2109,7 +2112,7 @@ void IndustryBuildData::MonthlyLoop()
*/
void GenerateIndustries()
{
- if (_game_mode != GM_EDITOR && _settings_game.difficulty.industry_density == ID_FUND_ONLY) return; // No industries in the game.
+ if (!GameState::GetInstance()->IsGameMode(GM_EDITOR) && _settings_game.difficulty.industry_density == ID_FUND_ONLY) return; // No industries in the game.
uint32 industry_probs[NUM_INDUSTRYTYPES];
bool force_at_least_one[NUM_INDUSTRYTYPES];
diff --git a/src/industry_gui.cpp b/src/industry_gui.cpp
index 41b3c57..39fd304 100644
--- a/src/industry_gui.cpp
+++ b/src/industry_gui.cpp
@@ -251,6 +251,7 @@ class BuildIndustryWindow : public Window {
IndustryType index[NUM_INDUSTRYTYPES + 1]; ///< Type of industry, in the order it was loaded
bool enabled[NUM_INDUSTRYTYPES + 1]; ///< availability state, coming from CBID_INDUSTRY_PROBABILITY (if ever)
Scrollbar *vscroll;
+ GameState *gs;
/** The offset for the text in the matrix. */
static const int MATRIX_TEXT_OFFSET = 17;
@@ -264,7 +265,7 @@ class BuildIndustryWindow : public Window {
this->enabled[i] = false;
}
- if (_game_mode == GM_EDITOR) { // give room for the Many Random "button"
+ if (this->gs->IsGameMode(GM_EDITOR)) { // give room for the Many Random "button"
this->index[this->count] = INVALID_INDUSTRYTYPE;
this->enabled[this->count] = true;
this->count++;
@@ -281,13 +282,13 @@ class BuildIndustryWindow : public Window {
/* Rule is that editor mode loads all industries.
* In game mode, all non raw industries are loaded too
* and raw ones are loaded only when setting allows it */
- if (_game_mode != GM_EDITOR && indsp->IsRawIndustry() && _settings_game.construction.raw_industry_construction == 0) {
+ if (!this->gs->IsGameMode(GM_EDITOR) && indsp->IsRawIndustry() && _settings_game.construction.raw_industry_construction == 0) {
/* Unselect if the industry is no longer in the list */
if (this->selected_type == ind) this->selected_index = -1;
continue;
}
this->index[this->count] = ind;
- this->enabled[this->count] = (_game_mode == GM_EDITOR) || GetIndustryProbabilityCallback(ind, IACT_USERCREATION, 1) > 0;
+ this->enabled[this->count] = this->gs->IsGameMode(GM_EDITOR) || GetIndustryProbabilityCallback(ind, IACT_USERCREATION, 1) > 0;
/* Keep the selection to the correct line */
if (this->selected_type == ind) this->selected_index = this->count;
this->count++;
@@ -314,6 +315,7 @@ class BuildIndustryWindow : public Window {
public:
BuildIndustryWindow() : Window(&_build_industry_desc)
{
+ this->gs = GameState::GetInstance();
this->timer_enabled = _loaded_newgrf_features.has_newindustries;
this->selected_index = -1;
@@ -351,7 +353,7 @@ public:
case WID_DPI_INFOPANEL: {
/* Extra line for cost outside of editor + extra lines for 'extra' information for NewGRFs. */
- int height = 2 + (_game_mode == GM_EDITOR ? 0 : 1) + (_loaded_newgrf_features.has_newindustries ? 4 : 0);
+ int height = 2 + (this->gs->IsGameMode(GM_EDITOR) ? 0 : 1) + (_loaded_newgrf_features.has_newindustries ? 4 : 0);
Dimension d = {0, 0};
for (byte i = 0; i < this->count; i++) {
if (this->index[i] == INVALID_INDUSTRYTYPE) continue;
@@ -411,7 +413,7 @@ public:
case WID_DPI_FUND_WIDGET:
/* Raw industries might be prospected. Show this fact by changing the string
* In Editor, you just build, while ingame, or you fund or you prospect */
- if (_game_mode == GM_EDITOR) {
+ if (this->gs->IsGameMode(GM_EDITOR)) {
/* We've chosen many random industries but no industries have been specified */
SetDParam(0, STR_FUND_INDUSTRY_BUILD_NEW_INDUSTRY);
} else {
@@ -470,7 +472,7 @@ public:
const IndustrySpec *indsp = GetIndustrySpec(this->selected_type);
- if (_game_mode != GM_EDITOR) {
+ if (!this->gs->IsGameMode(GM_EDITOR)) {
SetDParam(0, indsp->GetConstructionCost());
DrawString(left, right, y, STR_FUND_INDUSTRY_INDUSTRY_BUILD_COST);
y += FONT_HEIGHT_NORMAL;
@@ -542,7 +544,7 @@ public:
this->SetDirty();
if (_thd.GetCallbackWnd() == this &&
- ((_game_mode != GM_EDITOR && _settings_game.construction.raw_industry_construction == 2 && indsp != NULL && indsp->IsRawIndustry()) ||
+ ((!this->gs->IsGameMode(GM_EDITOR) && _settings_game.construction.raw_industry_construction == 2 && indsp != NULL && indsp->IsRawIndustry()) ||
this->selected_type == INVALID_INDUSTRYTYPE ||
!this->enabled[this->selected_index])) {
/* Reset the button state if going to prospecting or "build many industries" */
@@ -572,7 +574,7 @@ public:
GenerateIndustries();
_generating_world = false;
}
- } else if (_game_mode != GM_EDITOR && _settings_game.construction.raw_industry_construction == 2 && GetIndustrySpec(this->selected_type)->IsRawIndustry()) {
+ } else if (!this->gs->IsGameMode(GM_EDITOR) && _settings_game.construction.raw_industry_construction == 2 && GetIndustrySpec(this->selected_type)->IsRawIndustry()) {
DoCommandP(0, this->selected_type, InteractiveRandom(), CMD_BUILD_INDUSTRY | CMD_MSG(STR_ERROR_CAN_T_CONSTRUCT_THIS_INDUSTRY));
this->HandleButtonClick(WID_DPI_FUND_WIDGET);
} else {
@@ -596,7 +598,7 @@ public:
const IndustrySpec *indsp = GetIndustrySpec(this->selected_type);
uint32 seed = InteractiveRandom();
- if (_game_mode == GM_EDITOR) {
+ if (this->gs->IsGameMode(GM_EDITOR)) {
/* Show error if no town exists at all */
if (Town::GetNumItems() == 0) {
SetDParam(0, indsp->name);
@@ -674,7 +676,7 @@ public:
void ShowBuildIndustryWindow()
{
- if (_game_mode != GM_EDITOR && !Company::IsValidID(_local_company)) return;
+ if (!GameState::GetInstance()->IsGameMode(GM_EDITOR) && !Company::IsValidID(_local_company)) return;
if (BringWindowToFrontById(WC_BUILD_INDUSTRY, 0)) return;
new BuildIndustryWindow();
}
@@ -684,7 +686,7 @@ static void UpdateIndustryProduction(Industry *i);
static inline bool IsProductionAlterable(const Industry *i)
{
const IndustrySpec *is = GetIndustrySpec(i->type);
- return ((_game_mode == GM_EDITOR || _cheats.setup_prod.value) &&
+ return ((GameState::GetInstance()->IsGameMode(GM_EDITOR) || _cheats.setup_prod.value) &&
(is->production_rate[0] != 0 || is->production_rate[1] != 0 || is->IsRawIndustry()) &&
!_networking);
}
diff --git a/src/intro_gui.cpp b/src/intro_gui.cpp
index 3659b03..3966d96 100644
--- a/src/intro_gui.cpp
+++ b/src/intro_gui.cpp
@@ -284,7 +284,7 @@ void ShowSelectGameWindow()
static void AskExitGameCallback(Window *w, bool confirmed)
{
- if (confirmed) _exit_game = true;
+ if (confirmed) GameState::GetInstance()->ExitGame(true);
}
void AskExitGame()
@@ -322,7 +322,7 @@ void AskExitGame()
static void AskExitToGameMenuCallback(Window *w, bool confirmed)
{
if (confirmed) {
- _switch_mode = SM_MENU;
+ GameState::GetInstance()->SetSwitchMode(SM_MENU);
ClearErrorMessages();
}
}
@@ -331,7 +331,7 @@ void AskExitToGameMenu()
{
ShowQuery(
STR_ABANDON_GAME_CAPTION,
- (_game_mode != GM_EDITOR) ? STR_ABANDON_GAME_QUERY : STR_ABANDON_SCENARIO_QUERY,
+ !GameState::GetInstance()->IsGameMode(GM_EDITOR) ? STR_ABANDON_GAME_QUERY : STR_ABANDON_SCENARIO_QUERY,
NULL,
AskExitToGameMenuCallback
);
diff --git a/src/main_gui.cpp b/src/main_gui.cpp
index b13920a..576e4c4 100644
--- a/src/main_gui.cpp
+++ b/src/main_gui.cpp
@@ -191,7 +191,7 @@ void ZoomInOrOutToCursorWindow(bool in, Window *w)
{
assert(w != NULL);
- if (_game_mode != GM_MENU) {
+ if (!GameState::GetInstance()->IsGameMode(GM_MENU)) {
ViewPort *vp = w->viewport;
if ((in && vp->zoom <= _settings_client.gui.zoom_min) || (!in && vp->zoom >= _settings_client.gui.zoom_max)) return;
@@ -271,7 +271,7 @@ struct MainWindow : Window
virtual void OnPaint()
{
this->DrawWidgets();
- if (_game_mode == GM_MENU) {
+ if (GameState::GetInstance()->IsGameMode(GM_MENU)) {
static const SpriteID title_sprites[] = {SPR_OTTD_O, SPR_OTTD_P, SPR_OTTD_E, SPR_OTTD_N, SPR_OTTD_T, SPR_OTTD_T, SPR_OTTD_D};
static const uint LETTER_SPACING = 10;
int name_width = (lengthof(title_sprites) - 1) * LETTER_SPACING;
@@ -301,13 +301,15 @@ struct MainWindow : Window
* assertions that are hard to trigger and debug */
if (HasModalProgress()) return ES_NOT_HANDLED;
+ GameState *gs = GameState::GetInstance();
+
switch (hotkey) {
case GHK_ABANDON:
/* No point returning from the main menu to itself */
- if (_game_mode == GM_MENU) return ES_HANDLED;
+ if (gs->IsGameMode(GM_MENU)) return ES_HANDLED;
if (_settings_client.gui.autosave_on_exit) {
DoExitSave();
- _switch_mode = SM_MENU;
+ gs->SetSwitchMode(SM_MENU);
} else {
AskExitToGameMenu();
}
@@ -326,7 +328,7 @@ struct MainWindow : Window
return ES_HANDLED;
}
- if (_game_mode == GM_MENU) return ES_NOT_HANDLED;
+ if (gs->IsGameMode(GM_MENU)) return ES_NOT_HANDLED;
switch (hotkey) {
case GHK_CENTER:
@@ -558,7 +560,7 @@ void SetupColoursAndInitialWindow()
new MainWindow(&_main_window_desc);
/* XXX: these are not done */
- switch (_game_mode) {
+ switch (GameState::GetInstance()->GetGameMode()) {
default: NOT_REACHED();
case GM_MENU:
ShowSelectGameWindow();
@@ -579,7 +581,7 @@ void ShowVitalWindows()
AllocateToolbar();
/* Status bad only for normal games */
- if (_game_mode == GM_EDITOR) return;
+ if (GameState::GetInstance()->IsGameMode(GM_EDITOR)) return;
ShowStatusBar();
}
diff --git a/src/music_gui.cpp b/src/music_gui.cpp
index 279f376..a310251 100644
--- a/src/music_gui.cpp
+++ b/src/music_gui.cpp
@@ -11,6 +11,7 @@
#include "stdafx.h"
#include "openttd.h"
+#include "game_state.h"
#include "base_media_base.h"
#include "music/music_driver.hpp"
#include "window_gui.h"
@@ -217,7 +218,7 @@ static void SelectSongToPlay()
} while (_playlists[_settings_client.music.playlist][++i] != 0 && j < lengthof(_cur_playlist) - 1);
/* Do not shuffle when on the intro-start window, as the song to play has to be the original TTD Theme*/
- if (_settings_client.music.shuffle && _game_mode != GM_MENU) {
+ if (_settings_client.music.shuffle && !GameState::GetInstance()->IsGameMode(GM_MENU)) {
i = 500;
do {
uint32 r = InteractiveRandom();
@@ -279,7 +280,7 @@ void MusicLoop()
if (!_song_is_active) return;
if (!MusicDriver::GetInstance()->IsSongPlaying()) {
- if (_game_mode != GM_MENU) {
+ if (!GameState::GetInstance()->IsGameMode(GM_MENU)) {
StopMusic();
SkipToNextSong();
PlayPlaylistSong();
diff --git a/src/network/core/tcp_game.cpp b/src/network/core/tcp_game.cpp
index 9b3f7b5..01d1389 100644
--- a/src/network/core/tcp_game.cpp
+++ b/src/network/core/tcp_game.cpp
@@ -15,6 +15,7 @@
#include "../../stdafx.h"
+#include "../../game_state.h"
#include "../network.h"
#include "../network_internal.h"
#include "../../debug.h"
@@ -45,7 +46,7 @@ NetworkRecvStatus NetworkGameSocketHandler::CloseConnection(bool error)
{
/* Clients drop back to the main menu */
if (!_network_server && _networking) {
- _switch_mode = SM_MENU;
+ GameState::GetInstance()->SetSwitchMode(SM_MENU);
_networking = false;
ShowErrorMessage(STR_NETWORK_ERROR_LOSTCONNECTION, INVALID_STRING_ID, WL_CRITICAL);
diff --git a/src/network/network.cpp b/src/network/network.cpp
index 0bbdd0d..a91e7d4 100644
--- a/src/network/network.cpp
+++ b/src/network/network.cpp
@@ -13,6 +13,7 @@
#ifdef ENABLE_NETWORK
+#include "../game_state.h"
#include "../strings_func.h"
#include "../command_func.h"
#include "../date_func.h"
@@ -298,7 +299,7 @@ uint NetworkCalculateLag(const NetworkClientSocket *cs)
* error */
void NetworkError(StringID error_string)
{
- _switch_mode = SM_MENU;
+ GameState::GetInstance()->SetSwitchMode(SM_MENU);
ShowErrorMessage(error_string, INVALID_STRING_ID, WL_CRITICAL);
}
diff --git a/src/network/network_client.cpp b/src/network/network_client.cpp
index e3bcbb2..cad79b9 100644
--- a/src/network/network_client.cpp
+++ b/src/network/network_client.cpp
@@ -12,6 +12,7 @@
#ifdef ENABLE_NETWORK
#include "../stdafx.h"
+#include "../game_state.h"
#include "network_gui.h"
#include "../saveload/saveload.h"
#include "../saveload/saveload_filter.h"
@@ -199,7 +200,7 @@ void ClientNetworkGameSocketHandler::ClientError(NetworkRecvStatus res)
SendError(errorno);
}
- _switch_mode = SM_MENU;
+ GameState::GetInstance()->SetSwitchMode(SM_MENU);
this->CloseConnection(res);
_networking = false;
}
diff --git a/src/network/network_gui.cpp b/src/network/network_gui.cpp
index 3e4a4b0..ba626d7 100644
--- a/src/network/network_gui.cpp
+++ b/src/network/network_gui.cpp
@@ -2093,7 +2093,7 @@ struct NetworkJoinStatusWindow : Window {
{
if (widget == WID_NJS_CANCELOK) { // Disconnect button
NetworkDisconnect();
- SwitchToMode(SM_MENU);
+ GameState::GetInstance()->SwitchToMode(SM_MENU);
ShowNetworkGameWindow();
}
}
diff --git a/src/newgrf.cpp b/src/newgrf.cpp
index 24b0238..df10146 100644
--- a/src/newgrf.cpp
+++ b/src/newgrf.cpp
@@ -5770,7 +5770,7 @@ bool GetGlobalVariable(byte param, uint32 *value, const GRFFile *grffile)
return true;
case 0x12: // Game mode
- *value = _game_mode;
+ *value = GameState::GetInstance()->GetGameMode();
return true;
/* case 0x13: // Tile refresh offset to left not implemented */
diff --git a/src/newgrf_gui.cpp b/src/newgrf_gui.cpp
index c0aa160..c476e9f 100644
--- a/src/newgrf_gui.cpp
+++ b/src/newgrf_gui.cpp
@@ -45,7 +45,7 @@
void ShowNewGRFError()
{
/* Do not show errors when entering the main screen */
- if (_game_mode == GM_MENU) return;
+ if (GameState::GetInstance()->IsGameMode(GM_MENU)) return;
for (const GRFConfig *c = _grfconfig; c != NULL; c = c->next) {
/* We only want to show fatal errors */
diff --git a/src/newgrf_house.cpp b/src/newgrf_house.cpp
index 2bc85f9..a401566 100644
--- a/src/newgrf_house.cpp
+++ b/src/newgrf_house.cpp
@@ -537,7 +537,7 @@ bool CanDeleteHouse(TileIndex tile)
/* Humans are always allowed to remove buildings, as is water and disasters and
* anyone using the scenario editor. */
- if (Company::IsValidHumanID(_current_company) || _current_company == OWNER_WATER || _current_company == OWNER_NONE || _game_mode == GM_EDITOR || _generating_world) {
+ if (Company::IsValidHumanID(_current_company) || _current_company == OWNER_WATER || _current_company == OWNER_NONE || GameState::GetInstance()->IsGameMode(GM_EDITOR) || _generating_world) {
return true;
}
diff --git a/src/newgrf_object.cpp b/src/newgrf_object.cpp
index 058d5e0..245724e 100644
--- a/src/newgrf_object.cpp
+++ b/src/newgrf_object.cpp
@@ -61,7 +61,7 @@ ObjectSpec _object_specs[NUM_OBJECTS];
bool ObjectSpec::IsEverAvailable() const
{
return this->enabled && HasBit(this->climate, _settings_game.game_creation.landscape) &&
- (this->flags & ((_game_mode != GM_EDITOR && !_generating_world) ? OBJECT_FLAG_ONLY_IN_SCENEDIT : OBJECT_FLAG_ONLY_IN_GAME)) == 0;
+ (this->flags & ((!GameState::GetInstance()->IsGameMode(GM_EDITOR) && !_generating_world) ? OBJECT_FLAG_ONLY_IN_SCENEDIT : OBJECT_FLAG_ONLY_IN_GAME)) == 0;
}
/**
diff --git a/src/news_gui.cpp b/src/news_gui.cpp
index 6338b76..f4d187d 100644
--- a/src/news_gui.cpp
+++ b/src/news_gui.cpp
@@ -644,7 +644,7 @@ static void MoveToNextItem()
*/
void AddNewsItem(StringID string, NewsType type, NewsFlag flags, NewsReferenceType reftype1, uint32 ref1, NewsReferenceType reftype2, uint32 ref2, void *free_data)
{
- if (_game_mode == GM_MENU) return;
+ if (GameState::GetInstance()->IsGameMode(GM_MENU)) return;
/* Create new news item node */
NewsItem *ni = new NewsItem;
diff --git a/src/object_cmd.cpp b/src/object_cmd.cpp
index f7ba0d9..ca93f28 100644
--- a/src/object_cmd.cpp
+++ b/src/object_cmd.cpp
@@ -211,11 +211,12 @@ CommandCost CmdBuildObject(TileIndex tile, DoCommandFlag flags, uint32 p1, uint3
if (type >= NUM_OBJECTS) return CMD_ERROR;
uint8 view = GB(p2, 0, 2);
const ObjectSpec *spec = ObjectSpec::Get(type);
- if (_game_mode == GM_NORMAL && !spec->IsAvailable() && !_generating_world) return CMD_ERROR;
- if ((_game_mode == GM_EDITOR || _generating_world) && !spec->WasEverAvailable()) return CMD_ERROR;
+ GameState *gs = GameState::GetInstance();
+ if (gs->IsGameMode(GM_NORMAL) && !spec->IsAvailable() && !_generating_world) return CMD_ERROR;
+ if ((gs->IsGameMode(GM_EDITOR) || _generating_world) && !spec->WasEverAvailable()) return CMD_ERROR;
- if ((spec->flags & OBJECT_FLAG_ONLY_IN_SCENEDIT) != 0 && ((!_generating_world && _game_mode != GM_EDITOR) || _current_company != OWNER_NONE)) return CMD_ERROR;
- if ((spec->flags & OBJECT_FLAG_ONLY_IN_GAME) != 0 && (_generating_world || _game_mode != GM_NORMAL || _current_company > MAX_COMPANIES)) return CMD_ERROR;
+ if ((spec->flags & OBJECT_FLAG_ONLY_IN_SCENEDIT) != 0 && ((!_generating_world && !gs->IsGameMode(GM_EDITOR)) || _current_company != OWNER_NONE)) return CMD_ERROR;
+ if ((spec->flags & OBJECT_FLAG_ONLY_IN_GAME) != 0 && (_generating_world || !gs->IsGameMode(GM_NORMAL) || _current_company > MAX_COMPANIES)) return CMD_ERROR;
if (view >= spec->views) return CMD_ERROR;
if (!Object::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_OBJECTS);
@@ -485,7 +486,7 @@ static CommandCost ClearTile_Object(TileIndex tile, DoCommandFlag flags)
} else if (!(spec->flags & OBJECT_FLAG_AUTOREMOVE) && (flags & DC_AUTO)) {
/* No automatic removal by overbuilding stuff. */
return_cmd_error(type == OBJECT_HQ ? STR_ERROR_COMPANY_HEADQUARTERS_IN : STR_ERROR_OBJECT_IN_THE_WAY);
- } else if (_game_mode == GM_EDITOR) {
+ } else if (GameState::GetInstance()->IsGameMode(GM_EDITOR)) {
/* No further limitations for the editor. */
} else if (GetTileOwner(tile) == OWNER_NONE) {
/* Owned by nobody and unremovable, so we can only remove it with brute force! */
diff --git a/src/openttd.cpp b/src/openttd.cpp
index 10c31e9..3382326 100644
--- a/src/openttd.cpp
+++ b/src/openttd.cpp
@@ -305,7 +305,7 @@ static void ShutdownGame()
PoolBase::Clean(PT_ALL);
/* No NewGRFs were loaded when it was still bootstrapping. */
- if (_game_mode != GM_BOOTSTRAP) ResetNewGRFData();
+ if (!GameState::GetInstance()->IsGameMode(GM_BOOTSTRAP)) ResetNewGRFData();
/* Close all and any open filehandles */
FioCloseAll();
@@ -317,9 +317,9 @@ static void ShutdownGame()
* Load the introduction game.
* @param load_newgrfs Whether to load the NewGRFs or not.
*/
-static void LoadIntroGame(bool load_newgrfs = true)
+void LoadIntroGame(bool load_newgrfs = false)
{
- _game_mode = GM_MENU;
+ GameState::GetInstance()->SetGameMode(GM_MENU);
if (load_newgrfs) ResetGRFConfig(false);
@@ -452,9 +452,9 @@ struct AfterNewGRFScan : NewGRFScanCallback {
IConsoleInit();
InitializeGUI();
IConsoleCmdExec("exec scripts/autoexec.scr 0");
-
+ GameState *gs = GameState::GetInstance();
/* Make sure _settings is filled with _settings_newgame if we switch to a game directly */
- if (_switch_mode != SM_NONE) MakeNewgameSettingsLive();
+ if (!gs->IsSwitchMode(SM_NONE)) MakeNewgameSettingsLive();
#ifdef ENABLE_NETWORK
if (_network_available && network_conn != NULL) {
@@ -479,7 +479,8 @@ struct AfterNewGRFScan : NewGRFScanCallback {
if (port != NULL) rport = atoi(port);
LoadIntroGame();
- _switch_mode = SM_NONE;
+
+ gs->SetSwitchMode(SM_NONE);
NetworkClientConnectGame(NetworkAddress(network_conn, rport), join_as, join_server_password, join_company_password);
}
#endif /* ENABLE_NETWORK */
@@ -552,8 +553,10 @@ int openttd_main(int argc, char *argv[])
_dedicated_forks = false;
#endif /* ENABLE_NETWORK */
- _game_mode = GM_MENU;
- _switch_mode = SM_MENU;
+
+ GameState *gs = GameState::GetInstance();
+ gs->SetGameMode(GM_MENU);
+ gs->SetSwitchMode(SM_MENU);
_config_file = NULL;
GetOptData mgo(argc - 1, argv + 1, _options);
@@ -614,12 +617,12 @@ int openttd_main(int argc, char *argv[])
if (mgo.opt != NULL) SetDebugString(mgo.opt);
break;
}
- case 'e': _switch_mode = (_switch_mode == SM_LOAD_GAME || _switch_mode == SM_LOAD_SCENARIO ? SM_LOAD_SCENARIO : SM_EDITOR); break;
+ case 'e': gs->SetSwitchMode(gs->IsSwitchMode(SM_LOAD_GAME) || gs->IsSwitchMode(SM_LOAD_SCENARIO) ? SM_LOAD_SCENARIO : SM_EDITOR); break;
case 'g':
if (mgo.opt != NULL) {
_file_to_saveload.SetName(mgo.opt);
- bool is_scenario = _switch_mode == SM_EDITOR || _switch_mode == SM_LOAD_SCENARIO;
- _switch_mode = is_scenario ? SM_LOAD_SCENARIO : SM_LOAD_GAME;
+ bool is_scenario = gs->IsSwitchMode(SM_EDITOR) || gs->IsSwitchMode(SM_LOAD_SCENARIO);
+ gs->SetSwitchMode(is_scenario ? SM_LOAD_SCENARIO : SM_LOAD_GAME);
_file_to_saveload.SetMode(SLO_LOAD, is_scenario ? FT_SCENARIO : FT_SAVEGAME, DFT_GAME_FILE);
/* if the file doesn't exist or it is not a valid savegame, let the saveload code show an error */
@@ -632,7 +635,7 @@ int openttd_main(int argc, char *argv[])
break;
}
- _switch_mode = SM_NEWGAME;
+ gs->SetSwitchMode(SM_NEWGAME);
/* Give a random map if no seed has been given */
if (scanner->generation_seed == GENERATE_NEW_SEED) {
scanner->generation_seed = InteractiveRandom();
@@ -913,11 +916,13 @@ exit_normal:
void HandleExitGameRequest()
{
- if (_game_mode == GM_MENU || _game_mode == GM_BOOTSTRAP) { // do not ask to quit on the main screen
- _exit_game = true;
+ GameState *gs = GameState::GetInstance();
+
+ if (gs->IsGameMode(GM_MENU) || gs->IsGameMode(GM_BOOTSTRAP)) { // do not ask to quit on the main screen
+ gs->ExitGame(true);
} else if (_settings_client.gui.autosave_on_exit) {
DoExitSave();
- _exit_game = true;
+ gs->ExitGame(true);
} else {
AskExitGame();
}
@@ -962,9 +967,9 @@ static void MakeNewGameDone()
MarkWholeScreenDirty();
}
-static void MakeNewGame(bool from_heightmap, bool reset_settings)
+ void MakeNewGame(bool from_heightmap, bool reset_settings)
{
- _game_mode = GM_NORMAL;
+ GameState::GetInstance()->SetGameMode(GM_NORMAL);
ResetGRFConfig(true);
@@ -977,9 +982,9 @@ static void MakeNewEditorWorldDone()
SetLocalCompany(OWNER_NONE);
}
-static void MakeNewEditorWorld()
+void MakeNewEditorWorld()
{
- _game_mode = GM_EDITOR;
+ GameState::GetInstance()->SetGameMode(GM_EDITOR);
ResetGRFConfig(true);
@@ -1001,9 +1006,8 @@ bool SafeLoad(const char *filename, SaveLoadOperation fop, DetailedFileType dft,
{
assert(fop == SLO_LOAD);
assert(dft == DFT_GAME_FILE || (lf == NULL && dft == DFT_OLD_GAME_FILE));
- GameMode ogm = _game_mode;
-
- _game_mode = newgm;
+ GameState *gs = GameState::GetInstance();
+ gs->SetGameMode(newgm);
switch (lf == NULL ? SaveOrLoad(filename, fop, dft, subdir) : LoadWithFilter(lf)) {
case SL_OK: return true;
@@ -1027,7 +1031,7 @@ bool SafeLoad(const char *filename, SaveLoadOperation fop, DetailedFileType dft,
}
#endif /* ENABLE_NETWORK */
- switch (ogm) {
+ switch (gs->GetOldGameMode()) {
default:
case GM_MENU: LoadIntroGame(); break;
case GM_EDITOR: MakeNewEditorWorld(); break;
@@ -1035,153 +1039,11 @@ bool SafeLoad(const char *filename, SaveLoadOperation fop, DetailedFileType dft,
return false;
default:
- _game_mode = ogm;
+ gs->RestoreGameMode();
return false;
}
}
-void SwitchToMode(SwitchMode new_mode)
-{
-#ifdef ENABLE_NETWORK
- /* If we are saving something, the network stays in his current state */
- if (new_mode != SM_SAVE_GAME) {
- /* If the network is active, make it not-active */
- if (_networking) {
- if (_network_server && (new_mode == SM_LOAD_GAME || new_mode == SM_NEWGAME || new_mode == SM_RESTARTGAME)) {
- NetworkReboot();
- } else {
- NetworkDisconnect();
- }
- }
-
- /* If we are a server, we restart the server */
- if (_is_network_server) {
- /* But not if we are going to the menu */
- if (new_mode != SM_MENU) {
- /* check if we should reload the config */
- if (_settings_client.network.reload_cfg) {
- LoadFromConfig();
- MakeNewgameSettingsLive();
- ResetGRFConfig(false);
- }
- NetworkServerStart();
- } else {
- /* This client no longer wants to be a network-server */
- _is_network_server = false;
- }
- }
- }
-#endif /* ENABLE_NETWORK */
- /* Make sure all AI controllers are gone at quitting game */
- if (new_mode != SM_SAVE_GAME) AI::KillAll();
-
- switch (new_mode) {
- case SM_EDITOR: // Switch to scenario editor
- MakeNewEditorWorld();
- break;
-
- case SM_RESTARTGAME: // Restart --> 'Random game' with current settings
- case SM_NEWGAME: // New Game --> 'Random game'
-#ifdef ENABLE_NETWORK
- if (_network_server) {
- seprintf(_network_game_info.map_name, lastof(_network_game_info.map_name), "Random Map");
- }
-#endif /* ENABLE_NETWORK */
- MakeNewGame(false, new_mode == SM_NEWGAME);
- break;
-
- case SM_LOAD_GAME: { // Load game, Play Scenario
- ResetGRFConfig(true);
- ResetWindowSystem();
-
- if (!SafeLoad(_file_to_saveload.name, _file_to_saveload.file_op, _file_to_saveload.detail_ftype, GM_NORMAL, NO_DIRECTORY)) {
- SetDParamStr(0, GetSaveLoadErrorString());
- ShowErrorMessage(STR_JUST_RAW_STRING, INVALID_STRING_ID, WL_ERROR);
- } else {
- if (_file_to_saveload.abstract_ftype == FT_SCENARIO) {
- /* Reset engine pool to simplify changing engine NewGRFs in scenario editor. */
- EngineOverrideManager::ResetToCurrentNewGRFConfig();
- }
- /* Update the local company for a loaded game. It is either always
- * company #1 (eg 0) or in the case of a dedicated server a spectator */
- SetLocalCompany(_network_dedicated ? COMPANY_SPECTATOR : COMPANY_FIRST);
- /* Execute the game-start script */
- IConsoleCmdExec("exec scripts/game_start.scr 0");
- /* Decrease pause counter (was increased from opening load dialog) */
- DoCommandP(0, PM_PAUSED_SAVELOAD, 0, CMD_PAUSE);
-#ifdef ENABLE_NETWORK
- if (_network_server) {
- seprintf(_network_game_info.map_name, lastof(_network_game_info.map_name), "%s (Loaded game)", _file_to_saveload.title);
- }
-#endif /* ENABLE_NETWORK */
- }
- break;
- }
-
- case SM_START_HEIGHTMAP: // Load a heightmap and start a new game from it
-#ifdef ENABLE_NETWORK
- if (_network_server) {
- seprintf(_network_game_info.map_name, lastof(_network_game_info.map_name), "%s (Heightmap)", _file_to_saveload.title);
- }
-#endif /* ENABLE_NETWORK */
- MakeNewGame(true, true);
- break;
-
- case SM_LOAD_HEIGHTMAP: // Load heightmap from scenario editor
- SetLocalCompany(OWNER_NONE);
-
- GenerateWorld(GWM_HEIGHTMAP, 1 << _settings_game.game_creation.map_x, 1 << _settings_game.game_creation.map_y);
- MarkWholeScreenDirty();
- break;
-
- case SM_LOAD_SCENARIO: { // Load scenario from scenario editor
- if (SafeLoad(_file_to_saveload.name, _file_to_saveload.file_op, _file_to_saveload.detail_ftype, GM_EDITOR, NO_DIRECTORY)) {
- SetLocalCompany(OWNER_NONE);
- _settings_newgame.game_creation.starting_year = _cur_year;
- /* Cancel the saveload pausing */
- DoCommandP(0, PM_PAUSED_SAVELOAD, 0, CMD_PAUSE);
- } else {
- SetDParamStr(0, GetSaveLoadErrorString());
- ShowErrorMessage(STR_JUST_RAW_STRING, INVALID_STRING_ID, WL_ERROR);
- }
- break;
- }
-
- case SM_MENU: // Switch to game intro menu
- LoadIntroGame();
- if (BaseSounds::ini_set == NULL && BaseSounds::GetUsedSet()->fallback) {
- ShowErrorMessage(STR_WARNING_FALLBACK_SOUNDSET, INVALID_STRING_ID, WL_CRITICAL);
- BaseSounds::ini_set = stredup(BaseSounds::GetUsedSet()->name);
- }
- break;
-
- case SM_SAVE_GAME: // Save game.
- /* Make network saved games on pause compatible to singleplayer */
- if (SaveOrLoad(_file_to_saveload.name, SLO_SAVE, DFT_GAME_FILE, NO_DIRECTORY) != SL_OK) {
- SetDParamStr(0, GetSaveLoadErrorString());
- ShowErrorMessage(STR_JUST_RAW_STRING, INVALID_STRING_ID, WL_ERROR);
- } else {
- DeleteWindowById(WC_SAVELOAD, 0);
- }
- break;
-
- case SM_SAVE_HEIGHTMAP: // Save heightmap.
- MakeHeightmapScreenshot(_file_to_saveload.name);
- DeleteWindowById(WC_SAVELOAD, 0);
- break;
-
- case SM_GENRANDLAND: // Generate random land within scenario editor
- SetLocalCompany(OWNER_NONE);
- GenerateWorld(GWM_RANDOM, 1 << _settings_game.game_creation.map_x, 1 << _settings_game.game_creation.map_y);
- /* XXX: set date */
- MarkWholeScreenDirty();
- break;
-
- default: NOT_REACHED();
- }
-}
-
-
/**
* Check the validity of some of the caches.
* Especially in the sense of desyncs between
@@ -1353,7 +1215,7 @@ void StateGameLoop()
Layouter::ReduceLineCache();
- if (_game_mode == GM_EDITOR) {
+ if (GameState::GetInstance()->IsGameMode(GM_EDITOR)) {
BasePersistentStorageArray::SwitchMode(PSM_ENTER_GAMELOOP);
RunTileLoop();
CallVehicleTicks();
@@ -1432,7 +1294,9 @@ static void DoAutosave()
void GameLoop()
{
- if (_game_mode == GM_BOOTSTRAP) {
+ GameState *gs = GameState::GetInstance();
+
+ if (gs->IsGameMode(GM_BOOTSTRAP)) {
#ifdef ENABLE_NETWORK
/* Check for UDP stuff */
if (_network_available) NetworkBackgroundLoop();
@@ -1451,9 +1315,9 @@ void GameLoop()
}
/* switch game mode? */
- if (_switch_mode != SM_NONE && !HasModalProgress()) {
- SwitchToMode(_switch_mode);
- _switch_mode = SM_NONE;
+ if (!gs->IsSwitchMode(SM_NONE) && !HasModalProgress()) {
+ gs->SwitchToMode(gs->GetSwitchMode());
+ gs->SetSwitchMode(SM_NONE);
}
IncreaseSpriteLRU();
@@ -1492,7 +1356,7 @@ void GameLoop()
if (!_pause_mode && HasBit(_display_opt, DO_FULL_ANIMATION)) DoPaletteAnimations();
- if (!_pause_mode || _game_mode == GM_EDITOR || _settings_game.construction.command_pause_level > CMDPL_NO_CONSTRUCTION) MoveAllTextEffects();
+ if (!_pause_mode || gs->IsGameMode(GM_EDITOR) || _settings_game.construction.command_pause_level > CMDPL_NO_CONSTRUCTION) MoveAllTextEffects();
InputLoop();
diff --git a/src/openttd.h b/src/openttd.h
index 5e360d6..be8a418 100644
--- a/src/openttd.h
+++ b/src/openttd.h
@@ -14,30 +14,6 @@
#include "core/enum_type.hpp"
-/** Mode which defines the state of the game. */
-enum GameMode {
- GM_MENU,
- GM_NORMAL,
- GM_EDITOR,
- GM_BOOTSTRAP
-};
-
-/** Mode which defines what mode we're switching to. */
-enum SwitchMode {
- SM_NONE,
- SM_NEWGAME, ///< New Game --> 'Random game'.
- SM_RESTARTGAME, ///< Restart --> 'Random game' with current settings.
- SM_EDITOR, ///< Switch to scenario editor.
- SM_LOAD_GAME, ///< Load game, Play Scenario.
- SM_MENU, ///< Switch to game intro menu.
- SM_SAVE_GAME, ///< Save game.
- SM_SAVE_HEIGHTMAP, ///< Save heightmap.
- SM_GENRANDLAND, ///< Generate random land within scenario editor.
- SM_LOAD_SCENARIO, ///< Load scenario from scenario editor.
- SM_START_HEIGHTMAP, ///< Load a heightmap and start a new game from it.
- SM_LOAD_HEIGHTMAP, ///< Load heightmap from scenario editor.
-};
-
/** Display Options */
enum DisplayOptions {
DO_SHOW_TOWN_NAMES = 0, ///< Display town names.
@@ -49,10 +25,6 @@ enum DisplayOptions {
DO_SHOW_COMPETITOR_SIGNS = 7, ///< Display signs, station names and waypoint names of opponent companies. Buoys and oilrig-stations are always shown, even if this option is turned off.
};
-extern GameMode _game_mode;
-extern SwitchMode _switch_mode;
-extern bool _exit_game;
-
/** Modes of pausing we've got */
enum PauseMode {
PM_UNPAUSED = 0, ///< A normal unpaused game
@@ -78,6 +50,4 @@ void AskExitToGameMenu();
int openttd_main(int argc, char *argv[]);
void HandleExitGameRequest();
-void SwitchToMode(SwitchMode new_mode);
-
#endif /* OPENTTD_H */
diff --git a/src/rail_cmd.cpp b/src/rail_cmd.cpp
index 9f284fc..def6084 100644
--- a/src/rail_cmd.cpp
+++ b/src/rail_cmd.cpp
@@ -2311,8 +2311,10 @@ static void DrawTrackBits(TileInfo *ti, TrackBits track)
if (track & TRACK_BIT_RIGHT) DrawGroundSprite(rti->base_sprites.single_e, PAL_NONE);
}
+ GameState *gs = GameState::GetInstance();
+
/* PBS debugging, draw reserved tracks darker */
- if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation) {
+ if (!gs->IsGameMode(GM_MENU) && _settings_client.gui.show_track_reservation) {
/* Get reservation, but mask track on halftile slope */
TrackBits pbs = GetRailReservationTrackBits(ti->tile) & track;
if (pbs & TRACK_BIT_X) {
@@ -2350,7 +2352,7 @@ static void DrawTrackBits(TileInfo *ti, TrackBits track)
}
DrawGroundSprite(image, pal, &(_halftile_sub_sprite[halftile_corner]));
- if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasReservedTracks(ti->tile, CornerToTrackBits(halftile_corner))) {
+ if (!gs->IsGameMode(GM_MENU) && _settings_client.gui.show_track_reservation && HasReservedTracks(ti->tile, CornerToTrackBits(halftile_corner))) {
static const byte _corner_to_track_sprite[] = {3, 1, 2, 0};
DrawGroundSprite(_corner_to_track_sprite[halftile_corner] + rti->base_sprites.single_n, PALETTE_CRASH, NULL, 0, -(int)TILE_HEIGHT);
}
@@ -2482,7 +2484,7 @@ static void DrawTile_Track(TileInfo *ti)
}
} else {
/* PBS debugging, draw reserved tracks darker */
- if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasDepotReservation(ti->tile)) {
+ if (!GameState::GetInstance()->IsGameMode(GM_MENU) && _settings_client.gui.show_track_reservation && HasDepotReservation(ti->tile)) {
switch (GetRailDepotDirection(ti->tile)) {
case DIAGDIR_NE:
if (!IsInvisibilitySet(TO_BUILDINGS)) break;
diff --git a/src/rail_gui.cpp b/src/rail_gui.cpp
index 73fe29d..7cc4faa 100644
--- a/src/rail_gui.cpp
+++ b/src/rail_gui.cpp
@@ -778,7 +778,7 @@ struct BuildRailToolbarWindow : Window {
*/
static EventState RailToolbarGlobalHotkeys(int hotkey)
{
- if (_game_mode != GM_NORMAL || !CanBuildVehicleInfrastructure(VEH_TRAIN)) return ES_NOT_HANDLED;
+ if (!GameState::GetInstance()->IsGameMode(GM_NORMAL) || !CanBuildVehicleInfrastructure(VEH_TRAIN)) return ES_NOT_HANDLED;
extern RailType _last_built_railtype;
Window *w = ShowBuildRailToolbar(_last_built_railtype);
if (w == NULL) return ES_NOT_HANDLED;
diff --git a/src/road.cpp b/src/road.cpp
index f515975..ae4452a 100644
--- a/src/road.cpp
+++ b/src/road.cpp
@@ -111,7 +111,7 @@ bool HasRoadTypesAvail(const CompanyID company, const RoadTypes rts)
{
RoadTypes avail_roadtypes;
- if (company == OWNER_DEITY || company == OWNER_TOWN || _game_mode == GM_EDITOR || _generating_world) {
+ if (company == OWNER_DEITY || company == OWNER_TOWN || GameState::GetInstance()->IsGameMode(GM_EDITOR) || _generating_world) {
avail_roadtypes = ROADTYPES_ROAD;
} else {
Company *c = Company::GetIfValid(company);
diff --git a/src/road_cmd.cpp b/src/road_cmd.cpp
index 5e432a2..7edffe1 100644
--- a/src/road_cmd.cpp
+++ b/src/road_cmd.cpp
@@ -115,7 +115,7 @@ static Foundation GetRoadFoundation(Slope tileh, RoadBits bits);
*/
CommandCost CheckAllowRemoveRoad(TileIndex tile, RoadBits remove, Owner owner, RoadType rt, DoCommandFlag flags, bool town_check)
{
- if (_game_mode == GM_EDITOR || remove == ROAD_NONE) return CommandCost();
+ if (GameState::GetInstance()->IsGameMode(GM_EDITOR) || remove == ROAD_NONE) return CommandCost();
/* Water can always flood and towns can always remove "normal" road pieces.
* Towns are not be allowed to remove non "normal" road pieces, like tram
@@ -1335,6 +1335,7 @@ static void DrawTile_Road(TileInfo *ti)
PaletteID pal = PAL_NONE;
const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(ti->tile));
+ GameState *gs = GameState::GetInstance();
if (rti->UsesOverlay()) {
Axis axis = GetCrossingRailAxis(ti->tile);
@@ -1356,7 +1357,7 @@ static void DrawTile_Road(TileInfo *ti)
SpriteID rail = GetCustomRailSprite(rti, ti->tile, RTSG_CROSSING) + axis;
/* Draw tracks, but draw PBS reserved tracks darker. */
- pal = (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasCrossingReservation(ti->tile)) ? PALETTE_CRASH : PAL_NONE;
+ pal = (!gs->IsGameMode(GM_MENU) && _settings_client.gui.show_track_reservation && HasCrossingReservation(ti->tile)) ? PALETTE_CRASH : PAL_NONE;
DrawGroundSprite(rail, pal);
DrawRailTileSeq(ti, &_crossing_layout, TO_CATENARY, rail, 0, PAL_NONE);
@@ -1381,7 +1382,7 @@ static void DrawTile_Road(TileInfo *ti)
DrawGroundSprite(image, pal);
/* PBS debugging, draw reserved tracks darker */
- if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasCrossingReservation(ti->tile)) {
+ if (!gs->IsGameMode(GM_MENU) && _settings_client.gui.show_track_reservation && HasCrossingReservation(ti->tile)) {
DrawGroundSprite(GetCrossingRoadAxis(ti->tile) == AXIS_Y ? GetRailTypeInfo(GetRailType(ti->tile))->base_sprites.single_x : GetRailTypeInfo(GetRailType(ti->tile))->base_sprites.single_y, PALETTE_CRASH);
}
}
diff --git a/src/road_gui.cpp b/src/road_gui.cpp
index 801d334..78aa3f9 100644
--- a/src/road_gui.cpp
+++ b/src/road_gui.cpp
@@ -405,6 +405,7 @@ struct BuildRoadToolbarWindow : Window {
virtual void OnClick(Point pt, int widget, int click_count)
{
+ GameState *gs = GameState::GetInstance();
_remove_button_clicked = false;
_one_way_button_clicked = false;
switch (widget) {
@@ -429,7 +430,7 @@ struct BuildRoadToolbarWindow : Window {
break;
case WID_ROT_DEPOT:
- if (_game_mode == GM_EDITOR || !CanBuildVehicleInfrastructure(VEH_ROAD)) return;
+ if (gs->IsGameMode(GM_EDITOR) || !CanBuildVehicleInfrastructure(VEH_ROAD)) return;
if (HandlePlacePushButton(this, WID_ROT_DEPOT, SPR_CURSOR_ROAD_DEPOT, HT_RECT)) {
ShowRoadDepotPicker(this);
this->last_started_action = widget;
@@ -437,7 +438,7 @@ struct BuildRoadToolbarWindow : Window {
break;
case WID_ROT_BUS_STATION:
- if (_game_mode == GM_EDITOR || !CanBuildVehicleInfrastructure(VEH_ROAD)) return;
+ if (gs->IsGameMode(GM_EDITOR) || !CanBuildVehicleInfrastructure(VEH_ROAD)) return;
if (HandlePlacePushButton(this, WID_ROT_BUS_STATION, SPR_CURSOR_BUS_STATION, HT_RECT)) {
ShowRVStationPicker(this, ROADSTOP_BUS);
this->last_started_action = widget;
@@ -445,7 +446,7 @@ struct BuildRoadToolbarWindow : Window {
break;
case WID_ROT_TRUCK_STATION:
- if (_game_mode == GM_EDITOR || !CanBuildVehicleInfrastructure(VEH_ROAD)) return;
+ if (gs->IsGameMode(GM_EDITOR) || !CanBuildVehicleInfrastructure(VEH_ROAD)) return;
if (HandlePlacePushButton(this, WID_ROT_TRUCK_STATION, SPR_CURSOR_TRUCK_STATION, HT_RECT)) {
ShowRVStationPicker(this, ROADSTOP_TRUCK);
this->last_started_action = widget;
@@ -678,7 +679,7 @@ struct BuildRoadToolbarWindow : Window {
static EventState RoadToolbarGlobalHotkeys(int hotkey)
{
Window *w = NULL;
- switch (_game_mode) {
+ switch (GameState::GetInstance()->GetGameMode()) {
case GM_NORMAL: {
extern RoadType _last_built_roadtype;
w = ShowBuildRoadToolbar(_last_built_roadtype);
diff --git a/src/saveload/afterload.cpp b/src/saveload/afterload.cpp
index d5d9bc3..570ef74 100644
--- a/src/saveload/afterload.cpp
+++ b/src/saveload/afterload.cpp
@@ -786,7 +786,7 @@ bool AfterLoadGame()
}
/* make sure there is a town in the game */
- if (_game_mode == GM_NORMAL && Town::GetNumItems() == 0) {
+ if (GameState::GetInstance()->IsGameMode(GM_NORMAL) && Town::GetNumItems() == 0) {
SetSaveLoadError(STR_ERROR_NO_TOWN_IN_SCENARIO);
/* Restore the signals */
ResetSignalHandlers();
diff --git a/src/saveload/newgrf_sl.cpp b/src/saveload/newgrf_sl.cpp
index de261f0..2336c70 100644
--- a/src/saveload/newgrf_sl.cpp
+++ b/src/saveload/newgrf_sl.cpp
@@ -96,7 +96,7 @@ static void Load_NGRF()
{
Load_NGRF_common(_grfconfig);
- if (_game_mode == GM_MENU) {
+ if (GameState::GetInstance()->IsGameMode(GM_MENU)) {
/* Intro game must not have NewGRF. */
if (_grfconfig != NULL) SlErrorCorrupt("The intro game must not use NewGRF");
diff --git a/src/saveload/saveload.cpp b/src/saveload/saveload.cpp
index dfa3be7..52b1a2b 100644
--- a/src/saveload/saveload.cpp
+++ b/src/saveload/saveload.cpp
@@ -573,7 +573,7 @@ static ThreadObject *_save_thread; ///< The thread we're usin
*/
static void SetAsyncSaveFinish(AsyncSaveFinishProc proc)
{
- if (_exit_game) return;
+ if (GameState::GetInstance()->ExitGame()) return;
while (_async_save_finish != NULL) CSleep(10);
_async_save_finish = proc;
@@ -2478,7 +2478,7 @@ static void SaveFileStart()
/** Update the gui accordingly when saving is done and release locks on saveload. */
static void SaveFileDone()
{
- if (_game_mode != GM_MENU) _fast_forward = _sl.ff_state;
+ if (!GameState::GetInstance()->IsGameMode(GM_MENU)) _fast_forward = _sl.ff_state;
SetMouseCursorBusy(false);
InvalidateWindowData(WC_STATUS_BAR, 0, SBI_SAVELOAD_FINISH);
diff --git a/src/screenshot.cpp b/src/screenshot.cpp
index a24cc6b..c195f31 100644
--- a/src/screenshot.cpp
+++ b/src/screenshot.cpp
@@ -318,7 +318,7 @@ static bool MakePNGImage(const char *name, ScreenshotCallback *callb, void *user
char *p = buf;
p += seprintf(p, lastof(buf), "Graphics set: %s (%u)\n", BaseGraphics::GetUsedSet()->name, BaseGraphics::GetUsedSet()->version);
p = strecpy(p, "NewGRFs:\n", lastof(buf));
- for (const GRFConfig *c = _game_mode == GM_MENU ? NULL : _grfconfig; c != NULL; c = c->next) {
+ for (const GRFConfig *c = GameState::GetInstance()->IsGameMode(GM_MENU) ? NULL : _grfconfig; c != NULL; c = c->next) {
p += seprintf(p, lastof(buf), "%08X ", BSWAP32(c->ident.grfid));
p = md5sumToString(p, lastof(buf), c->ident.md5sum);
p += seprintf(p, lastof(buf), " %s\n", c->filename);
@@ -676,7 +676,9 @@ static const char *MakeScreenshotName(const char *default_fn, const char *ext, b
bool generate = StrEmpty(_screenshot_name);
if (generate) {
- if (_game_mode == GM_EDITOR || _game_mode == GM_MENU || _local_company == COMPANY_SPECTATOR) {
+ GameState *gs = GameState::GetInstance();
+
+ if (gs->IsGameMode(GM_EDITOR) || gs->IsGameMode(GM_MENU) || _local_company == COMPANY_SPECTATOR) {
strecpy(_screenshot_name, default_fn, lastof(_screenshot_name));
} else {
GenerateDefaultSaveName(_screenshot_name, lastof(_screenshot_name));
diff --git a/src/script/script_config.cpp b/src/script/script_config.cpp
index a6e4147..33d2c9a 100644
--- a/src/script/script_config.cpp
+++ b/src/script/script_config.cpp
@@ -31,7 +31,7 @@ void ScriptConfig::Change(const char *name, int version, bool force_exact_match,
this->ClearConfigList();
- if (_game_mode == GM_NORMAL && this->info != NULL) {
+ if (GameState::GetInstance()->IsGameMode(GM_NORMAL) && this->info != NULL) {
/* If we're in an existing game and the Script is changed, set all settings
* for the Script that have the random flag to a random value. */
for (ScriptConfigItemList::const_iterator it = this->info->GetConfigList()->begin(); it != this->info->GetConfigList()->end(); it++) {
diff --git a/src/settings.cpp b/src/settings.cpp
index d819450..1630c24 100644
--- a/src/settings.cpp
+++ b/src/settings.cpp
@@ -764,12 +764,14 @@ void IniSaveWindowSettings(IniFile *ini, const char *grpname, void *desc)
*/
bool SettingDesc::IsEditable(bool do_command) const
{
+ GameState * gs = GameState::GetInstance();
+
if (!do_command && !(this->save.conv & SLF_NO_NETWORK_SYNC) && _networking && !_network_server && !(this->desc.flags & SGF_PER_COMPANY)) return false;
- if ((this->desc.flags & SGF_NETWORK_ONLY) && !_networking && _game_mode != GM_MENU) return false;
+ if ((this->desc.flags & SGF_NETWORK_ONLY) && !_networking && !gs->IsGameMode(GM_MENU)) return false;
if ((this->desc.flags & SGF_NO_NETWORK) && _networking) return false;
if ((this->desc.flags & SGF_NEWGAME_ONLY) &&
- (_game_mode == GM_NORMAL ||
- (_game_mode == GM_EDITOR && !(this->desc.flags & SGF_SCENEDIT_TOO)))) return false;
+ (gs->IsGameMode(GM_NORMAL) ||
+ (gs->IsGameMode(GM_EDITOR) && !(this->desc.flags & SGF_SCENEDIT_TOO)))) return false;
return true;
}
@@ -788,14 +790,14 @@ SettingType SettingDesc::GetType() const
/** Reposition the main toolbar as the setting changed. */
static bool v_PositionMainToolbar(int32 p1)
{
- if (_game_mode != GM_MENU) PositionMainToolbar(NULL);
+ if (!GameState::GetInstance()->IsGameMode(GM_MENU)) PositionMainToolbar(NULL);
return true;
}
/** Reposition the statusbar as the setting changed. */
static bool v_PositionStatusbar(int32 p1)
{
- if (_game_mode != GM_MENU) {
+ if (!GameState::GetInstance()->IsGameMode(GM_MENU)) {
PositionStatusbar(NULL);
PositionNewsMessage(NULL);
PositionNetworkChatWindow(NULL);
@@ -883,7 +885,7 @@ static bool CheckInterval(int32 p1)
{
bool update_vehicles;
VehicleDefaultSettings *vds;
- if (_game_mode == GM_MENU || !Company::IsValidID(_current_company)) {
+ if (GameState::GetInstance()->IsGameMode(GM_MENU) || !Company::IsValidID(_current_company)) {
vds = &_settings_client.company.vehicle;
update_vehicles = false;
} else {
@@ -923,7 +925,7 @@ static bool UpdateInterval(VehicleType type, int32 p1)
{
bool update_vehicles;
VehicleDefaultSettings *vds;
- if (_game_mode == GM_MENU || !Company::IsValidID(_current_company)) {
+ if (GameState::GetInstance()->IsGameMode(GM_MENU) || !Company::IsValidID(_current_company)) {
vds = &_settings_client.company.vehicle;
update_vehicles = false;
} else {
@@ -1050,7 +1052,7 @@ static bool DragSignalsDensityChanged(int32)
static bool TownFoundingChanged(int32 p1)
{
- if (_game_mode != GM_EDITOR && _settings_game.economy.found_town == TF_FORBIDDEN) {
+ if (!GameState::GetInstance()->IsGameMode(GM_EDITOR) && _settings_game.economy.found_town == TF_FORBIDDEN) {
DeleteWindowById(WC_FOUND_TOWN, 0);
return true;
}
@@ -1156,7 +1158,7 @@ static void ValidateSettings()
static bool DifficultyNoiseChange(int32 i)
{
- if (_game_mode == GM_NORMAL) {
+ if (GameState::GetInstance()->IsGameMode(GM_NORMAL)) {
UpdateAirportsNoise();
if (_settings_game.economy.station_noise_level) {
InvalidateWindowClassesData(WC_TOWN_VIEW, 0);
@@ -1185,7 +1187,7 @@ static bool MaxNoAIsChange(int32 i)
static bool CheckRoadSide(int p1)
{
extern bool RoadVehiclesAreBuilt();
- return _game_mode == GM_MENU || !RoadVehiclesAreBuilt();
+ return GameState::GetInstance()->IsGameMode(GM_MENU) || !RoadVehiclesAreBuilt();
}
/**
@@ -1203,7 +1205,7 @@ static size_t ConvertLandscape(const char *value)
static bool CheckFreeformEdges(int32 p1)
{
- if (_game_mode == GM_MENU) return true;
+ if (GameState::GetInstance()->IsGameMode(GM_MENU)) return true;
if (p1 != 0) {
Ship *s;
FOR_ALL_SHIPS(s) {
@@ -1268,7 +1270,7 @@ static bool CheckFreeformEdges(int32 p1)
*/
static bool ChangeDynamicEngines(int32 p1)
{
- if (_game_mode == GM_MENU) return true;
+ if (GameState::GetInstance()->IsGameMode(GM_MENU)) return true;
if (!EngineOverrideManager::ResetToCurrentNewGRFConfig()) {
ShowErrorMessage(STR_CONFIG_SETTING_DYNAMIC_ENGINES_EXISTING_VEHICLES, INVALID_STRING_ID, WL_ERROR);
@@ -1280,8 +1282,8 @@ static bool ChangeDynamicEngines(int32 p1)
static bool ChangeMaxHeightLevel(int32 p1)
{
- if (_game_mode == GM_NORMAL) return false;
- if (_game_mode != GM_EDITOR) return true;
+ if (GameState::GetInstance()->IsGameMode(GM_NORMAL)) return false;
+ if (!GameState::GetInstance()->IsGameMode(GM_EDITOR)) return true;
/* Check if at least one mountain on the map is higher than the new value.
* If yes, disallow the change. */
@@ -1927,7 +1929,7 @@ bool SetSettingValue(uint index, int32 value, bool force_newgame)
void *var = GetVariableAddress(&GetGameSettings(), &sd->save);
Write_ValidateSetting(var, sd, value);
- if (_game_mode != GM_MENU) {
+ if (!GameState::GetInstance()->IsGameMode(GM_MENU)) {
void *var2 = GetVariableAddress(&_settings_newgame, &sd->save);
Write_ValidateSetting(var2, sd, value);
}
@@ -1960,7 +1962,7 @@ bool SetSettingValue(uint index, int32 value, bool force_newgame)
void SetCompanySetting(uint index, int32 value)
{
const SettingDesc *sd = &_company_settings[index];
- if (Company::IsValidID(_local_company) && _game_mode != GM_MENU) {
+ if (Company::IsValidID(_local_company) && !GameState::GetInstance()->IsGameMode(GM_MENU)) {
DoCommandP(0, index, value, CMD_CHANGE_COMPANY_SETTING);
} else {
void *var = GetVariableAddress(&_settings_client.company, &sd->save);
@@ -2026,7 +2028,7 @@ bool SetSettingValue(uint index, const char *value, bool force_newgame)
assert(sd->save.conv & SLF_NO_NETWORK_SYNC);
if (GetVarMemType(sd->save.conv) == SLE_VAR_STRQ) {
- char **var = (char**)GetVariableAddress((_game_mode == GM_MENU || force_newgame) ? &_settings_newgame : &_settings_game, &sd->save);
+ char **var = (char**)GetVariableAddress((GameState::GetInstance()->IsGameMode(GM_MENU) || force_newgame) ? &_settings_newgame : &_settings_game, &sd->save);
free(*var);
*var = strcmp(value, "(null)") == 0 ? NULL : stredup(value);
} else {
@@ -2136,7 +2138,7 @@ void IConsoleGetSetting(const char *name, bool force_newgame)
return;
}
- ptr = GetVariableAddress((_game_mode == GM_MENU || force_newgame) ? &_settings_newgame : &_settings_game, &sd->save);
+ ptr = GetVariableAddress((GameState::GetInstance()->IsGameMode(GM_MENU) || force_newgame) ? &_settings_newgame : &_settings_game, &sd->save);
if (sd->desc.cmd == SDT_STRING) {
IConsolePrintF(CC_WARNING, "Current value for '%s' is: '%s'", name, (GetVarMemType(sd->save.conv) == SLE_VAR_STRQ) ? *(const char * const *)ptr : (const char *)ptr);
diff --git a/src/settings_gui.cpp b/src/settings_gui.cpp
index 0420ba1..bf361fc 100644
--- a/src/settings_gui.cpp
+++ b/src/settings_gui.cpp
@@ -121,7 +121,7 @@ static DropDownList *BuiltSetDropDownList(int *selected_index)
DropDownList *list = new DropDownList();
for (int i = 0; i < n; i++) {
- *list->Append() = new DropDownListCharStringItem(T::GetSet(i)->name, i, (_game_mode == GM_MENU) ? false : (*selected_index != i));
+ *list->Append() = new DropDownListCharStringItem(T::GetSet(i)->name, i, GameState::GetInstance()->IsGameMode(GM_MENU) ? false : (*selected_index != i));
}
return list;
@@ -177,7 +177,7 @@ struct GameOptionsWindow : Window {
~GameOptionsWindow()
{
DeleteWindowById(WC_CUSTOM_CURRENCY, 0);
- if (this->reload) _switch_mode = SM_MENU;
+ if (this->reload) GameState::GetInstance()->SetSwitchMode(SM_MENU);
}
/**
@@ -188,13 +188,14 @@ struct GameOptionsWindow : Window {
*/
DropDownList *BuildDropDownList(int widget, int *selected_index) const
{
+ GameState *gs = GameState::GetInstance();
DropDownList *list = NULL;
switch (widget) {
case WID_GO_CURRENCY_DROPDOWN: { // Setup currencies dropdown
list = new DropDownList();
*selected_index = this->opt->locale.currency;
StringID *items = BuildCurrencyDropdown();
- uint64 disabled = _game_mode == GM_MENU ? 0LL : ~GetMaskOfAllowedCurrencies();
+ uint64 disabled = gs->IsGameMode(GM_MENU) ? 0LL : ~GetMaskOfAllowedCurrencies();
/* Add non-custom currencies; sorted naturally */
for (uint i = 0; i < CURRENCY_END; items++, i++) {
@@ -218,7 +219,7 @@ struct GameOptionsWindow : Window {
/* You can only change the drive side if you are in the menu or ingame with
* no vehicles present. In a networking game only the server can change it */
extern bool RoadVehiclesAreBuilt();
- if ((_game_mode != GM_MENU && RoadVehiclesAreBuilt()) || (_networking && !_network_server)) {
+ if ((!gs->IsGameMode(GM_MENU) && RoadVehiclesAreBuilt()) || (_networking && !_network_server)) {
disabled = ~(1 << this->opt->vehicle.road_side); // disable the other value
}
@@ -232,7 +233,7 @@ struct GameOptionsWindow : Window {
list = new DropDownList();
*selected_index = this->opt->game_creation.town_name;
- int enabled_item = (_game_mode == GM_MENU || Town::GetNumItems() == 0) ? -1 : *selected_index;
+ int enabled_item = (gs->IsGameMode(GM_MENU) || Town::GetNumItems() == 0) ? -1 : *selected_index;
/* Add and sort newgrf townnames generators */
for (int i = 0; i < _nb_grf_names; i++) {
@@ -471,7 +472,7 @@ struct GameOptionsWindow : Window {
template <class T>
void SetMediaSet(int index)
{
- if (_game_mode == GM_MENU) {
+ if (GameState::GetInstance()->IsGameMode(GM_MENU)) {
const char *name = T::GetSet(index)->name;
free(T::ini_set);
@@ -502,7 +503,7 @@ struct GameOptionsWindow : Window {
break;
case WID_GO_TOWNNAME_DROPDOWN: // Town names
- if (_game_mode == GM_MENU || Town::GetNumItems() == 0) {
+ if (GameState::GetInstance()->IsGameMode(GM_MENU) || Town::GetNumItems() == 0) {
this->opt->game_creation.town_name = index;
SetWindowDirty(WC_GAME_OPTIONS, WN_GAME_OPTIONS_GAME_OPTIONS);
}
@@ -1067,7 +1068,7 @@ bool SettingEntry::UpdateFilterState(SettingFilter &filter, bool force_visible)
static const void *ResolveVariableAddress(const GameSettings *settings_ptr, const SettingDesc *sd)
{
if ((sd->desc.flags & SGF_PER_COMPANY) != 0) {
- if (Company::IsValidID(_local_company) && _game_mode != GM_MENU) {
+ if (Company::IsValidID(_local_company) && !GameState::GetInstance()->IsGameMode(GM_MENU)) {
return GetVariableAddress(&Company::Get(_local_company)->settings, &sd->save);
} else {
return GetVariableAddress(&_settings_client.company, &sd->save);
@@ -1904,9 +1905,10 @@ struct GameSettingsWindow : Window {
break;
case WID_GS_TYPE_DROPDOWN:
+ GameState *gs = GameState::GetInstance();
switch (this->filter.type) {
- case ST_GAME: SetDParam(0, _game_mode == GM_MENU ? STR_CONFIG_SETTING_TYPE_DROPDOWN_GAME_MENU : STR_CONFIG_SETTING_TYPE_DROPDOWN_GAME_INGAME); break;
- case ST_COMPANY: SetDParam(0, _game_mode == GM_MENU ? STR_CONFIG_SETTING_TYPE_DROPDOWN_COMPANY_MENU : STR_CONFIG_SETTING_TYPE_DROPDOWN_COMPANY_INGAME); break;
+ case ST_GAME: SetDParam(0, gs->IsGameMode(GM_MENU) ? STR_CONFIG_SETTING_TYPE_DROPDOWN_GAME_MENU : STR_CONFIG_SETTING_TYPE_DROPDOWN_GAME_INGAME); break;
+ case ST_COMPANY: SetDParam(0, gs->IsGameMode(GM_MENU) ? STR_CONFIG_SETTING_TYPE_DROPDOWN_COMPANY_MENU : STR_CONFIG_SETTING_TYPE_DROPDOWN_COMPANY_INGAME); break;
case ST_CLIENT: SetDParam(0, STR_CONFIG_SETTING_TYPE_DROPDOWN_CLIENT); break;
default: SetDParam(0, STR_CONFIG_SETTING_TYPE_DROPDOWN_ALL); break;
}
@@ -1931,10 +1933,11 @@ struct GameSettingsWindow : Window {
break;
case WID_GS_TYPE_DROPDOWN:
+ GameState *gs = GameState::GetInstance();
list = new DropDownList();
*list->Append() = new DropDownListStringItem(STR_CONFIG_SETTING_TYPE_DROPDOWN_ALL, ST_ALL, false);
- *list->Append() = new DropDownListStringItem(_game_mode == GM_MENU ? STR_CONFIG_SETTING_TYPE_DROPDOWN_GAME_MENU : STR_CONFIG_SETTING_TYPE_DROPDOWN_GAME_INGAME, ST_GAME, false);
- *list->Append() = new DropDownListStringItem(_game_mode == GM_MENU ? STR_CONFIG_SETTING_TYPE_DROPDOWN_COMPANY_MENU : STR_CONFIG_SETTING_TYPE_DROPDOWN_COMPANY_INGAME, ST_COMPANY, false);
+ *list->Append() = new DropDownListStringItem(gs->IsGameMode(GM_MENU) ? STR_CONFIG_SETTING_TYPE_DROPDOWN_GAME_MENU : STR_CONFIG_SETTING_TYPE_DROPDOWN_GAME_INGAME, ST_GAME, false);
+ *list->Append() = new DropDownListStringItem(gs->IsGameMode(GM_MENU) ? STR_CONFIG_SETTING_TYPE_DROPDOWN_COMPANY_MENU : STR_CONFIG_SETTING_TYPE_DROPDOWN_COMPANY_INGAME, ST_COMPANY, false);
*list->Append() = new DropDownListStringItem(STR_CONFIG_SETTING_TYPE_DROPDOWN_CLIENT, ST_CLIENT, false);
break;
}
@@ -1956,12 +1959,13 @@ struct GameSettingsWindow : Window {
case WID_GS_HELP_TEXT:
if (this->last_clicked != NULL) {
const SettingDesc *sd = this->last_clicked->setting;
+ GameState *gs = GameState::GetInstance();
int y = r.top;
switch (sd->GetType()) {
- case ST_COMPANY: SetDParam(0, _game_mode == GM_MENU ? STR_CONFIG_SETTING_TYPE_COMPANY_MENU : STR_CONFIG_SETTING_TYPE_COMPANY_INGAME); break;
+ case ST_COMPANY: SetDParam(0, gs->IsGameMode(GM_MENU) ? STR_CONFIG_SETTING_TYPE_COMPANY_MENU : STR_CONFIG_SETTING_TYPE_COMPANY_INGAME); break;
case ST_CLIENT: SetDParam(0, STR_CONFIG_SETTING_TYPE_CLIENT); break;
- case ST_GAME: SetDParam(0, _game_mode == GM_MENU ? STR_CONFIG_SETTING_TYPE_GAME_MENU : STR_CONFIG_SETTING_TYPE_GAME_INGAME); break;
+ case ST_GAME: SetDParam(0, gs->IsGameMode(GM_MENU) ? STR_CONFIG_SETTING_TYPE_GAME_MENU : STR_CONFIG_SETTING_TYPE_GAME_INGAME); break;
default: NOT_REACHED();
}
DrawString(r.left, r.right, y, STR_CONFIG_SETTING_TYPE);
diff --git a/src/settings_type.h b/src/settings_type.h
index 2dc9ec9..a62c51f 100644
--- a/src/settings_type.h
+++ b/src/settings_type.h
@@ -21,6 +21,7 @@
#include "linkgraph/linkgraph_type.h"
#include "zoom_type.h"
#include "openttd.h"
+#include "game_state.h"
/** Settings profiles and highscore tables. */
@@ -584,7 +585,7 @@ extern VehicleDefaultSettings _old_vds;
*/
static inline GameSettings &GetGameSettings()
{
- return (_game_mode == GM_MENU) ? _settings_newgame : _settings_game;
+ return GameState::GetInstance()->IsGameMode(GM_MENU) ? _settings_newgame : _settings_game;
}
#endif /* SETTINGS_TYPE_H */
diff --git a/src/signs_cmd.cpp b/src/signs_cmd.cpp
index 4badd36..67acf0f 100644
--- a/src/signs_cmd.cpp
+++ b/src/signs_cmd.cpp
@@ -47,7 +47,7 @@ CommandCost CmdPlaceSign(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32
/* When we execute, really make the sign */
if (flags & DC_EXEC) {
- Sign *si = new Sign(_game_mode == GM_EDITOR ? OWNER_DEITY : _current_company);
+ Sign *si = new Sign(GameState::GetInstance()->IsGameMode(GM_EDITOR) ? OWNER_DEITY : _current_company);
int x = TileX(tile) * TILE_SIZE;
int y = TileY(tile) * TILE_SIZE;
@@ -80,7 +80,9 @@ CommandCost CmdRenameSign(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32
{
Sign *si = Sign::GetIfValid(p1);
if (si == NULL) return CMD_ERROR;
- if (si->owner == OWNER_DEITY && _current_company != OWNER_DEITY && _game_mode != GM_EDITOR) return CMD_ERROR;
+
+ GameState *gs = GameState::GetInstance();
+ if (si->owner == OWNER_DEITY && _current_company != OWNER_DEITY && !gs->IsGameMode(GM_EDITOR)) return CMD_ERROR;
/* Rename the signs when empty, otherwise remove it */
if (!StrEmpty(text)) {
@@ -91,7 +93,7 @@ CommandCost CmdRenameSign(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32
free(si->name);
/* Assign the new one */
si->name = stredup(text);
- if (_game_mode != GM_EDITOR) si->owner = _current_company;
+ if (!gs->IsGameMode(GM_EDITOR)) si->owner = _current_company;
si->UpdateVirtCoord();
InvalidateWindowData(WC_SIGN_LIST, 0, 1);
diff --git a/src/signs_gui.cpp b/src/signs_gui.cpp
index 15adef0..64a00d2 100644
--- a/src/signs_gui.cpp
+++ b/src/signs_gui.cpp
@@ -131,7 +131,7 @@ struct SignList {
void FilterSignList()
{
this->signs.Filter(&SignNameFilter, this->string_filter);
- if (_game_mode != GM_EDITOR) this->signs.Filter(&OwnerDeityFilter, this->string_filter);
+ if (!GameState::GetInstance()->IsGameMode(GM_EDITOR)) this->signs.Filter(&OwnerDeityFilter, this->string_filter);
if (!HasBit(_display_opt, DO_SHOW_COMPETITOR_SIGNS)) {
this->signs.Filter(&OwnerVisibilityFilter, this->string_filter);
}
@@ -346,7 +346,7 @@ struct SignListWindow : Window, SignList {
*/
static EventState SignListGlobalHotkeys(int hotkey)
{
- if (_game_mode == GM_MENU) return ES_NOT_HANDLED;
+ if (GameState::GetInstance()->IsGameMode(GM_MENU)) return ES_NOT_HANDLED;
Window *w = ShowSignList();
if (w == NULL) return ES_NOT_HANDLED;
return w->OnHotkey(hotkey);
@@ -554,7 +554,7 @@ static WindowDesc _query_sign_edit_desc(
*/
void HandleClickOnSign(const Sign *si)
{
- if (_ctrl_pressed && (si->owner == _local_company || (si->owner == OWNER_DEITY && _game_mode == GM_EDITOR))) {
+ if (_ctrl_pressed && (si->owner == _local_company || (si->owner == OWNER_DEITY && GameState::GetInstance()->IsGameMode(GM_EDITOR)))) {
RenameSign(si->index, NULL);
return;
}
diff --git a/src/station_cmd.cpp b/src/station_cmd.cpp
index 5fd865a..8cf1987 100644
--- a/src/station_cmd.cpp
+++ b/src/station_cmd.cpp
@@ -2879,12 +2879,13 @@ draw_default_foundation:
SpriteID image = t->ground.sprite;
PaletteID pal = t->ground.pal;
RailTrackOffset overlay_offset;
+ GameState *gs = GameState::GetInstance();
if (rti != NULL && rti->UsesOverlay() && SplitGroundSpriteForOverlay(ti, &image, &overlay_offset)) {
SpriteID ground = GetCustomRailSprite(rti, ti->tile, RTSG_GROUND);
DrawGroundSprite(image, PAL_NONE);
DrawGroundSprite(ground + overlay_offset, PAL_NONE);
- if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasStationReservation(ti->tile)) {
+ if (!gs->IsGameMode(GM_MENU) && _settings_client.gui.show_track_reservation && HasStationReservation(ti->tile)) {
SpriteID overlay = GetCustomRailSprite(rti, ti->tile, RTSG_OVERLAY);
DrawGroundSprite(overlay + overlay_offset, PALETTE_CRASH);
}
@@ -2894,7 +2895,7 @@ draw_default_foundation:
DrawGroundSprite(image, GroundSpritePaletteTransform(image, pal, palette));
/* PBS debugging, draw reserved tracks darker */
- if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasStationRail(ti->tile) && HasStationReservation(ti->tile)) {
+ if (!gs->IsGameMode(GM_MENU) && _settings_client.gui.show_track_reservation && HasStationRail(ti->tile) && HasStationReservation(ti->tile)) {
const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(ti->tile));
DrawGroundSprite(GetRailStationAxis(ti->tile) == AXIS_X ? rti->base_sprites.single_x : rti->base_sprites.single_y, PALETTE_CRASH);
}
@@ -3622,7 +3623,7 @@ static void StationHandleSmallTick(BaseStation *st)
void OnTick_Station()
{
- if (_game_mode == GM_EDITOR) return;
+ if (GameState::GetInstance()->IsGameMode(GM_EDITOR)) return;
BaseStation *st;
FOR_ALL_BASE_STATIONS(st) {
diff --git a/src/terraform_cmd.cpp b/src/terraform_cmd.cpp
index aad9822..04ff7cc 100644
--- a/src/terraform_cmd.cpp
+++ b/src/terraform_cmd.cpp
@@ -282,7 +282,7 @@ CommandCost CmdTerraformLand(TileIndex tile, DoCommandFlag flags, uint32 p1, uin
/* Check tiletype-specific things, and add extra-cost */
const bool curr_gen = _generating_world;
- if (_game_mode == GM_EDITOR) _generating_world = true; // used to create green terraformed land
+ if (GameState::GetInstance()->IsGameMode(GM_EDITOR)) _generating_world = true; // used to create green terraformed land
DoCommandFlag tile_flags = flags | DC_AUTO | DC_FORCE_CLEAR_TILE;
if (pass == 0) {
tile_flags &= ~DC_EXEC;
diff --git a/src/terraform_gui.cpp b/src/terraform_gui.cpp
index 97749a8..12bdd9c 100644
--- a/src/terraform_gui.cpp
+++ b/src/terraform_gui.cpp
@@ -54,7 +54,7 @@ void CcTerraform(const CommandCost &result, TileIndex tile, uint32 p1, uint32 p2
/** Scenario editor command that generates desert areas */
static void GenerateDesertArea(TileIndex end, TileIndex start)
{
- if (_game_mode != GM_EDITOR) return;
+ if (!GameState::GetInstance()->IsGameMode(GM_EDITOR)) return;
_generating_world = true;
@@ -71,7 +71,7 @@ static void GenerateDesertArea(TileIndex end, TileIndex start)
/** Scenario editor command that generates rocky areas */
static void GenerateRockyArea(TileIndex end, TileIndex start)
{
- if (_game_mode != GM_EDITOR) return;
+ if (!GameState::GetInstance()->IsGameMode(GM_EDITOR)) return;
bool success = false;
TileArea ta(start, end);
@@ -292,7 +292,7 @@ struct TerraformToolbarWindow : Window {
*/
static EventState TerraformToolbarGlobalHotkeys(int hotkey)
{
- if (_game_mode != GM_NORMAL) return ES_NOT_HANDLED;
+ if (!GameState::GetInstance()->IsGameMode(GM_NORMAL)) return ES_NOT_HANDLED;
Window *w = ShowTerraformToolbar(NULL);
if (w == NULL) return ES_NOT_HANDLED;
return w->OnHotkey(hotkey);
@@ -718,7 +718,7 @@ struct ScenarioEditorLandscapeGenerationWindow : Window {
*/
static EventState TerraformToolbarEditorGlobalHotkeys(int hotkey)
{
- if (_game_mode != GM_EDITOR) return ES_NOT_HANDLED;
+ if (!GameState::GetInstance()->IsGameMode(GM_EDITOR)) return ES_NOT_HANDLED;
Window *w = ShowEditorTerraformToolbar();
if (w == NULL) return ES_NOT_HANDLED;
return w->OnHotkey(hotkey);
diff --git a/src/texteff.cpp b/src/texteff.cpp
index cdb8b8c..dfd5884 100644
--- a/src/texteff.cpp
+++ b/src/texteff.cpp
@@ -41,7 +41,7 @@ static SmallVector<struct TextEffect, 32> _text_effects; ///< Text effects are s
/* Text Effects */
TextEffectID AddTextEffect(StringID msg, int center, int y, uint8 duration, TextEffectMode mode)
{
- if (_game_mode == GM_MENU) return INVALID_TE_ID;
+ if (GameState::GetInstance()->IsGameMode(GM_MENU)) return INVALID_TE_ID;
TextEffectID i;
for (i = 0; i < _text_effects.Length(); i++) {
diff --git a/src/toolbar_gui.cpp b/src/toolbar_gui.cpp
index f253be8..4456e7d 100644
--- a/src/toolbar_gui.cpp
+++ b/src/toolbar_gui.cpp
@@ -425,7 +425,7 @@ static CallBackFunction ToolbarScenSaveOrLoad(Window *w)
*/
static CallBackFunction MenuClickSaveLoad(int index = 0)
{
- if (_game_mode == GM_EDITOR) {
+ if (GameState::GetInstance()->IsGameMode(GM_EDITOR)) {
switch (index) {
case SLEME_SAVE_SCENARIO: ShowSaveLoadDialog(FT_SCENARIO, SLO_SAVE); break;
case SLEME_LOAD_SCENARIO: ShowSaveLoadDialog(FT_SCENARIO, SLO_LOAD); break;
@@ -847,7 +847,7 @@ static CallBackFunction MenuClickShowAir(int index)
static CallBackFunction ToolbarZoomInClick(Window *w)
{
if (DoZoomInOutWindow(ZOOM_IN, FindWindowById(WC_MAIN_WINDOW, 0))) {
- w->HandleButtonClick((_game_mode == GM_EDITOR) ? (byte)WID_TE_ZOOM_IN : (byte)WID_TN_ZOOM_IN);
+ w->HandleButtonClick(GameState::GetInstance()->IsGameMode(GM_EDITOR) ? (byte)WID_TE_ZOOM_IN : (byte)WID_TN_ZOOM_IN);
if (_settings_client.sound.click_beep) SndPlayFx(SND_15_BEEP);
}
return CBF_NONE;
@@ -858,7 +858,7 @@ static CallBackFunction ToolbarZoomInClick(Window *w)
static CallBackFunction ToolbarZoomOutClick(Window *w)
{
if (DoZoomInOutWindow(ZOOM_OUT, FindWindowById(WC_MAIN_WINDOW, 0))) {
- w->HandleButtonClick((_game_mode == GM_EDITOR) ? (byte)WID_TE_ZOOM_OUT : (byte)WID_TN_ZOOM_OUT);
+ w->HandleButtonClick(GameState::GetInstance()->IsGameMode(GM_EDITOR) ? (byte)WID_TE_ZOOM_OUT : (byte)WID_TN_ZOOM_OUT);
if (_settings_client.sound.click_beep) SndPlayFx(SND_15_BEEP);
}
return CBF_NONE;
@@ -2013,7 +2013,7 @@ struct MainToolbarWindow : Window {
virtual void OnClick(Point pt, int widget, int click_count)
{
- if (_game_mode != GM_MENU && !this->IsWidgetDisabled(widget)) _toolbar_button_procs[widget](this);
+ if (!GameState::GetInstance()->IsGameMode(GM_MENU) && !this->IsWidgetDisabled(widget)) _toolbar_button_procs[widget](this);
}
virtual void OnDropdownSelect(int widget, int index)
@@ -2369,7 +2369,7 @@ struct ScenarioEditorToolbarWindow : Window {
virtual void OnClick(Point pt, int widget, int click_count)
{
- if (_game_mode == GM_MENU) return;
+ if (GameState::GetInstance()->IsGameMode(GM_MENU)) return;
CallBackFunction cbf = _scen_toolbar_button_procs[widget](this);
if (cbf != CBF_NONE) _last_started_action = cbf;
}
@@ -2571,7 +2571,7 @@ void AllocateToolbar()
/* Clean old GUI values; railtype is (re)set by rail_gui.cpp */
_last_built_roadtype = ROADTYPE_ROAD;
- if (_game_mode == GM_EDITOR) {
+ if (GameState::GetInstance()->IsGameMode(GM_EDITOR)) {
new ScenarioEditorToolbarWindow(&_toolb_scen_desc);
} else {
new MainToolbarWindow(&_toolb_normal_desc);
diff --git a/src/town_cmd.cpp b/src/town_cmd.cpp
index daaad7e..5f5425f 100644
--- a/src/town_cmd.cpp
+++ b/src/town_cmd.cpp
@@ -794,7 +794,7 @@ static void TownTickHandler(Town *t)
void OnTick_Town()
{
- if (_game_mode == GM_EDITOR) return;
+ if (GameState::GetInstance()->IsGameMode(GM_EDITOR)) return;
Town *t;
FOR_ALL_TOWNS(t) {
@@ -1407,7 +1407,7 @@ static bool GrowTownAtRoad(Town *t, TileIndex tile)
/* Don't allow building over roads of other cities */
if (IsRoadOwner(tile, ROADTYPE_ROAD, OWNER_TOWN) && Town::GetByTile(tile) != t) {
return false;
- } else if (IsRoadOwner(tile, ROADTYPE_ROAD, OWNER_NONE) && _game_mode == GM_EDITOR) {
+ } else if (IsRoadOwner(tile, ROADTYPE_ROAD, OWNER_NONE) && GameState::GetInstance()->IsGameMode(GM_EDITOR)) {
/* If we are in the SE, and this road-piece has no town owner yet, it just found an
* owner :) (happy happy happy road now) */
SetRoadOwner(tile, ROADTYPE_ROAD, OWNER_TOWN);
@@ -1611,7 +1611,7 @@ static void DoCreateTown(Town *t, TileIndex tile, uint32 townnameparts, TownSize
int x = (int)size * 16 + 3;
if (size == TSZ_RANDOM) x = (Random() & 0xF) + 8;
/* Don't create huge cities when founding town in-game */
- if (city && (!manual || _game_mode == GM_EDITOR)) x *= _settings_game.economy.initial_city_size;
+ if (city && (!manual || GameState::GetInstance()->IsGameMode(GM_EDITOR))) x *= _settings_game.economy.initial_city_size;
t->cache.num_houses += x;
UpdateTownRadius(t);
@@ -1693,7 +1693,7 @@ CommandCost CmdFoundTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32
if (layout >= NUM_TLS) return CMD_ERROR;
/* Some things are allowed only in the scenario editor and for game scripts. */
- if (_game_mode != GM_EDITOR && _current_company != OWNER_DEITY) {
+ if (!GameState::GetInstance()->IsGameMode(GM_EDITOR) && _current_company != OWNER_DEITY) {
if (_settings_game.economy.found_town == TF_FORBIDDEN) return CMD_ERROR;
if (size == TSZ_LARGE) return CMD_ERROR;
if (random) return CMD_ERROR;
@@ -1760,7 +1760,7 @@ CommandCost CmdFoundTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32
t->UpdateVirtCoord();
}
- if (_game_mode != GM_EDITOR) {
+ if (!GameState::GetInstance()->IsGameMode(GM_EDITOR)) {
/* 't' can't be NULL since 'random' is false outside scenedit */
assert(!random);
char company_name[MAX_LENGTH_COMPANY_NAME_CHARS * MAX_CHAR_LENGTH];
@@ -1895,7 +1895,7 @@ static TileIndex FindNearestGoodCoastalTownSpot(TileIndex tile, TownLayout layou
static Town *CreateRandomTown(uint attempts, uint32 townnameparts, TownSize size, bool city, TownLayout layout)
{
- assert(_game_mode == GM_EDITOR || _generating_world); // These are the preconditions for CMD_DELETE_TOWN
+ assert(GameState::GetInstance()->IsGameMode(GM_EDITOR) || _generating_world); // These are the preconditions for CMD_DELETE_TOWN
if (!Town::CanAllocateItem()) return NULL;
@@ -1949,7 +1949,7 @@ static const byte _num_initial_towns[4] = {5, 11, 23, 46}; // very low, low, no
bool GenerateTowns(TownLayout layout)
{
uint current_number = 0;
- uint difficulty = (_game_mode != GM_EDITOR) ? _settings_game.difficulty.number_towns : 0;
+ uint difficulty = (!GameState::GetInstance()->IsGameMode(GM_EDITOR)) ? _settings_game.difficulty.number_towns : 0;
uint total = (difficulty == (uint)CUSTOM_TOWN_NUMBER_DIFFICULTY) ? _settings_game.game_creation.custom_town_number : ScaleByMapSize(_num_initial_towns[difficulty] + (Random() & 7));
total = min(TownPool::MAX_SIZE, total);
uint32 townnameparts;
@@ -1981,7 +1981,7 @@ bool GenerateTowns(TownLayout layout)
}
/* If there are no towns at all and we are generating new game, bail out */
- if (Town::GetNumItems() == 0 && _game_mode != GM_EDITOR) {
+ if (Town::GetNumItems() == 0 && !GameState::GetInstance()->IsGameMode(GM_EDITOR)) {
ShowErrorMessage(STR_ERROR_COULD_NOT_CREATE_TOWN, INVALID_STRING_ID, WL_CRITICAL);
}
@@ -2319,7 +2319,7 @@ static bool BuildTownHouse(Town *t, TileIndex tile)
const HouseSpec *hs = HouseSpec::Get(house);
if (_loaded_newgrf_features.has_newhouses && !_generating_world &&
- _game_mode != GM_EDITOR && (hs->extra_flags & BUILDING_IS_HISTORICAL) != 0) {
+ !GameState::GetInstance()->IsGameMode(GM_EDITOR) && (hs->extra_flags & BUILDING_IS_HISTORICAL) != 0) {
continue;
}
@@ -2366,7 +2366,7 @@ static bool BuildTownHouse(Town *t, TileIndex tile)
byte construction_counter = 0;
byte construction_stage = 0;
- if (_generating_world || _game_mode == GM_EDITOR) {
+ if (_generating_world || GameState::GetInstance()->IsGameMode(GM_EDITOR)) {
uint32 r = Random();
construction_stage = TOWN_HOUSE_COMPLETED;
@@ -2628,7 +2628,7 @@ CommandCost CmdTownGrowthRate(TileIndex tile, DoCommandFlag flags, uint32 p1, ui
*/
CommandCost CmdExpandTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
- if (_game_mode != GM_EDITOR && _current_company != OWNER_DEITY) return CMD_ERROR;
+ if (!GameState::GetInstance()->IsGameMode(GM_EDITOR) && _current_company != OWNER_DEITY) return CMD_ERROR;
Town *t = Town::GetIfValid(p1);
if (t == NULL) return CMD_ERROR;
@@ -2668,7 +2668,7 @@ CommandCost CmdExpandTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32
*/
CommandCost CmdDeleteTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
- if (_game_mode != GM_EDITOR && !_generating_world) return CMD_ERROR;
+ if (!GameState::GetInstance()->IsGameMode(GM_EDITOR) && !_generating_world) return CMD_ERROR;
Town *t = Town::GetIfValid(p1);
if (t == NULL) return CMD_ERROR;
diff --git a/src/town_gui.cpp b/src/town_gui.cpp
index 696b71a..b002840 100644
--- a/src/town_gui.cpp
+++ b/src/town_gui.cpp
@@ -596,7 +596,7 @@ static WindowDesc _town_editor_view_desc(
void ShowTownViewWindow(TownID town)
{
- if (_game_mode == GM_EDITOR) {
+ if (GameState::GetInstance()->IsGameMode(GM_EDITOR)) {
AllocateWindowDescFront<TownViewWindow>(&_town_editor_view_desc, town);
} else {
AllocateWindowDescFront<TownViewWindow>(&_town_game_view_desc, town);
@@ -772,7 +772,7 @@ public:
assert(t->xy != INVALID_TILE);
/* Draw rating icon. */
- if (_game_mode == GM_EDITOR || !HasBit(t->have_ratings, _local_company)) {
+ if (GameState::GetInstance()->IsGameMode(GM_EDITOR) || !HasBit(t->have_ratings, _local_company)) {
DrawSprite(SPR_TOWN_RATING_NA, PAL_NONE, icon_x, y + (this->resize.step_height - icon_size.height) / 2);
} else {
SpriteID icon = SPR_TOWN_RATING_APALLING;
@@ -1078,7 +1078,7 @@ public:
void UpdateButtons(bool check_availability)
{
- if (check_availability && _game_mode != GM_EDITOR) {
+ if (check_availability && !GameState::GetInstance()->IsGameMode(GM_EDITOR)) {
this->SetWidgetsDisabledState(true, WID_TF_RANDOM_TOWN, WID_TF_MANY_RANDOM_TOWNS, WID_TF_SIZE_LARGE, WIDGET_LIST_END);
this->SetWidgetsDisabledState(_settings_game.economy.found_town != TF_CUSTOM_LAYOUT,
WID_TF_LAYOUT_ORIGINAL, WID_TF_LAYOUT_BETTER, WID_TF_LAYOUT_GRID2, WID_TF_LAYOUT_GRID3, WID_TF_LAYOUT_RANDOM, WIDGET_LIST_END);
@@ -1195,6 +1195,6 @@ static WindowDesc _found_town_desc(
void ShowFoundTownWindow()
{
- if (_game_mode != GM_EDITOR && !Company::IsValidID(_local_company)) return;
+ if (!GameState::GetInstance()->IsGameMode(GM_EDITOR) && !Company::IsValidID(_local_company)) return;
AllocateWindowDescFront<FoundTownWindow>(&_found_town_desc, 0);
}
diff --git a/src/transparency.h b/src/transparency.h
index ab6f9a6..c3c5602 100644
--- a/src/transparency.h
+++ b/src/transparency.h
@@ -14,6 +14,7 @@
#include "gfx_func.h"
#include "openttd.h"
+#include "game_state.h"
#include "core/bitmath_func.hpp"
/**
@@ -49,7 +50,7 @@ extern byte _display_opt;
*/
static inline bool IsTransparencySet(TransparencyOption to)
{
- return (HasBit(_transparency_opt, to) && _game_mode != GM_MENU);
+ return (HasBit(_transparency_opt, to) && !GameState::GetInstance()->IsGameMode(GM_MENU));
}
/**
@@ -60,7 +61,7 @@ static inline bool IsTransparencySet(TransparencyOption to)
*/
static inline bool IsInvisibilitySet(TransparencyOption to)
{
- return (HasBit(_transparency_opt & _invisibility_opt, to) && _game_mode != GM_MENU);
+ return (HasBit(_transparency_opt & _invisibility_opt, to) && !GameState::GetInstance()->IsGameMode(GM_MENU));
}
/**
diff --git a/src/tree_cmd.cpp b/src/tree_cmd.cpp
index 7240cf8..4ca5dd4 100644
--- a/src/tree_cmd.cpp
+++ b/src/tree_cmd.cpp
@@ -246,9 +246,10 @@ static void PlaceTreeAtSameHeight(TileIndex tile, int height)
void PlaceTreesRandomly()
{
int i, j, ht;
+ GameState *gs = GameState::GetInstance();
i = ScaleByMapSize(DEFAULT_TREE_STEPS);
- if (_game_mode == GM_EDITOR) i /= EDITOR_TREE_DIV;
+ if (gs->IsGameMode(GM_EDITOR)) i /= EDITOR_TREE_DIV;
do {
uint32 r = Random();
TileIndex tile = RandomTileSeed(r);
@@ -276,7 +277,7 @@ void PlaceTreesRandomly()
/* place extra trees at rainforest area */
if (_settings_game.game_creation.landscape == LT_TROPIC) {
i = ScaleByMapSize(DEFAULT_RAINFOREST_TREE_STEPS);
- if (_game_mode == GM_EDITOR) i /= EDITOR_TREE_DIV;
+ if (gs->IsGameMode(GM_EDITOR)) i /= EDITOR_TREE_DIV;
do {
uint32 r = Random();
@@ -342,7 +343,8 @@ CommandCost CmdPlantTree(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32
/* Check the tree type within the current climate */
if (tree_to_plant != TREE_INVALID && !IsInsideBS(tree_to_plant, _tree_base_by_landscape[_settings_game.game_creation.landscape], _tree_count_by_landscape[_settings_game.game_creation.landscape])) return CMD_ERROR;
- Company *c = (_game_mode != GM_EDITOR) ? Company::GetIfValid(_current_company) : NULL;
+ GameState *gs = GameState::GetInstance();
+ Company *c = (!gs->IsGameMode(GM_EDITOR)) ? Company::GetIfValid(_current_company) : NULL;
int limit = (c == NULL ? INT32_MAX : GB(c->tree_limit, 16, 16));
TileArea ta(tile, p2);
@@ -350,7 +352,7 @@ CommandCost CmdPlantTree(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32
switch (GetTileType(tile)) {
case MP_TREES:
/* no more space for trees? */
- if (_game_mode != GM_EDITOR && GetTreeCount(tile) == 4) {
+ if (!gs->IsGameMode(GM_EDITOR) && GetTreeCount(tile) == 4) {
msg = STR_ERROR_TREE_ALREADY_HERE;
continue;
}
@@ -389,7 +391,7 @@ CommandCost CmdPlantTree(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32
/* No cacti outside the desert */
(treetype == TREE_CACTUS && GetTropicZone(tile) != TROPICZONE_DESERT) ||
/* No rain forest trees outside the rain forest, except in the editor mode where it makes those tiles rain forest tile */
- (IsInsideMM(treetype, TREE_RAINFOREST, TREE_CACTUS) && GetTropicZone(tile) != TROPICZONE_RAINFOREST && _game_mode != GM_EDITOR) ||
+ (IsInsideMM(treetype, TREE_RAINFOREST, TREE_CACTUS) && GetTropicZone(tile) != TROPICZONE_RAINFOREST && !gs->IsGameMode(GM_EDITOR)) ||
/* And no subtropical trees in the desert/rain forest */
(IsInsideMM(treetype, TREE_SUB_TROPICAL, TREE_TOYLAND) && GetTropicZone(tile) != TROPICZONE_NORMAL))) {
msg = STR_ERROR_TREE_WRONG_TERRAIN_FOR_TREE_TYPE;
@@ -417,7 +419,7 @@ CommandCost CmdPlantTree(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32
}
}
- if (_game_mode != GM_EDITOR && Company::IsValidID(_current_company)) {
+ if (!gs->IsGameMode(GM_EDITOR) && Company::IsValidID(_current_company)) {
Town *t = ClosestTownFromTile(tile, _settings_game.economy.dist_local_authority);
if (t != NULL) ChangeTownRating(t, RATING_TREE_UP_STEP, RATING_TREE_MAXIMUM, flags);
}
@@ -429,12 +431,12 @@ CommandCost CmdPlantTree(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32
}
/* Plant full grown trees in scenario editor */
- PlantTreesOnTile(tile, treetype, 0, _game_mode == GM_EDITOR ? 3 : 0);
+ PlantTreesOnTile(tile, treetype, 0, gs->IsGameMode(GM_EDITOR) ? 3 : 0);
MarkTileDirtyByTile(tile);
if (c != NULL) c->tree_limit -= 1 << 16;
/* When planting rainforest-trees, set tropiczone to rainforest in editor. */
- if (_game_mode == GM_EDITOR && IsInsideMM(treetype, TREE_RAINFOREST, TREE_CACTUS)) {
+ if (gs->IsGameMode(GM_EDITOR) && IsInsideMM(treetype, TREE_RAINFOREST, TREE_CACTUS)) {
SetTropicZone(tile, TROPICZONE_RAINFOREST);
}
}
diff --git a/src/tree_gui.cpp b/src/tree_gui.cpp
index f21eeae..633887d 100644
--- a/src/tree_gui.cpp
+++ b/src/tree_gui.cpp
@@ -96,7 +96,7 @@ public:
if (widget != WID_BT_MANY_RANDOM) return;
- if (_game_mode != GM_EDITOR) {
+ if (!GameState::GetInstance()->IsGameMode(GM_EDITOR)) {
size->width = 0;
size->height = 0;
}
@@ -244,6 +244,6 @@ static WindowDesc _build_trees_desc(
void ShowBuildTreesToolbar()
{
- if (_game_mode != GM_EDITOR && !Company::IsValidID(_local_company)) return;
+ if (!GameState::GetInstance()->IsGameMode(GM_EDITOR) && !Company::IsValidID(_local_company)) return;
AllocateWindowDescFront<BuildTreesWindow>(&_build_trees_desc, 0);
}
diff --git a/src/tunnelbridge_cmd.cpp b/src/tunnelbridge_cmd.cpp
index 9ba9b26..2fbc600 100644
--- a/src/tunnelbridge_cmd.cpp
+++ b/src/tunnelbridge_cmd.cpp
@@ -338,7 +338,7 @@ CommandCost CmdBuildBridge(TileIndex end_tile, DoCommandFlag flags, uint32 p1, u
/* Do not replace town bridges with lower speed bridges, unless in scenario editor. */
if (!(flags & DC_QUERY_COST) && IsTileOwner(tile_start, OWNER_TOWN) &&
GetBridgeSpec(bridge_type)->speed < GetBridgeSpec(GetBridgeType(tile_start))->speed &&
- _game_mode != GM_EDITOR) {
+ !GameState::GetInstance()->IsGameMode(GM_EDITOR)) {
Town *t = ClosestTownFromTile(tile_start, UINT_MAX);
if (t == NULL) {
@@ -749,7 +749,7 @@ CommandCost CmdBuildTunnel(TileIndex start_tile, DoCommandFlag flags, uint32 p1,
static inline CommandCost CheckAllowRemoveTunnelBridge(TileIndex tile)
{
/* Floods can remove anything as well as the scenario editor */
- if (_current_company == OWNER_WATER || _game_mode == GM_EDITOR) return CommandCost();
+ if (_current_company == OWNER_WATER || GameState::GetInstance()->IsGameMode(GM_EDITOR)) return CommandCost();
switch (GetTunnelBridgeTransportType(tile)) {
case TRANSPORT_ROAD: {
@@ -805,8 +805,9 @@ static CommandCost DoClearTunnel(TileIndex tile, DoCommandFlag flags)
_build_tunnel_endtile = endtile;
+ GameState *gs = GameState::GetInstance();
Town *t = NULL;
- if (IsTileOwner(tile, OWNER_TOWN) && _game_mode != GM_EDITOR) {
+ if (IsTileOwner(tile, OWNER_TOWN) && !gs->IsGameMode(GM_EDITOR)) {
t = ClosestTownFromTile(tile, UINT_MAX); // town penalty rating
/* Check if you are allowed to remove the tunnel owned by a town
@@ -817,7 +818,7 @@ static CommandCost DoClearTunnel(TileIndex tile, DoCommandFlag flags)
/* checks if the owner is town then decrease town rating by RATING_TUNNEL_BRIDGE_DOWN_STEP until
* you have a "Poor" (0) town rating */
- if (IsTileOwner(tile, OWNER_TOWN) && _game_mode != GM_EDITOR) {
+ if (IsTileOwner(tile, OWNER_TOWN) && !gs->IsGameMode(GM_EDITOR)) {
ChangeTownRating(t, RATING_TUNNEL_BRIDGE_DOWN_STEP, RATING_TUNNEL_BRIDGE_MINIMUM, flags);
}
@@ -889,9 +890,10 @@ static CommandCost DoClearBridge(TileIndex tile, DoCommandFlag flags)
DiagDirection direction = GetTunnelBridgeDirection(tile);
TileIndexDiff delta = TileOffsByDiagDir(direction);
+ GameState *gs = GameState::GetInstance();
Town *t = NULL;
- if (IsTileOwner(tile, OWNER_TOWN) && _game_mode != GM_EDITOR) {
+ if (IsTileOwner(tile, OWNER_TOWN) && !gs->IsGameMode(GM_EDITOR)) {
t = ClosestTownFromTile(tile, UINT_MAX); // town penalty rating
/* Check if you are allowed to remove the bridge owned by a town
@@ -902,7 +904,7 @@ static CommandCost DoClearBridge(TileIndex tile, DoCommandFlag flags)
/* checks if the owner is town then decrease town rating by RATING_TUNNEL_BRIDGE_DOWN_STEP until
* you have a "Poor" (0) town rating */
- if (IsTileOwner(tile, OWNER_TOWN) && _game_mode != GM_EDITOR) {
+ if (IsTileOwner(tile, OWNER_TOWN) && !gs->IsGameMode(GM_EDITOR)) {
ChangeTownRating(t, RATING_TUNNEL_BRIDGE_DOWN_STEP, RATING_TUNNEL_BRIDGE_MINIMUM, flags);
}
@@ -1142,6 +1144,7 @@ static void DrawTile_TunnelBridge(TileInfo *ti)
{
TransportType transport_type = GetTunnelBridgeTransportType(ti->tile);
DiagDirection tunnelbridge_direction = GetTunnelBridgeDirection(ti->tile);
+ GameState *gs = GameState::GetInstance();
if (IsTunnel(ti->tile)) {
/* Front view of tunnel bounding boxes:
@@ -1207,7 +1210,7 @@ static void DrawTile_TunnelBridge(TileInfo *ti)
}
/* PBS debugging, draw reserved tracks darker */
- if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasTunnelBridgeReservation(ti->tile)) {
+ if (!gs->IsGameMode(GM_MENU) && _settings_client.gui.show_track_reservation && HasTunnelBridgeReservation(ti->tile)) {
if (rti->UsesOverlay()) {
SpriteID overlay = GetCustomRailSprite(rti, ti->tile, RTSG_OVERLAY);
DrawGroundSprite(overlay + RTO_X + DiagDirToAxis(tunnelbridge_direction), PALETTE_CRASH);
@@ -1323,7 +1326,7 @@ static void DrawTile_TunnelBridge(TileInfo *ti)
}
/* PBS debugging, draw reserved tracks darker */
- if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasTunnelBridgeReservation(ti->tile)) {
+ if (!gs->IsGameMode(GM_MENU) && _settings_client.gui.show_track_reservation && HasTunnelBridgeReservation(ti->tile)) {
if (rti->UsesOverlay()) {
SpriteID overlay = GetCustomRailSprite(rti, ti->tile, RTSG_OVERLAY);
if (HasBridgeFlatRamp(ti->tileh, DiagDirToAxis(tunnelbridge_direction))) {
@@ -1480,7 +1483,7 @@ void DrawBridgeMiddle(const TileInfo *ti)
}
}
- if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && !IsInvisibilitySet(TO_BRIDGES) && HasTunnelBridgeReservation(rampnorth)) {
+ if (!GameState::GetInstance()->IsGameMode(GM_MENU) && _settings_client.gui.show_track_reservation && !IsInvisibilitySet(TO_BRIDGES) && HasTunnelBridgeReservation(rampnorth)) {
if (rti->UsesOverlay()) {
SpriteID overlay = GetCustomRailSprite(rti, ti->tile, RTSG_OVERLAY);
AddSortableSpriteToDraw(overlay + RTO_X + axis, PALETTE_CRASH, ti->x, ti->y, 16, 16, 0, bridge_z, IsTransparencySet(TO_BRIDGES));
diff --git a/src/vehicle.cpp b/src/vehicle.cpp
index dff9feb..fb0070f 100644
--- a/src/vehicle.cpp
+++ b/src/vehicle.cpp
@@ -888,7 +888,7 @@ void VehicleEnteredDepotThisTick(Vehicle *v)
*/
static void RunVehicleDayProc()
{
- if (_game_mode != GM_NORMAL) return;
+ if (!GameState::GetInstance()->IsGameMode(GM_NORMAL)) return;
/* Run the day_proc for every DAY_TICKS vehicle starting at _date_fract. */
for (size_t i = _date_fract; i < Vehicle::GetPoolSize(); i += DAY_TICKS) {
@@ -1196,7 +1196,7 @@ void CheckVehicleBreakdown(Vehicle *v)
if (v->breakdown_ctr != 0 || (v->vehstatus & VS_STOPPED) ||
_settings_game.difficulty.vehicle_breakdowns < 1 ||
- v->cur_speed < 5 || _game_mode == GM_MENU) {
+ v->cur_speed < 5 || GameState::GetInstance()->IsGameMode(GM_MENU)) {
return;
}
diff --git a/src/video/dedicated_v.cpp b/src/video/dedicated_v.cpp
index 5e2be48..1c2d10a 100644
--- a/src/video/dedicated_v.cpp
+++ b/src/video/dedicated_v.cpp
@@ -14,6 +14,7 @@
#ifdef ENABLE_NETWORK
#include "../gfx_func.h"
+#include "../game_state.h"
#include "../network/network.h"
#include "../network/network_internal.h"
#include "../console_func.h"
@@ -71,8 +72,10 @@ static void OS2_SwitchToConsoleMode()
/* Signal handlers */
static void DedicatedSignalHandler(int sig)
{
- if (_game_mode == GM_NORMAL && _settings_client.gui.autosave_on_exit) DoExitSave();
- _exit_game = true;
+ GameState *gs = GameState::GetInstance();
+
+ if (gs->IsGameState(GM_NORMAL) && _settings_client.gui.autosave_on_exit) DoExitSave();
+ gs->ExitGame(true);
signal(sig, DedicatedSignalHandler);
}
#endif
@@ -240,7 +243,7 @@ static void DedicatedHandleKeyInput()
if (!InputWaiting()) return;
- if (_exit_game) return;
+ if (GameState::GetInstance()->ExitGame()) return;
#if defined(UNIX) || defined(__OS2__) || defined(PSP)
if (fgets(input_line, lengthof(input_line), stdin) == NULL) return;
@@ -280,13 +283,15 @@ void VideoDriver_Dedicated::MainLoop()
_network_dedicated = true;
_current_company = _local_company = COMPANY_SPECTATOR;
+ GameState *gs = GameState::GetInstance();
+
/* If SwitchMode is SM_LOAD_GAME, it means that the user used the '-g' options */
- if (_switch_mode != SM_LOAD_GAME) {
+ if (!gs->IsSwitchMode(SM_LOAD_GAME)) {
StartNewGameWithoutGUI(GENERATE_NEW_SEED);
- SwitchToMode(_switch_mode);
- _switch_mode = SM_NONE;
+ gs->SwitchToMode(gs->GetSwitchMode());
+ gs->SetSwitchMode(SM_NONE);
} else {
- _switch_mode = SM_NONE;
+ gs->SetSwitchMode(SM_NONE);
/* First we need to test if the savegame can be loaded, else we will end up playing the
* intro game... */
if (!SafeLoad(_file_to_saveload.name, _file_to_saveload.file_op, _file_to_saveload.detail_ftype, GM_NORMAL, BASE_DIR)) {
@@ -295,7 +300,7 @@ void VideoDriver_Dedicated::MainLoop()
_networking = false;
} else {
/* We can load this game, so go ahead */
- SwitchToMode(SM_LOAD_GAME);
+ gs->SwitchToMode(SM_LOAD_GAME);
}
}
@@ -306,7 +311,7 @@ void VideoDriver_Dedicated::MainLoop()
return;
}
- while (!_exit_game) {
+ while (!gs->ExitGame()) {
uint32 prev_cur_ticks = cur_ticks; // to check for wrapping
InteractiveRandom(); // randomness
diff --git a/src/video/sdl_v.cpp b/src/video/sdl_v.cpp
index 3668f86..0312e82 100644
--- a/src/video/sdl_v.cpp
+++ b/src/video/sdl_v.cpp
@@ -23,6 +23,7 @@
#include "../core/random_func.hpp"
#include "../core/math_func.hpp"
#include "../fileio_func.h"
+#include "../game_state.h"
#include "sdl_v.h"
#include <SDL.h>
@@ -695,7 +696,7 @@ void VideoDriver_SDL::MainLoop()
InteractiveRandom(); // randomness
while (PollEvent() == -1) {}
- if (_exit_game) break;
+ if (GameState::GetInstance()->ExitGame()) break;
mod = SDL_CALL SDL_GetModState();
#if SDL_VERSION_ATLEAST(1, 3, 0)
@@ -715,7 +716,7 @@ void VideoDriver_SDL::MainLoop()
#endif /* SDL_VERSION_ATLEAST(1, 3, 0) */
#endif /* defined(_DEBUG) */
{
- if (!_networking && _game_mode != GM_MENU) _fast_forward |= 2;
+ if (!_networking && !GameState::GetInstance()->IsGameMode(GM_MENU)) _fast_forward |= 2;
} else if (_fast_forward & 2) {
_fast_forward = 0;
}
diff --git a/src/video/win32_v.cpp b/src/video/win32_v.cpp
index 4a9861b..4128592 100644
--- a/src/video/win32_v.cpp
+++ b/src/video/win32_v.cpp
@@ -11,6 +11,7 @@
#include "../stdafx.h"
#include "../openttd.h"
+#include "../game_state.h"
#include "../gfx_func.h"
#include "../os/windows/win32.h"
#include "../rev.h"
@@ -980,7 +981,7 @@ static LRESULT CALLBACK WndProcGdi(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lP
#if !defined(WINCE)
case WM_ACTIVATE: {
/* Don't do anything if we are closing openttd */
- if (_exit_game) break;
+ if (GameState::GetInstance()->ExitGame()) break;
bool active = (LOWORD(wParam) != WA_INACTIVE);
bool minimized = (HIWORD(wParam) != 0);
@@ -1218,6 +1219,7 @@ void VideoDriver_Win32::MainLoop()
_wnd.running = true;
+ GameState *gs = GameState::GetInstance();
CheckPaletteAnim();
for (;;) {
uint32 prev_cur_ticks = cur_ticks; // to check for wrapping
@@ -1228,7 +1230,7 @@ void VideoDriver_Win32::MainLoop()
if (EditBoxInGlobalFocus()) TranslateMessage(&mesg);
DispatchMessage(&mesg);
}
- if (_exit_game) return;
+ if (gs->ExitGame()) return;
#if defined(_DEBUG)
if (_wnd.has_focus && GetAsyncKeyState(VK_SHIFT) < 0 &&
@@ -1236,7 +1238,7 @@ void VideoDriver_Win32::MainLoop()
/* Speed up using TAB, but disable for ALT+TAB of course */
if (_wnd.has_focus && GetAsyncKeyState(VK_TAB) < 0 && GetAsyncKeyState(VK_MENU) >= 0 &&
#endif
- !_networking && _game_mode != GM_MENU) {
+ !_networking && !gs->IsGameMode(GM_MENU)) {
_fast_forward |= 2;
} else if (_fast_forward & 2) {
_fast_forward = 0;
diff --git a/src/viewport.cpp b/src/viewport.cpp
index df431ff..c17c0f8 100644
--- a/src/viewport.cpp
+++ b/src/viewport.cpp
@@ -1250,7 +1250,7 @@ void ViewportAddString(const DrawPixelInfo *dpi, ZoomLevel small_from, const Vie
static void ViewportAddTownNames(DrawPixelInfo *dpi)
{
- if (!HasBit(_display_opt, DO_SHOW_TOWN_NAMES) || _game_mode == GM_MENU) return;
+ if (!HasBit(_display_opt, DO_SHOW_TOWN_NAMES) || GameState::GetInstance()->IsGameMode(GM_MENU)) return;
const Town *t;
FOR_ALL_TOWNS(t) {
@@ -1264,7 +1264,7 @@ static void ViewportAddTownNames(DrawPixelInfo *dpi)
static void ViewportAddStationNames(DrawPixelInfo *dpi)
{
- if (!(HasBit(_display_opt, DO_SHOW_STATION_NAMES) || HasBit(_display_opt, DO_SHOW_WAYPOINT_NAMES)) || _game_mode == GM_MENU) return;
+ if (!(HasBit(_display_opt, DO_SHOW_STATION_NAMES) || HasBit(_display_opt, DO_SHOW_WAYPOINT_NAMES)) || GameState::GetInstance()->IsGameMode(GM_MENU)) return;
const BaseStation *st;
FOR_ALL_BASE_STATIONS(st) {
@@ -2125,7 +2125,7 @@ static bool CheckClickOnSign(const ViewPort *vp, int x, int y)
FOR_ALL_SIGNS(si) {
/* If competitor signs are hidden, don't check signs that aren't owned by local company */
if (!HasBit(_display_opt, DO_SHOW_COMPETITOR_SIGNS) && _local_company != si->owner && si->owner != OWNER_DEITY) continue;
- if (si->owner == OWNER_DEITY && _game_mode != GM_EDITOR) continue;
+ if (si->owner == OWNER_DEITY && !GameState::GetInstance()->IsGameMode(GM_EDITOR)) continue;
if (CheckClickOnViewportSign(vp, x, y, &si->sign)) {
HandleClickOnSign(si);
diff --git a/src/water_cmd.cpp b/src/water_cmd.cpp
index edce4cd..f52619c 100644
--- a/src/water_cmd.cpp
+++ b/src/water_cmd.cpp
@@ -396,13 +396,15 @@ CommandCost CmdBuildCanal(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32
WaterClass wc = Extract<WaterClass, 0, 2>(p2);
if (p1 >= MapSize() || wc == WATER_CLASS_INVALID) return CMD_ERROR;
+ GameState *gs = GameState::GetInstance();
+
/* Outside of the editor you can only build canals, not oceans */
- if (wc != WATER_CLASS_CANAL && _game_mode != GM_EDITOR) return CMD_ERROR;
+ if (wc != WATER_CLASS_CANAL && !gs->IsGameMode(GM_EDITOR)) return CMD_ERROR;
TileArea ta(tile, p1);
/* Outside the editor you can only drag canals, and not areas */
- if (_game_mode != GM_EDITOR && ta.w != 1 && ta.h != 1) return CMD_ERROR;
+ if (!gs->IsGameMode(GM_EDITOR) && ta.w != 1 && ta.h != 1) return CMD_ERROR;
CommandCost cost(EXPENSES_CONSTRUCTION);
TILE_AREA_LOOP(tile, ta) {
@@ -426,7 +428,7 @@ CommandCost CmdBuildCanal(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32
switch (wc) {
case WATER_CLASS_RIVER:
MakeRiver(tile, Random());
- if (_game_mode == GM_EDITOR) {
+ if (gs->IsGameMode(GM_EDITOR)) {
TileIndex tile2 = tile;
CircularTileSearch(&tile2, 5, RiverModifyDesertZone, NULL);
}
diff --git a/src/window.cpp b/src/window.cpp
index 6538caf..a519ee4 100644
--- a/src/window.cpp
+++ b/src/window.cpp
@@ -2703,7 +2703,7 @@ static int _input_events_this_tick = 0;
*/
static void HandleAutoscroll()
{
- if (_game_mode == GM_MENU || HasModalProgress()) return;
+ if (GameState::GetInstance()->IsGameMode(GM_MENU) || HasModalProgress()) return;
if (_settings_client.gui.auto_scrolling == VA_DISABLED) return;
if (_settings_client.gui.auto_scrolling == VA_MAIN_VIEWPORT_FULLSCREEN && !_fullscreen) return;
@@ -2749,7 +2749,7 @@ extern EventState VpHandlePlaceSizingDrag();
static void ScrollMainViewport(int x, int y)
{
- if (_game_mode != GM_MENU) {
+ if (!GameState::GetInstance()->IsGameMode(GM_MENU)) {
Window *w = FindWindowById(WC_MAIN_WINDOW, 0);
assert(w);
@@ -2827,7 +2827,7 @@ static void MouseLoop(MouseClick click, int mousewheel)
ViewPort *vp = IsPtInWindowViewport(w, x, y);
/* Don't allow any action in a viewport if either in menu or when having a modal progress window */
- if (vp != NULL && (_game_mode == GM_MENU || HasModalProgress())) return;
+ if (vp != NULL && (GameState::GetInstance()->IsGameMode(GM_MENU) || HasModalProgress())) return;
if (mousewheel != 0) {
/* Send mousewheel event to window */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment