Пример #1
0
CProfiler2GPU::CProfiler2GPU(CProfiler2& profiler) :
	m_Profiler(profiler), m_ProfilerARB(NULL), m_ProfilerEXT(NULL), m_ProfilerINTEL(NULL)
{
	bool enabledARB = false;
	bool enabledEXT = false;
	bool enabledINTEL = false;
	CFG_GET_VAL("profiler2.gpu.arb.enable", Bool, enabledARB);
	CFG_GET_VAL("profiler2.gpu.ext.enable", Bool, enabledEXT);
	CFG_GET_VAL("profiler2.gpu.intel.enable", Bool, enabledINTEL);

	// Only enable either ARB or EXT, not both, because they are redundant
	// (EXT is only needed for compatibility with older systems), and because
	// using both triggers GL_INVALID_OPERATION on AMD drivers (see comment
	// in CProfiler2GPU_EXT_timer_query::RecordRegion)
	if (enabledARB && CProfiler2GPU_ARB_timer_query::IsSupported())
	{
		m_ProfilerARB = new CProfiler2GPU_ARB_timer_query(m_Profiler);
	}
	else if (enabledEXT && CProfiler2GPU_EXT_timer_query::IsSupported())
	{
		m_ProfilerEXT = new CProfiler2GPU_EXT_timer_query(m_Profiler);
	}

	// The INTEL mode should be compatible with ARB/EXT (though no current
	// drivers support both), and provides complementary data, so enable it
	// when possible
	if (enabledINTEL && CProfiler2GPU_INTEL_performance_queries::IsSupported())
	{
		m_ProfilerINTEL = new CProfiler2GPU_INTEL_performance_queries(m_Profiler);
	}
}
Пример #2
0
/**
 * Construct the xmpp client
 */
XmppClient::XmppClient(const std::string& sUsername, const std::string& sPassword, const std::string& sRoom, const std::string& sNick, bool regOpt)
	: m_client(NULL), m_mucRoom(NULL), m_registration(NULL), m_username(sUsername), m_password(sPassword), m_nick(sNick)
{
	// Read lobby configuration from default.cfg
	std::string sServer;
	std::string sXpartamupp;
	CFG_GET_VAL("lobby.server", String, sServer);
	CFG_GET_VAL("lobby.xpartamupp", String, sXpartamupp);

	m_xpartamuppId = sXpartamupp + "@" + sServer + "/CC";
	glooxwrapper::JID clientJid(sUsername + "@" + sServer + "/0ad");
	glooxwrapper::JID roomJid(sRoom + "@conference." + sServer + "/" + sNick);

	// If we are connecting, use the full jid and a password
	// If we are registering, only use the server name
	if(!regOpt)
		m_client = new glooxwrapper::Client(clientJid, sPassword);
	else
		m_client = new glooxwrapper::Client(sServer);

	// Disable TLS as we haven't set a certificate on the server yet
	m_client->setTls(gloox::TLSDisabled);

	// Disable use of the SASL PLAIN mechanism, to prevent leaking credentials
	// if the server doesn't list any supported SASL mechanism or the response
	// has been modified to exclude those.
	const int mechs = gloox::SaslMechAll ^ gloox::SaslMechPlain;
	m_client->setSASLMechanisms(mechs);

	m_client->registerConnectionListener( this );
	m_client->setPresence(gloox::Presence::Available, -1);
	m_client->disco()->setVersion( "Pyrogenesis", "0.0.15" );
	m_client->disco()->setIdentity( "client", "bot" );
	m_client->setCompression(false);

	m_client->registerStanzaExtension( new GameListQuery() );
	m_client->registerIqHandler( this, ExtGameListQuery);

	m_client->registerStanzaExtension( new BoardListQuery() );
	m_client->registerIqHandler( this, ExtBoardListQuery);

	m_client->registerMessageHandler( this );

	// Uncomment to see the raw stanzas
	//m_client->logInstance().registerLogHandler( LogLevelDebug, LogAreaAll, this );

	if (!regOpt)
	{
		// Create a Multi User Chat Room
		m_mucRoom = new glooxwrapper::MUCRoom(m_client, roomJid, this, 0);
		// Disable the history because its anoying
		m_mucRoom->setRequestHistory(0, gloox::MUCRoom::HistoryMaxStanzas);
	}
	else
	{
		// Registration
		m_registration = new glooxwrapper::Registration(m_client);
		m_registration->registerRegistrationHandler(this);
	}
}
Пример #3
0
CSoundManager::CSoundManager()
	: m_Context(nullptr), m_Device(nullptr), m_ALSourceBuffer(nullptr),
	m_CurrentTune(nullptr), m_CurrentEnvirons(nullptr),
	m_Worker(nullptr), m_DistressMutex(), m_PlayListItems(nullptr), m_SoundGroups(),
	m_Gain(.5f), m_MusicGain(.5f), m_AmbientGain(.5f), m_ActionGain(.5f), m_UIGain(.5f),
	m_Enabled(false), m_BufferSize(98304), m_BufferCount(50),
	m_SoundEnabled(true), m_MusicEnabled(true), m_MusicPaused(false),
	m_AmbientPaused(false), m_ActionPaused(false),
	m_RunningPlaylist(false), m_PlayingPlaylist(false), m_LoopingPlaylist(false),
	m_PlaylistGap(0), m_DistressErrCount(0), m_DistressTime(0)
{
	CFG_GET_VAL("sound.mastergain", m_Gain);
	CFG_GET_VAL("sound.musicgain", m_MusicGain);
	CFG_GET_VAL("sound.ambientgain", m_AmbientGain);
	CFG_GET_VAL("sound.actiongain", m_ActionGain);
	CFG_GET_VAL("sound.uigain", m_UIGain);

	AlcInit();

	if (m_Enabled)
	{
		SetMasterGain(m_Gain);
		InitListener();

		m_PlayListItems = new PlayList;
	}

	if (!CXeromyces::AddValidator(g_VFS, "sound_group", "audio/sound_group.rng"))
		LOGERROR("CSoundManager: failed to load grammar file 'audio/sound_group.rng'");

	RegisterFileReloadFunc(ReloadChangedFileCB, this);
}
Пример #4
0
void CVideoMode::ReadConfig()
{
	bool windowed = !m_ConfigFullscreen;
	CFG_GET_VAL("windowed", Bool, windowed);
	m_ConfigFullscreen = !windowed;

	CFG_GET_VAL("xres", Int, m_ConfigW);
	CFG_GET_VAL("yres", Int, m_ConfigH);
	CFG_GET_VAL("bpp", Int, m_ConfigBPP);
	CFG_GET_VAL("force_s3tc_enable", Bool, m_ConfigForceS3TCEnable);
}
Пример #5
0
void CONFIG_Init(const CmdLineArgs& args)
{
	TIMER(L"CONFIG_Init");

	new CConfigDB;

	// Load the global, default config file
	g_ConfigDB.SetConfigFile(CFG_DEFAULT, L"config/default.cfg");
	g_ConfigDB.Reload(CFG_DEFAULT);	// 216ms
	// Try loading the local system config file (which doesn't exist by
	// default) - this is designed as a way of letting developers edit the
	// system config without accidentally committing their changes back to SVN.
	g_ConfigDB.SetConfigFile(CFG_SYSTEM, L"config/local.cfg");
	g_ConfigDB.Reload(CFG_SYSTEM);

	g_ConfigDB.SetConfigFile(CFG_USER, L"config/user.cfg");
	g_ConfigDB.Reload(CFG_USER);

	g_ConfigDB.SetConfigFile(CFG_MOD, L"config/mod.cfg");
	// No point in reloading mod.cfg here - we haven't mounted mods yet

	ProcessCommandLineArgs(args);

	// Initialise console history file
	int max_history_lines = 200;
	CFG_GET_VAL("console.history.size", Int, max_history_lines);
	g_Console->UseHistoryFile(L"config/console.txt", max_history_lines);

	// Collect information from system.cfg, the profile file,
	// and any command-line overrides to fill in the globals.
	LoadGlobals();	// 64ms
}
Пример #6
0
static void InitSDL()
{
#if OS_LINUX
	// In fullscreen mode when SDL is compiled with DGA support, the mouse
	// sensitivity often appears to be unusably wrong (typically too low).
	// (This seems to be reported almost exclusively on Ubuntu, but can be
	// reproduced on Gentoo after explicitly enabling DGA.)
	// Disabling the DGA mouse appears to fix that problem, and doesn't
	// have any obvious negative effects.
	setenv("SDL_VIDEO_X11_DGAMOUSE", "0", 0);
#endif

	if(SDL_Init(SDL_INIT_VIDEO|SDL_INIT_TIMER|SDL_INIT_NOPARACHUTE) < 0)
	{
		LOGERROR("SDL library initialization failed: %s", SDL_GetError());
		throw PSERROR_System_SDLInitFailed();
	}
	atexit(SDL_Quit);

#if !SDL_VERSION_ATLEAST(2, 0, 0)
	SDL_EnableUNICODE(1);
#endif

#if OS_MACOSX && SDL_VERSION_ATLEAST(2, 0, 0)
	// Some Mac mice only have one button, so they can't right-click
	// but SDL2 can emulate that with Ctrl+Click
	bool macMouse = false;
	CFG_GET_VAL("macmouse", macMouse);
	SDL_SetHint(SDL_HINT_MAC_CTRL_CLICK_EMULATE_RIGHT_CLICK, macMouse ? "1" : "0");
#endif
}
Пример #7
0
std::string CUserReporter::LoadUserID()
{
	std::string userID;

	// Read the user ID from user.cfg (if there is one)
	CFG_GET_VAL("userreport.id", userID);

	// If we don't have a validly-formatted user ID, generate a new one
	if (userID.length() != 16)
	{
		u8 bytes[8] = {0};
		sys_generate_random_bytes(bytes, ARRAY_SIZE(bytes));
		// ignore failures - there's not much we can do about it

		userID = "";
		for (size_t i = 0; i < ARRAY_SIZE(bytes); ++i)
		{
			char hex[3];
			sprintf_s(hex, ARRAY_SIZE(hex), "%02x", (unsigned int)bytes[i]);
			userID += hex;
		}

		g_ConfigDB.SetValueString(CFG_USER, "userreport.id", userID);
		g_ConfigDB.WriteValueToFile(CFG_USER, "userreport.id", userID);
	}

	return userID;
}
Пример #8
0
	CSimulation2Impl(CUnitManager* unitManager, shared_ptr<ScriptRuntime> rt, CTerrain* terrain) :
		m_SimContext(), m_ComponentManager(m_SimContext, rt),
		m_EnableOOSLog(false), m_EnableSerializationTest(false)
	{
		m_SimContext.m_UnitManager = unitManager;
		m_SimContext.m_Terrain = terrain;
		m_ComponentManager.LoadComponentTypes();

		RegisterFileReloadFunc(ReloadChangedFileCB, this);

		// Tests won't have config initialised
		if (CConfigDB::IsInitialised())
		{
			CFG_GET_VAL("ooslog", Bool, m_EnableOOSLog);
			CFG_GET_VAL("serializationtest", Bool, m_EnableSerializationTest);
		}
	}
Пример #9
0
CMaterialManager::CMaterialManager()
{
	qualityLevel = 5.0;
	CFG_GET_VAL("materialmgr.quality", qualityLevel);
	qualityLevel = clamp(qualityLevel, 0.0f, 10.0f);

	if (VfsDirectoryExists(L"art/materials/") && !CXeromyces::AddValidator(g_VFS, "material", "art/materials/material.rng"))
		LOGERROR("CMaterialManager: failed to load grammar file 'art/materials/material.rng'");
}
Пример #10
0
void CUserReporter::Initialize()
{
	ENSURE(!m_Worker); // must only be called once

	std::string userID = LoadUserID();
	std::string url;
	CFG_GET_VAL("userreport.url", url);

	// Initialise everything except Win32 sockets (because our networking
	// system already inits those)
	curl_global_init(CURL_GLOBAL_ALL & ~CURL_GLOBAL_WIN32);

	m_Worker = new CUserReporterWorker(userID, url);

	m_Worker->SetEnabled(IsReportingEnabled());
}
Пример #11
0
// Try to find the best dictionary locale based on user configuration and system locale, set the currentLocale and reload the dictionary.
void L10n::ReevaluateCurrentLocaleAndReload()
{
	std::string locale;
	CFG_GET_VAL("locale", locale);

	if (locale == "long")
	{
		// Set ICU to en_US to have a valid language for displaying dates
		currentLocale = Locale::getUS();
		currentLocaleIsOriginalGameLocale = false;
		useLongStrings = true;
	}
	else
	{
		GetDictionaryLocale(locale, currentLocale);
		currentLocaleIsOriginalGameLocale = (currentLocale == Locale::getUS()) == TRUE;
		useLongStrings = false;
	}
	LoadDictionaryForCurrentLocale();
}
Пример #12
0
L10n::L10n()
	: currentLocaleIsOriginalGameLocale(false), useLongStrings(false), dictionary(new tinygettext::Dictionary())
{
	// Determine whether or not to print tinygettext messages to the standard
	// error output, which it tinygettext’s default behavior, but not ours.
	bool tinygettext_debug = false;
	CFG_GET_VAL("tinygettext.debug", tinygettext_debug);
	if (!tinygettext_debug)
	{
		tinygettext::Log::log_info_callback = 0;
		tinygettext::Log::log_warning_callback = 0;
		tinygettext::Log::log_error_callback = 0;
	}

	LoadListOfAvailableLocales();
	ReevaluateCurrentLocaleAndReload();

	// Handle hotloading
	RegisterFileReloadFunc(ReloadChangedFileCB, this);
}
Пример #13
0
static void InitPs(bool setup_gui, const CStrW& gui_page, ScriptInterface* srcScriptInterface, JS::HandleValue initData)
{
	{
		// console
		TIMER(L"ps_console");

		g_Console->UpdateScreenSize(g_xres, g_yres);

		// Calculate and store the line spacing
		CFontMetrics font(CStrIntern(CONSOLE_FONT));
		g_Console->m_iFontHeight = font.GetLineSpacing();
		g_Console->m_iFontWidth = font.GetCharacterWidth(L'C');
		g_Console->m_charsPerPage = (size_t)(g_xres / g_Console->m_iFontWidth);
		// Offset by an arbitrary amount, to make it fit more nicely
		g_Console->m_iFontOffset = 7;

		double blinkRate = 0.5;
		CFG_GET_VAL("gui.cursorblinkrate", blinkRate);
		g_Console->SetCursorBlinkRate(blinkRate);
	}

	// hotkeys
	{
		TIMER(L"ps_lang_hotkeys");
		LoadHotkeys();
	}

	if (!setup_gui)
	{
		// We do actually need *some* kind of GUI loaded, so use the
		// (currently empty) Atlas one
		g_GUI->SwitchPage(L"page_atlas.xml", srcScriptInterface, initData);
		return;
	}

	// GUI uses VFS, so this must come after VFS init.
	g_GUI->SwitchPage(gui_page, srcScriptInterface, initData);
}
Пример #14
0
CMaterialManager::CMaterialManager()
{
	qualityLevel = 5.0;
	CFG_GET_VAL("materialmgr.quality", Float, qualityLevel);
	qualityLevel = clamp(qualityLevel, 0.0f, 10.0f);
}
Пример #15
0
CMiniMap::CMiniMap() :
	m_TerrainTexture(0), m_TerrainData(0), m_MapSize(0), m_Terrain(0), m_TerrainDirty(true), m_MapScale(1.f),
	m_EntitiesDrawn(0), m_IndexArray(GL_STATIC_DRAW), m_VertexArray(GL_DYNAMIC_DRAW),
	m_NextBlinkTime(0.0), m_PingDuration(25.0), m_BlinkState(false)
{
	AddSetting(GUIST_CColor,	"fov_wedge_color");
	AddSetting(GUIST_CStrW,		"tooltip");
	AddSetting(GUIST_CStr,		"tooltip_style");
	m_Clicking = false;
	m_MouseHovering = false;
	
	// Get the maximum height for unit passage in water.
	CParamNode externalParamNode;
	CParamNode::LoadXML(externalParamNode, L"simulation/data/pathfinder.xml");
	const CParamNode pathingSettings = externalParamNode.GetChild("Pathfinder").GetChild("PassabilityClasses");
	if (pathingSettings.GetChild("default").IsOk() && pathingSettings.GetChild("default").GetChild("MaxWaterDepth").IsOk())
		m_ShallowPassageHeight = pathingSettings.GetChild("default").GetChild("MaxWaterDepth").ToFloat();
	else
		m_ShallowPassageHeight = 0.0f;
		
	m_AttributePos.type = GL_FLOAT;
	m_AttributePos.elems = 2;
	m_VertexArray.AddAttribute(&m_AttributePos);
	
	m_AttributeColor.type = GL_UNSIGNED_BYTE;
	m_AttributeColor.elems = 4;
	m_VertexArray.AddAttribute(&m_AttributeColor);
	
	m_VertexArray.SetNumVertices(MAX_ENTITIES_DRAWN);
	m_VertexArray.Layout();

	m_IndexArray.SetNumVertices(MAX_ENTITIES_DRAWN);
	m_IndexArray.Layout();
	VertexArrayIterator<u16> index = m_IndexArray.GetIterator();
	for (u16 i = 0; i < MAX_ENTITIES_DRAWN; ++i)
	{
		*index++ = i;
	}
	m_IndexArray.Upload();
	m_IndexArray.FreeBackingStore();
	
	
	VertexArrayIterator<float[2]> attrPos = m_AttributePos.GetIterator<float[2]>();
	VertexArrayIterator<u8[4]> attrColor = m_AttributeColor.GetIterator<u8[4]>();
	for (u16 i = 0; i < MAX_ENTITIES_DRAWN; i++)
	{
		(*attrColor)[0] = 0;
		(*attrColor)[1] = 0;
		(*attrColor)[2] = 0;
		(*attrColor)[3] = 0;
		++attrColor;

		(*attrPos)[0] = -10000.0f;
		(*attrPos)[1] = -10000.0f;
		
		++attrPos;
		
	}
	m_VertexArray.Upload();

	double blinkDuration = 1.0;

	// Tests won't have config initialised
	if (CConfigDB::IsInitialised())
	{
		CFG_GET_VAL("gui.session.minimap.pingduration", Double, m_PingDuration);
		CFG_GET_VAL("gui.session.minimap.blinkduration", Double, blinkDuration);
	}
	m_HalfBlinkDuration = blinkDuration/2;
}
Пример #16
0
void InitGraphics(const CmdLineArgs& args, int flags)
{
	const bool setup_vmode = (flags & INIT_HAVE_VMODE) == 0;

	if(setup_vmode)
	{
		InitSDL();

		if (!g_VideoMode.InitSDL())
			throw PSERROR_System_VmodeFailed(); // abort startup

#if !SDL_VERSION_ATLEAST(2, 0, 0)
		SDL_WM_SetCaption("0 A.D.", "0 A.D.");
#endif
	}

	RunHardwareDetection();

	const int quality = SANE_TEX_QUALITY_DEFAULT;	// TODO: set value from config file
	SetTextureQuality(quality);

	ogl_WarnIfError();

	// Optionally start profiler GPU timings automatically
	// (By default it's only enabled by a hotkey, for performance/compatibility)
	bool profilerGPUEnable = false;
	CFG_GET_VAL("profiler2.autoenable", profilerGPUEnable);
	if (profilerGPUEnable)
		g_Profiler2.EnableGPU();

	if(!g_Quickstart)
	{
		WriteSystemInfo();
		// note: no longer vfs_display here. it's dog-slow due to unbuffered
		// file output and very rarely needed.
	}

	if(g_DisableAudio)
		ISoundManager::SetEnabled(false);

	g_GUI = new CGUIManager();

	// (must come after SetVideoMode, since it calls ogl_Init)
	if (ogl_HaveExtensions(0, "GL_ARB_vertex_program", "GL_ARB_fragment_program", NULL) != 0 // ARB
		&& ogl_HaveExtensions(0, "GL_ARB_vertex_shader", "GL_ARB_fragment_shader", NULL) != 0) // GLSL
	{
		DEBUG_DISPLAY_ERROR(
			L"Your graphics card doesn't appear to be fully compatible with OpenGL shaders."
			L" In the future, the game will not support pre-shader graphics cards."
			L" You are advised to try installing newer drivers and/or upgrade your graphics card."
			L" For more information, please see http://www.wildfiregames.com/forum/index.php?showtopic=16734"
		);
		// TODO: actually quit once fixed function support is dropped
	}

	const char* missing = ogl_HaveExtensions(0,
		"GL_ARB_multitexture",
		"GL_EXT_draw_range_elements",
		"GL_ARB_texture_env_combine",
		"GL_ARB_texture_env_dot3",
		NULL);
	if(missing)
	{
		wchar_t buf[500];
		swprintf_s(buf, ARRAY_SIZE(buf),
			L"The %hs extension doesn't appear to be available on your computer."
			L" The game may still work, though - you are welcome to try at your own risk."
			L" If not or it doesn't look right, upgrade your graphics card.",
			missing
		);
		DEBUG_DISPLAY_ERROR(buf);
		// TODO: i18n
	}

	if (!ogl_HaveExtension("GL_ARB_texture_env_crossbar"))
	{
		DEBUG_DISPLAY_ERROR(
			L"The GL_ARB_texture_env_crossbar extension doesn't appear to be available on your computer."
			L" Shadows are not available and overall graphics quality might suffer."
			L" You are advised to try installing newer drivers and/or upgrade your graphics card.");
		g_Shadows = false;
	}

	ogl_WarnIfError();
	InitRenderer();

	InitInput();

	ogl_WarnIfError();

	try
	{
		if (!Autostart(args))
		{
			const bool setup_gui = ((flags & INIT_NO_GUI) == 0);
			// We only want to display the splash screen at startup
			shared_ptr<ScriptInterface> scriptInterface = g_GUI->GetScriptInterface();
			JSContext* cx = scriptInterface->GetContext();
			JSAutoRequest rq(cx);
			JS::RootedValue data(cx);
			if (g_GUI)
			{
				scriptInterface->Eval("({})", &data);
				scriptInterface->SetProperty(data, "isStartup", true);
			}
			InitPs(setup_gui, L"page_pregame.xml", g_GUI->GetScriptInterface().get(), data);
		}
	}
	catch (PSERROR_Game_World_MapLoadFailed& e)
	{
		// Map Loading failed

		// Start the engine so we have a GUI
		InitPs(true, L"page_pregame.xml", NULL, JS::UndefinedHandleValue);

		// Call script function to do the actual work
		//	(delete game data, switch GUI page, show error, etc.)
		CancelLoad(CStr(e.what()).FromUTF8());
	}
}
Пример #17
0
bool Init(const CmdLineArgs& args, int flags)
{
	h_mgr_init();

	// Do this as soon as possible, because it chdirs
	// and will mess up the error reporting if anything
	// crashes before the working directory is set.
	InitVfs(args, flags);

	// This must come after VFS init, which sets the current directory
	// (required for finding our output log files).
	g_Logger = new CLogger;

	new CProfileViewer;
	new CProfileManager;	// before any script code

	g_ScriptStatsTable = new CScriptStatsTable;
	g_ProfileViewer.AddRootTable(g_ScriptStatsTable);

	// Set up the console early, so that debugging
	// messages can be logged to it. (The console's size
	// and fonts are set later in InitPs())
	g_Console = new CConsole();

	// g_ConfigDB, command line args, globals
	CONFIG_Init(args);
	
	// Using a global object for the runtime is a workaround until Simulation and AI use 
	// their own threads and also their own runtimes.
	const int runtimeSize = 384 * 1024 * 1024;
	const int heapGrowthBytesGCTrigger = 20 * 1024 * 1024;
	g_ScriptRuntime = ScriptInterface::CreateRuntime(shared_ptr<ScriptRuntime>(), runtimeSize, heapGrowthBytesGCTrigger);

	// Special command-line mode to dump the entity schemas instead of running the game.
	// (This must be done after loading VFS etc, but should be done before wasting time
	// on anything else.)
	if (args.Has("dumpSchema"))
	{
		CSimulation2 sim(NULL, g_ScriptRuntime, NULL);
		sim.LoadDefaultScripts();
		std::ofstream f("entity.rng", std::ios_base::out | std::ios_base::trunc);
		f << sim.GenerateSchema();
		std::cout << "Generated entity.rng\n";
		exit(0);
	}

	// override ah_translate with our i18n code.
	AppHooks hooks = {0};
	hooks.translate = psTranslate;
	hooks.translate_free = psTranslateFree;
	app_hooks_update(&hooks);

	CNetHost::Initialize();

#if CONFIG2_AUDIO
	ISoundManager::CreateSoundManager();
#endif

	// Check if there are mods specified on the command line,
	// or if we already set the mods (~INIT_MODS),
	// else check if there are mods that should be loaded specified
	// in the config and load those (by aborting init and restarting
	// the engine).
	if (!args.Has("mod") && (flags & INIT_MODS) == INIT_MODS)
	{
		CStr modstring;
		CFG_GET_VAL("mod.enabledmods", modstring);
		if (!modstring.empty())
		{
			std::vector<CStr> mods;
			boost::split(mods, modstring, boost::is_any_of(" "), boost::token_compress_on);
			std::swap(g_modsLoaded, mods);

			// Abort init and restart
			restart_engine();
			return false;
		}
	}

	new L10n;

	// before scripting 
	// JS debugger temporarily disabled during the SpiderMonkey upgrade (check trac ticket #2348 for details)
	//if (g_JSDebuggerEnabled)
	//	g_DebuggingServer = new CDebuggingServer();

	// Optionally start profiler HTTP output automatically
	// (By default it's only enabled by a hotkey, for security/performance)
	bool profilerHTTPEnable = false;
	CFG_GET_VAL("profiler2.autoenable", profilerHTTPEnable);
	if (profilerHTTPEnable)
		g_Profiler2.EnableHTTP();

	if (!g_Quickstart)
		g_UserReporter.Initialize(); // after config

	PROFILE2_EVENT("Init finished");
	return true;
}
Пример #18
0
static void Frame()
{
	g_Profiler2.RecordFrameStart();
	PROFILE2("frame");
	g_Profiler2.IncrementFrameNumber();
	PROFILE2_ATTR("%d", g_Profiler2.GetFrameNumber());

	ogl_WarnIfError();

	// get elapsed time
	const double time = timer_Time();
	g_frequencyFilter->Update(time);
	// .. old method - "exact" but contains jumps
#if 0
	static double last_time;
	const double time = timer_Time();
	const float TimeSinceLastFrame = (float)(time-last_time);
	last_time = time;
	ONCE(return);	// first call: set last_time and return

	// .. new method - filtered and more smooth, but errors may accumulate
#else
	const float realTimeSinceLastFrame = 1.0 / g_frequencyFilter->SmoothedFrequency();
#endif
	ENSURE(realTimeSinceLastFrame > 0.0f);

	// decide if update/render is necessary
	bool need_render = !g_app_minimized;
	bool need_update = true;

	// If we are not running a multiplayer game, disable updates when the game is
	// minimized or out of focus and relinquish the CPU a bit, in order to make
	// debugging easier.
	if(g_PauseOnFocusLoss && !g_NetClient && !g_app_has_focus)
	{
		PROFILE3("non-focus delay");
		need_update = false;
		// don't use SDL_WaitEvent: don't want the main loop to freeze until app focus is restored
		SDL_Delay(10);
	}

	// Throttling: limit update and render frequency to the minimum to 50 FPS
	// in the "inactive" state, so that other windows get enough CPU time,
	// (and it's always nice for power+thermal management).
	// TODO: when the game performance is high enough, implementing a limit for
	// in-game framerate might be sensible.
	const float maxFPSMenu = 50.0;
	bool limit_fps = false;
	CFG_GET_VAL("gui.menu.limitfps", limit_fps);
	if (limit_fps && (!g_Game || !g_Game->IsGameStarted()))
	{
		float remainingFrameTime = (1000.0 / maxFPSMenu) - realTimeSinceLastFrame;
		if (remainingFrameTime > 0)
			SDL_Delay(remainingFrameTime);
	}


	// this scans for changed files/directories and reloads them, thus
	// allowing hotloading (changes are immediately assimilated in-game).
	ReloadChangedFiles();

	ProgressiveLoad();

	RendererIncrementalLoad();

	PumpEvents();

	// if the user quit by closing the window, the GL context will be broken and
	// may crash when we call Render() on some drivers, so leave this loop
	// before rendering
	if (quit)
		return;

	// respond to pumped resize events
	if (g_ResizedW || g_ResizedH)
	{
		g_VideoMode.ResizeWindow(g_ResizedW, g_ResizedH);
		g_ResizedW = g_ResizedH = 0;
	}

	if (g_NetClient)
		g_NetClient->Poll();

	ogl_WarnIfError();

	g_GUI->TickObjects();

	ogl_WarnIfError();

	if (g_Game && g_Game->IsGameStarted() && need_update)
	{
		g_Game->Update(realTimeSinceLastFrame);

		g_Game->GetView()->Update(float(realTimeSinceLastFrame));
	}

	// Immediately flush any messages produced by simulation code
	if (g_NetClient)
		g_NetClient->Flush();

	// Keep us connected to any XMPP servers
	if (g_XmppClient)
		g_XmppClient->recv();

	g_UserReporter.Update();

	g_Console->Update(realTimeSinceLastFrame);

	ogl_WarnIfError();
	if(need_render)
	{
		Render();

		PROFILE3("swap buffers");
		SDL_GL_SwapWindow(g_VideoMode.GetWindow());
	}
	ogl_WarnIfError();

	g_Profiler.Frame();

	g_GameRestarted = false;
}
Пример #19
0
bool CUserReporter::IsReportingEnabled()
{
	int version = -1;
	CFG_GET_VAL("userreport.enabledversion", version);
	return (version >= REPORTER_VERSION);
}
Пример #20
0
// Fill in the globals from the config files.
static void LoadGlobals()
{
    CFG_GET_VAL("vsync", g_VSync);

    CFG_GET_VAL("nos3tc", g_NoGLS3TC);
    CFG_GET_VAL("noautomipmap", g_NoGLAutoMipmap);
    CFG_GET_VAL("novbo", g_NoGLVBO);
    CFG_GET_VAL("pauseonfocusloss", g_PauseOnFocusLoss);
    CFG_GET_VAL("renderactors", g_RenderActors);
    CFG_GET_VAL("shadows", g_Shadows);
    CFG_GET_VAL("shadowpcf", g_ShadowPCF);

    CFG_GET_VAL("waterugly", g_WaterUgly);
    CFG_GET_VAL("waterfancyeffects", g_WaterFancyEffects);
    CFG_GET_VAL("waterrealdepth", g_WaterRealDepth);
    CFG_GET_VAL("waterrefraction", g_WaterRefraction);
    CFG_GET_VAL("waterreflection", g_WaterReflection);
    CFG_GET_VAL("shadowsonwater", g_WaterShadows);

    CFG_GET_VAL("renderpath", g_RenderPath);
    CFG_GET_VAL("particles", g_Particles);
    CFG_GET_VAL("silhouettes", g_Silhouettes);
    CFG_GET_VAL("showsky", g_ShowSky);
    CFG_GET_VAL("gui.scale", g_GuiScale);

    CFG_GET_VAL("jsdebugger.enable", g_JSDebuggerEnabled);
    CFG_GET_VAL("profiler2.script.enable", g_ScriptProfilingEnabled);

    if (g_JSDebuggerEnabled)
        LOGERROR("JS debugger temporarily disabled during the SpiderMonkey upgrade (check trac ticket #2348 for details)");
    // Script Debugging and profiling does not make sense together because of the hooks
    // that reduce performance a lot - and it wasn't tested if it even works together.
    if (g_JSDebuggerEnabled && g_ScriptProfilingEnabled)
        LOGERROR("Enabling both script profiling and script debugging is not supported!");
}
Пример #21
0
void InitGraphics(const CmdLineArgs& args, int flags)
{
	const bool setup_vmode = (flags & INIT_HAVE_VMODE) == 0;

	if(setup_vmode)
	{
		InitSDL();

		if (!g_VideoMode.InitSDL())
			throw PSERROR_System_VmodeFailed(); // abort startup

#if !SDL_VERSION_ATLEAST(2, 0, 0)
		SDL_WM_SetCaption("0 A.D.", "0 A.D.");
#endif
	}

	RunHardwareDetection();

	tex_codec_register_all();

	const int quality = SANE_TEX_QUALITY_DEFAULT;	// TODO: set value from config file
	SetTextureQuality(quality);

	ogl_WarnIfError();

	// Optionally start profiler GPU timings automatically
	// (By default it's only enabled by a hotkey, for performance/compatibility)
	bool profilerGPUEnable = false;
	CFG_GET_VAL("profiler2.gpu.autoenable", Bool, profilerGPUEnable);
	if (profilerGPUEnable)
		g_Profiler2.EnableGPU();

	if(!g_Quickstart)
	{
		WriteSystemInfo();
		// note: no longer vfs_display here. it's dog-slow due to unbuffered
		// file output and very rarely needed.
	}

	if(g_DisableAudio)
	{
		// speed up startup by disabling all sound
		// (OpenAL init will be skipped).
		// must be called before first snd_open.
#if CONFIG2_AUDIO
		CSoundManager::SetEnabled(false);
#endif
	}

	g_GUI = new CGUIManager(g_ScriptingHost.GetScriptInterface());

	// (must come after SetVideoMode, since it calls ogl_Init)
	const char* missing = ogl_HaveExtensions(0,
		"GL_ARB_multitexture",
		"GL_EXT_draw_range_elements",
		"GL_ARB_texture_env_combine",
		"GL_ARB_texture_env_dot3",
		NULL);
	if(missing)
	{
		wchar_t buf[500];
		swprintf_s(buf, ARRAY_SIZE(buf),
			L"The %hs extension doesn't appear to be available on your computer."
			L" The game may still work, though - you are welcome to try at your own risk."
			L" If not or it doesn't look right, upgrade your graphics card.",
			missing
		);
		DEBUG_DISPLAY_ERROR(buf);
		// TODO: i18n
	}

	if (!ogl_HaveExtension("GL_ARB_texture_env_crossbar"))
	{
		DEBUG_DISPLAY_ERROR(
			L"The GL_ARB_texture_env_crossbar extension doesn't appear to be available on your computer."
			L" Shadows are not available and overall graphics quality might suffer."
			L" You are advised to try installing newer drivers and/or upgrade your graphics card.");
		g_Shadows = false;
	}

	ogl_WarnIfError();
	InitRenderer();

	InitInput();

	ogl_WarnIfError();

	try
	{
		if (!Autostart(args))
		{
			const bool setup_gui = ((flags & INIT_NO_GUI) == 0);
			// We only want to display the splash screen at startup
			CScriptValRooted data;
			if (g_GUI)
			{
				ScriptInterface& scriptInterface = g_GUI->GetScriptInterface();
				scriptInterface.Eval("({})", data);
				scriptInterface.SetProperty(data.get(), "isStartup", true);
			}
			InitPs(setup_gui, L"page_pregame.xml", data.get());
		}
	}
	catch (PSERROR_Game_World_MapLoadFailed e)
	{
		// Map Loading failed

		// Start the engine so we have a GUI
		InitPs(true, L"page_pregame.xml", JSVAL_VOID);

		// Call script function to do the actual work
		//	(delete game data, switch GUI page, show error, etc.)
		CancelLoad(CStr(e.what()).FromUTF8());
	}
}
Пример #22
0
CMaterial CMaterialManager::LoadMaterial(const VfsPath& pathname)
{
	if (pathname.empty())
		return CMaterial();

	std::map<VfsPath, CMaterial>::iterator iter = m_Materials.find(pathname);
	if (iter != m_Materials.end())
		return iter->second;

	CXeromyces xeroFile;
	if (xeroFile.Load(g_VFS, pathname, "material") != PSRETURN_OK)
		return CMaterial();

	#define EL(x) int el_##x = xeroFile.GetElementID(#x)
	#define AT(x) int at_##x = xeroFile.GetAttributeID(#x)
	EL(alpha_blending);
	EL(alternative);
	EL(define);
	EL(shader);
	EL(uniform);
	EL(renderquery);
	EL(required_texture);
	EL(conditional_define);
	AT(effect);
	AT(if);
	AT(define);
	AT(quality);
	AT(material);
	AT(name);
	AT(value);
	AT(type);
	AT(min);
	AT(max);
	AT(conf);
	#undef AT
	#undef EL

	CMaterial material;

	XMBElement root = xeroFile.GetRoot();

	CPreprocessorWrapper preprocessor;
	preprocessor.AddDefine("CFG_FORCE_ALPHATEST", g_Renderer.m_Options.m_ForceAlphaTest ? "1" : "0");

	CVector4D vec(qualityLevel,0,0,0);
	material.AddStaticUniform("qualityLevel", vec);

	XERO_ITER_EL(root, node)
	{
		int token = node.GetNodeName();
		XMBAttributeList attrs = node.GetAttributes();
		if (token == el_alternative)
		{
			CStr cond = attrs.GetNamedItem(at_if);
			if (cond.empty() || !preprocessor.TestConditional(cond))
			{
				cond = attrs.GetNamedItem(at_quality);
				if (cond.empty())
					continue;
				else
				{
					if (cond.ToFloat() <= qualityLevel)
						continue;
				}
			}

			material = LoadMaterial(VfsPath("art/materials") / attrs.GetNamedItem(at_material).FromUTF8());
			break;
		}
		else if (token == el_alpha_blending)
		{
			material.SetUsesAlphaBlending(true);
		}
		else if (token == el_shader)
		{
			material.SetShaderEffect(attrs.GetNamedItem(at_effect));
		}
		else if (token == el_define)
		{
			material.AddShaderDefine(CStrIntern(attrs.GetNamedItem(at_name)), CStrIntern(attrs.GetNamedItem(at_value)));
		}
		else if (token == el_conditional_define)
		{
			std::vector<float> args;

			CStr type = attrs.GetNamedItem(at_type).c_str();
			int typeID = -1;

			if (type == CStr("draw_range"))
			{
				typeID = DCOND_DISTANCE;

				float valmin = -1.0f;
				float valmax = -1.0f;

				CStr conf = attrs.GetNamedItem(at_conf);
				if (!conf.empty())
				{
					CFG_GET_VAL("materialmgr." + conf + ".min", valmin);
					CFG_GET_VAL("materialmgr." + conf + ".max", valmax);
				}
				else
				{
					CStr dmin = attrs.GetNamedItem(at_min);
					if (!dmin.empty())
						valmin = attrs.GetNamedItem(at_min).ToFloat();

					CStr dmax = attrs.GetNamedItem(at_max);
					if (!dmax.empty())
						valmax = attrs.GetNamedItem(at_max).ToFloat();
				}

				args.push_back(valmin);
				args.push_back(valmax);

				if (valmin >= 0.0f)
				{
					std::stringstream sstr;
					sstr << valmin;
					material.AddShaderDefine(CStrIntern(conf + "_MIN"), CStrIntern(sstr.str()));
				}

				if (valmax >= 0.0f)
				{
					std::stringstream sstr;
					sstr << valmax;
					material.AddShaderDefine(CStrIntern(conf + "_MAX"), CStrIntern(sstr.str()));
				}
			}

			material.AddConditionalDefine(attrs.GetNamedItem(at_name).c_str(),
						      attrs.GetNamedItem(at_value).c_str(),
						      typeID, args);
		}
		else if (token == el_uniform)
		{
			std::stringstream str(attrs.GetNamedItem(at_value));
			CVector4D vec;
			str >> vec.X >> vec.Y >> vec.Z >> vec.W;
			material.AddStaticUniform(attrs.GetNamedItem(at_name).c_str(), vec);
		}
Пример #23
0
void* CNetServerWorker::SetupUPnP(void*)
{
	// Values we want to set.
	char psPort[6];
	sprintf_s(psPort, ARRAY_SIZE(psPort), "%d", PS_DEFAULT_PORT);
	const char* leaseDuration = "0"; // Indefinite/permanent lease duration.
	const char* description = "0AD Multiplayer";
	const char* protocall = "UDP";
	char internalIPAddress[64];
	char externalIPAddress[40];
	// Variables to hold the values that actually get set.
	char intClient[40];
	char intPort[6];
	char duration[16];
	// Intermediate variables.
	struct UPNPUrls urls;
	struct IGDdatas data;
	struct UPNPDev* devlist = NULL;

	// Cached root descriptor URL.
	std::string rootDescURL;
	CFG_GET_VAL("network.upnprootdescurl", rootDescURL);
	if (!rootDescURL.empty())
		LOGMESSAGE("Net server: attempting to use cached root descriptor URL: %s", rootDescURL.c_str());

	int ret = 0;
	bool allocatedUrls = false;

	// Try a cached URL first
	if (!rootDescURL.empty() && UPNP_GetIGDFromUrl(rootDescURL.c_str(), &urls, &data, internalIPAddress, sizeof(internalIPAddress)))
	{
		LOGMESSAGE("Net server: using cached IGD = %s", urls.controlURL);
		ret = 1;
	}
	// No cached URL, or it did not respond. Try getting a valid UPnP device for 10 seconds.
	else if ((devlist = upnpDiscover(10000, 0, 0, 0, 0, 0)) != NULL)
	{
		ret = UPNP_GetValidIGD(devlist, &urls, &data, internalIPAddress, sizeof(internalIPAddress));
		allocatedUrls = ret != 0; // urls is allocated on non-zero return values
	}
	else
	{
		LOGMESSAGE("Net server: upnpDiscover failed and no working cached URL.");
		return NULL;
	}

	switch (ret)
	{
	case 0:
		LOGMESSAGE("Net server: No IGD found");
		break;
	case 1:
		LOGMESSAGE("Net server: found valid IGD = %s", urls.controlURL);
		break;
	case 2:
		LOGMESSAGE("Net server: found a valid, not connected IGD = %s, will try to continue anyway", urls.controlURL);
		break;
	case 3:
		LOGMESSAGE("Net server: found a UPnP device unrecognized as IGD = %s, will try to continue anyway", urls.controlURL);
		break;
	default:
		debug_warn(L"Unrecognized return value from UPNP_GetValidIGD");
	}

	// Try getting our external/internet facing IP. TODO: Display this on the game-setup page for conviniance.
	ret = UPNP_GetExternalIPAddress(urls.controlURL, data.first.servicetype, externalIPAddress);
	if (ret != UPNPCOMMAND_SUCCESS)
	{
		LOGMESSAGE("Net server: GetExternalIPAddress failed with code %d (%s)", ret, strupnperror(ret));
		return NULL;
	}
	LOGMESSAGE("Net server: ExternalIPAddress = %s", externalIPAddress);

	// Try to setup port forwarding.
	ret = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype, psPort, psPort,
							internalIPAddress, description, protocall, 0, leaseDuration);
	if (ret != UPNPCOMMAND_SUCCESS)
	{
		LOGMESSAGE("Net server: AddPortMapping(%s, %s, %s) failed with code %d (%s)",
			   psPort, psPort, internalIPAddress, ret, strupnperror(ret));
		return NULL;
	}

	// Check that the port was actually forwarded.
	ret = UPNP_GetSpecificPortMappingEntry(urls.controlURL,
									 data.first.servicetype,
									 psPort, protocall,
#if defined(MINIUPNPC_API_VERSION) && MINIUPNPC_API_VERSION >= 10
									 NULL/*remoteHost*/,
#endif
									 intClient, intPort, NULL/*desc*/,
									 NULL/*enabled*/, duration);

	if (ret != UPNPCOMMAND_SUCCESS)
	{
		LOGMESSAGE("Net server: GetSpecificPortMappingEntry() failed with code %d (%s)", ret, strupnperror(ret));
		return NULL;
	}

	LOGMESSAGE("Net server: External %s:%s %s is redirected to internal %s:%s (duration=%s)",
				   externalIPAddress, psPort, protocall, intClient, intPort, duration);

	// Cache root descriptor URL to try to avoid discovery next time.
	g_ConfigDB.SetValueString(CFG_USER, "network.upnprootdescurl", urls.controlURL);
	g_ConfigDB.WriteFile(CFG_USER);
	LOGMESSAGE("Net server: cached UPnP root descriptor URL as %s", urls.controlURL);

	// Make sure everything is properly freed.
	if (allocatedUrls)
		FreeUPNPUrls(&urls);
    
	freeUPNPDevlist(devlist);

	return NULL;
}
Пример #24
0
void Render()
{
	PROFILE3("render");

	if (g_SoundManager)
		g_SoundManager->IdleTask();

	ogl_WarnIfError();

	g_Profiler2.RecordGPUFrameStart();

	ogl_WarnIfError();

	// prepare before starting the renderer frame
	if (g_Game && g_Game->IsGameStarted())
		g_Game->GetView()->BeginFrame();

	if (g_Game)
		g_Renderer.SetSimulation(g_Game->GetSimulation2());

	// start new frame
	g_Renderer.BeginFrame();

	ogl_WarnIfError();

	if (g_Game && g_Game->IsGameStarted())
		g_Game->GetView()->Render();

	ogl_WarnIfError();

	g_Renderer.RenderTextOverlays();

	if (g_DoRenderGui)
		g_GUI->Draw();

	ogl_WarnIfError();

	// If we're in Atlas game view, render special overlays (e.g. editor bandbox)
	if (g_AtlasGameLoop && g_AtlasGameLoop->view)
	{
		g_AtlasGameLoop->view->DrawOverlays();
		ogl_WarnIfError();
	}

	// Text:

 	glDisable(GL_DEPTH_TEST);

	g_Console->Render();

	ogl_WarnIfError();

	if (g_DoRenderLogger)
		g_Logger->Render();

	ogl_WarnIfError();

	// Profile information

	g_ProfileViewer.RenderProfile();

	ogl_WarnIfError();

	// Draw the cursor (or set the Windows cursor, on Windows)
	if (g_DoRenderCursor)
	{
		PROFILE3_GPU("cursor");
		CStrW cursorName = g_CursorName;
		if (cursorName.empty())
		{
			cursor_draw(g_VFS, NULL, g_mouse_x, g_yres-g_mouse_y, false);
		}
		else
		{
			bool forceGL = false;
			CFG_GET_VAL("nohwcursor", forceGL);

#if CONFIG2_GLES
#warning TODO: implement cursors for GLES
#else
			// set up transform for GL cursor
			glMatrixMode(GL_PROJECTION);
			glPushMatrix();
			glLoadIdentity();
			glMatrixMode(GL_MODELVIEW);
			glPushMatrix();
			glLoadIdentity();
			CMatrix3D transform;
			transform.SetOrtho(0.f, (float)g_xres, 0.f, (float)g_yres, -1.f, 1000.f);
			glLoadMatrixf(&transform._11);
#endif

#if OS_ANDROID
#warning TODO: cursors for Android
#else
			if (cursor_draw(g_VFS, cursorName.c_str(), g_mouse_x, g_yres-g_mouse_y, forceGL) < 0)
				LOGWARNING("Failed to draw cursor '%s'", utf8_from_wstring(cursorName));
#endif

#if CONFIG2_GLES
#warning TODO: implement cursors for GLES
#else
			// restore transform
			glMatrixMode(GL_PROJECTION);
			glPopMatrix();
			glMatrixMode(GL_MODELVIEW);
			glPopMatrix();
#endif
		}
	}

	glEnable(GL_DEPTH_TEST);

	g_Renderer.EndFrame();

	PROFILE2_ATTR("draw calls: %d", (int)g_Renderer.GetStats().m_DrawCalls);
	PROFILE2_ATTR("terrain tris: %d", (int)g_Renderer.GetStats().m_TerrainTris);
	PROFILE2_ATTR("water tris: %d", (int)g_Renderer.GetStats().m_WaterTris);
	PROFILE2_ATTR("model tris: %d", (int)g_Renderer.GetStats().m_ModelTris);
	PROFILE2_ATTR("overlay tris: %d", (int)g_Renderer.GetStats().m_OverlayTris);
	PROFILE2_ATTR("blend splats: %d", (int)g_Renderer.GetStats().m_BlendSplats);
	PROFILE2_ATTR("particles: %d", (int)g_Renderer.GetStats().m_Particles);

	ogl_WarnIfError();

	g_Profiler2.RecordGPUFrameEnd();

	ogl_WarnIfError();
}
Пример #25
0
int CGameView::Initialize()
{
	CFG_GET_VAL("view.scroll.speed", m->ViewScrollSpeed);
	CFG_GET_VAL("view.scroll.speed.modifier", m->ViewScrollSpeedModifier);
	CFG_GET_VAL("view.rotate.x.speed", m->ViewRotateXSpeed);
	CFG_GET_VAL("view.rotate.x.min", m->ViewRotateXMin);
	CFG_GET_VAL("view.rotate.x.max", m->ViewRotateXMax);
	CFG_GET_VAL("view.rotate.x.default", m->ViewRotateXDefault);
	CFG_GET_VAL("view.rotate.y.speed", m->ViewRotateYSpeed);
	CFG_GET_VAL("view.rotate.y.speed.wheel", m->ViewRotateYSpeedWheel);
	CFG_GET_VAL("view.rotate.y.default", m->ViewRotateYDefault);
	CFG_GET_VAL("view.rotate.speed.modifier", m->ViewRotateSpeedModifier);
	CFG_GET_VAL("view.drag.speed", m->ViewDragSpeed);
	CFG_GET_VAL("view.zoom.speed", m->ViewZoomSpeed);
	CFG_GET_VAL("view.zoom.speed.wheel", m->ViewZoomSpeedWheel);
	CFG_GET_VAL("view.zoom.min", m->ViewZoomMin);
	CFG_GET_VAL("view.zoom.max", m->ViewZoomMax);
	CFG_GET_VAL("view.zoom.default", m->ViewZoomDefault);
	CFG_GET_VAL("view.zoom.speed.modifier", m->ViewZoomSpeedModifier);

	CFG_GET_VAL("joystick.camera.pan.x", m->JoystickPanX);
	CFG_GET_VAL("joystick.camera.pan.y", m->JoystickPanY);
	CFG_GET_VAL("joystick.camera.rotate.x", m->JoystickRotateX);
	CFG_GET_VAL("joystick.camera.rotate.y", m->JoystickRotateY);
	CFG_GET_VAL("joystick.camera.zoom.in", m->JoystickZoomIn);
	CFG_GET_VAL("joystick.camera.zoom.out", m->JoystickZoomOut);

	CFG_GET_VAL("view.height.smoothness", m->HeightSmoothness);
	CFG_GET_VAL("view.height.min", m->HeightMin);

	CFG_GET_VAL("view.pos.smoothness", m->PosX.m_Smoothness);
	CFG_GET_VAL("view.pos.smoothness", m->PosY.m_Smoothness);
	CFG_GET_VAL("view.pos.smoothness", m->PosZ.m_Smoothness);
	CFG_GET_VAL("view.zoom.smoothness", m->Zoom.m_Smoothness);
	CFG_GET_VAL("view.rotate.x.smoothness", m->RotateX.m_Smoothness);
	CFG_GET_VAL("view.rotate.y.smoothness", m->RotateY.m_Smoothness);

	CFG_GET_VAL("view.near", m->ViewNear);
	CFG_GET_VAL("view.far", m->ViewFar);
	CFG_GET_VAL("view.fov", m->ViewFOV);

	// Convert to radians
	m->RotateX.SetValue(DEGTORAD(m->ViewRotateXDefault));
	m->RotateY.SetValue(DEGTORAD(m->ViewRotateYDefault));
	m->ViewFOV = DEGTORAD(m->ViewFOV);

	return 0;
}
Пример #26
0
// Fill in the globals from the config files.
static void LoadGlobals()
{
	CFG_GET_VAL("vsync", Bool, g_VSync);

	CFG_GET_VAL("nos3tc", Bool, g_NoGLS3TC);
	CFG_GET_VAL("noautomipmap", Bool, g_NoGLAutoMipmap);
	CFG_GET_VAL("novbo", Bool, g_NoGLVBO);
	CFG_GET_VAL("pauseonfocusloss", Bool, g_PauseOnFocusLoss);
	CFG_GET_VAL("shadows", Bool, g_Shadows);
	CFG_GET_VAL("shadowpcf", Bool, g_ShadowPCF);

	CFG_GET_VAL("waternormals",Bool, g_WaterNormal);
	CFG_GET_VAL("waterrealdepth",Bool, g_WaterRealDepth);
	CFG_GET_VAL("waterfoam",Bool, g_WaterFoam);
	CFG_GET_VAL("watercoastalwaves",Bool, g_WaterCoastalWaves);
	if (g_WaterCoastalWaves && !g_WaterNormal)
		g_WaterCoastalWaves = false;
	CFG_GET_VAL("waterrefraction",Bool, g_WaterRefraction);
	CFG_GET_VAL("waterreflection",Bool, g_WaterReflection);
	CFG_GET_VAL("watershadows",Bool, g_WaterShadows);

	CFG_GET_VAL("renderpath", String, g_RenderPath);
	CFG_GET_VAL("particles", Bool, g_Particles);
	CFG_GET_VAL("silhouettes", Bool, g_Silhouettes);
	CFG_GET_VAL("showsky", Bool, g_ShowSky);

#if CONFIG2_AUDIO
	float gain = 0.5f;
	float musicGain = 0.5f;
	float ambientGain = 0.5f;
	float actionGain = 0.5f;
	int bufferCount = 50;
	unsigned long bufferSize = 65536;

	CFG_GET_VAL("sound.mastergain", Float, gain);
	CFG_GET_VAL("sound.musicgain", Float, musicGain);
	CFG_GET_VAL("sound.ambientgain", Float, ambientGain);
	CFG_GET_VAL("sound.actiongain", Float, actionGain);

	CFG_GET_VAL("sound.bufferCount", Int, bufferCount);
	CFG_GET_VAL("sound.bufferSize", UnsignedLong, bufferSize);

	if (g_SoundManager) {
		g_SoundManager->SetMasterGain(gain);
		g_SoundManager->SetMusicGain(musicGain);
		g_SoundManager->SetAmbientGain(ambientGain);
		g_SoundManager->SetActionGain(actionGain);

		g_SoundManager->SetMemoryUsage(bufferSize, bufferCount);
	}
#endif // CONFIG2_AUDIO

	CFG_GET_VAL("jsdebugger.enable", Bool, g_JSDebuggerEnabled);
	CFG_GET_VAL("profiler2.script.enable", Bool, g_ScriptProfilingEnabled);

	// Script Debugging and profiling does not make sense together because of the hooks
	// that reduce performance a lot - and it wasn't tested if it even works together.
	if (g_JSDebuggerEnabled && g_ScriptProfilingEnabled)
		LOGERROR(L"Enabling both script profiling and script debugging is not supported!");
}
Пример #27
0
void Init(const CmdLineArgs& args, int UNUSED(flags))
{
	h_mgr_init();

	// Do this as soon as possible, because it chdirs
	// and will mess up the error reporting if anything
	// crashes before the working directory is set.
	InitVfs(args);

	// This must come after VFS init, which sets the current directory
	// (required for finding our output log files).
	g_Logger = new CLogger;

	// Special command-line mode to dump the entity schemas instead of running the game.
	// (This must be done after loading VFS etc, but should be done before wasting time
	// on anything else.)
	if (args.Has("dumpSchema"))
	{
		CSimulation2 sim(NULL, NULL);
		sim.LoadDefaultScripts();
		std::ofstream f("entity.rng", std::ios_base::out | std::ios_base::trunc);
		f << sim.GenerateSchema();
		std::cout << "Generated entity.rng\n";
		exit(0);
	}

	// override ah_translate with our i18n code.
	AppHooks hooks = {0};
	hooks.translate = psTranslate;
	hooks.translate_free = psTranslateFree;
	app_hooks_update(&hooks);

	// Set up the console early, so that debugging
	// messages can be logged to it. (The console's size
	// and fonts are set later in InitPs())
	g_Console = new CConsole();

	CNetHost::Initialize();

	new CProfileViewer;
	new CProfileManager;	// before any script code

	g_ScriptStatsTable = new CScriptStatsTable;
	g_ProfileViewer.AddRootTable(g_ScriptStatsTable);


#if CONFIG2_AUDIO
	CSoundManager::CreateSoundManager();
#endif

	InitScripting();	// before GUI

	// g_ConfigDB, command line args, globals
	CONFIG_Init(args);

	// Optionally start profiler HTTP output automatically
	// (By default it's only enabled by a hotkey, for security/performance)
	bool profilerHTTPEnable = false;
	CFG_GET_VAL("profiler2.http.autoenable", Bool, profilerHTTPEnable);
	if (profilerHTTPEnable)
		g_Profiler2.EnableHTTP();

	if (!g_Quickstart)
		g_UserReporter.Initialize(); // after config

	PROFILE2_EVENT("Init finished");
}