18 #include "precompiled.h"
93 #include "tools/atlas/GameInterface/GameLoop.h"
94 #include "tools/atlas/GameInterface/View.h"
96 #if !(OS_WIN || OS_MACOSX || OS_ANDROID) // assume all other platforms use X11 for wxWidgets
97 #define MUST_INIT_X11 1
100 #define MUST_INIT_X11 0
112 ERROR_TYPE(System, RequiredExtensionsMissing);
147 filter = GL_NEAREST_MIPMAP_LINEAR;
152 filter = GL_LINEAR_MIPMAP_LINEAR;
157 filter = GL_LINEAR_MIPMAP_LINEAR;
163 filter = GL_LINEAR_MIPMAP_LINEAR;
167 debug_warn(L
"SetTextureQuality: invalid quality");
185 g_ScriptingHost.GetScriptInterface().SetGlobal(
"g_Progress", percent,
true);
186 g_ScriptingHost.GetScriptInterface().SetGlobal(
"g_LoadDescription", pending_task,
true);
238 glDisable(GL_DEPTH_TEST);
260 if (cursorName.empty())
266 bool forceGL =
false;
270 #warning TODO: implement cursors for GLES
273 glMatrixMode(GL_PROJECTION);
276 glMatrixMode(GL_MODELVIEW);
281 glLoadMatrixf(&transform.
_11);
285 LOGWARNING(L
"Failed to draw cursor '%ls'", cursorName.c_str());
288 #warning TODO: implement cursors for GLES
291 glMatrixMode(GL_PROJECTION);
293 glMatrixMode(GL_MODELVIEW);
299 glEnable(GL_DEPTH_TEST);
334 TIMER(L
"InitScripting");
380 cache = std::min(cache, (
ssize_t)200);
383 cache = std::min(cache, total-os-game);
386 cache = std::max(cache, (
ssize_t)64);
388 debug_printf(L
"Cache: %d (total: %d) MiB\n", (
int)cache, (
int)total);
389 return size_t(cache)*
MiB;
401 static bool reentering =
false;
418 mods.insert(mods.begin(),
"public");
422 if (!dev && !args.
Has(
"noUserMod"))
423 mods.push_back(
"user");
434 const Paths paths(args);
454 const OsPath readonlyConfig = paths.
RData()/
"config"/
"";
455 g_VFS->Mount(L
"config/", readonlyConfig);
456 bool dev = (
g_VFS->GetFileInfo(L
"config/dev.cfg", NULL) ==
INFO::OK);
458 const std::vector<CStr> mods =
GetMods(args, dev);
462 for (
size_t i = 0; i < mods.size(); ++i)
464 size_t priority = (i+1)*2;
474 g_VFS->Mount(L
"", modPath / modName/
"", baseFlags, priority);
476 g_VFS->Mount(L
"", modUserPath / modName/
"", userFlags, priority);
480 g_VFS->Mount(L
"", modPath / modName/
"", baseFlags, priority);
482 g_VFS->Mount(L
"", modUserPath / modName/
"", userFlags, priority+1);
487 g_VFS->Mount(L
"screenshots/", paths.
UserData()/
"screenshots"/
"");
490 g_VFS->Mount(L
"config/", readonlyConfig, 0, (
size_t)-1);
491 if(readonlyConfig != paths.
Config())
492 g_VFS->Mount(L
"config/", paths.
Config(), 0, (size_t)-1);
505 TIMER(L
"ps_console");
517 double blinkRate = 0.5;
518 CFG_GET_VAL(
"gui.cursorblinkrate", Double, blinkRate);
524 TIMER(L
"ps_lang_hotkeys");
543 #if !SDL_VERSION_ATLEAST(2, 0, 0)
589 TIMER(L
"InitRenderer");
649 setenv(
"SDL_VIDEO_X11_DGAMOUSE",
"0", 0);
659 #if SDL_VERSION_ATLEAST(2, 0, 0)
660 SDL_StartTextInput();
766 #if OS_MACOSX || OS_BSD
771 setlocale(LC_CTYPE,
"UTF-8");
783 const char*
const LocaleEnvVars[] = {
801 catch (std::runtime_error&)
805 for (
size_t i = 0; i <
ARRAY_SIZE(LocaleEnvVars); i++)
807 if (
char* envval = getenv(LocaleEnvVars[i]))
808 LOGWARNING(L
" %hs=\"%hs\"", LocaleEnvVars[i], envval);
810 LOGWARNING(L
" %hs=\"(unset)\"", LocaleEnvVars[i]);
814 if (
setenv(
"LC_ALL", std::locale::classic().name().c_str(), 1))
815 debug_warn(L
"Invalid locale settings, and unable to set LC_ALL env variable.");
817 LOGWARNING(L
"Setting LC_ALL env variable to: %hs", getenv(
"LC_ALL"));
852 int status = XInitThreads();
854 debug_printf(L
"Error enabling thread-safety via XInitThreads\n");
879 if (args.
Has(
"dumpSchema"))
885 std::cout <<
"Generated entity.rng\n";
924 bool profilerHTTPEnable =
false;
925 CFG_GET_VAL(
"profiler2.http.autoenable", Bool, profilerHTTPEnable);
926 if (profilerHTTPEnable)
946 #if !SDL_VERSION_ATLEAST(2, 0, 0)
962 bool profilerGPUEnable =
false;
963 CFG_GET_VAL(
"profiler2.gpu.autoenable", Bool, profilerGPUEnable);
964 if (profilerGPUEnable)
980 if (
ogl_HaveExtensions(0,
"GL_ARB_vertex_program",
"GL_ARB_fragment_program", NULL) != 0
981 &&
ogl_HaveExtensions(0,
"GL_ARB_vertex_shader",
"GL_ARB_fragment_shader", NULL) != 0)
984 L
"Your graphics card doesn't appear to be fully compatible with OpenGL shaders."
985 L
" In the future, the game will not support pre-shader graphics cards."
986 L
" You are advised to try installing newer drivers and/or upgrade your graphics card."
987 L
" For more information, please see http://www.wildfiregames.com/forum/index.php?showtopic=16734"
993 "GL_ARB_multitexture",
994 "GL_EXT_draw_range_elements",
995 "GL_ARB_texture_env_combine",
996 "GL_ARB_texture_env_dot3",
1002 L
"The %hs extension doesn't appear to be available on your computer."
1003 L
" The game may still work, though - you are welcome to try at your own risk."
1004 L
" If not or it doesn't look right, upgrade your graphics card.",
1014 L
"The GL_ARB_texture_env_crossbar extension doesn't appear to be available on your computer."
1015 L
" Shadows are not available and overall graphics quality might suffer."
1016 L
" You are advised to try installing newer drivers and/or upgrade your graphics card.");
1031 const bool setup_gui = ((flags &
INIT_NO_GUI) == 0);
1037 scriptInterface.
Eval(
"({})", data);
1040 InitPs(setup_gui, L
"page_pregame.xml", data.
get());
1048 InitPs(
true, L
"page_pregame.xml", JSVAL_VOID);
1091 CStr autoStartName = args.
Get(
"autostart");
1096 autoStartName =
"Oasis";
1099 if (autoStartName.empty())
1109 scriptInterface.
Eval(
"({})", attrs);
1111 scriptInterface.
Eval(
"({})", settings);
1113 scriptInterface.
Eval(
"([])", playerData);
1116 if (args.
Has(
"autostart-random"))
1118 CStr seedArg = args.
Get(
"autostart-random");
1122 if (!seedArg.empty())
1124 if (seedArg.compare(
"-1") == 0)
1130 seed = seedArg.ToULong();
1135 std::wstring scriptPath = L
"maps/random/" + autoStartName.FromUTF8() + L
".json";
1140 std::wstring scriptFile;
1141 scriptInterface.
GetProperty(settings.
get(),
"Script", scriptFile);
1147 LOGERROR(L
"Error reading random map script '%ls'", scriptPath.c_str());
1153 if (args.
Has(
"autostart-size"))
1155 CStr size = args.
Get(
"autostart-size");
1156 mapSize = size.ToUInt();
1159 scriptInterface.
SetProperty(attrs.
get(),
"map", std::string(autoStartName));
1160 scriptInterface.
SetProperty(attrs.
get(),
"mapType", std::string(
"random"));
1165 size_t numPlayers = 2;
1166 if (args.
Has(
"autostart-players"))
1168 CStr num = args.
Get(
"autostart-players");
1169 numPlayers = num.ToUInt();
1173 for (
size_t i = 0; i < numPlayers; ++i)
1176 scriptInterface.
Eval(
"({})", player);
1180 scriptInterface.
SetProperty(player.
get(),
"Civ", std::string(
"athen"));
1187 std::string mapFile =
"maps/scenarios/" + autoStartName;
1189 scriptInterface.
SetProperty(attrs.
get(),
"mapType", std::string(
"scenario"));
1194 if (args.
Has(
"autostart-ai"))
1196 std::vector<CStr> aiArgs = args.
GetMultiple(
"autostart-ai");
1197 for (
size_t i = 0; i < aiArgs.size(); ++i)
1203 scriptInterface.
Eval(
"({})", player);
1206 int playerID = aiArgs[i].BeforeFirst(
":").ToInt();
1207 CStr name = aiArgs[i].AfterFirst(
":");
1209 scriptInterface.
SetProperty(player.
get(),
"AI", std::string(name));
1215 if (args.
Has(
"autostart-aidiff"))
1217 std::vector<CStr> civArgs = args.
GetMultiple(
"autostart-aidiff");
1218 for (
size_t i = 0; i < civArgs.size(); ++i)
1224 scriptInterface.
Eval(
"({})", player);
1227 int playerID = civArgs[i].BeforeFirst(
":").ToInt();
1228 int difficulty = civArgs[i].AfterFirst(
":").ToInt();
1235 if (args.
Has(
"autostart-civ"))
1237 std::vector<CStr> civArgs = args.
GetMultiple(
"autostart-civ");
1238 for (
size_t i = 0; i < civArgs.size(); ++i)
1244 scriptInterface.
Eval(
"({})", player);
1247 int playerID = civArgs[i].BeforeFirst(
":").ToInt();
1248 CStr name = civArgs[i].AfterFirst(
":");
1250 scriptInterface.
SetProperty(player.
get(),
"Civ", std::string(name));
1256 scriptInterface.
SetProperty(settings.
get(),
"PlayerData", playerData);
1267 CStrW userName = L
"anonymous";
1268 if (args.
Has(
"autostart-playername"))
1270 userName = args.
Get(
"autostart-playername").FromUTF8();
1273 if (args.
Has(
"autostart-host"))
1275 InitPs(
true, L
"page_loading.xml", mpInitData.
get());
1277 size_t maxPlayers = 2;
1278 if (args.
Has(
"autostart-players"))
1280 maxPlayers = args.
Get(
"autostart-players").ToUInt();
1294 else if (args.
Has(
"autostart-client"))
1296 InitPs(
true, L
"page_loading.xml", mpInitData.
get());
1299 g_NetClient->SetUserName(userName);
1301 CStr ip =
"127.0.0.1";
1302 if (args.
Has(
"autostart-ip"))
1304 ip = args.
Get(
"autostart-ip");
1307 bool ok = g_NetClient->SetupConnection(ip);
1320 InitPs(
true, L
"page_session.xml", JSVAL_VOID);
1342 if (ok && !JSVAL_IS_VOID(fval))
CDebuggingServer * g_DebuggingServer
The container that holds the rules, resources and attributes of the game.
void InitGraphics(const CmdLineArgs &args, int flags)
Error/warning/message logging class.
#define PROFILE2_EVENT(name)
Record the named event at the current time.
CScriptStatsTable * g_ScriptStatsTable
InReaction gui_handler(const SDL_Event_ *ev)
CStr Get(const char *name) const
Get the value of the named parameter.
void psBundleLogs(FILE *f)
CUserReporter g_UserReporter
void ogl_tex_override(OglTexOverrides what, OglTexAllow allow)
Override the default decision and force/disallow use of the given feature.
static void InitScripting()
#define UNUSED(param)
mark a function parameter as unused and avoid the corresponding compiler warning. ...
bool Autostart(const CmdLineArgs &args)
CNetClient * g_NetClient
Global network client for the standard game.
const OsPath & psLogDir()
Status LDR_NonprogressiveLoad()
ErrorReactionInternal(* display_error)(const wchar_t *text, size_t flags)
void Initialise()
Initialises joystick support.
int setenv(const char *envname, const char *envval, int overwrite)
rationale: the Windows headers declare many POSIX functions (e.g.
const PSRETURN PSRETURN_OK
CLightEnv g_LightEnv
File : World.cpp Project : engine Description : Contains the CWorld Class implementation.
const wchar_t *(* translate)(const wchar_t *text)
bool SetupConnection()
Begin listening for network connections.
ISoundManager * g_SoundManager
void GUI_DisplayLoadProgress(int percent, const wchar_t *pending_task)
int GetCharacterWidth(wchar_t c)
void Shutdown()
Explicit shutdown of the vertex buffer subsystem; releases all currently-allocated buffers...
CVertexBufferManager g_VBMan
Status sys_cursor_reset()
reset any cached cursor data.
const OsPath & UserData() const
Returns directory for user-created data Only things created in response to an explicit user action sh...
std::vector< CStr > GetMultiple(const char *name) const
Get all the values given to the named parameter.
#define CFG_GET_VAL(name, type, destination)
special return value for the display_error app hook stub to indicate that it has done nothing and tha...
static void out(const wchar_t *fmt,...)
virtual void IdleTask()=0
static RenderPath GetRenderPathByName(const CStr &name)
const OsPath & RData() const
Returns directory for read-only data installed with the game.
const jsval & get() const
Returns the current value.
void GuiScriptingInit(ScriptInterface &scriptInterface)
const OsPath &(* get_log_dir)()
CNetServer * g_NetServer
Global network server for the standard game.
void psSetLogDir(const OsPath &newLogDir)
Class CProfileViewer: Manage and display profiling tables.
A trivial wrapper around a jsval.
void RenderGui(bool RenderingState)
enable/disable rendering of the GUI (intended mainly for screenshots)
GameLoopState * g_AtlasGameLoop
std::string GenerateSchema()
static size_t OperatingSystemFootprint()
int swprintf_s(wchar_t *buf, size_t max_chars, const wchar_t *fmt,...) WPRINTF_ARGS(3)
void EnableHTTP()
Call in main thread to enable the HTTP server.
bool SetPropertyInt(jsval obj, int name, const T &value, bool constant=false, bool enumerate=true)
Set the integer-named property on the given object.
static void Initialize()
Initialize ENet.
bool LoadDefaultScripts()
Call LoadScripts for each of the game's standard simulation script paths.
static const int SANE_TEX_QUALITY_DEFAULT
static void InitRenderer()
Public API for simulation system.
static void InitPs(bool setup_gui, const CStrW &gui_page, CScriptVal initData)
size_t os_cpu_MemorySize()
static size_t ChooseCacheSize()
void SetCursorBlinkRate(double rate)
LIB_API void debug_SetThreadName(const char *name)
inform the debugger of the current thread's name.
#define TIMER_BEGIN(description)
Measures the time taken to execute code between BEGIN and END markers; displays it via debug_printf...
return ERR::VFS_DIR_NOT_FOUND if the given real path doesn't exist.
#define ENSURE(expr)
ensure the expression <expr> evaluates to non-zero.
void SDL_WM_SetCaption(const char *title, const char *icon)
void Shutdown()
Shut down after InitSDL/InitNonSDL, so that they can be used again.
static void Init()
Initialise global settings.
void CONFIG_Init(const CmdLineArgs &args)
PIVFS CreateVfs(size_t cacheSize)
create an instance of a Virtual File System.
Status cursor_draw(const PIVFS &vfs, const wchar_t *name, int x, int y, bool forceGL)
Draw the cursor on-screen.
void SetPlayerID(int playerID)
static void InitVfs(const CmdLineArgs &args, int flags)
static void ScriptingInit()
Initializes GUI script classes.
#define SDL_DEFAULT_REPEAT_DELAY
bool Has(const char *name) const
Test whether the given name was specified, as either -name or -name=value
New profiler (complementing the older CProfileManager)
CScriptValRooted ReadJSONFile(const VfsPath &path)
Read a JSON file.
void timer_LatchStartTime()
timer_Time will subsequently return values relative to the current time.
#define TIMER_END(description)
#define file_stats_dump()
void SetMainThread()
Set the current thread as the 'main' thread.
void UpdateGameAttributes(const CScriptVal &attrs, ScriptInterface &scriptInterface)
Call from the GUI to update the game setup attributes.
virtual const char * what() const
InReaction GlobalsInputHandler(const SDL_Event_ *ev)
void StartGame(const CScriptValRooted &attribs, const std::string &savedState)
void SetUserName(const CStrW &username)
Set the user's name that will be displayed to all players.
JSObject * GetScriptObject()
See CGUI::GetScriptObject; applies to the currently active page.
ScriptInterface & GetScriptInterface() const
const OsPath & Cache() const
Returns cache directory.
#define SAFE_DELETE(p)
delete memory ensuing from new and set the pointer to zero (thus making double-frees safe / a no-op) ...
bool undefined() const
Returns whether the value is uninitialised or is JSVAL_VOID.
emphatically require full quality for this texture.
bool Eval(const char *code)
InReaction game_view_handler(const SDL_Event_ *ev)
static jsval ToJSVal(JSContext *cx, T const &val)
Convert a C++ type to a jsval.
anything mounted from here should be included when building archives.
all real directories mounted during this operation will be watched for changes.
#define SDL_INIT_NOPARACHUTE
void(* translate_free)(const wchar_t *text)
void debug_filter_add(const wchar_t *tag)
debug output is very useful, but "too much of a good thing can kill you".
void cursor_shutdown()
Forcibly frees all cursor handles.
CGame * g_Game
Globally accessible pointer to the CGame object.
void ShutdownGPU()
Call in main thread to shut down the GPU profiling support, before shutting down OpenGL.
Network server interface.
#define SDL_EnableKeyRepeat(delay, interval)
void Initialise()
Call in main thread to set up the profiler, before calling any other profiler functions.
void RenderCursor(bool RenderingState)
enable/disable rendering of the cursor - this does not hide cursor, but reverts to OS style ...
void(* bundle_logs)(FILE *f)
void CancelLoad(const CStrW &message)
jsval CloneValueFromOtherContext(ScriptInterface &otherContext, jsval val)
Construct a new value (usable in this ScriptInterface's context) by cloning a value from a different ...
CSimulation2 * GetSimulation2()
Get the pointer to the simulation2 object.
ScriptInterface & GetScriptInterface()
static std::vector< CStr > GetMods(const CmdLineArgs &args, bool dev)
store the texture at half its original resolution.
#define TIMER(description)
Measures the time taken to execute code up until end of the current scope; displays it via debug_prin...
bool GetProperty(jsval obj, const char *name, T &out)
Get the named property on the given object.
static InReaction InputThunk(const SDL_Event_ *ev)
InputThunk: Delegate to the singleton's Input() member function if the singleton has been initialized...
void RunHardwareDetection()
Runs hardware-detection script to adjust default config settings and/or emit warnings depending on th...
int SDL_Init(Uint32 flags)
const size_t WVERSION_XP64
#define PROFILE2_ATTR
Associates a string (with printf-style formatting) with the current region or event.
int SDL_EnableUNICODE(int enable)
#define SDL_DEFAULT_REPEAT_INTERVAL
CGameView * GetView()
Get the pointer to the game view object.
bool SetupConnection(const CStr &server)
Set up a connection to the remote networked server.
static void RegisterJavascriptInterfaces()
bool ogl_HaveExtension(const char *ext)
check if an extension is supported by the OpenGL implementation.
void RenderLogger(bool RenderingState)
store the texture at half the normal bit depth (4 bits per pixel component, as opposed to 8)...
Wrapper class for OS paths used by the game.
void SwitchPage(const CStrW &name, CScriptVal initData)
Load a new GUI page and make it active.
void RegisterScriptFunctions(ScriptInterface &scriptInterface)
InReaction HotkeyInputHandler(const SDL_Event_ *ev)
static void SetEnabled(bool doEnable)
void RecordGPUFrameStart()
void EnableGPU()
Call in main thread to enable the GPU profiling support, after OpenGL has been initialised.
bool GetPropertyInt(jsval obj, int name, T &out)
Get the integer-named property on the given object.
void EarlyInit()
initialize global modules that are be needed before Init.
bool IsGameStarted() const
Get m_GameStarted.
#define DEBUG_DISPLAY_ERROR(description)
void psTranslateFree(const wchar_t *text)
const OsPath & Config() const
Returns config file directory.
bool IsMainThread()
Returns whether the current thread is the 'main' thread (i.e.
jsval get() const
Returns the current value (or JSVAL_VOID if uninitialised).
bool SetFullscreen(bool fullscreen)
Switch to fullscreen or windowed mode.
Abstraction around a SpiderMonkey JSContext.
void ogl_WarnIfError()
raise a warning (break into the debugger) if an OpenGL error is pending.
#define PROFILE3_GPU(name)
#define debug_warn(expr)
display the error dialog with the given text.
void Draw()
See CGUI::Draw; applies to all loaded pages.
static void CreateSoundManager()
void tex_codec_register_all()
Manually register codecs.
void ogl_tex_set_defaults(int q_flags, GLint filter)
Change default settings - these affect performance vs.
bool undefined() const
Returns whether the value is JSVAL_VOID.
void SetOrtho(float l, float r, float b, float t, float n, float f)
External interface to the GUI system.
bool SetProperty(jsval obj, const char *name, const T &value, bool constant=false, bool enumerate=true)
Set the named property on the given object.
static void SetTextureQuality(int quality)
const wchar_t * psTranslate(const wchar_t *text)
static void ShutdownSDL()
size_t rand(size_t min_inclusive, size_t max_exclusive)
return random integer in [min, max).
PSRETURN ReallyStartGame()
Game initialization has been completed.
holds a function pointer (allowed to be NULL) for each hook.
Status CreateDirectories(const OsPath &path, mode_t mode)
bool DirectoryExists(const OsPath &path)
bool InitSDL()
Initialise the video mode, for use in an SDL-using application.
bool HasPages()
Returns whether there are any current pages.
void app_hooks_update(AppHooks *new_ah)
update the app hook function pointers.
void tex_codec_unregister_all()
remove all codecs that have been registered.
void UpdateScreenSize(int w, int h)
const size_t WVERSION_VISTA
void SendEventToAll(const CStr &eventName)
See CGUI::SendEventToAll; applies to the currently active page.
static void Deinitialize()
Deinitialize ENet.
void debug_printf(const wchar_t *fmt,...)
write a formatted string to the debug channel, subject to filtering (see below).
const OsPath & Logs() const
Returns logs directory.
ErrorReactionInternal psDisplayError(const wchar_t *text, size_t flags)
InReaction conInputHandler(const SDL_Event_ *ev)
void timer_DisplayClientTotals()
display all clients' totals; does not reset them.
ErrorReactionInternal
all choices offered by the error dialog.
void ColorActivateFastImpl()
const char * ogl_HaveExtensions(int dummy,...)
check if a list of extensions are all supported (as determined by ogl_HaveExtension).
mark a directory replaceable, so that when writing a file to this path new real directories will be c...