def main(parser): opts, args = parser.parse_args() levels = {'debug': logging.DEBUG, 'info': logging.INFO, 'warning': logging.WARNING, 'error': logging.ERROR, 'critical': logging.CRITICAL} #TODO: setup formating logging.basicConfig(filename=opts.logfile, level=levels[opts.loglevel]) logger = logging.getLogger('parpg') try: old_path = sys.path if opts.fife_path: sys.path = [opts.fife_path] import fife except ImportError: logger.critical("Could not import fife module. Please install fife or set the --fife-path command line value") parser.print_help() sys.exit(1) finally: sys.path = old_path from fife.extensions.fife_settings import Setting settings = Setting(settings_file="settings.xml") data_dir = abspath(settings.get("parpg","DataPath")) settings.set("parpg", "DataPath", data_dir) settings.set("FIFE", "WindowIcon", data_dir + "/" + settings.get("FIFE", "WindowIcon")) settings.set("FIFE", "Font", data_dir + "/" + settings.get("FIFE", "Font")) from parpg.application import PARPGApplication from parpg.common import utils # enable psyco if available and in settings file try: import psyco psyco_available = True except ImportError: logger.warning('Psyco Acceleration unavailable') psyco_available = False if settings.get("fife", "UsePsyco"): if psyco_available: psyco.full() logger.info('Psyco Acceleration enabled') else: logger.warning('Please install psyco before attempting to use it' 'Psyco Acceleration disabled') else: logger.info('Psycho Acceleration disabled') # run the game app = PARPGApplication(settings) app.run()
class ApplicationBase(object): """ ApplicationBase is an extendable class that provides a basic environment for a FIFE-based client. The unextended application reads in and initializes engine settings, sets up a simple event listener, and pumps the engine while listening for a quit message. Specialized applications can modify settings.py to change initial engine settings. They can provide their own event listener by overriding L{createListener}. And they can override the L{_pump} method to define runtime behavior of the application. """ def __init__(self, setting=None): if setting: self._setting = setting else: self._setting = Setting(app_name="", settings_file="./settings.xml", settings_gui_xml="") self.engine = fife.Engine() self.loadSettings() self.initLogging() self.engine.init() self._animationloader = XMLAnimationLoader(self.engine.getImagePool(), self.engine.getVFS()) self.engine.getAnimationPool().addResourceLoader(self._animationloader) pychan.init(self.engine, debug=self._setting.get("FIFE", "PychanDebug", False)) pychan.setupModalExecution(self.mainLoop, self.breakFromMainLoop) self.quitRequested = False self.breakRequested = False self.returnValues = [] def loadSettings(self): """ Load the settings from a python file and load them into the engine. Called in the ApplicationBase constructor. """ glyphDft = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.,!?-+/():;%&`'*#=[]\\\"" engineSetting = self.engine.getSettings() engineSetting.setDefaultFontGlyphs(self._setting.get("FIFE", "FontGlyphs", glyphDft)) engineSetting.setDefaultFontPath(self._setting.get("FIFE", "Font", "fonts/FreeSans.ttf")) engineSetting.setDefaultFontSize(self._setting.get("FIFE", "DefaultFontSize", 12)) engineSetting.setBitsPerPixel(self._setting.get("FIFE", "BitsPerPixel", 0)) engineSetting.setInitialVolume(self._setting.get("FIFE", "InitialVolume", 5.0)) engineSetting.setSDLRemoveFakeAlpha(self._setting.get("FIFE", "SDLRemoveFakeAlpha", 1)) (width, height) = self._setting.get("FIFE", "ScreenResolution", "1024x768").split("x") engineSetting.setScreenWidth(int(width)) engineSetting.setScreenHeight(int(height)) engineSetting.setRenderBackend(self._setting.get("FIFE", "RenderBackend", "OpenGL")) engineSetting.setFullScreen(self._setting.get("FIFE", "FullScreen", False)) try: engineSetting.setColorKeyEnabled(self._setting.get("FIFE", "ColorKeyEnabled", False)) except: pass try: key = self._setting.get("FIFE", "ColorKey", "255,0,255").split(",") engineSetting.setColorKey(int(key[0]), int(key[1]), int(key[2])) except: pass try: engineSetting.setWindowTitle(self._setting.get("FIFE", "WindowTitle", "No window title set")) engineSetting.setWindowIcon(self._setting.get("FIFE", "WindowIcon", "")) except: pass try: engineSetting.setImageChunkingSize(self._setting.get("FIFE", "ImageChunkSize", 256)) except: pass def initLogging(self): """ Initialize the LogManager. """ engineSetting = self.engine.getSettings() logmodules = self._setting.get("FIFE", "LogModules", ["controller"]) # log to both the console and log file self._log = fifelog.LogManager( self.engine, self._setting.get("FIFE", "LogToPrompt", "0"), self._setting.get("FIFE", "LogToFile", "0") ) self._log.setLevelFilter(self._setting.get("FIFE", "LogLevelFilter", fife.LogManager.LEVEL_DEBUG)) if logmodules: self._log.setVisibleModules(*logmodules) def createListener(self): """ This creates a default event listener, which will just close the program after pressing ESC. You should override this method to provide your own event handling. """ return ExitEventListener(self) def run(self): """ Initialize the event listener and event loop - and start it. """ eventlistener = self.createListener() self.engine.initializePumping() retval = self.mainLoop() self.engine.finalizePumping() self.engine.destroy() return retval def mainLoop(self): """ The programs main loop. Do not override this, instead provide your own L{_pump} method. You can call this recursively, e.g. to provide synchronous Dialogs :-) and break out of the current mainLoop by calling L{breakFromMainLoop}. It will return the argument passed to L{breakFromMainLoop}. """ self.returnValues.append(None) while not self.quitRequested: try: self.engine.pump() except RuntimeError, e: print str(e) self._pump() if self.breakRequested: self.breakRequested = False break return self.returnValues.pop()
if not os.path.isdir(mapSaveDir): os.makedirs(mapSaveDir) # save map file to directory self.world.save(mapSaveDir + "/savefile.xml") else: self.world.pump() def main(): app = IslandDemo() app.run() if __name__ == '__main__': if TDS.get("FIFE", "ProfilingOn"): import hotshot, hotshot.stats print "Starting profiler" prof = hotshot.Profile("fife.prof") prof.runcall(main) prof.close() print "analysing profiling results" stats = hotshot.stats.load("fife.prof") stats.strip_dirs() stats.sort_stats('time', 'calls') stats.print_stats(20) else: if TDS.get("FIFE", "UsePsyco"): # Import Psyco if available try: import psyco
class Fife(ApplicationBase): """ """ def __init__(self): self.pump = [] self._setup_settings() self.engine = fife.Engine() self.loadSettings() self.engine_settings = self.engine.getSettings() self.pychan = pychan self._doQuit = False self._doBreak = False self._doReturn = None self._gotInited = False self.emitter = {} self.emitter['bgsound'] = None self.emitter['effects'] = None self.emitter['speech'] = None def _setup_settings(self): self._setting = Setting(app_name="unknownhorizons", settings_file=PATHS.USER_CONFIG_FILE, settings_gui_xml="content/gui/settings.xml", changes_gui_xml="content/gui/requirerestart.xml") self._setting.setGuiStyle("book") #self.createAndAddEntry(self, module, name, widgetname, applyfunction=None, initialdata=None, requiresrestart=False) self._setting.createAndAddEntry(UH_MODULE, "AutosaveInterval", "autosaveinterval", initialdata=range(0, 60, 2)) self._setting.createAndAddEntry(UH_MODULE, "AutosaveMaxCount", "autosavemaxcount", initialdata=range(1, 30)) self._setting.createAndAddEntry(UH_MODULE, "QuicksaveMaxCount", "quicksavemaxcount", initialdata=range(1, 30)) self._setting.createAndAddEntry(FIFE_MODULE, "BitsPerPixel", "screen_bpp", initialdata=[0, 16, 32], requiresrestart=True) languages_map = dict(find_available_languages()) languages_map[_('System default')] = '' self._setting.createAndAddEntry(UH_MODULE, "Language", "language", applyfunction=self.update_languages, initialdata= [LANGUAGENAMES[x] for x in sorted(languages_map.keys())]) self._setting.createAndAddEntry(UH_MODULE, "VolumeMusic", "volume_music", applyfunction=lambda x: self.set_volume_music(x)) self._setting.createAndAddEntry(UH_MODULE, "VolumeEffects", "volume_effects", applyfunction=lambda x: self.set_volume_effects(x)) self._setting.entries[FIFE_MODULE]['PlaySounds'].applyfunction = lambda x: self.setup_sound() self._setting.entries[FIFE_MODULE]['PlaySounds'].requiresrestart = False def update_languages(self, data=None): if data is None: data = self._setting.get(UH_MODULE, "Language") languages_map = dict(find_available_languages()) languages_map['System default'] = '' symbol = None if data == unicode('System default'): symbol = 'System default' else: for key, value in LANGUAGENAMES.iteritems(): if value == data: symbol = key assert symbol is not None, "Something went badly wrong with the translation update!" + \ " Searching for: " + str(data) + " in " + str(LANGUAGENAMES) index = sorted(languages_map.keys()).index(symbol) name, position = sorted(languages_map.items())[index] try: if name != 'System default': trans = gettext.translation('unknownhorizons', position, languages=[name]) trans.install(unicode=1) else: gettext.install('unknownhorizons', 'build/mo', unicode=1) name = '' except IOError: print _("Configured language %(lang)s at %(place)s could not be loaded") % {'lang': settings.language.name, 'place': settings.language.position} install('unknownhorizons', 'build/mo', unicode=1) self._setting.set(UH_MODULE, "Language", 'System default') update_all_translations() def init(self): """ """ logToPrompt, logToFile, debugPychan = True, True, False if self._gotInited: return #start modules self.log = fifelog.LogManager(self.engine, 1 if logToPrompt else 0, 1 if logToFile else 0) #self.log.setVisibleModules('all') self.engine.init() #temporarily select a random music file to play. TODO: Replace with proper playlist self.ingame_music = glob.glob('content/audio/music/*.ogg') self.menu_music = glob.glob('content/audio/music/menu/*.ogg') self.initial_menu_music_element = None self.next_menu_music_element = None self.menu_music_played = 0 #init stuff self.eventmanager = self.engine.getEventManager() #self.eventmanager.setNonConsumableKeys([fife.Key.ESCAPE, fife.Key.F10]) self.guimanager = self.engine.getGuiManager() self.console = self.guimanager.getConsole() self.soundmanager = self.engine.getSoundManager() self.soundmanager.init() self.setup_sound() self.imagepool = self.engine.getImagePool() self.animationpool = self.engine.getAnimationPool() self.animationloader = SQLiteAnimationLoader() self.animationpool.addResourceLoader(self.animationloader) #Set game cursor self.cursor = self.engine.getCursor() self.default_cursor_image = self.imagepool.addResourceFromFile('content/gui/images/misc/cursor.png') self.tearing_cursor_image = self.imagepool.addResourceFromFile('content/gui/images/misc/cursor_tear.png') self.cursor.set(fife.CURSOR_IMAGE, self.default_cursor_image) #init pychan self.pychan.init(self.engine, debugPychan) self.pychan.setupModalExecution(self.loop, self.breakLoop) from gui.widgets.inventory import Inventory from gui.widgets.imagefillstatusbutton import ImageFillStatusButton from gui.widgets.progressbar import ProgressBar from gui.widgets.toggleimagebutton import ToggleImageButton from gui.widgets.tooltip import TooltipIcon, TooltipButton, TooltipLabel, TooltipProgressBar pychan.widgets.registerWidget(Inventory) pychan.widgets.registerWidget(ImageFillStatusButton) pychan.widgets.registerWidget(ProgressBar) pychan.widgets.registerWidget(ToggleImageButton) pychan.widgets.registerWidget(TooltipIcon) pychan.widgets.registerWidget(TooltipButton) pychan.widgets.registerWidget(TooltipLabel) pychan.widgets.registerWidget(TooltipProgressBar) for name, stylepart in horizons.gui.style.STYLES.iteritems(): self.pychan.manager.addStyle(name, stylepart) self.pychan.loadFonts("content/fonts/libertine.fontdef") self._gotInited = True def setup_sound(self): if self._setting.get(FIFE_MODULE, "PlaySounds"): self.enable_sound() else: self.disable_sound() def get_fife_setting(self, settingname): return self._setting.get(FIFE_MODULE, settingname) def get_uh_setting(self, settingname): return self._setting.get(UH_MODULE, settingname) def enable_sound(self): """Enable all sound and start playing music.""" if self._setting.get(FIFE_MODULE, "PlaySounds"): # Set up sound if it is enabled self.soundclippool = self.engine.getSoundClipPool() self.emitter['bgsound'] = self.soundmanager.createEmitter() self.emitter['bgsound'].setGain(self._setting.get(UH_MODULE, "VolumeMusic")) self.emitter['bgsound'].setLooping(False) self.emitter['effects'] = self.soundmanager.createEmitter() self.emitter['effects'].setGain(self._setting.get(UH_MODULE, "VolumeEffects")) self.emitter['effects'].setLooping(False) self.emitter['speech'] = self.soundmanager.createEmitter() self.emitter['speech'].setGain(self._setting.get(UH_MODULE, "VolumeEffects")) self.emitter['speech'].setLooping(False) self.emitter['ambient'] = [] self.music_rand_element = random.randint(0, len(self.menu_music) - 1) self.initial_menu_music_element = self.music_rand_element self.check_music() # Start background music ExtScheduler().add_new_object(self.check_music, self, loops=-1) def disable_sound(self): """Disable all sound outputs.""" if self.emitter['bgsound'] is not None: self.emitter['bgsound'].reset() if self.emitter['effects'] is not None: self.emitter['effects'].reset() if self.emitter['speech'] is not None: self.emitter['speech'].reset() ExtScheduler().rem_call(self, self.check_music) def check_music(self): """Used as callback to check if music is still running or if we have to load the next song.""" if self.menu_music_played == 0: if self.initial_menu_music_element == self.next_menu_music_element: self.ingame_music.extend(self.menu_music) self.music = self.ingame_music self.music_rand_element = random.randint(0, len(self.ingame_music) - 1) self.menu_music_played = 1 else: self.music = self.menu_music if hasattr(self, '_bgsound_old_byte_pos') and hasattr(self, '_bgsound_old_sample_pos'): if self._bgsound_old_byte_pos == self.emitter['bgsound'].getCursor(fife.SD_BYTE_POS) and self._bgsound_old_sample_pos == self.emitter['bgsound'].getCursor(fife.SD_SAMPLE_POS): self.music_rand_element = self.music_rand_element + 1 if \ self.music_rand_element + 1 < len(self.music) else 0 self.play_sound('bgsound', self.music[self.music_rand_element]) if self.menu_music_played == 0: self.next_menu_music_element = self.music_rand_element self._bgsound_old_byte_pos, self._bgsound_old_sample_pos = \ self.emitter['bgsound'].getCursor(fife.SD_BYTE_POS), \ self.emitter['bgsound'].getCursor(fife.SD_SAMPLE_POS) def play_sound(self, emitter, soundfile): """Plays a soundfile on the given emitter. @param emitter: string with the emitters name in horizons.main.fife.emitter that is to play the sound @param soundfile: string containing the path to the soundfile""" if self._setting.get(FIFE_MODULE, "PlaySounds"): emitter = self.emitter[emitter] assert emitter is not None, "You need to supply a initialised emitter" assert soundfile is not None, "You need to supply a soundfile" emitter.reset() emitter.setSoundClip(horizons.main.fife.soundclippool.addResourceFromFile(soundfile)) emitter.play() def set_volume(self, emitter_name, value): """Sets the volume on the emitter specified by emitter_name. @param emitter_name: string with the emitters name, used as key for the self.emitter dict @param value: double which value the emitter is to be set to range[0, 1] """ if self._setting.get(FIFE_MODULE, "PlaySounds"): self.emitter[emitter_name].setGain(value) def set_volume_music(self, value): """Sets the volume of the music emitters to 'value'. @param value: double - value that's used to set the emitters gain. """ if self._setting.get(FIFE_MODULE, "PlaySounds"): self.emitter['bgsound'].setGain(value) def set_volume_effects(self, value): """Sets the volume of effects, speech and ambient emitters. @param value: double - value that's used to set the emitters gain. """ if self._setting.get(FIFE_MODULE, "PlaySounds"): self.emitter['effects'].setGain(value) self.emitter['speech'].setGain(value) for e in self.emitter['ambient']: e.setGain(value*2) def run(self): """ """ self.init() self.engine.initializePumping() self.loop() self.engine.finalizePumping() def loop(self): """ """ while not self._doQuit: try: self.engine.pump() except fife.Exception, e: print e.getMessage() break for f in self.pump: f() if self._doBreak: self._doBreak = False return self._doReturn self.__kill_engine()
class ApplicationBase(object): """ ApplicationBase is an extendable class that provides a basic environment for a FIFE-based client. This kind of application base does not offer GUI support. The unextended application reads in and initializes engine settings, sets up a simple event listener, and pumps the engine while listening for a quit message. Specialized applications can modify settings.py to change initial engine settings. They can provide their own event listener by overriding L{createListener}. And they can override the L{_pump} method to define runtime behavior of the application. """ def __init__(self, setting=None): if setting: self._setting = setting else: self._setting = Setting(app_name="", settings_file="./settings.xml") self.engine = fife.Engine() self.initLogging() self.loadSettings() self.engine.init() """ we are giving users a valid screen resolution option that is supported """ screen_modes = self.engine.getDeviceCaps().getSupportedScreenModes() resolutions = list(set([(mode.getWidth(), mode.getHeight()) for mode in screen_modes])) resolutions = ["{0}x{1}".format(item[0], item[1]) for item in sorted(resolutions)[1:]] self._setting.setValidResolutions(resolutions) self.quitRequested = False self.breakRequested = False self.returnValues = [] def loadSettings(self): """ Load the settings from a python file and load them into the engine. Called in the ApplicationBase constructor. """ # get finalSetting (from the xml file, or if absent the default value) self._finalSetting = self._setting.getSettingsFromFile("FIFE", self._log) engineSetting = self.engine.getSettings() engineSetting.setDefaultFontGlyphs(self._finalSetting['FontGlyphs']) engineSetting.setDefaultFontPath(self._finalSetting['Font']) engineSetting.setDefaultFontSize(self._finalSetting['DefaultFontSize']) engineSetting.setBitsPerPixel(self._finalSetting['BitsPerPixel']) engineSetting.setInitialVolume(self._finalSetting['InitialVolume']) engineSetting.setSDLRemoveFakeAlpha(self._finalSetting['SDLRemoveFakeAlpha']) engineSetting.setGLCompressImages(self._finalSetting['GLCompressImages']) engineSetting.setGLUseFramebuffer(self._finalSetting['GLUseFramebuffer']) engineSetting.setGLUseNPOT(self._finalSetting['GLUseNPOT']) engineSetting.setGLUseMipmapping(self._finalSetting['GLUseMipmapping']) engineSetting.setGLUseMonochrome(self._finalSetting['GLUseMonochrome']) engineSetting.setGLUseDepthBuffer(self._finalSetting['GLUseDepthBuffer']) engineSetting.setGLAlphaTestValue(self._finalSetting['GLAlphaTestValue']) if self._finalSetting['GLTextureFiltering'] == 'None': engineSetting.setGLTextureFiltering(fife.TEXTURE_FILTER_NONE) elif self._finalSetting['GLTextureFiltering'] == 'Bilinear': engineSetting.setGLTextureFiltering(fife.TEXTURE_FILTER_BILINEAR) elif self._finalSetting['GLTextureFiltering'] == 'Trilinear': engineSetting.setGLTextureFiltering(fife.TEXTURE_FILTER_TRILINEAR) elif self._finalSetting['GLTextureFiltering'] == 'Anisotropic': engineSetting.setGLTextureFiltering(fife.TEXTURE_FILTER_ANISOTROPIC) (width, height) = self._finalSetting['ScreenResolution'].split('x') engineSetting.setScreenWidth(int(width)) engineSetting.setScreenHeight(int(height)) engineSetting.setRenderBackend(self._finalSetting['RenderBackend']) engineSetting.setFullScreen(self._finalSetting['FullScreen']) engineSetting.setRefreshRate(self._finalSetting['RefreshRate']) engineSetting.setDisplay(self._finalSetting['Display']) engineSetting.setVSync(self._finalSetting['VSync']) engineSetting.setVideoDriver(self._finalSetting['VideoDriver']) engineSetting.setSDLDriver(self._finalSetting['RenderDriver']) engineSetting.setLightingModel(self._finalSetting['Lighting']) try: engineSetting.setColorKeyEnabled(self._finalSetting['ColorKeyEnabled']) except: pass try: engineSetting.setColorKey(self._finalSetting['ColorKey'][0],self._finalSetting['ColorKey'][1],self._finalSetting['ColorKey'][2]) except: pass try: engineSetting.setWindowTitle(self._finalSetting['WindowTitle']) engineSetting.setWindowIcon(self._finalSetting['WindowIcon']) except: pass try: engineSetting.setFrameLimitEnabled(self._finalSetting['FrameLimitEnabled']) engineSetting.setFrameLimit(self._finalSetting['FrameLimit']) except: pass try: engineSetting.setMouseSensitivity(self._finalSetting['MouseSensitivity']) except: pass try: engineSetting.setMouseAccelerationEnabled(self._finalSetting['MouseAcceleration']) except: pass def initLogging(self): """ Initialize the LogManager. """ engineSetting = self.engine.getSettings() logmodules = self._setting.get("FIFE", "LogModules", ["controller"]) #log to both the console and log file self._log = fifelog.LogManager(self.engine, self._setting.get("FIFE", "LogToPrompt", False), self._setting.get("FIFE", "LogToFile", False)) self._log.setLevelFilter(self._setting.get("FIFE", "LogLevelFilter", fife.LogManager.LEVEL_DEBUG)) if logmodules: self._log.setVisibleModules(*logmodules) def createListener(self): """ This creates a default event listener, which will just close the program after pressing ESC. You should override this method to provide your own event handling. """ return ExitEventListener(self) def run(self): """ Initialize the event listener and event loop - and start it. """ eventlistener = self.createListener() self.engine.initializePumping() retval = self.mainLoop() self.engine.finalizePumping() self.engine.destroy() return retval def mainLoop(self): """ The programs main loop. Do not override this, instead provide your own L{_pump} method. You can call this recursively, e.g. to provide synchronous Dialogs :-) and break out of the current mainLoop by calling L{breakFromMainLoop}. It will return the argument passed to L{breakFromMainLoop}. """ self.returnValues.append(None) while not self.quitRequested: try: self.engine.pump() except RuntimeError, e: print str(e) self.quitRequested = True except:
class ApplicationBase(object): """ ApplicationBase is an extendable class that provides a basic environment for a FIFE-based client. This kind of application base does not offer GUI support. The unextended application reads in and initializes engine settings, sets up a simple event listener, and pumps the engine while listening for a quit message. Specialized applications can modify settings.py to change initial engine settings. They can provide their own event listener by overriding L{createListener}. And they can override the L{_pump} method to define runtime behavior of the application. """ def __init__(self, setting=None): if setting: self._setting = setting else: self._setting = Setting(app_name="", settings_file="./settings.xml") self.engine = fife.Engine() self.initLogging() self.loadSettings() self.engine.init() """ we are giving users a valid screen resolution option that is supported """ screen_modes = self.engine.getDeviceCaps().getSupportedScreenModes() resolutions = list( set([(mode.getWidth(), mode.getHeight()) for mode in screen_modes])) resolutions = [ "{0}x{1}".format(item[0], item[1]) for item in sorted(resolutions)[1:] ] self._setting.setValidResolutions(resolutions) self.quitRequested = False self.breakRequested = False self.returnValues = [] def loadSettings(self): """ Load the settings from a python file and load them into the engine. Called in the ApplicationBase constructor. """ # get finalSetting (from the xml file, or if absent the default value) self._finalSetting = self._setting.getSettingsFromFile( "FIFE", self._log) engineSetting = self.engine.getSettings() engineSetting.setDefaultFontGlyphs(self._finalSetting['FontGlyphs']) engineSetting.setDefaultFontPath(self._finalSetting['Font']) engineSetting.setDefaultFontSize(self._finalSetting['DefaultFontSize']) engineSetting.setBitsPerPixel(self._finalSetting['BitsPerPixel']) engineSetting.setInitialVolume(self._finalSetting['InitialVolume']) engineSetting.setSDLRemoveFakeAlpha( self._finalSetting['SDLRemoveFakeAlpha']) engineSetting.setGLCompressImages( self._finalSetting['GLCompressImages']) engineSetting.setGLUseFramebuffer( self._finalSetting['GLUseFramebuffer']) engineSetting.setGLUseNPOT(self._finalSetting['GLUseNPOT']) engineSetting.setGLUseMipmapping(self._finalSetting['GLUseMipmapping']) engineSetting.setGLUseMonochrome(self._finalSetting['GLUseMonochrome']) engineSetting.setGLUseDepthBuffer( self._finalSetting['GLUseDepthBuffer']) engineSetting.setGLAlphaTestValue( self._finalSetting['GLAlphaTestValue']) if self._finalSetting['GLTextureFiltering'] == 'None': engineSetting.setGLTextureFiltering(fife.TEXTURE_FILTER_NONE) elif self._finalSetting['GLTextureFiltering'] == 'Bilinear': engineSetting.setGLTextureFiltering(fife.TEXTURE_FILTER_BILINEAR) elif self._finalSetting['GLTextureFiltering'] == 'Trilinear': engineSetting.setGLTextureFiltering(fife.TEXTURE_FILTER_TRILINEAR) elif self._finalSetting['GLTextureFiltering'] == 'Anisotropic': engineSetting.setGLTextureFiltering( fife.TEXTURE_FILTER_ANISOTROPIC) (width, height) = self._finalSetting['ScreenResolution'].split('x') engineSetting.setScreenWidth(int(width)) engineSetting.setScreenHeight(int(height)) engineSetting.setRenderBackend(self._finalSetting['RenderBackend']) engineSetting.setFullScreen(self._finalSetting['FullScreen']) engineSetting.setRefreshRate(self._finalSetting['RefreshRate']) engineSetting.setDisplay(self._finalSetting['Display']) engineSetting.setVSync(self._finalSetting['VSync']) engineSetting.setVideoDriver(self._finalSetting['VideoDriver']) engineSetting.setSDLDriver(self._finalSetting['RenderDriver']) engineSetting.setLightingModel(self._finalSetting['Lighting']) engineSetting.setNativeImageCursorEnabled( self._finalSetting['NativeImageCursor']) engineSetting.setJoystickSupport(self._finalSetting['JoystickSupport']) try: engineSetting.setColorKeyEnabled( self._finalSetting['ColorKeyEnabled']) except: pass try: engineSetting.setColorKey(self._finalSetting['ColorKey'][0], self._finalSetting['ColorKey'][1], self._finalSetting['ColorKey'][2]) except: pass try: engineSetting.setWindowTitle(self._finalSetting['WindowTitle']) engineSetting.setWindowIcon(self._finalSetting['WindowIcon']) except: pass try: engineSetting.setFrameLimitEnabled( self._finalSetting['FrameLimitEnabled']) engineSetting.setFrameLimit(self._finalSetting['FrameLimit']) except: pass try: engineSetting.setMouseSensitivity( self._finalSetting['MouseSensitivity']) except: pass try: engineSetting.setMouseAccelerationEnabled( self._finalSetting['MouseAcceleration']) except: pass def initLogging(self): """ Initialize the LogManager. """ engineSetting = self.engine.getSettings() logmodules = self._setting.get("FIFE", "LogModules", ["controller"]) #log to both the console and log file self._log = fifelog.LogManager( self.engine, self._setting.get("FIFE", "LogToPrompt", False), self._setting.get("FIFE", "LogToFile", False)) self._log.setLevelFilter( self._setting.get("FIFE", "LogLevelFilter", fife.LogManager.LEVEL_DEBUG)) if logmodules: self._log.setVisibleModules(*logmodules) def createListener(self): """ This creates a default event listener, which will just close the program after pressing ESC. You should override this method to provide your own event handling. """ return ExitEventListener(self) def run(self): """ Initialize the event listener and event loop - and start it. """ eventlistener = self.createListener() self.engine.initializePumping() retval = self.mainLoop() self.engine.finalizePumping() self.engine.destroy() return retval def mainLoop(self): """ The programs main loop. Do not override this, instead provide your own L{_pump} method. You can call this recursively, e.g. to provide synchronous Dialogs :-) and break out of the current mainLoop by calling L{breakFromMainLoop}. It will return the argument passed to L{breakFromMainLoop}. """ self.returnValues.append(None) while not self.quitRequested: try: self.engine.pump() except fife.Exception as e: print(str(e)) self.quitRequested = True self._pump() if self.breakRequested: self.breakRequested = False break return self.returnValues.pop() def breakFromMainLoop(self, returnValue): """ Break from the currently running L{mainLoop}. The passed argument will be returned by the mainLoop. """ self.returnValues[-1] = returnValue self.breakRequested = True def _pump(self): """ Application pump. Derived classes can specialize this for unique behavior. This is called every frame. """ def quit(self): """ Quit the application. Really! """ self.quitRequested = True
print "Using the FIFE python module found here: ", os.path.dirname(fife.__file__) from fife.extensions.fife_settings import Setting from scripts.rpg import RPGApplication TDS = Setting(app_name="rpg", settings_file="./settings.xml", settings_gui_xml="") def main(): app = RPGApplication(TDS) app.run() if __name__ == '__main__': if TDS.get("FIFE", "ProfilingOn"): import hotshot, hotshot.stats print "Starting profiler" prof = hotshot.Profile("fife.prof") prof.runcall(main) prof.close() print "analysing profiling results" stats = hotshot.stats.load("fife.prof") stats.strip_dirs() stats.sort_stats('time', 'calls') stats.print_stats(20) else: if TDS.get("FIFE", "UsePsyco"): # Import Psyco if available try: import psyco
print("Using the FIFE python module found here: ", os.path.dirname(fife.__file__)) from fife.extensions.fife_settings import Setting from scripts.fife_test import FifeTestApplication TDS = Setting(app_name="fife_test", settings_file="./settings.xml") def main(): app = FifeTestApplication(TDS) app.run() if __name__ == '__main__': if TDS.get("FIFE", "ProfilingOn"): import hotshot import hotshot.stats print("Starting profiler") prof = hotshot.Profile("fife.prof") prof.runcall(main) prof.close() print("analysing profiling results") stats = hotshot.stats.load("fife.prof") stats.strip_dirs() stats.sort_stats('time', 'calls') stats.print_stats(20) else: main()
from fife import fife print "Using the FIFE python module found here: ", os.path.dirname(fife.__file__) from fife.extensions.fife_settings import Setting from scripts.fife_test import FifeTestApplication TDS = Setting(app_name="fife_test", settings_file="./settings.xml") def main(): app = FifeTestApplication(TDS) app.run() if __name__ == '__main__': if TDS.get("FIFE", "ProfilingOn"): import hotshot import hotshot.stats print "Starting profiler" prof = hotshot.Profile("fife.prof") prof.runcall(main) prof.close() print "analysing profiling results" stats = hotshot.stats.load("fife.prof") stats.strip_dirs() stats.sort_stats('time', 'calls') stats.print_stats(20) else: main()