Add proper initializations and remove manual memory management in app classes

master
Piotr Dziwinski 2015-08-07 08:31:34 +02:00
parent 22415e183d
commit e9e1c8d4dd
16 changed files with 194 additions and 196 deletions

View File

@ -100,11 +100,14 @@ struct ApplicationPrivate
CApplication::CApplication() CApplication::CApplication(CSystemUtils* systemUtils)
: m_private(MakeUnique<ApplicationPrivate>()) : m_systemUtils(systemUtils),
, m_configFile(MakeUnique<CConfigFile>()) m_private(MakeUnique<ApplicationPrivate>()),
, m_input(MakeUnique<CInput>()) m_configFile(MakeUnique<CConfigFile>()),
, m_pathManager(MakeUnique<CPathManager>()) m_input(MakeUnique<CInput>()),
m_pathManager(MakeUnique<CPathManager>(systemUtils)),
m_performanceCounters(),
m_performanceCountersData()
{ {
m_exitCode = 0; m_exitCode = 0;
m_active = false; m_active = false;
@ -128,14 +131,14 @@ CApplication::CApplication()
m_absTime = 0.0f; m_absTime = 0.0f;
m_relTime = 0.0f; m_relTime = 0.0f;
m_baseTimeStamp = GetSystemUtils()->CreateTimeStamp(); m_baseTimeStamp = m_systemUtils->CreateTimeStamp();
m_curTimeStamp = GetSystemUtils()->CreateTimeStamp(); m_curTimeStamp = m_systemUtils->CreateTimeStamp();
m_lastTimeStamp = GetSystemUtils()->CreateTimeStamp(); m_lastTimeStamp = m_systemUtils->CreateTimeStamp();
for (int i = 0; i < PCNT_MAX; ++i) for (int i = 0; i < PCNT_MAX; ++i)
{ {
m_performanceCounters[i][0] = GetSystemUtils()->CreateTimeStamp(); m_performanceCounters[i][0] = m_systemUtils->CreateTimeStamp();
m_performanceCounters[i][1] = GetSystemUtils()->CreateTimeStamp(); m_performanceCounters[i][1] = m_systemUtils->CreateTimeStamp();
} }
m_joystickEnabled = false; m_joystickEnabled = false;
@ -158,15 +161,51 @@ CApplication::CApplication()
CApplication::~CApplication() CApplication::~CApplication()
{ {
GetSystemUtils()->DestroyTimeStamp(m_baseTimeStamp); m_systemUtils->DestroyTimeStamp(m_baseTimeStamp);
GetSystemUtils()->DestroyTimeStamp(m_curTimeStamp); m_systemUtils->DestroyTimeStamp(m_curTimeStamp);
GetSystemUtils()->DestroyTimeStamp(m_lastTimeStamp); m_systemUtils->DestroyTimeStamp(m_lastTimeStamp);
for (int i = 0; i < PCNT_MAX; ++i) for (int i = 0; i < PCNT_MAX; ++i)
{ {
GetSystemUtils()->DestroyTimeStamp(m_performanceCounters[i][0]); m_systemUtils->DestroyTimeStamp(m_performanceCounters[i][0]);
GetSystemUtils()->DestroyTimeStamp(m_performanceCounters[i][1]); m_systemUtils->DestroyTimeStamp(m_performanceCounters[i][1]);
} }
m_joystickEnabled = false;
m_controller.reset();
m_sound.reset();
if (m_engine != nullptr)
{
m_engine->Destroy();
m_engine.reset();
}
if (m_device != nullptr)
{
m_device->Destroy();
m_device.reset();
}
if (m_private->joystick != nullptr)
{
SDL_JoystickClose(m_private->joystick);
m_private->joystick = nullptr;
}
if (m_private->surface != nullptr)
{
SDL_FreeSurface(m_private->surface);
m_private->surface = nullptr;
}
IMG_Quit();
if (SDL_WasInit(0))
SDL_Quit();
} }
CEventQueue* CApplication::GetEventQueue() CEventQueue* CApplication::GetEventQueue()
@ -558,7 +597,7 @@ bool CApplication::Create()
{ {
GetLogger()->Error("Unknown graphics device: %s\n", m_graphics.c_str()); GetLogger()->Error("Unknown graphics device: %s\n", m_graphics.c_str());
GetLogger()->Info("Changing to default device\n"); GetLogger()->Info("Changing to default device\n");
GetSystemUtils()->SystemDialog(SDT_ERROR, "Graphics initialization error", "You have selected invalid graphics device with -graphics switch. Game will use default OpenGL device instead."); m_systemUtils->SystemDialog(SDT_ERROR, "Graphics initialization error", "You have selected invalid graphics device with -graphics switch. Game will use default OpenGL device instead.");
m_device = Gfx::CreateDevice(m_deviceConfig, "opengl"); m_device = Gfx::CreateDevice(m_deviceConfig, "opengl");
} }
} }
@ -575,7 +614,7 @@ bool CApplication::Create()
} }
// Create the 3D engine // Create the 3D engine
m_engine = MakeUnique<Gfx::CEngine>(this); m_engine = MakeUnique<Gfx::CEngine>(this, m_systemUtils);
m_engine->SetDevice(m_device.get()); m_engine->SetDevice(m_device.get());
@ -654,44 +693,6 @@ bool CApplication::CreateVideoSurface()
return true; return true;
} }
void CApplication::Destroy()
{
m_joystickEnabled = false;
m_controller.reset();
m_sound.reset();
if (m_engine != nullptr)
{
m_engine->Destroy();
m_engine.reset();
}
if (m_device != nullptr)
{
m_device->Destroy();
m_device.reset();
}
if (m_private->joystick != nullptr)
{
SDL_JoystickClose(m_private->joystick);
m_private->joystick = nullptr;
}
if (m_private->surface != nullptr)
{
SDL_FreeSurface(m_private->surface);
m_private->surface = nullptr;
}
IMG_Quit();
SDL_Quit();
}
void CApplication::Restart() void CApplication::Restart()
{ {
m_restart = true; m_restart = true;
@ -728,7 +729,7 @@ bool CApplication::ChangeVideoConfig(const Gfx::DeviceConfig &newConfig)
std::string(SDL_GetError()) + std::string("\n") + std::string(SDL_GetError()) + std::string("\n") +
std::string("Previous mode will be restored"); std::string("Previous mode will be restored");
GetLogger()->Error(error.c_str()); GetLogger()->Error(error.c_str());
GetSystemUtils()->SystemDialog( SDT_ERROR, "COLOBOT - Error", error); m_systemUtils->SystemDialog( SDT_ERROR, "COLOBOT - Error", error);
restore = true; restore = true;
ChangeVideoConfig(m_lastDeviceConfig); ChangeVideoConfig(m_lastDeviceConfig);
@ -741,7 +742,7 @@ bool CApplication::ChangeVideoConfig(const Gfx::DeviceConfig &newConfig)
std::string error = std::string("SDL error while restoring previous video mode:\n") + std::string error = std::string("SDL error while restoring previous video mode:\n") +
std::string(SDL_GetError()); std::string(SDL_GetError());
GetLogger()->Error(error.c_str()); GetLogger()->Error(error.c_str());
GetSystemUtils()->SystemDialog( SDT_ERROR, "COLOBOT - Fatal Error", error); m_systemUtils->SystemDialog( SDT_ERROR, "COLOBOT - Fatal Error", error);
// Fatal error, so post the quit event // Fatal error, so post the quit event
@ -885,9 +886,9 @@ int CApplication::Run()
{ {
m_active = true; m_active = true;
GetSystemUtils()->GetCurrentTimeStamp(m_baseTimeStamp); m_systemUtils->GetCurrentTimeStamp(m_baseTimeStamp);
GetSystemUtils()->GetCurrentTimeStamp(m_lastTimeStamp); m_systemUtils->GetCurrentTimeStamp(m_lastTimeStamp);
GetSystemUtils()->GetCurrentTimeStamp(m_curTimeStamp); m_systemUtils->GetCurrentTimeStamp(m_curTimeStamp);
MoveMouse(Math::Point(0.5f, 0.5f)); // center mouse on start MoveMouse(Math::Point(0.5f, 0.5f)); // center mouse on start
@ -1022,14 +1023,12 @@ int CApplication::Run()
if (m_lowCPU) if (m_lowCPU)
{ {
GetSystemUtils()->Usleep(20000); // should still give plenty of fps m_systemUtils->Usleep(20000); // should still give plenty of fps
} }
} }
} }
end: end:
Destroy();
return m_exitCode; return m_exitCode;
} }
@ -1339,8 +1338,8 @@ void CApplication::ResetTimeAfterLoading()
void CApplication::InternalResumeSimulation() void CApplication::InternalResumeSimulation()
{ {
GetSystemUtils()->GetCurrentTimeStamp(m_baseTimeStamp); m_systemUtils->GetCurrentTimeStamp(m_baseTimeStamp);
GetSystemUtils()->CopyTimeStamp(m_curTimeStamp, m_baseTimeStamp); m_systemUtils->CopyTimeStamp(m_curTimeStamp, m_baseTimeStamp);
m_realAbsTimeBase = m_realAbsTime; m_realAbsTimeBase = m_realAbsTime;
m_absTimeBase = m_exactAbsTime; m_absTimeBase = m_exactAbsTime;
} }
@ -1354,7 +1353,7 @@ void CApplication::SetSimulationSpeed(float speed)
{ {
m_simulationSpeed = speed; m_simulationSpeed = speed;
GetSystemUtils()->GetCurrentTimeStamp(m_baseTimeStamp); m_systemUtils->GetCurrentTimeStamp(m_baseTimeStamp);
m_realAbsTimeBase = m_realAbsTime; m_realAbsTimeBase = m_realAbsTime;
m_absTimeBase = m_exactAbsTime; m_absTimeBase = m_exactAbsTime;
@ -1366,12 +1365,12 @@ Event CApplication::CreateUpdateEvent()
if (m_simulationSuspended) if (m_simulationSuspended)
return Event(EVENT_NULL); return Event(EVENT_NULL);
GetSystemUtils()->CopyTimeStamp(m_lastTimeStamp, m_curTimeStamp); m_systemUtils->CopyTimeStamp(m_lastTimeStamp, m_curTimeStamp);
GetSystemUtils()->GetCurrentTimeStamp(m_curTimeStamp); m_systemUtils->GetCurrentTimeStamp(m_curTimeStamp);
long long absDiff = GetSystemUtils()->TimeStampExactDiff(m_baseTimeStamp, m_curTimeStamp); long long absDiff = m_systemUtils->TimeStampExactDiff(m_baseTimeStamp, m_curTimeStamp);
long long newRealAbsTime = m_realAbsTimeBase + absDiff; long long newRealAbsTime = m_realAbsTimeBase + absDiff;
long long newRealRelTime = GetSystemUtils()->TimeStampExactDiff(m_lastTimeStamp, m_curTimeStamp); long long newRealRelTime = m_systemUtils->TimeStampExactDiff(m_lastTimeStamp, m_curTimeStamp);
if (newRealAbsTime < m_realAbsTime || newRealRelTime < 0) if (newRealAbsTime < m_realAbsTime || newRealRelTime < 0)
{ {
@ -1804,12 +1803,12 @@ bool CApplication::GetLowCPU() const
void CApplication::StartPerformanceCounter(PerformanceCounter counter) void CApplication::StartPerformanceCounter(PerformanceCounter counter)
{ {
GetSystemUtils()->GetCurrentTimeStamp(m_performanceCounters[counter][0]); m_systemUtils->GetCurrentTimeStamp(m_performanceCounters[counter][0]);
} }
void CApplication::StopPerformanceCounter(PerformanceCounter counter) void CApplication::StopPerformanceCounter(PerformanceCounter counter)
{ {
GetSystemUtils()->GetCurrentTimeStamp(m_performanceCounters[counter][1]); m_systemUtils->GetCurrentTimeStamp(m_performanceCounters[counter][1]);
} }
float CApplication::GetPerformanceCounterData(PerformanceCounter counter) const float CApplication::GetPerformanceCounterData(PerformanceCounter counter) const
@ -1828,13 +1827,13 @@ void CApplication::ResetPerformanceCounters()
void CApplication::UpdatePerformanceCountersData() void CApplication::UpdatePerformanceCountersData()
{ {
long long sum = GetSystemUtils()->TimeStampExactDiff(m_performanceCounters[PCNT_ALL][0], long long sum = m_systemUtils->TimeStampExactDiff(m_performanceCounters[PCNT_ALL][0],
m_performanceCounters[PCNT_ALL][1]); m_performanceCounters[PCNT_ALL][1]);
for (int i = 0; i < PCNT_MAX; ++i) for (int i = 0; i < PCNT_MAX; ++i)
{ {
long long diff = GetSystemUtils()->TimeStampExactDiff(m_performanceCounters[i][0], long long diff = m_systemUtils->TimeStampExactDiff(m_performanceCounters[i][0],
m_performanceCounters[i][1]); m_performanceCounters[i][1]);
m_performanceCountersData[static_cast<PerformanceCounter>(i)] = m_performanceCountersData[static_cast<PerformanceCounter>(i)] =
static_cast<float>(diff) / static_cast<float>(sum); static_cast<float>(diff) / static_cast<float>(sum);

View File

@ -31,8 +31,6 @@
#include "graphics/core/device.h" #include "graphics/core/device.h"
#include "graphics/engine/engine.h"
#include "object/level_category.h" #include "object/level_category.h"
@ -44,12 +42,13 @@ class CEventQueue;
class CController; class CController;
class CSoundInterface; class CSoundInterface;
class CInput; class CInput;
class CObjectManager;
class CPathManager; class CPathManager;
class CSystemUtils;
struct SystemTimeStamp;
namespace Gfx namespace Gfx
{ {
class CModelManager; class CEngine;
} }
/** /**
@ -190,7 +189,7 @@ class CApplication : public CSingleton<CApplication>
{ {
public: public:
//! Constructor (can only be called once!) //! Constructor (can only be called once!)
CApplication(); CApplication(CSystemUtils* systemUtils);
//! Destructor //! Destructor
~CApplication(); ~CApplication();
@ -212,9 +211,6 @@ public:
//! Returns the message of error (set to something if exit code is not 0) //! Returns the message of error (set to something if exit code is not 0)
const std::string& GetErrorMessage() const; const std::string& GetErrorMessage() const;
//! Cleans up before exit
void Destroy();
//! Restart //! Restart
void Restart(); void Restart();
//! Should we restart after app quits? //! Should we restart after app quits?
@ -357,6 +353,8 @@ protected:
void UpdatePerformanceCountersData(); void UpdatePerformanceCountersData();
protected: protected:
//! System utils instance
CSystemUtils* m_systemUtils;
//! Private (SDL-dependent data) //! Private (SDL-dependent data)
std::unique_ptr<ApplicationPrivate> m_private; std::unique_ptr<ApplicationPrivate> m_private;
//! Global event queue //! Global event queue

View File

@ -35,6 +35,7 @@
template<> CInput* CSingleton<CInput>::m_instance = nullptr; template<> CInput* CSingleton<CInput>::m_instance = nullptr;
CInput::CInput() CInput::CInput()
: m_keyPresses()
{ {
m_keyTable = m_keyTable =
{ {

View File

@ -53,9 +53,9 @@ struct InputBinding
struct JoyAxisBinding struct JoyAxisBinding
{ {
//! Axis index or AXIS_INVALID //! Axis index or AXIS_INVALID
int axis; int axis = 0;
//! True to invert axis value //! True to invert axis value
bool invert; bool invert = false;
}; };
//! Invalid value for axis binding (no axis assigned) //! Invalid value for axis binding (no axis assigned)

View File

@ -31,7 +31,7 @@
#endif #endif
#include "common/logger.h" #include "common/logger.h"
#include "common/misc.h" #include "common/make_unique.h"
#include "common/restext.h" #include "common/restext.h"
#include "common/resources/resourcemanager.h" #include "common/resources/resourcemanager.h"
@ -40,6 +40,8 @@
#include <windows.h> #include <windows.h>
#endif #endif
#include <memory>
#include <vector>
/* Doxygen main page */ /* Doxygen main page */
@ -91,20 +93,30 @@ int SDL_MAIN_FUNC(int argc, char *argv[])
// Workaround for character encoding in argv on Windows // Workaround for character encoding in argv on Windows
#if PLATFORM_WINDOWS #if PLATFORM_WINDOWS
int wargc; int wargc = 0;
wchar_t** wargv = CommandLineToArgvW(GetCommandLineW(), &wargc); wchar_t** wargv = CommandLineToArgvW(GetCommandLineW(), &wargc);
if(wargv == nullptr) if (wargv == nullptr)
{ {
logger.Error("CommandLineToArgvW failed\n"); logger.Error("CommandLineToArgvW failed\n");
return 1; return 1;
} }
argv = new char*[wargc];
for(int i = 0; i < wargc; i++) { std::vector<std::vector<char>> windowsArgs;
for (int i = 0; i < wargc; i++)
{
std::wstring warg = wargv[i]; std::wstring warg = wargv[i];
std::string arg = CSystemUtilsWindows::UTF8_Encode(warg); std::string arg = CSystemUtilsWindows::UTF8_Encode(warg);
argv[i] = new char[arg.length()+1]; std::vector<char> argVec(arg.begin(), arg.end());
strcpy(argv[i], arg.c_str()); argVec.push_back('\0');
windowsArgs.push_back(std::move(argVec));
} }
auto windowsArgvPtrs = MakeUniqueArray<char*>(wargc);
for (int i = 0; i < wargc; i++)
windowsArgvPtrs[i] = windowsArgs[i].data();
argv = windowsArgvPtrs.get();
LocalFree(wargv); LocalFree(wargv);
#endif #endif
@ -119,50 +131,44 @@ int SDL_MAIN_FUNC(int argc, char *argv[])
int code = 0; int code = 0;
while (true) while (true)
{ {
CSystemUtils* systemUtils = CSystemUtils::Create(); // platform-specific utils auto systemUtils = CSystemUtils::Create(); // platform-specific utils
systemUtils->Init(); systemUtils->Init();
CApplication* app = new CApplication(); // single instance of the application CApplication app(systemUtils.get()); // single instance of the application
ParseArgsStatus status = app->ParseArguments(argc, argv); ParseArgsStatus status = app.ParseArguments(argc, argv);
if (status == PARSE_ARGS_FAIL) if (status == PARSE_ARGS_FAIL)
{ {
systemUtils->SystemDialog(SDT_ERROR, "COLOBOT - Fatal Error", "Invalid commandline arguments!\n"); systemUtils->SystemDialog(SDT_ERROR, "COLOBOT - Fatal Error", "Invalid commandline arguments!\n");
return app->GetExitCode(); return app.GetExitCode();
} }
else if (status == PARSE_ARGS_HELP) else if (status == PARSE_ARGS_HELP)
{ {
return app->GetExitCode(); return app.GetExitCode();
} }
if (! app->Create()) if (! app.Create())
{ {
app->Destroy(); // ensure a clean exit code = app.GetExitCode();
code = app->GetExitCode(); if (code != 0 && !app.GetErrorMessage().empty())
if ( code != 0 && !app->GetErrorMessage().empty() )
{ {
systemUtils->SystemDialog(SDT_ERROR, "COLOBOT - Fatal Error", app->GetErrorMessage()); systemUtils->SystemDialog(SDT_ERROR, "COLOBOT - Fatal Error", app.GetErrorMessage());
} }
logger.Info("Didn't run main loop. Exiting with code %d\n", code); logger.Info("Didn't run main loop. Exiting with code %d\n", code);
return code; return code;
} }
code = app->Run(); code = app.Run();
bool restarting = app->IsRestarting();
delete app; bool restarting = app.IsRestarting();
delete systemUtils;
if(!restarting) break; if (!restarting)
break;
} }
logger.Info("Exiting with code %d\n", code); logger.Info("Exiting with code %d\n", code);
#if PLATFORM_WINDOWS
// See the workaround above
delete[] argv;
#endif
return code; return code;
} }

View File

@ -22,6 +22,8 @@
#include "common/config.h" #include "common/config.h"
#include "common/make_unique.h"
#if defined(PLATFORM_WINDOWS) #if defined(PLATFORM_WINDOWS)
#include "app/system_windows.h" #include "app/system_windows.h"
@ -37,25 +39,24 @@
#include <iostream> #include <iostream>
template<> std::unique_ptr<CSystemUtils> CSystemUtils::Create()
CSystemUtils* CSingleton<CSystemUtils>::m_instance = nullptr;
CSystemUtils* CSystemUtils::Create()
{ {
assert(m_instance == nullptr); std::unique_ptr<CSystemUtils> instance;
#if defined(PLATFORM_WINDOWS) #if defined(PLATFORM_WINDOWS)
m_instance = new CSystemUtilsWindows(); instance = MakeUnique<CSystemUtilsWindows>();
#elif defined(PLATFORM_LINUX) #elif defined(PLATFORM_LINUX)
m_instance = new CSystemUtilsLinux(); instance = MakeUnique<CSystemUtilsLinux>();
#elif defined(PLATFORM_MACOSX) #elif defined(PLATFORM_MACOSX)
m_instance = new CSystemUtilsMacOSX(); instance = MakeUnique<CSystemUtilsMacOSX>();
#else #else
m_instance = new CSystemUtilsOther(); instance = MakeUnique<CSystemUtilsOther>();
#endif #endif
return m_instance; return instance;
} }
CSystemUtils::~CSystemUtils()
{}
SystemDialogResult CSystemUtils::ConsoleSystemDialog(SystemDialogType type, const std::string& title, const std::string& message) SystemDialogResult CSystemUtils::ConsoleSystemDialog(SystemDialogType type, const std::string& title, const std::string& message)
{ {
switch (type) switch (type)
@ -144,12 +145,19 @@ SystemDialogResult CSystemUtils::ConsoleSystemDialog(SystemDialogType type, cons
SystemTimeStamp* CSystemUtils::CreateTimeStamp() SystemTimeStamp* CSystemUtils::CreateTimeStamp()
{ {
return new SystemTimeStamp(); auto timeStamp = MakeUnique<SystemTimeStamp>();
SystemTimeStamp* timeStampPtr = timeStamp.get();
m_timeStamps.push_back(std::move(timeStamp));
return timeStampPtr;
} }
void CSystemUtils::DestroyTimeStamp(SystemTimeStamp *stamp) void CSystemUtils::DestroyTimeStamp(SystemTimeStamp *stamp)
{ {
delete stamp; for (auto& timeStamp : m_timeStamps)
{
if (timeStamp.get() == stamp)
timeStamp.reset();
}
} }
void CSystemUtils::CopyTimeStamp(SystemTimeStamp *dst, SystemTimeStamp *src) void CSystemUtils::CopyTimeStamp(SystemTimeStamp *dst, SystemTimeStamp *src)

View File

@ -24,9 +24,9 @@
#pragma once #pragma once
#include "common/singleton.h" #include <memory>
#include <string> #include <string>
#include <vector>
/** /**
* \enum SystemDialogType * \enum SystemDialogType
@ -88,11 +88,13 @@ struct SystemTimeStamp;
* This class provides system-specific utilities like displaying user dialogs and * This class provides system-specific utilities like displaying user dialogs and
* querying system timers for exact timestamps. * querying system timers for exact timestamps.
*/ */
class CSystemUtils : public CSingleton<CSystemUtils> class CSystemUtils
{ {
public: public:
virtual ~CSystemUtils();
//! Creates system utils for specific platform //! Creates system utils for specific platform
static CSystemUtils* Create(); static std::unique_ptr<CSystemUtils> Create();
//! Performs platform-specific initialization //! Performs platform-specific initialization
virtual void Init() = 0; virtual void Init() = 0;
@ -134,11 +136,7 @@ public:
//! Sleep for given amount of microseconds //! Sleep for given amount of microseconds
virtual void Usleep(int usecs) = 0; virtual void Usleep(int usecs) = 0;
private:
std::vector<std::unique_ptr<SystemTimeStamp>> m_timeStamps;
}; };
//! Global function to get CSystemUtils instance
inline CSystemUtils* GetSystemUtils()
{
return CSystemUtils::GetInstancePointer();
}

View File

@ -29,12 +29,7 @@
struct SystemTimeStamp struct SystemTimeStamp
{ {
timespec clockTime; timespec clockTime = {0, 0};
SystemTimeStamp()
{
clockTime.tv_sec = clockTime.tv_nsec = 0;
}
}; };
class CSystemUtilsLinux : public CSystemUtils class CSystemUtilsLinux : public CSystemUtils
@ -52,6 +47,6 @@ public:
virtual void Usleep(int usec) override; virtual void Usleep(int usec) override;
private: private:
bool m_zenityAvailable; bool m_zenityAvailable = false;
}; };

View File

@ -27,12 +27,7 @@
struct SystemTimeStamp struct SystemTimeStamp
{ {
long long counterValue; long long counterValue = 0;
SystemTimeStamp()
{
counterValue = 0;
}
}; };
class CSystemUtilsWindows : public CSystemUtils class CSystemUtilsWindows : public CSystemUtils
@ -54,6 +49,6 @@ public:
static std::wstring UTF8_Decode(const std::string &str); static std::wstring UTF8_Decode(const std::string &str);
protected: protected:
long long m_counterFrequency; long long m_counterFrequency = 0;
}; };

View File

@ -41,19 +41,20 @@
template<> CPathManager* CSingleton<CPathManager>::m_instance = nullptr; template<> CPathManager* CSingleton<CPathManager>::m_instance = nullptr;
CPathManager::CPathManager() CPathManager::CPathManager(CSystemUtils* systemUtils)
: m_systemUtils(systemUtils)
{ {
#ifdef PORTABLE #ifdef PORTABLE
m_dataPath = "./data"; m_dataPath = "./data";
m_langPath = "./lang"; m_langPath = "./lang";
m_savePath = "./saves"; m_savePath = "./saves";
#else #else
m_dataPath = GetSystemUtils()->GetDataPath(); m_dataPath = m_systemUtils->GetDataPath();
m_langPath = GetSystemUtils()->GetLangPath(); m_langPath = m_systemUtils->GetLangPath();
#ifdef DEV_BUILD #ifdef DEV_BUILD
m_savePath = "./saves"; m_savePath = "./saves";
#else #else
m_savePath = GetSystemUtils()->GetSaveDir(); m_savePath = m_systemUtils->GetSaveDir();
#endif #endif
#endif #endif
} }
@ -164,7 +165,7 @@ void CPathManager::LoadModsFromDir(const std::string &dir)
#endif #endif
} }
} }
catch(std::exception &e) catch (std::exception &e)
{ {
GetLogger()->Warn("Unable to load mods from directory '%s': %s\n", dir.c_str(), e.what()); GetLogger()->Warn("Unable to load mods from directory '%s': %s\n", dir.c_str(), e.what());
} }

View File

@ -28,6 +28,8 @@
#include <string> #include <string>
class CSystemUtils;
/** /**
* \class CPathManager * \class CPathManager
* \brief Class for managing data/lang/save paths, and %something% replacements * \brief Class for managing data/lang/save paths, and %something% replacements
@ -35,7 +37,7 @@
class CPathManager : public CSingleton<CPathManager> class CPathManager : public CSingleton<CPathManager>
{ {
public: public:
CPathManager(); CPathManager(CSystemUtils* systemUtils);
~CPathManager(); ~CPathManager();
void SetDataPath(std::string dataPath); void SetDataPath(std::string dataPath);
@ -57,6 +59,7 @@ private:
void LoadModsFromDir(const std::string &dir); void LoadModsFromDir(const std::string &dir);
private: private:
CSystemUtils* m_systemUtils;
//! Data path //! Data path
std::string m_dataPath; std::string m_dataPath;
//! Lang path //! Lang path

View File

@ -22,6 +22,7 @@
#include "app/app.h" #include "app/app.h"
#include "app/input.h" #include "app/input.h"
#include "app/system.h"
#include "common/image.h" #include "common/image.h"
#include "common/key.h" #include "common/key.h"
@ -62,15 +63,16 @@ template<> Gfx::CEngine* CSingleton<Gfx::CEngine>::m_instance = nullptr;
namespace Gfx namespace Gfx
{ {
CEngine::CEngine(CApplication *app) CEngine::CEngine(CApplication *app, CSystemUtils* systemUtils)
: m_ambientColor(), : m_app(app),
m_systemUtils(systemUtils),
m_ambientColor(),
m_fogColor(), m_fogColor(),
m_deepView(), m_deepView(),
m_fogStart(), m_fogStart(),
m_highlightRank(), m_highlightRank(),
m_mice() m_mice()
{ {
m_app = app;
m_device = nullptr; m_device = nullptr;
m_lightMan = nullptr; m_lightMan = nullptr;
@ -180,8 +182,8 @@ CEngine::CEngine(CApplication *app)
m_mouseType = ENG_MOUSE_NORM; m_mouseType = ENG_MOUSE_NORM;
m_fpsCounter = 0; m_fpsCounter = 0;
m_lastFrameTime = GetSystemUtils()->CreateTimeStamp(); m_lastFrameTime = m_systemUtils->CreateTimeStamp();
m_currentFrameTime = GetSystemUtils()->CreateTimeStamp(); m_currentFrameTime = m_systemUtils->CreateTimeStamp();
m_shadowColor = 0.5f; m_shadowColor = 0.5f;
@ -219,9 +221,9 @@ CEngine::~CEngine()
m_terrain = nullptr; m_terrain = nullptr;
m_pause = nullptr; m_pause = nullptr;
GetSystemUtils()->DestroyTimeStamp(m_lastFrameTime); m_systemUtils->DestroyTimeStamp(m_lastFrameTime);
m_lastFrameTime = nullptr; m_lastFrameTime = nullptr;
GetSystemUtils()->DestroyTimeStamp(m_currentFrameTime); m_systemUtils->DestroyTimeStamp(m_currentFrameTime);
m_currentFrameTime = nullptr; m_currentFrameTime = nullptr;
} }
@ -334,8 +336,8 @@ bool CEngine::Create()
params.mipmap = false; params.mipmap = false;
m_miceTexture = LoadTexture("textures/interface/mouse.png", params); m_miceTexture = LoadTexture("textures/interface/mouse.png", params);
GetSystemUtils()->GetCurrentTimeStamp(m_currentFrameTime); m_systemUtils->GetCurrentTimeStamp(m_currentFrameTime);
GetSystemUtils()->GetCurrentTimeStamp(m_lastFrameTime); m_systemUtils->GetCurrentTimeStamp(m_lastFrameTime);
return true; return true;
} }
@ -436,11 +438,11 @@ void CEngine::FrameUpdate()
{ {
m_fpsCounter++; m_fpsCounter++;
GetSystemUtils()->GetCurrentTimeStamp(m_currentFrameTime); m_systemUtils->GetCurrentTimeStamp(m_currentFrameTime);
float diff = GetSystemUtils()->TimeStampDiff(m_lastFrameTime, m_currentFrameTime, STU_SEC); float diff = m_systemUtils->TimeStampDiff(m_lastFrameTime, m_currentFrameTime, STU_SEC);
if (diff > 1.0f) if (diff > 1.0f)
{ {
GetSystemUtils()->CopyTimeStamp(m_lastFrameTime, m_currentFrameTime); m_systemUtils->CopyTimeStamp(m_lastFrameTime, m_currentFrameTime);
m_fps = m_fpsCounter / diff; m_fps = m_fpsCounter / diff;
m_fpsCounter = 0; m_fpsCounter = 0;

View File

@ -24,8 +24,6 @@
#pragma once #pragma once
#include "app/system.h"
#include "common/singleton.h" #include "common/singleton.h"
#include "graphics/core/color.h" #include "graphics/core/color.h"
@ -52,6 +50,8 @@ class CObject;
class CSoundInterface; class CSoundInterface;
class CImage; class CImage;
class CPauseManager; class CPauseManager;
class CSystemUtils;
struct SystemTimeStamp;
struct Event; struct Event;
@ -616,7 +616,7 @@ struct EngineMouse
class CEngine : public CSingleton<CEngine> class CEngine : public CSingleton<CEngine>
{ {
public: public:
CEngine(CApplication* app); CEngine(CApplication* app, CSystemUtils* systemUtils);
~CEngine(); ~CEngine();
//! Sets the device to be used //! Sets the device to be used
@ -1295,6 +1295,7 @@ protected:
protected: protected:
CApplication* m_app; CApplication* m_app;
CSystemUtils* m_systemUtils;
CSoundInterface* m_sound; CSoundInterface* m_sound;
CDevice* m_device; CDevice* m_device;
std::unique_ptr<COldModelManager> m_modelManager; std::unique_ptr<COldModelManager> m_modelManager;

View File

@ -22,6 +22,8 @@
#include "app/app.h" #include "app/app.h"
#include "graphics/engine/engine.h"
#include "common/image.h" #include "common/image.h"
#include "common/logger.h" #include "common/logger.h"
#include "common/stringutils.h" #include "common/stringutils.h"

View File

@ -19,13 +19,7 @@
#include "app/app.h" #include "app/app.h"
#if defined(PLATFORM_WINDOWS) #include "app/system_other.h"
#include "app/system_windows.h"
#elif defined(PLATFORM_LINUX)
#include "app/system_linux.h"
#else
#include "app/system_other.h"
#endif
#include "common/make_unique.h" #include "common/make_unique.h"
@ -49,7 +43,8 @@ struct FakeSystemTimeStamp : public SystemTimeStamp
class CApplicationWrapper : public CApplication class CApplicationWrapper : public CApplication
{ {
public: public:
CApplicationWrapper() CApplicationWrapper(CSystemUtils* systemUtils)
: CApplication(systemUtils)
{ {
SDL_Init(0); SDL_Init(0);
m_eventQueue = MakeUnique<CEventQueue>(); m_eventQueue = MakeUnique<CEventQueue>();
@ -97,6 +92,7 @@ protected:
std::unique_ptr<CApplicationWrapper> m_app; std::unique_ptr<CApplicationWrapper> m_app;
MockRepository m_mocks; MockRepository m_mocks;
CSystemUtils* m_systemUtils; CSystemUtils* m_systemUtils;
std::vector<std::unique_ptr<FakeSystemTimeStamp>> m_timeStamps;
private: private:
int m_stampUid; int m_stampUid;
@ -106,7 +102,6 @@ private:
void ApplicationUT::SetUp() void ApplicationUT::SetUp()
{ {
m_systemUtils = m_mocks.Mock<CSystemUtils>(); m_systemUtils = m_mocks.Mock<CSystemUtils>();
CSystemUtils::ReplaceInstance(m_systemUtils);
m_mocks.OnCall(m_systemUtils, CSystemUtils::GetDataPath).Return(""); m_mocks.OnCall(m_systemUtils, CSystemUtils::GetDataPath).Return("");
m_mocks.OnCall(m_systemUtils, CSystemUtils::GetLangPath).Return(""); m_mocks.OnCall(m_systemUtils, CSystemUtils::GetLangPath).Return("");
@ -118,23 +113,24 @@ void ApplicationUT::SetUp()
m_mocks.OnCall(m_systemUtils, CSystemUtils::GetCurrentTimeStamp).Do(std::bind(&ApplicationUT::GetCurrentTimeStamp, this, ph::_1)); m_mocks.OnCall(m_systemUtils, CSystemUtils::GetCurrentTimeStamp).Do(std::bind(&ApplicationUT::GetCurrentTimeStamp, this, ph::_1));
m_mocks.OnCall(m_systemUtils, CSystemUtils::TimeStampExactDiff).Do(std::bind(&ApplicationUT::TimeStampExactDiff, this, ph::_1, ph::_2)); m_mocks.OnCall(m_systemUtils, CSystemUtils::TimeStampExactDiff).Do(std::bind(&ApplicationUT::TimeStampExactDiff, this, ph::_1, ph::_2));
m_app.reset(new CApplicationWrapper()); m_app = MakeUnique<CApplicationWrapper>(m_systemUtils);
} }
void ApplicationUT::TearDown() void ApplicationUT::TearDown()
{ {
m_app.reset(); m_app.reset();
CSystemUtils::ReplaceInstance(nullptr);
} }
SystemTimeStamp* ApplicationUT::CreateTimeStamp() SystemTimeStamp* ApplicationUT::CreateTimeStamp()
{ {
return new FakeSystemTimeStamp(++m_stampUid); auto stamp = MakeUnique<FakeSystemTimeStamp>(++m_stampUid);
auto stampPtr = stamp.get();
m_timeStamps.push_back(std::move(stamp));
return stampPtr;
} }
void ApplicationUT::DestroyTimeStamp(SystemTimeStamp *stamp) void ApplicationUT::DestroyTimeStamp(SystemTimeStamp *stamp)
{ {
delete static_cast<FakeSystemTimeStamp*>(stamp);
} }
void ApplicationUT::CopyTimeStamp(SystemTimeStamp *dst, SystemTimeStamp *src) void ApplicationUT::CopyTimeStamp(SystemTimeStamp *dst, SystemTimeStamp *src)

View File

@ -16,8 +16,11 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see http://gnu.org/licenses * along with this program. If not, see http://gnu.org/licenses
*/ */
#include "graphics/engine/lightman.h" #include "graphics/engine/lightman.h"
#include "common/make_unique.h"
#include "graphics/core/device.h" #include "graphics/core/device.h"
#include <gtest/gtest.h> #include <gtest/gtest.h>
@ -34,7 +37,6 @@ class LightManagerUT : public testing::Test
{ {
protected: protected:
LightManagerUT() : LightManagerUT() :
m_systemUtils(nullptr),
m_engine(nullptr), m_engine(nullptr),
m_device(nullptr) m_device(nullptr)
{} {}
@ -42,7 +44,6 @@ protected:
{} {}
void SetUp() override; void SetUp() override;
void TearDown() override;
void PrepareLightTesting(int maxLights, Math::Vector eyePos); void PrepareLightTesting(int maxLights, Math::Vector eyePos);
void CheckLightSorting(EngineObjectType objectType, const std::vector<int>& expectedLights); void CheckLightSorting(EngineObjectType objectType, const std::vector<int>& expectedLights);
@ -53,7 +54,6 @@ protected:
std::unique_ptr<CLightManager> m_lightManager; std::unique_ptr<CLightManager> m_lightManager;
MockRepository m_mocks; MockRepository m_mocks;
CSystemUtils* m_systemUtils;
CEngine* m_engine; CEngine* m_engine;
CDevice* m_device; CDevice* m_device;
@ -65,17 +65,10 @@ private:
void LightManagerUT::SetUp() void LightManagerUT::SetUp()
{ {
m_systemUtils = m_mocks.Mock<CSystemUtils>();
CSystemUtils::ReplaceInstance(m_systemUtils);
m_engine = m_mocks.Mock<CEngine>(); m_engine = m_mocks.Mock<CEngine>();
m_device = m_mocks.Mock<CDevice>(); m_device = m_mocks.Mock<CDevice>();
m_lightManager.reset(new CLightManager(m_engine)); m_lightManager = MakeUnique<CLightManager>(m_engine);
}
void LightManagerUT::TearDown()
{
CSystemUtils::ReplaceInstance(nullptr);
} }
void LightManagerUT::PrepareLightTesting(int maxLights, Math::Vector eyePos) void LightManagerUT::PrepareLightTesting(int maxLights, Math::Vector eyePos)