-
Notifications
You must be signed in to change notification settings - Fork 89
/
GameEngine.py
632 lines (534 loc) · 25 KB
/
GameEngine.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
#####################################################################
# -*- coding: utf-8 -*- #
# #
# Frets on Fire #
# Copyright (C) 2006 Sami Ky?stil? #
# 2008 Alarian #
# 2008 myfingershurt #
# 2008 Glorandwarf #
# 2008 Spikehead777 #
# 2008 QQStarS #
# 2008 Blazingamer #
# 2008 evilynux <evilynux@gmail.com> #
# 2008 fablaculp #
# #
# This program is free software; you can redistribute it and/or #
# modify it under the terms of the GNU General Public License #
# as published by the Free Software Foundation; either version 2 #
# of the License, or (at your option) any later version. #
# #
# This program is distributed in the hope that it will be useful, #
# but WITHOUT ANY WARRANTY; without even the implied warranty of #
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
# GNU General Public License for more details. #
# #
# You should have received a copy of the GNU General Public License #
# along with this program; if not, write to the Free Software #
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, #
# MA 02110-1301, USA. #
#####################################################################
import OpenGL
from OpenGL.GL import *
import numpy as np
from PIL import Image
import pygame
import gc
import os
import sys
import imp
import logging
from fretwork.audio import Audio
from fretwork.task import TaskEngine
from fretwork.timer import FpsTimer
from fofix.core.constants import *
from fofix.core.Video import Video
from fofix.core.View import View
from fofix.core.Input import Input, KeyListener, SystemEventListener
from fofix.core.Resource import Resource
from fofix.core.Data import Data
from fofix.core.Image import SvgContext, ImgDrawing
from fofix.core.Language import _
from fofix.core.Theme import Theme
from fofix.core.Shader import shaders
from fofix.core.Image import drawImage
from fofix.core import cmgl
from fofix.core import Config
from fofix.core import ConfigDefs
from fofix.core import Version
from fofix.core import Player
from fofix.core import Mod
from fofix.game import Dialogs
from fofix.game.World import World
from fofix.game.Debug import DebugLayer
log = logging.getLogger(__name__)
# evilynux - Grab name and version from Version class.
version = "%s v%s" % ( Version.PROGRAM_NAME, Version.version() )
def _init_allthemes():
""" Alarian: Get unlimited themes by foldername """
# this global code is in a function to hide vars from rest of file
themepath = os.path.join(Version.dataPath(), "themes")
themes = []
defaultTheme = None #myfingershurt
allthemes = os.listdir(themepath)
for name in allthemes:
if os.path.exists(os.path.join(themepath,name,"notes","notes.png")):
themes.append(name)
if name == "MegaLight V4":
defaultTheme = name
i = len(themes)
if i == 0:
if os.name == 'posix':
log.error("No valid theme found!\n" +
"Make sure theme files are properly cased " +
"e.g. notes.png works, Notes.png doesn't\n")
else:
log.error("No valid theme found!")
sys.exit(1)
if defaultTheme is None:
defaultTheme = themes[0] #myfingershurt
#myfingershurt: default theme must be an existing one!
Config.define("coffee", "themename", str, defaultTheme, text = _("Theme"), options = dict([(str(themes[n]),themes[n]) for n in range(0, i)]), tipText = _("Sets the overall graphical feel of the game. You can find and download many more at fretsonfire.net"))
_init_allthemes()
Player.loadControls()
class FullScreenSwitcher(KeyListener):
"""
A keyboard listener that looks for special built-in key combinations,
such as the fullscreen toggle (Alt-Enter).
"""
def __init__(self, engine):
self.engine = engine
self.altStatus = False
def keyPressed(self, key, unicode):
if key == pygame.K_LALT:
self.altStatus = True
elif key == pygame.K_RETURN and self.altStatus:
if not self.engine.toggleFullscreen():
log.error("Unable to toggle fullscreen mode.")
return True
elif key == pygame.K_d and self.altStatus:
self.engine.setDebugModeEnabled(not self.engine.isDebugModeEnabled())
return True
elif key == pygame.K_g and self.altStatus and self.engine.isDebugModeEnabled():
self.engine.debugLayer.gcDump()
return True
def keyReleased(self, key):
if key == pygame.K_LALT:
self.altStatus = False
class SystemEventHandler(SystemEventListener):
"""
A system event listener that takes care of restarting the game when needed
and reacting to screen resize events.
"""
def __init__(self, engine):
self.engine = engine
def screenResized(self, size):
self.engine.resizeScreen(size[0], size[1])
def restartRequested(self):
self.engine.restart()
def quit(self):
self.engine.quit()
class GameEngine(object):
"""The main game engine."""
def __init__(self, config = None):
log.debug("GameEngine class init (GameEngine.py)...")
self.mainMenu = None #placeholder for main menu object - to prevent reinstantiation
self.currentScene = None
self.versionString = version #stump: other version stuff moved to allow full version string to be retrieved without instantiating GameEngine
self.uploadVersion = "%s-4.0" % Version.PROGRAM_NAME #akedrou - the version passed to the upload site.
self.dataPath = Version.dataPath()
log.debug(self.versionString + " starting up...")
log.debug("Python version: " + sys.version.split(' ')[0])
log.debug("Pygame version: " + str(pygame.version.ver) )
log.debug("PyOpenGL version: " + OpenGL.__version__)
log.debug("Numpy version: " + np.__version__)
log.debug("PIL version: " + Image.VERSION)
log.debug("sys.argv: " + repr(sys.argv))
log.debug("os.name: " + os.name)
log.debug("sys.platform: " + sys.platform)
if os.name == 'nt':
import win32api
log.debug("win32api.GetVersionEx(1): " + repr(win32api.GetVersionEx(1)))
elif os.name == 'posix':
log.debug("os.uname(): " + repr(os.uname()))
"""
Constructor.
@param config: L{Config} instance for settings
"""
self.tutorialFolder = "tutorials"
if config is None:
config = Config.load()
self.config = config
self.fps = self.config.get("video", "fps")
self.running = True
self.clock = FpsTimer()
self.tickDelta = 0
self.task = TaskEngine(self)
# Compatiblity task management
self.addTask = self.task.addTask
self.removeTask = self.task.removeTask
self.pauseTask = self.task.pauseTask
self.resumeTask = self.task.resumeTask
self.title = self.versionString
self.restartRequested = False
# Load window icon
icon = os.path.join(Version.dataPath(), "fofix_icon.png")
self.video = Video(self.title, icon)
if self.config.get("video", "disable_screensaver"):
self.video.disableScreensaver()
self.audio = Audio()
self.fpsEstimate = 0
self.priority = self.config.get("engine", "highpriority")
self.show_fps = self.config.get("video", "show_fps")
self.advSettings = self.config.get("game", "adv_settings")
self.restartRequired = False
self.quicksetRestart = False
self.quicksetPerf = self.config.get("quickset", "performance")
self.scrollRate = self.config.get("game", "scroll_rate")
self.scrollDelay = self.config.get("game", "scroll_delay")
log.debug("Initializing audio.")
frequency = self.config.get("audio", "frequency")
bits = self.config.get("audio", "bits")
stereo = self.config.get("audio", "stereo")
bufferSize = self.config.get("audio", "buffersize")
self.audio.open(frequency = frequency, bits = bits, stereo = stereo, bufferSize = bufferSize)
self.gameStarted = False
self.world = None
self.audioSpeedFactor = 1.0
log.debug("Initializing video.")
#myfingershurt: ensuring windowed mode starts up in center of the screen instead of cascading positions:
os.environ['SDL_VIDEO_WINDOW_POS'] = 'center'
width, height = [int(s) for s in self.config.get("video", "resolution").split("x")]
fullscreen = self.config.get("video", "fullscreen")
multisamples = self.config.get("video", "multisamples")
self.video.setMode((width, height), fullscreen = fullscreen, multisamples = multisamples)
log.debug("OpenGL version: " + glGetString(GL_VERSION))
log.debug("OpenGL vendor: " + glGetString(GL_VENDOR))
log.debug("OpenGL renderer: " + glGetString(GL_RENDERER))
log.debug("OpenGL extensions: " + ' '.join(sorted(glGetString(GL_EXTENSIONS).split())))
if self.video.default:
self.config.set("video", "fullscreen", False)
self.config.set("video", "resolution", "800x600")
if self.config.get("video", "shader_use"):
shaders.set(os.path.join(Version.dataPath(), "shaders"))
# Enable the high priority timer if configured
if self.priority:
log.debug("Enabling high priority timer.")
self.fps = 0 # High priority
# evilynux - This was generating an error on the first pass (at least under
# GNU/Linux) as the Viewport was not set yet.
try:
viewport = glGetIntegerv(GL_VIEWPORT)
except Exception:
viewport = [0, 0, width, height]
h = viewport[3] - viewport[1]
w = viewport[2] - viewport[0]
geometry = (0, 0, w, h)
self.svg = SvgContext(geometry)
glViewport(int(viewport[0]), int(viewport[1]), int(viewport[2]), int(viewport[3]))
self.startupMessages = self.video.error
self.input = Input()
self.view = View(self, geometry)
self.resizeScreen(w, h)
self.resource = Resource(Version.dataPath())
self.mainloop = self.loading
self.menuMusic = False
self.setlistMsg = None
# Init theme system
themename = self.config.get("coffee", "themename")
themepath = os.path.join(Version.dataPath(), "themes", themename)
self._initTheme(themename, themepath)
self._initStages()
# Load game modifications
Mod.init(self)
self.task.addTask(self.input, synced = False)
self.task.addTask(self.view, synced = False)
self.task.addTask(self.resource, synced = False)
self.data = Data(self.resource, self.svg)
self.input.addKeyListener(FullScreenSwitcher(self), priority = True)
self.input.addSystemEventListener(SystemEventHandler(self))
self.debugLayer = None
self.startupLayer = None
self.loadingScreenShown = False
self.graphicMenuShown = False
log.debug("Ready.")
# evilynux - This stops the crowd cheers if they're still playing (issue 317).
def quit(self):
# evilynux - self.audio.close() crashes when we attempt to restart
if not self.restartRequested:
self.audio.close()
Player.savePlayers()
for taskData in list(self.task.tasks):
self.task.removeTask(taskData['task'])
self.running = False
def _initTheme(self, themename, themepath):
"""
Select the source of graphics for the game.
Note that currently this can only be called GameEngine on startup.
:param themename: what to call this theme
:type themename: str
:param themepath: absolute path to theme folder
:type themepath: str
"""
log.info('Setting theme %s from "%s"' % (themename,themepath))
self.theme = None
try:
# Look for "CustomTheme.py" inside theme dir
fp, pathname, description = imp.find_module("CustomTheme",[themepath])
try:
# Found it! Load it.
theme = imp.load_module("CustomTheme", fp, pathname, description)
self.theme = theme.CustomTheme(themepath, themename)
log.info('Theme activated using custom class "%s"' % pathname)
except ImportError as e:
# Unable to load module; log it, but continue with default Theme.
log.error('Failed to load CustomTheme.py from "%s"' % pathname)
finally:
fp.close()
except ImportError:
# CustomTheme.py file is optional, but notify developer anyway.
log.info("No CustomTheme.py found in theme")
pass
if self.theme is None:
self.theme = Theme(themepath, themename)
log.info("Theme activated using built-in Theme class")
self.task.addTask(self.theme)
def _initStages(self):
"""
Setup animated stages from already-setup theme.
Only call this after _initTheme().
# <themename>\Stages still contains the backgrounds for when stage rotation is off, and practice.png
# subfolders under Stages\ will each be treated as a separate animated stage set
"""
self.stageFolders = []
currentTheme = self.theme.name
themepath = self.theme.path
stagespath = os.path.join(themepath, "backgrounds")
if os.path.exists(stagespath):
self.stageFolders = []
allFolders = os.listdir(stagespath)
# this also includes all the stage files - so check to see if there
# is at least one .png file inside each folder to be sure it's an
# animated stage folder
for name in allFolders:
aniStageFolderListing = []
thisIsAnAnimatedStageFolder = False
try:
aniStageFolderListing = os.listdir(os.path.join(stagespath,name))
except Exception:
thisIsAnAnimatedStageFolder = False
for aniFile in aniStageFolderListing:
if os.path.splitext(aniFile)[1] in [".png", ".jpg", ".jpeg"]:
# we've found at least one .png file here, chances are this is a valid animated stage folder
thisIsAnAnimatedStageFolder = True
if thisIsAnAnimatedStageFolder:
self.stageFolders.append(name)
i = len(self.stageFolders)
if i > 0:
# only set default to first animated subfolder if one exists - otherwise use Normal!
defaultAniStage = str(self.stageFolders[0])
else:
defaultAniStage = "Normal"
log.debug("Default animated stage for " + currentTheme + " theme = " + defaultAniStage)
aniStageOptions = dict([(str(self.stageFolders[n]),self.stageFolders[n]) for n in range(0, i)])
aniStageOptions.update({"Normal":_("Slideshow")})
if i > 1:
# only add Random setting if more than one animated stage exists
aniStageOptions.update({"Random":_("Random")})
Config.define("game", "animated_stage_folder", str, defaultAniStage, text = _("Animated Stage"), options = aniStageOptions )
#MFH: here, need to track and check a new ini entry for last theme - so when theme changes we can re-default animated stage to first found
lastTheme = self.config.get("game","last_theme")
if lastTheme == "" or lastTheme != currentTheme:
#MFH - no last theme, and theme just changed:
# force defaultAniStage
self.config.set("game","animated_stage_folder",defaultAniStage)
self.config.set("game","last_theme",currentTheme)
selectedAnimatedStage = self.config.get("game", "animated_stage_folder")
if selectedAnimatedStage != "Normal" and selectedAnimatedStage != "Random":
if not os.path.exists(os.path.join(stagespath,selectedAnimatedStage)):
log.warn("Selected animated stage folder " + selectedAnimatedStage + " does not exist, forcing Normal.")
self.config.set("game","animated_stage_folder","Normal") #MFH: force "Standard" currently selected animated stage folder is invalid
else:
Config.define("game", "animated_stage_folder", str, "None", text = _("Animated Stage"), options = ["None",_("None")])
log.warn("No stages\ folder found, forcing None setting for Animated Stage.")
self.config.set("game","animated_stage_folder", "None") #MFH: force "None" when Stages folder can't be found
def setStartupLayer(self, startupLayer):
"""
Set the L{Layer} that will be shown when the all
the resources have been loaded. See L{Data}
@param startupLayer: Startup L{Layer}
"""
self.startupLayer = startupLayer
def isDebugModeEnabled(self):
return bool(self.debugLayer)
def setDebugModeEnabled(self, enabled):
"""
Show or hide the debug layer.
@type enabled: bool
"""
if enabled:
self.debugLayer = DebugLayer(self)
else:
self.debugLayer = None
def toggleFullscreen(self):
"""
Toggle between fullscreen and windowed mode.
@return: True on success
"""
if not self.video.toggleFullscreen():
# on windows, the fullscreen toggle kills our textures, se we must restart the whole game
self.input.broadcastSystemEvent("restartRequested")
self.config.set("video", "fullscreen", not self.video.fullscreen)
return True
self.config.set("video", "fullscreen", self.video.fullscreen)
return True
def restart(self):
"""Restart the game."""
if not self.restartRequested:
self.restartRequested = True
self.input.broadcastSystemEvent("restartRequested")
else:
self.quit()
def resizeScreen(self, width, height):
"""
Resize the game screen.
@param width: New width in pixels
@param height: New height in pixels
"""
self.view.setGeometry((0, 0, width, height))
self.svg.setGeometry((0, 0, width, height))
def startWorld(self, players, maxplayers = None, gameMode = 0, multiMode = 0, allowGuitar = True, allowDrum = True, allowMic = False, tutorial = False):
self.world = World(self, players, maxplayers, gameMode, multiMode, allowGuitar, allowDrum, allowMic, tutorial)
def finishGame(self):
if not self.world:
log.info("GameEngine.finishGame called before World created.")
return
self.world.finishGame()
self.world = None
self.gameStarted = False
self.view.pushLayer(self.mainMenu)
def loadImgDrawing(self, target, name, fileName, textureSize = None):
"""
Load an SVG drawing synchronously.
@param target: An object that will own the drawing
@param name: The name of the attribute the drawing will be assigned to
@param fileName: The name of the file in the data directory
@param textureSize: Either None or (x, y), in which case the file will
be rendered to an x by y texture
@return: L{ImgDrawing} instance
"""
return self.data.loadImgDrawing(target, name, fileName, textureSize)
#volshebnyi
def drawStarScore(self, screenwidth, screenheight, xpos, ypos, stars, scale = None, horiz_spacing = 1.2, space = 1.0, hqStar = False, align = LEFT):
minScale = 0.02
w = screenwidth
h = screenheight
if scale is None:
scale = minScale
elif scale < minScale:
scale = minScale
if self.data.fcStars and stars == 7:
star = self.data.starFC
else:
star = self.data.starPerfect
wide = scale * horiz_spacing
if align == CENTER: #center - akedrou (simplifying the alignment...)
xpos -= (2 * wide)
elif align == RIGHT: #right
xpos -= (4 * wide)
if stars > 5:
for j in range(5):
if self.data.maskStars:
if self.data.theme == 2:
drawImage(star, scale = (scale,-scale), coord = (w*(xpos+wide*j)*space**4,h*ypos), color = (1, 1, 0, 1), stretched = KEEP_ASPECT | FIT_WIDTH)
else:
drawImage(star, scale = (scale,-scale), coord = (w*(xpos+wide*j)*space**4,h*ypos), color = (0, 1, 0, 1), stretched = KEEP_ASPECT | FIT_WIDTH)
else:
drawImage(star, scale = (scale,-scale), coord = (w*(xpos+wide*j)*space**4,h*ypos), stretched = KEEP_ASPECT | FIT_WIDTH)
else:
for j in range(5):
if j < stars:
if hqStar:
star = self.data.star4
else:
star = self.data.star2
else:
if hqStar:
star = self.data.star3
else:
star = self.data.star1
drawImage(star, scale = (scale,-scale), coord = (w*(xpos+wide*j)*space**4,h*ypos), stretched = KEEP_ASPECT | FIT_WIDTH)
#glorandwarf: renamed to retrieve the path of the file
def fileExists(self, fileName):
return self.data.fileExists(fileName)
def getPath(self, fileName):
return self.data.getPath(fileName)
def loading(self):
"""Loading state loop."""
done = self.task.run()
self.clearScreen()
if self.data.essentialResourcesLoaded():
if not self.loadingScreenShown:
self.loadingScreenShown = True
Dialogs.showLoadingScreen(self, self.data.resourcesLoaded)
if self.startupLayer:
self.view.pushLayer(self.startupLayer)
self.mainloop = self.main
self.view.render()
self.video.flip()
return done
def clearScreen(self):
self.svg.clear(*self.theme.backgroundColor)
def fadeScreen(self, v):
"""
Fade the screen to a dark color to make whatever is on top easier to read.
@param v: Visibility factor [0..1], 0 is fully visible
"""
glEnable(GL_BLEND)
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
glEnable(GL_COLOR_MATERIAL)
glBegin(GL_TRIANGLE_STRIP)
glColor4f(0, 0, 0, .3 - v * .3)
glVertex2f(0, 0)
glColor4f(0, 0, 0, .3 - v * .3)
glVertex2f(1, 0)
glColor4f(0, 0, 0, .9 - v * .9)
glVertex2f(0, 1)
glColor4f(0, 0, 0, .9 - v * .9)
glVertex2f(1, 1)
glEnd()
def enableGarbageCollection(self, enabled):
"""
Enable or disable garbage collection whenever a random garbage
collection run would be undesirable. Disabling the garbage collector
has the unfortunate side-effect that your memory usage will skyrocket.
"""
if enabled:
gc.enable()
else:
gc.disable()
def collectGarbage(self):
"""
Run a garbage collection run.
"""
gc.collect()
def main(self):
"""Main state loop."""
done = self.task.run()
self.clearScreen()
self.view.render()
if self.debugLayer:
self.debugLayer.render(1.0, True)
self.video.flip()
# Calculate FPS every 2 seconds
if self.clock.fpsTime >= 2000:
# evilynux - Printing on the console with a frozen binary may cause a crash.
self.fpsEstimate = self.clock.get_fps()
if self.show_fps and not Version.isWindowsExe():
print("%.2f fps" % self.fpsEstimate)
return done
def run(self):
# Move tick and fps limiting here, the old location did not work well.
self.tickDelta = self.clock.tick()
rtn = self.mainloop()
self.clock.delay(self.fps)
return rtn