FIFE  be64c707dea6b3250bd4355bf5c825d25920087d
engine.cpp
Go to the documentation of this file.
1 /***************************************************************************
2  * Copyright (C) 2005-2019 by the FIFE team *
3  * http://www.fifengine.net *
4  * This file is part of FIFE. *
5  * *
6  * FIFE is free software; you can redistribute it and/or *
7  * modify it under the terms of the GNU Lesser General Public *
8  * License as published by the Free Software Foundation; either *
9  * version 2.1 of the License, or (at your option) any later version. *
10  * *
11  * This library is distributed in the hope that it will be useful, *
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of *
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
14  * Lesser General Public License for more details. *
15  * *
16  * You should have received a copy of the GNU Lesser General Public *
17  * License along with this library; if not, write to the *
18  * Free Software Foundation, Inc., *
19  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *
20  ***************************************************************************/
21 
22 // Standard C++ library includes
23 #include <iostream>
24 #include <algorithm>
25 
26 // 3rd party library includes
27 #include <SDL.h>
28 #include <SDL_ttf.h>
29 
30 // FIFE includes
31 // These includes are split up in two parts, separated by one empty line
32 // First block: files included from the FIFE root src directory
33 // Second block: files included from the same folder
34 #include "util/base/exception.h"
35 #include "util/log/logger.h"
36 #include "util/time/timemanager.h"
37 #include "audio/soundmanager.h"
38 #include "gui/guimanager.h"
39 #include "vfs/vfs.h"
40 #include "vfs/vfsdirectory.h"
41 #include "vfs/directoryprovider.h"
42 #include "vfs/zip/zipprovider.h"
44 #include "video/imagemanager.h"
45 #include "video/animationmanager.h"
46 #include "audio/soundclipmanager.h"
47 #include "video/renderbackend.h"
48 #include "video/cursor.h"
49 #include "video/devicecaps.h"
50 #ifdef HAVE_OPENGL
53 #endif
57 #include "model/model.h"
73 #include "video/image.h"
74 #include "engine.h"
75 #include "version.h"
76 
77 #ifdef USE_COCOA
78 
79 #include <objc/message.h>
80 #include <dlfcn.h>
81 
82 int32_t main(int32_t argc, char **argv)
83 {
84  return 0;
85 }
86 #endif
87 
88 namespace FIFE {
89  static Logger _log(LM_CONTROLLER);
90 
92  m_renderbackend(0),
93  m_guimanager(0),
94  m_eventmanager(0),
95  m_soundmanager(0),
96  m_timemanager(0),
97  m_imagemanager(0),
98  m_animationmanager(0),
99  m_soundclipmanager(0),
100  m_vfs(0),
101  m_model(0),
102  m_logmanager(0),
103  m_cursor(0),
104  m_destroyed(false),
105  m_settings(),
106  m_devcaps(),
107  m_offrenderer(0),
108  m_targetrenderer(0),
109  m_changelisteners() {
110 #ifdef USE_COCOA
111  // The next lines ensure that Cocoa is initialzed correctly.
112  // This is needed for SDL to function properly on MAC OS X.
113  void* cocoa_lib;
114  cocoa_lib = dlopen( "/System/Library/Frameworks/Cocoa.framework/Cocoa", RTLD_LAZY );
115  void (*nsappload)(void);
116  nsappload = (void(*)()) dlsym( cocoa_lib, "NSApplicationLoad");
117  nsappload();
118 
119  // Create an autorelease pool, so autoreleased SDL objects don't leak.
120 #ifdef OSX_109
121  Class NSAutoreleasePool = objc_getClass("NSAutoreleasePool");
122  m_autoreleasePool = class_createInstance(NSAutoreleasePool, 0);
123 #else
124  objc_object *NSAutoreleasePool = objc_getClass("NSAutoreleasePool");
125  m_autoreleasePool =
126  objc_msgSend(NSAutoreleasePool, sel_registerName("new"));
127 #endif
128 #endif
130  }
131 
133  return m_settings;
134  }
135 
137  return m_devcaps;
138  }
139 
141  m_cursor->invalidate();
142 
144 
145  // recreate main screen
147 
148  if (m_guimanager) {
149  m_guimanager->resizeTopContainer(0,0,mode.getWidth(), mode.getHeight());
150  }
151 
152  std::vector<IEngineChangeListener*>::iterator i = m_changelisteners.begin();
153  while (i != m_changelisteners.end()) {
154  (*i)->onScreenModeChanged(mode);
155  ++i;
156  }
157  }
158 
159  void Engine::init() {
160  m_destroyed = false;
161 
162  FL_LOG(_log, LMsg("Fifengine v") << FIFE::getVersion());
163  FL_LOG(_log, "================== Engine initialize start =================");
164  m_timemanager = new TimeManager();
165  FL_LOG(_log, "Time manager created");
166 
167  FL_LOG(_log, "Creating VFS");
168  m_vfs = new VFS();
169 
170  FL_LOG(_log, "Adding root directory to VFS");
173 
174  FL_LOG(_log, "Adding zip provider to VFS");
175  m_vfs->addProvider( new ZipProvider() );
176 
177  //m_vfs->addProvider(ProviderDAT2());
178  //m_vfs->addProvider(ProviderDAT1());
179  FL_LOG(_log, "Engine pre-init done");
180 
181  // If failed to init SDL throw exception.
182  if (SDL_Init(SDL_INIT_NOPARACHUTE | SDL_INIT_TIMER) < 0) {
183  throw SDLException(SDL_GetError());
184  }
185 
186  TTF_Init();
187 
188  FL_LOG(_log, "Creating event manager");
193 
194  FL_LOG(_log, "Creating resource managers");
195 
199 
200  FL_LOG(_log, "Creating render backend");
201  std::string rbackend(m_settings.getRenderBackend());
202  if (rbackend == "SDL") {
204  FL_LOG(_log, "SDL Render backend created");
205  } else {
206 #ifdef HAVE_OPENGL
208  FL_LOG(_log, "OpenGL Render backend created");
209 #else
211  // Remember the choice so we pick the right graphics class.
212  rbackend = "SDL";
213  FL_WARN(_log, "Tried to select OpenGL, even though it is not compiled into the engine. Falling back to SDL Render backend");
214 #endif
215  }
216  FL_LOG(_log, "Initializing render backend");
218  // we always set this to false
219  //m_renderbackend->setAlphaOptimizerEnabled(false);
232  }
233 
234  std::string driver = m_settings.getVideoDriver();
235  if (driver != ""){
236  std::vector<std::string> drivers = m_devcaps.getAvailableVideoDrivers();
237  if (std::find (drivers.begin(), drivers.end(), driver) == drivers.end()) {
238  FL_WARN(_log, "Selected video driver is not supported for your Operating System! Reverting to default driver.");
239  driver = "";
240  }
242  }
243  // init backend with selected video driver or default
244  m_renderbackend->init(driver);
245 
246  // in case of SDL we use this to create the SDL_Renderer
247  driver = m_settings.getSDLDriver();
248  if (driver != ""){
249  std::vector<std::string> drivers = m_devcaps.getAvailableRenderDrivers();
250  if (std::find (drivers.begin(), drivers.end(), driver) == drivers.end()) {
251  FL_WARN(_log, "Selected render driver is not supported for your Operating System! Reverting to default driver.");
252  driver = "";
253  }
255  }
256 
257  FL_LOG(_log, "Querying device capabilities");
259 
261 
265  bpp,
266  rbackend,
270 
271  FL_LOG(_log, "Creating main screen");
273  m_screenMode,
276  FL_LOG(_log, "Main screen created");
277 
278 #ifdef HAVE_OPENGL
279  if (m_settings.getLightingModel() != 0) {
281  }
282 
283 #endif
284  FL_LOG(_log, "Creating sound manager");
286  m_soundmanager->setVolume(static_cast<float>(m_settings.getInitialVolume()) / 10);
287 
288  FL_LOG(_log, "Creating renderers");
291  m_renderers.push_back(new InstanceRenderer(m_renderbackend, 10));
292  m_renderers.push_back(new GridRenderer(m_renderbackend, 20));
296  m_renderers.push_back(new QuadTreeRenderer(m_renderbackend, 60));
297  m_renderers.push_back(new CoordinateRenderer(m_renderbackend, 70));
298  m_renderers.push_back(new GenericRenderer(m_renderbackend, 80));
299  m_renderers.push_back(new LightRenderer(m_renderbackend, 90));
300  m_renderers.push_back(new CellRenderer(m_renderbackend, 100));
301 
302  FL_LOG(_log, "Creating model");
304  FL_LOG(_log, "Adding pathers to model");
306  FL_LOG(_log, "Adding grid prototypes to model");
308  m_model->adoptCellGrid(new HexGrid(false));
309  m_model->adoptCellGrid(new HexGrid(true));
310 
313  FL_LOG(_log, "Engine initialized");
314  }
315 
317  if( !m_destroyed ) {
318  destroy();
319  }
320  }
321 
323  FL_LOG(_log, "Destructing engine");
324  delete m_cursor;
325  delete m_model;
326  delete m_soundmanager;
327  delete m_guimanager;
328 
329  delete m_animationmanager;
330  delete m_imagemanager;
331  delete m_soundclipmanager;
332  delete m_eventmanager;
333 
334  // properly remove all the renderers created during init
335  delete m_offrenderer;
336  delete m_targetrenderer;
337  std::vector<RendererBase*>::iterator rendererIter = m_renderers.begin();
338  for ( ; rendererIter != m_renderers.end(); ++rendererIter)
339  {
340  delete *rendererIter;
341  }
342  m_renderers.clear();
343 
344  delete m_renderbackend;
345  delete m_vfs;
346  delete m_timemanager;
347 
348  TTF_Quit();
349  SDL_Quit();
350 
351 #ifdef USE_COCOA
352  objc_msgSend(m_autoreleasePool, sel_registerName("release"));
353 #endif
354 
355  FL_LOG(_log, "================== Engine destructed ==================");
356  m_destroyed = true;
357  //delete m_logmanager;
358  }
361  }
362 
363  void Engine::pump() {
368 
370  if (m_model->getActiveCameraCount() == 0) {
373  } else {
374  m_model->update();
375  }
376 
377  if (m_guimanager) {
378  m_guimanager->turn();
379  }
380 
381  m_cursor->draw();
383  }
384 
386  // nothing here at the moment..
387  }
388 
390  m_changelisteners.push_back(listener);
391  }
392 
394  std::vector<IEngineChangeListener*>::iterator i = m_changelisteners.begin();
395  while (i != m_changelisteners.end()) {
396  if ((*i) == listener) {
397  m_changelisteners.erase(i);
398  return;
399  }
400  ++i;
401  }
402  }
403 }
EngineSettings m_settings
Definition: engine.h:219
#define FL_WARN(logger, msg)
Definition: logger.h:72
uint16_t getHeight() const
Returns the height of the screen mode.
Definition: devicecaps.h:68
void pump()
Runs one cycle for the engine.
Definition: engine.cpp:363
This class defines the engine settings on engine init.
virtual void turn()=0
Performs the GUI logic and draws the GUI accordingly.
void adoptCellGrid(CellGrid *grid)
Adds cellgrid to model.
Definition: model.cpp:122
ImageManager * m_imagemanager
Definition: engine.h:208
void addProvider(VFSSourceProvider *provider)
add new VFSSourceProvider
Definition: vfs.cpp:66
void addChangeListener(IEngineChangeListener *listener)
Adds new change listener.
Definition: engine.cpp:389
ImageManager.
Definition: imagemanager.h:54
void setMonochromeEnabled(bool enabled)
Enables or disables monochrome rendering.
void setVideoDriverName(const std::string &driver)
Sets the name of the video driver.
Definition: devicecaps.h:191
bool isColorKeyEnabled() const
Gets whether the colorkey feature is in use.
uint16_t getFrameLimit() const
Gets the frame limit.
std::vector< std::string > getAvailableVideoDrivers() const
Gets the available video drivers for your operating system.
Definition: devicecaps.h:167
Helper class to create log strings out from separate parts Usage: LMsg("some text") << variable << "...
Definition: logger.h:82
uint32_t getActiveCameraCount() const
Return the number of enabled cameras in this model.
Definition: model.cpp:187
const std::string & getSDLDriver() const
Gets the used SDL render driver.
RenderBackend * m_renderbackend
Definition: engine.h:203
The main class of the SDL-based renderer.
std::vector< std::string > getAvailableRenderDrivers() const
Gets the available render drivers for your operating system.
Definition: devicecaps.h:171
void finalizePumping()
Finalizes the continuous processing of the engine Call this only once in your program, after you have called initializePumping + (pump() * N times)
Definition: engine.cpp:385
std::vector< IEngineChangeListener * > m_changelisteners
Definition: engine.h:228
Engine()
Constructor.
Definition: engine.cpp:91
void destroy()
Explicit destruction of engine.
Definition: engine.cpp:322
virtual void createMainScreen(const ScreenMode &mode, const std::string &title, const std::string &icon)=0
Creates the mainscreen (the display window).
uint8_t getDisplay() const
Gets the display index, starts with 0.
const DeviceCaps & getDeviceCaps() const
Gets device capabilities.
Definition: engine.cpp:136
void update()
Called periodically to update events on model.
Definition: model.cpp:327
static Logger _log(LM_AUDIO)
bool m_destroyed
Definition: engine.h:217
TargetRenderer * m_targetrenderer
Definition: engine.h:225
void setColorKeyEnabled(bool colorkeyenable)
Sets whether to use the colorkey feature.
void setMouseAccelerationEnabled(bool acceleration)
Sets mouse acceleration if mouse acceleration is enabled, then the mouse sensitivity is used as speed...
TextureFiltering getGLTextureFiltering() const
Gets current texture filter which uses OpenGL.
void setFramebufferEnabled(bool enabled)
Enables or disable the usage of the framebuffer, if available.
virtual void init(const std::string &driver)=0
Initializes the backend.
SoundManager * m_soundmanager
Definition: engine.h:206
void initializePumping()
Initializes the continuous processing of the engine Call this only once in your program.
Definition: engine.cpp:359
virtual void clearBackBuffer()=0
Forces a clear of the backbuffer.
DeviceCaps m_devcaps
Definition: engine.h:220
SoundClipManager.
void init()
Initializes the engine.
Definition: engine.cpp:159
EngineSettings & getSettings()
Gets settings class for engine.
Definition: engine.cpp:132
AnimationManager.
LogManager * m_logmanager
Definition: engine.h:214
void invalidate()
Definition: cursor.cpp:169
float getGLAlphaTestValue() const
Gets current alpha test value which uses OpenGL.
void setNativeImageCursorEnabled(bool native_image_cursor_enabled)
Enables or disables the native image cursor feature.
Definition: cursor.cpp:329
virtual void draw()
draws cursor on screen
Definition: cursor.cpp:179
Provider for OS directories.
void setVolume(float vol)
Sets the Master Volume.
bool isFrameLimitEnabled() const
Gets whether the frame limiter is in use.
bool isVSync() const
True, if vsync is enable, otherwise false.
virtual void startFrame()
Called when a new frame starts.
void setMipmappingEnabled(bool enabled)
Enables or disables the usage of mipmapping.
void setAlphaTestValue(float alpha)
Sets the value for alpha test.
void setFrameLimit(uint16_t framelimit)
Sets the frame limit.
void setNPOTEnabled(bool enabled)
Enables or disable the usage of npot, if available.
const SDL_Color & getColorKey() const
Gets the global colorkey setting.
void removeChangeListener(IEngineChangeListener *listener)
Removes associated change listener.
Definition: engine.cpp:393
uint16_t getRefreshRate() const
Gets the refresh rate.
EventManager * m_eventmanager
Definition: engine.h:205
float getMouseSensitivity() const
Gets mouse sensitivity.
const std::string & getWindowIcon() const
Gets the icon in the window title bar.
bool isGLUseDepthBuffer() const
Tells if OpenGL renderbackend should use depth buffer.
void update()
Called once a frame and updates the sound objects.
TimeManager * m_timemanager
Definition: engine.h:207
void addSource(VFSSource *source)
Add a new VFSSource.
Definition: vfs.cpp:110
uint8_t getBitsPerPixel() const
Gets currently set bits per pixel value.
virtual void resizeTopContainer(uint32_t x, uint32_t y, uint32_t width, uint32_t height)=0
Resizes the top container.
bool isGLCompressImages() const
Tells if images are compress by video driver in OpenGL renderbackend.
void setTextureFiltering(TextureFiltering filter)
Sets the texture filtering method.
AnimationManager * m_animationmanager
Definition: engine.h:209
A model is a facade for everything in the model.
Definition: model.h:54
CellSelectionRenderer renders a frame around selected cells.
uint32_t getLightingModel() const
Gets the currently set light model.
ScreenMode getNearestScreenMode(uint16_t width, uint16_t height, uint16_t bpp, const std::string &renderer, bool fs) const
Gets the nearest valid screen mode based on the arguments passed.
Definition: devicecaps.cpp:211
OffRenderer * m_offrenderer
Definition: engine.h:224
unsigned short uint16_t
Definition: core.h:39
IGUIManager * m_guimanager
Definition: engine.h:204
virtual void invalidateAll()
Cursor * m_cursor
Definition: engine.h:216
void setRenderDriverName(const std::string &driver)
Sets the name of the render driver.
Definition: devicecaps.cpp:265
void setDepthBufferEnabled(bool enabled)
Enables or disables depth buffer rendering.
bool isFullScreen() const
True, if set to fullscreen.
Event Manager manages all events related to FIFE.
Definition: eventmanager.h:79
Time Manager.
Definition: timemanager.h:50
virtual ~Engine()
Destructor.
Definition: engine.cpp:316
bool isMouseAccelerationEnabled() const
Returns if mouse acceleration is enabled or not.
#define FL_LOG(logger, msg)
Definition: logger.h:71
virtual void endFrame()
Called when a frame is finished and ready to be displayed.
static LogManager * instance()
Returns instance to log manager.
Definition: logger.cpp:65
uint16_t getScreenWidth() const
Gets screen width (pixels)
void fillDeviceCaps()
Should be called AFTER SDL_Init() has been called.
Definition: devicecaps.cpp:144
bool isNativeImageCursorEnabled() const
Returns whether cursors set to an image or an animation are drawn natively.
Cursor class manages mouse cursor handling.
Definition: cursor.h:73
void setFrameLimitEnabled(bool limited)
Sets whether to use the frame limiter.
std::vector< RendererBase * > m_renderers
Definition: engine.h:226
the main VFS (virtual file system) class
Definition: vfs.h:58
void setJoystickSupport(bool support)
Sets the joystick support to enabled or disabled.
ScreenMode m_screenMode
Definition: engine.h:222
float getInitialVolume() const
Gets initial engine sound volume.
void adoptPather(IPather *pather)
Adds pather to model.
Definition: model.cpp:107
const std::string & getVideoDriver() const
Gets the video driver.
void update()
Called once a frame and updates the timer objects and events.
Definition: timemanager.cpp:51
bool isGLUseNPOT() const
Tells if OpenGL renderbackend should use NPOT Textures.
const std::string & getWindowTitle() const
Gets the current window title.
bool isJoystickSupport() const
Returns whether joystick and gamepad support is enabled or not.
const std::string & getRenderBackend() const
Gets currently set renderbackend name.
The most basic VFSSource for "normal" filesystems.
Definition: vfsdirectory.h:44
A VFS provider for Zip archives.
Definition: zipprovider.h:43
bool isGLUseMonochrome() const
Tells if OpenGL renderbackend should render only monochrome.
Model * m_model
Definition: engine.h:213
void setMouseSensitivity(float sensitivity)
Sets mouse sensitivity The sensitivity is limited to the range -0.99 - 10.0.
uint16_t getWidth() const
Returns the width of the screen mode.
Definition: devicecaps.h:62
void processEvents()
Process the SDL event queue.
SoundClipManager * m_soundclipmanager
Definition: engine.h:210
void setImageCompressingEnabled(bool enabled)
Enables or disable compressing images by video driver.
uint16_t getScreenHeight() const
Gets screen height (pixels)
VFS * m_vfs
Definition: engine.h:212
void setVSyncEnabled(bool vsync)
Sets whether to use VSync.
bool isGLUseMipmapping() const
Tells if OpenGL renderbackend should use mipmapping.
The main class of the OpenGL-based renderer.
bool isGLUseFramebuffer() const
Tells if OpenGL renderbackend should use FramebufferObject.
virtual void setLightingModel(uint32_t lighting)=0
Initializes the light.
void changeScreenMode(const ScreenMode &mode)
Changes the screen mode.
Definition: engine.cpp:140