Package fife :: Package extensions :: Module basicapplication
[hide private]
[frames] | no frames]

Source Code for Module fife.extensions.basicapplication

  1  # -*- coding: utf-8 -*- 
  2   
  3  # #################################################################### 
  4  #  Copyright (C) 2005-2019 by the FIFE team 
  5  #  http://www.fifengine.net 
  6  #  This file is part of FIFE. 
  7  # 
  8  #  FIFE is free software; you can redistribute it and/or 
  9  #  modify it under the terms of the GNU Lesser General Public 
 10  #  License as published by the Free Software Foundation; either 
 11  #  version 2.1 of the License, or (at your option) any later version. 
 12  # 
 13  #  This library is distributed in the hope that it will be useful, 
 14  #  but WITHOUT ANY WARRANTY; without even the implied warranty of 
 15  #  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU 
 16  #  Lesser General Public License for more details. 
 17  # 
 18  #  You should have received a copy of the GNU Lesser General Public 
 19  #  License along with this library; if not, write to the 
 20  #  Free Software Foundation, Inc., 
 21  #  51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA 
 22  # #################################################################### 
 23   
 24  """ 
 25  The basic application and main loop. 
 26   
 27  See the L{ApplicationBase} documentation. 
 28  """ 
 29  from __future__ import print_function 
 30   
 31  from builtins import str 
 32  from builtins import object 
 33  from fife import fife 
 34  from fife.extensions import fifelog 
 35  from fife.extensions.fife_settings import Setting 
 36   
37 -class ExitEventListener(fife.IKeyListener):
38 """ 39 Default, rudimentary event listener. 40 41 Will cause the application to quit on pressing ESC. 42 """
43 - def __init__(self, app):
44 self.app = app 45 self.engine = app.engine 46 eventmanager = self.engine.getEventManager() 47 #eventmanager.setNonConsumableKeys([fife.Key.ESCAPE]) 48 fife.IKeyListener.__init__(self) 49 eventmanager.addKeyListener(self) 50 self.quitRequested = False
51
52 - def keyPressed(self, evt):
53 keyval = evt.getKey().getValue() 54 if keyval == fife.Key.ESCAPE: 55 self.app.quit()
56
57 - def keyReleased(self, evt):
58 pass
59
60 -class ApplicationBase(object):
61 """ 62 ApplicationBase is an extendable class that provides a basic environment for a FIFE-based client. 63 This kind of application base does not offer GUI support. 64 65 The unextended application reads in and initializes engine settings, sets up a simple event 66 listener, and pumps the engine while listening for a quit message. Specialized applications can 67 modify settings.py to change initial engine settings. They can provide their own event listener 68 by overriding L{createListener}. And they can override the L{_pump} method 69 to define runtime behavior of the application. 70 71 """
72 - def __init__(self, setting=None):
73 if setting: 74 self._setting = setting 75 else: 76 self._setting = Setting(app_name="", settings_file="./settings.xml") 77 78 self.engine = fife.Engine() 79 80 self.initLogging() 81 self.loadSettings() 82 83 self.engine.init() 84 85 """ 86 we are giving users a valid screen resolution option that is supported 87 """ 88 screen_modes = self.engine.getDeviceCaps().getSupportedScreenModes() 89 resolutions = list(set([(mode.getWidth(), mode.getHeight()) 90 for mode in screen_modes])) 91 92 resolutions = ["{0}x{1}".format(item[0], item[1]) for item in sorted(resolutions)[1:]] 93 self._setting.setValidResolutions(resolutions) 94 95 self.quitRequested = False 96 self.breakRequested = False 97 self.returnValues = []
98
99 - def loadSettings(self):
100 """ 101 Load the settings from a python file and load them into the engine. 102 Called in the ApplicationBase constructor. 103 """ 104 105 106 # get finalSetting (from the xml file, or if absent the default value) 107 self._finalSetting = self._setting.getSettingsFromFile("FIFE", self._log) 108 109 engineSetting = self.engine.getSettings() 110 111 engineSetting.setDefaultFontGlyphs(self._finalSetting['FontGlyphs']) 112 engineSetting.setDefaultFontPath(self._finalSetting['Font']) 113 engineSetting.setDefaultFontSize(self._finalSetting['DefaultFontSize']) 114 engineSetting.setBitsPerPixel(self._finalSetting['BitsPerPixel']) 115 engineSetting.setInitialVolume(self._finalSetting['InitialVolume']) 116 engineSetting.setSDLRemoveFakeAlpha(self._finalSetting['SDLRemoveFakeAlpha']) 117 engineSetting.setGLCompressImages(self._finalSetting['GLCompressImages']) 118 engineSetting.setGLUseFramebuffer(self._finalSetting['GLUseFramebuffer']) 119 engineSetting.setGLUseNPOT(self._finalSetting['GLUseNPOT']) 120 engineSetting.setGLUseMipmapping(self._finalSetting['GLUseMipmapping']) 121 engineSetting.setGLUseMonochrome(self._finalSetting['GLUseMonochrome']) 122 engineSetting.setGLUseDepthBuffer(self._finalSetting['GLUseDepthBuffer']) 123 engineSetting.setGLAlphaTestValue(self._finalSetting['GLAlphaTestValue']) 124 if self._finalSetting['GLTextureFiltering'] == 'None': 125 engineSetting.setGLTextureFiltering(fife.TEXTURE_FILTER_NONE) 126 elif self._finalSetting['GLTextureFiltering'] == 'Bilinear': 127 engineSetting.setGLTextureFiltering(fife.TEXTURE_FILTER_BILINEAR) 128 elif self._finalSetting['GLTextureFiltering'] == 'Trilinear': 129 engineSetting.setGLTextureFiltering(fife.TEXTURE_FILTER_TRILINEAR) 130 elif self._finalSetting['GLTextureFiltering'] == 'Anisotropic': 131 engineSetting.setGLTextureFiltering(fife.TEXTURE_FILTER_ANISOTROPIC) 132 (width, height) = self._finalSetting['ScreenResolution'].split('x') 133 engineSetting.setScreenWidth(int(width)) 134 engineSetting.setScreenHeight(int(height)) 135 engineSetting.setRenderBackend(self._finalSetting['RenderBackend']) 136 engineSetting.setFullScreen(self._finalSetting['FullScreen']) 137 engineSetting.setRefreshRate(self._finalSetting['RefreshRate']) 138 engineSetting.setDisplay(self._finalSetting['Display']) 139 engineSetting.setVSync(self._finalSetting['VSync']) 140 engineSetting.setVideoDriver(self._finalSetting['VideoDriver']) 141 engineSetting.setSDLDriver(self._finalSetting['RenderDriver']) 142 engineSetting.setLightingModel(self._finalSetting['Lighting']) 143 engineSetting.setNativeImageCursorEnabled(self._finalSetting['NativeImageCursor']) 144 engineSetting.setJoystickSupport(self._finalSetting['JoystickSupport']) 145 146 try: 147 engineSetting.setColorKeyEnabled(self._finalSetting['ColorKeyEnabled']) 148 except: 149 pass 150 151 try: 152 engineSetting.setColorKey(self._finalSetting['ColorKey'][0],self._finalSetting['ColorKey'][1],self._finalSetting['ColorKey'][2]) 153 except: 154 pass 155 156 try: 157 engineSetting.setWindowTitle(self._finalSetting['WindowTitle']) 158 engineSetting.setWindowIcon(self._finalSetting['WindowIcon']) 159 except: 160 pass 161 162 try: 163 engineSetting.setFrameLimitEnabled(self._finalSetting['FrameLimitEnabled']) 164 engineSetting.setFrameLimit(self._finalSetting['FrameLimit']) 165 except: 166 pass 167 168 try: 169 engineSetting.setMouseSensitivity(self._finalSetting['MouseSensitivity']) 170 except: 171 pass 172 173 try: 174 engineSetting.setMouseAccelerationEnabled(self._finalSetting['MouseAcceleration']) 175 except: 176 pass
177 178
179 - def initLogging(self):
180 """ 181 Initialize the LogManager. 182 """ 183 184 engineSetting = self.engine.getSettings() 185 logmodules = self._setting.get("FIFE", "LogModules", ["controller"]) 186 187 #log to both the console and log file 188 self._log = fifelog.LogManager(self.engine, 189 self._setting.get("FIFE", "LogToPrompt", False), 190 self._setting.get("FIFE", "LogToFile", False)) 191 192 self._log.setLevelFilter(self._setting.get("FIFE", "LogLevelFilter", fife.LogManager.LEVEL_DEBUG)) 193 194 if logmodules: 195 self._log.setVisibleModules(*logmodules)
196
197 - def createListener(self):
198 """ 199 This creates a default event listener, which will just close the program 200 after pressing ESC. 201 202 You should override this method to provide your own event handling. 203 """ 204 return ExitEventListener(self)
205
206 - def run(self):
207 """ 208 Initialize the event listener and event loop - and start it. 209 """ 210 eventlistener = self.createListener() 211 self.engine.initializePumping() 212 retval = self.mainLoop() 213 self.engine.finalizePumping() 214 self.engine.destroy() 215 return retval
216
217 - def mainLoop(self):
218 """ 219 The programs main loop. 220 221 Do not override this, instead provide your own L{_pump} method. 222 You can call this recursively, e.g. to provide synchronous 223 Dialogs :-) and break out of the current mainLoop by calling 224 L{breakFromMainLoop}. It will return the argument passed 225 to L{breakFromMainLoop}. 226 """ 227 self.returnValues.append(None) 228 while not self.quitRequested: 229 try: 230 self.engine.pump() 231 except fife.Exception as e: 232 print(str(e)) 233 self.quitRequested = True 234 235 self._pump() 236 237 if self.breakRequested: 238 self.breakRequested = False 239 break 240 241 return self.returnValues.pop()
242
243 - def breakFromMainLoop(self,returnValue):
244 """ 245 Break from the currently running L{mainLoop}. 246 247 The passed argument will be returned by the mainLoop. 248 """ 249 self.returnValues[-1] = returnValue 250 self.breakRequested = True
251 252
253 - def _pump(self):
254 """ 255 Application pump. 256 257 Derived classes can specialize this for unique behavior. 258 This is called every frame. 259 """
260
261 - def quit(self):
262 """ 263 Quit the application. Really! 264 """ 265 self.quitRequested = True
266