Beispiel #1
0
def getAvailableMods(engine):
    modPath = _getModPath(engine)
    try:
        dirList = os.listdir(modPath)
    except OSError:
        Log.warn("Could not find mods directory")
        return []
    return [m for m in dirList if os.path.isdir(os.path.join(modPath, m)) and not m.startswith(".")]
Beispiel #2
0
    def __init__(self, guitarScene, configFileName):
        self.scene = guitarScene
        self.engine = guitarScene.engine
        self.config = LinedConfigParser()
        self.backgroundLayers = []
        self.foregroundLayers = []
        self.textures = {}
        self.reset()

        self.wFull = None  #MFH - needed for new stage background handling
        self.hFull = None

        # evilynux - imported myfingershurt stuff from GuitarScene
        self.mode = self.engine.config.get("game", "stage_mode")
        self.songStage = self.engine.config.get("game", "song_stage")
        self.animatedFolder = self.engine.config.get("game",
                                                     "animated_stage_folder")

        # evilynux - imported myfingershurt stuff from GuitarScene w/ minor modifs
        #MFH TODO - alter logic to accommodate separated animation and slideshow
        #           settings based on selected animated stage folder
        animationMode = self.engine.config.get("game", "stage_animate")
        slideShowMode = self.engine.config.get("game", "rotate_stages")

        if self.animatedFolder == _("None"):
            self.rotationMode = 0  #MFH: if no animated stage folders are available, disable rotation.
        elif self.animatedFolder == "Normal":
            self.rotationMode = slideShowMode
        else:
            self.rotationMode = animationMode

        self.imgArr = []  #QQstarS:random
        self.imgArrScaleFactors = []  #MFH - for precalculated scale factors
        self.rotateDelay = self.engine.config.get(
            "game", "stage_rotate_delay"
        )  #myfingershurt - user defined stage rotate delay
        self.animateDelay = self.engine.config.get(
            "game", "stage_animate_delay"
        )  #myfingershurt - user defined stage rotate delay
        self.animation = False

        self.indexCount = 0  #QQstarS:random time counter
        self.arrNum = 0  #QQstarS:random the array num
        self.arrDir = 1  #forwards

        self.config.read(configFileName)

        # evilynux - Improved stage error handling
        self.themename = self.engine.data.themeLabel
        self.path = os.path.join("themes", self.themename, "backgrounds")
        self.pathfull = self.engine.getPath(self.path)
        if not os.path.exists(self.pathfull):  # evilynux
            Log.warn("Stage folder does not exist: %s" % self.pathfull)
            self.mode = 1  # Fallback to song-specific stage

        self.loadLayers(configFileName)
Beispiel #3
0
def getAvailableMods(engine):
    modPath = _getModPath(engine)
    try:
        dirList = os.listdir(modPath)
    except OSError:
        Log.warn("Could not find mods directory")
        return []
    return [
        m for m in dirList
        if os.path.isdir(os.path.join(modPath, m)) and not m.startswith(".")
    ]
Beispiel #4
0
 def multisampleReset(self, resolution):
     Log.warn("Video setup failed. Trying without antialiasing.")
     pygame.display.gl_set_attribute(pygame.GL_MULTISAMPLEBUFFERS, 0)
     pygame.display.gl_set_attribute(pygame.GL_MULTISAMPLESAMPLES, 0)
     self.multisamples = 0
     try:
         self.screen = pygame.display.set_mode(resolution, self.flags)
     except Exception, e:
         if "video mode" in str(e):
             self.resolutionReset()
         else:
             self.screenError()
Beispiel #5
0
    def __init__(self, guitarScene, configFileName):
        self.scene            = guitarScene
        self.engine           = guitarScene.engine
        self.config           = LinedConfigParser()
        self.backgroundLayers = []
        self.foregroundLayers = []
        self.textures         = {}
        self.reset()


        self.wFull = None   #MFH - needed for new stage background handling
        self.hFull = None

        # evilynux - imported myfingershurt stuff from GuitarScene
        self.mode = self.engine.config.get("game", "stage_mode")
        self.songStage = self.engine.config.get("game", "song_stage")
        self.animatedFolder = self.engine.config.get("game", "animated_stage_folder")

        # evilynux - imported myfingershurt stuff from GuitarScene w/ minor modifs
        #MFH TODO - alter logic to accommodate separated animation and slideshow
        #           settings based on selected animated stage folder
        animationMode = self.engine.config.get("game", "stage_animate")
        slideShowMode = self.engine.config.get("game", "rotate_stages")

        if self.animatedFolder == _("None"):
            self.rotationMode = 0   #MFH: if no animated stage folders are available, disable rotation.
        elif self.animatedFolder == "Normal":
            self.rotationMode = slideShowMode
        else:
            self.rotationMode = animationMode

        self.imgArr = [] #QQstarS:random
        self.imgArrScaleFactors = []  #MFH - for precalculated scale factors
        self.rotateDelay = self.engine.config.get("game",  "stage_rotate_delay") #myfingershurt - user defined stage rotate delay
        self.animateDelay = self.engine.config.get("game",  "stage_animate_delay") #myfingershurt - user defined stage rotate delay
        self.animation = False

        self.indexCount = 0 #QQstarS:random time counter
        self.arrNum = 0 #QQstarS:random the array num
        self.arrDir = 1 #forwards

        self.config.read(configFileName)

        # evilynux - Improved stage error handling
        self.themename = self.engine.data.themeLabel
        self.path = os.path.join("themes",self.themename,"backgrounds")
        self.pathfull = self.engine.getPath(self.path)
        if not os.path.exists(self.pathfull): # evilynux
            Log.warn("Stage folder does not exist: %s" % self.pathfull)
            self.mode = 1 # Fallback to song-specific stage

        self.loadLayers(configFileName)
Beispiel #6
0
    def init_oneshot(self):
        """ Determine if oneshot mode is valid. """
        # I think this code can be moved elsewhere...
        self.engine.cmdPlay = 0

        # Check for a valid invocation of one-shot mode.
        if self.playing is not None:
            Log.debug("Validating song directory for one-shot mode.")

            library = Config.get("setlist", "base_library")
            basefolder = os.path.join(Version.dataPath(), library, "songs", self.playing)

            if not os.path.exists(os.path.join(basefolder, "song.ini")):

                if not (
                    os.path.exists(os.path.join(basefolder, "notes.mid"))
                    or os.path.exists(os.path.join(basefolder, "notes-unedited.mid"))
                ):

                    if not (
                        os.path.exists(os.path.join(basefolder, "song.ogg"))
                        or os.path.exists(os.path.join(basefolder, "guitar.ogg"))
                    ):

                        Log.warn(
                            "Song directory provided ('%s') is not a valid song directory. Starting up FoFiX in standard mode."
                            % self.playing
                        )
                        self.engine.startupMessages.append(
                            _(
                                "Song directory provided ('%s') is not a valid song directory. Starting up FoFiX in standard mode."
                            )
                            % self.playing
                        )
                        return

            # Set up one-shot mode
            Log.debug("Entering one-shot mode.")
            Config.set("setlist", "selected_song", playing)

            self.engine.cmdPlay = 1

            if diff is not None:
                self.engine.cmdDiff = int(diff)
            if part is not None:
                self.engine.cmdPart = int(part)

            if players == 1:
                self.engine.cmdMode = players, mode, 0
            else:
                self.engine.cmdMode = players, 0, mode
Beispiel #7
0
 def resolutionReset(self):
     Log.warn("Video setup failed. Trying default windowed resolution.")
     self.error.append(_("Video setup failed with your resolution settings, and so were reset to defaults."))
     if self.fullscreen:
         self.flags ^= pygame.FULLSCREEN
         self.fullscreen = False
     try:
         self.screen = pygame.display.set_mode((800,600), self.flags)
         self.default = True
     except Exception:
         if self.multisamples:
             self.multisampleReset((800, 600))
         else:
             self.screenError()
Beispiel #8
0
    def init_oneshot(self):
        ''' Determine if oneshot mode is valid. '''
        # I think this code can be moved elsewhere...
        self.engine.cmdPlay = 0

        # Check for a valid invocation of one-shot mode.
        if self.playing is not None:
            Log.debug('Validating song directory for one-shot mode.')

            library = Config.get("setlist", "base_library")
            basefolder = os.path.join(Version.dataPath(), library, "songs",
                                      self.playing)

            if not os.path.exists(os.path.join(basefolder, "song.ini")):

                if not (os.path.exists(os.path.join(basefolder, "notes.mid"))
                        or os.path.exists(
                            os.path.join(basefolder, "notes-unedited.mid"))):

                    if not (os.path.exists(os.path.join(
                            basefolder, "song.ogg")) or os.path.exists(
                                os.path.join(basefolder, "guitar.ogg"))):

                        Log.warn(
                            "Song directory provided ('%s') is not a valid song directory. Starting up FoFiX in standard mode."
                            % self.playing)
                        self.engine.startupMessages.append(
                            _("Song directory provided ('%s') is not a valid song directory. Starting up FoFiX in standard mode."
                              ) % self.playing)
                        return

            # Set up one-shot mode
            Log.debug('Entering one-shot mode.')
            Config.set("setlist", "selected_song", playing)

            self.engine.cmdPlay = 1

            if diff is not None:
                self.engine.cmdDiff = int(diff)
            if part is not None:
                self.engine.cmdPart = int(part)

            if players == 1:
                self.engine.cmdMode = players, mode, 0
            else:
                self.engine.cmdMode = players, 0, mode
Beispiel #9
0
    def open(self, frequency = 22050, bits = 16, stereo = True, bufferSize = 1024):
        try:
            pygame.mixer.quit()
        except:
            pass

        try:
            pygame.mixer.init(frequency, -bits, stereo and 2 or 1, bufferSize)
        except:
            Log.warn("Audio setup failed. Trying with default configuration.")
            pygame.mixer.init()

        Log.debug("Audio configuration: %s" % str(pygame.mixer.get_init()))

        #myfingershurt: ensuring we have enough audio channels!
        pygame.mixer.set_num_channels(10)

        return True
Beispiel #10
0
    def open(self, frequency = 22050, bits = 16, stereo = True, bufferSize = 1024):
        try:
            pygame.mixer.quit()
        except:
            pass

        try:
            pygame.mixer.init(frequency, -bits, stereo and 2 or 1, bufferSize)
        except:
            Log.warn("Audio setup failed. Trying with default configuration.")
            pygame.mixer.init()

        Log.debug("Audio configuration: %s" % str(pygame.mixer.get_init()))

        #myfingershurt: ensuring we have enough audio channels!
        pygame.mixer.set_num_channels(10)

        return True
Beispiel #11
0
 def loadImage(self, image):
     """Load the texture from a PIL image"""
     image = image.transpose(Image.FLIP_TOP_BOTTOM)
     if image.mode == "RGBA":
         string = image.tostring('raw', 'RGBA', 0, -1)
         self.loadRaw(image.size, string, GL_RGBA, 4)
     elif image.mode == "RGB":
         string = image.tostring('raw', 'RGB', 0, -1)
         self.loadRaw(image.size, string, GL_RGB, 3)
     elif image.mode == "L":
         string = image.tostring('raw', 'L', 0, -1)
         self.loadRaw(image.size, string, GL_LUMINANCE, 1)
     else:
         try:
             image = image.convert('RGB')
             Log.warn("Unsupported image mode '%s' converted to 'RGB'. May have unexpected results." % image.mode)
             string = image.tostring('raw', 'RGB', 0, -1)
             self.loadRaw(image.size, string, GL_RGB, 3)
         except:
             raise TextureException("Unsupported image mode '%s'" % image.mode)
Beispiel #12
0
    def loadVideo(self, libraryName, songName):
        vidSource = None

        if self.songStage == 1:
            songBackgroundVideoPath = os.path.join(libraryName, songName,
                                                   "background.ogv")
            if os.path.isfile(songBackgroundVideoPath):
                vidSource = songBackgroundVideoPath
                loop = False
            else:
                Log.warn("Video not found: %s" % songBackgroundVideoPath)

        if vidSource is None:
            vidSource = os.path.join(self.pathfull, "default.ogv")
            loop = True

        if not os.path.isfile(vidSource):
            Log.warn("Video not found: %s" % vidSource)
            Log.warn("Falling back to default stage mode.")
            self.mode = 1  # Fallback
            return

        try:  # Catches invalid video files or unsupported formats
            Log.debug("Attempting to load video: %s" % vidSource)
            self.vidPlayer = VideoLayer(self.engine,
                                        vidSource,
                                        mute=True,
                                        loop=loop)
            self.engine.view.pushLayer(self.vidPlayer)
        except (IOError, VideoPlayerError):
            self.mode = 1
            Log.error(
                "Failed to load song video (falling back to default stage mode):"
            )
Beispiel #13
0
    def loadVideo(self, libraryName, songName):
        vidSource = None

        if self.songStage == 1:
            songBackgroundVideoPath = os.path.join(libraryName, songName, "background.ogv")
            if os.path.isfile(songBackgroundVideoPath):
                vidSource = songBackgroundVideoPath
                loop = False
            else:
                Log.warn("Video not found: %s" % songBackgroundVideoPath)

        if vidSource is None:
            vidSource = os.path.join(self.pathfull, "default.ogv")
            loop = True

        if not os.path.isfile(vidSource):
            Log.warn("Video not found: %s" % vidSource)
            Log.warn("Falling back to default stage mode.")
            self.mode = 1 # Fallback
            return

        try: # Catches invalid video files or unsupported formats
            Log.debug("Attempting to load video: %s" % vidSource)
            self.vidPlayer = VideoLayer(self.engine, vidSource,
                                        mute = True, loop = loop)
            self.engine.view.pushLayer(self.vidPlayer)
        except (IOError, VideoPlayerError):
            self.mode = 1
            Log.error("Failed to load song video (falling back to default stage mode):")
Beispiel #14
0
 def getImgDrawing(self, fileName, openImage=True):
     imgDrawing = None
     for dataPath in self.resource.dataPaths:
         fileName1 = os.path.join(dataPath, fileName)
         if self.logLoadings == 1:
             if openImage:
                 Log.notice("Trying to load image: %s" % fileName1)
             else:
                 Log.notice("Checking image: %s" % fileName1)
         #check if fileName1 exists (has extension)
         if os.path.exists(fileName1):
             if openImage:
                 try:
                     imgDrawing = ImgDrawing(self.svg, fileName1)
                     return imgDrawing
                 except IOError:
                     Log.warn("Unable to load image file: %s" % fileName1)
                 except OverflowError:
                     Log.warn("Unable to read image file: %s" % fileName1)
             else:
                 return True
         else:
             #find extension
             fileName1 = os.path.splitext(fileName1)[0]
             files = glob.glob('%s.*' % fileName1)
             if openImage:
                 for i in range(len(files)):
                     try:
                         imgDrawing = ImgDrawing(self.svg, files[i])
                         return imgDrawing
                     except IOError:
                         Log.warn("Unable to load image file: %s" %
                                  files[i])
             elif len(files) > 0:
                 return True
     #image not found
     if self.logImageNotFound:
         Log.debug("Image not found: %s" % fileName)
     return False
Beispiel #15
0
 def getImgDrawing(self, fileName, openImage=True):
     imgDrawing = None
     for dataPath in self.resource.dataPaths:
         fileName1 = os.path.join(dataPath, fileName)
         if self.logLoadings == 1:
             if openImage:
                 Log.notice("Trying to load image: %s" % fileName1)
             else:
                 Log.notice("Checking image: %s" % fileName1)
         #check if fileName1 exists (has extension)
         if os.path.exists(fileName1):
             if openImage == True:
                 try:
                     imgDrawing = ImgDrawing(self.svg, fileName1)
                     return imgDrawing
                 except IOError:
                     Log.warn("Unable to load image file: %s" % fileName1)
                 except OverflowError:
                     Log.warn("Unable to read image file: %s" % fileName1)
             else:
                 return True
         else:
             #find extension
             fileName1 = os.path.splitext(fileName1)[0]
             files = glob.glob('%s.*' % fileName1)
             if openImage == True:
                 for i in range(len(files)):
                     try:
                         imgDrawing = ImgDrawing(self.svg, files[i])
                         return imgDrawing
                     except IOError:
                         Log.warn("Unable to load image file: %s" % files[i])
             elif len(files) > 0:
                 return True
     #image not found
     if self.logImageNotFound:
         Log.debug("Image not found: %s" % fileName)
     return False
Beispiel #16
0
    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 not config:
            config = Config.load()

        self.config  = config

        fps          = self.config.get("video", "fps")

        self.fps = 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

        # evilynux - Check if theme icon exists first, then fallback on FoFiX icon.
        themename = self.config.get("coffee", "themename")
        themeicon = os.path.join(Version.dataPath(), "themes", themename, "icon.png")
        fofixicon = os.path.join(Version.dataPath(), "fofix_icon.png")
        icon = None
        if os.path.exists(themeicon):
            icon = themeicon
        elif os.path.exists(fofixicon):
            icon = fofixicon

        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.cmdPlay           = 0
        self.cmdMode           = None
        self.cmdDiff           = None
        self.cmdPart           = None

        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:
            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


        # 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)

        ##MFH: Animated stage folder selection option
        #<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 = themename

        stagespath = os.path.join(Version.dataPath(), "themes", currentTheme, "backgrounds")
        themepath  = os.path.join(Version.dataPath(), "themes", currentTheme)
        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:
                self.config.set("game","animated_stage_folder",defaultAniStage)   #force 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



        try:
            fp, pathname, description = imp.find_module("CustomTheme",[themepath])
            theme = imp.load_module("CustomTheme", fp, pathname, description)
            self.theme = theme.CustomTheme(themepath, themename)
        except ImportError:
            self.theme = Theme(themepath, themename)

        self.task.addTask(self.theme)


        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.")
Beispiel #17
0
 def checkControls(self):
     if self.controls.isKeyMappingOK() is False:
         Log.warn("Conflicting player controls, resetting to defaults")
         self.controls.restoreDefaultKeyMappings()
         self.reloadControls()
Beispiel #18
0
    def __init__(self, engine):
        self.engine              = engine

        self.logClassInits = Config.get("game", "log_class_inits")
        if self.logClassInits == 1:
            Log.debug("MainMenu class init (MainMenu.py)...")

        self.time                = 0.0
        self.nextLayer           = None
        self.visibility          = 0.0
        self.active              = False

        self.showStartupMessages = False

        self.gfxVersionTag = Config.get("game", "gfx_version_tag")

        self.chosenNeck = Config.get("game", "default_neck")
        exists = 0

        if engine.loadImgDrawing(self, "ok", os.path.join("necks",self.chosenNeck+".png")):
            exists = 1
        elif engine.loadImgDrawing(self, "ok", os.path.join("necks","Neck_"+self.chosenNeck+".png")):
            exists = 1

        #MFH - fallback logic now supports a couple valid default neck filenames
        #MFH - check for Neck_1
        if exists == 0:
            if engine.loadImgDrawing(self, "ok", os.path.join("necks","Neck_1.png")):
                Config.set("game", "default_neck", "1")
                Log.warn("Default chosen neck not valid; fallback Neck_1.png forced.")
                exists = 1

        #MFH - check for defaultneck
        if exists == 0:
            if engine.loadImgDrawing(self, "ok", os.path.join("necks","defaultneck.png")):
                Log.warn("Default chosen neck not valid; fallback defaultneck.png forced.")
                Config.set("game", "default_neck", "defaultneck")
                exists = 1
            else:
                Log.error("Default chosen neck not valid; fallbacks Neck_1.png and defaultneck.png also not valid!")

        #Get theme
        self.theme       = self.engine.data.theme
        self.themeCoOp   = self.engine.data.themeCoOp
        self.themename   = self.engine.data.themeLabel
        self.useSoloMenu = self.engine.theme.use_solo_submenu

        allowMic = True

        self.menux = self.engine.theme.menuPos[0]
        self.menuy = self.engine.theme.menuPos[1]

        self.rbmenu = self.engine.theme.menuRB

        #MFH
        self.main_menu_scale = self.engine.theme.main_menu_scaleVar
        self.main_menu_vspacing = self.engine.theme.main_menu_vspacingVar

        if not self.engine.loadImgDrawing(self, "background", os.path.join("themes",self.themename,"menu","mainbg.png")):
            self.background = None
        self.engine.loadImgDrawing(self, "BGText", os.path.join("themes",self.themename,"menu","maintext.png"))
        self.engine.loadImgDrawing(self, "optionsBG", os.path.join("themes",self.themename,"menu","optionsbg.png"))
        self.engine.loadImgDrawing(self, "optionsPanel", os.path.join("themes",self.themename,"menu","optionspanel.png"))

        #racer: added version tag
        if self.gfxVersionTag or self.engine.theme.versiontag:
            if not self.engine.loadImgDrawing(self, "version", os.path.join("themes",self.themename,"menu","versiontag.png")):
                if not self.engine.loadImgDrawing(self, "version", "versiontag.png"): #falls back on default versiontag.png in data\ folder
                    self.version = None
        else:
            self.version = None

        #myfingershurt: random main menu music function, menu.ogg and menuXX.ogg (any filename with "menu" as the first 4 letters)
        self.files = None
        filepath = self.engine.getPath(os.path.join("themes",self.themename,"sounds"))
        if os.path.isdir(filepath):
            self.files = []
            allfiles = os.listdir(filepath)
            for name in allfiles:
                if os.path.splitext(name)[1] == ".ogg":
                    if string.find(name,"menu") > -1:
                        self.files.append(name)


        if self.files:
            i = random.randint(0,len(self.files)-1)
            filename = self.files[i]
            sound = os.path.join("themes",self.themename,"sounds",filename)
            self.menumusic = True
            engine.menuMusic = True

            self.song = Audio.Music(self.engine.resource.fileName(sound))
            self.song.setVolume(self.engine.config.get("audio", "menu_volume"))
            self.song.play(0)  #no loop
        else:
            self.menumusic = False

        self.opt_text_color     = self.engine.theme.opt_text_colorVar
        self.opt_selected_color = self.engine.theme.opt_selected_colorVar

        trainingMenu = [
          (_("Tutorials"), self.showTutorial),
          (_("Practice"), lambda: self.newLocalGame(mode1p = 1)),
        ]

        self.opt_bkg_size = [float(i) for i in self.engine.theme.opt_bkg_size]
        self.opt_text_color = self.engine.theme.opt_text_colorVar
        self.opt_selected_color = self.engine.theme.opt_selected_colorVar

        if self.BGText:
            strCareer = ""
            strQuickplay = ""
            strSolo = ""
            strMultiplayer = ""
            strTraining = ""
            strSettings = ""
            strQuit = ""
        else:
            strCareer = "Career"
            strQuickplay = "Quickplay"
            strSolo = "Solo"
            strMultiplayer = "Multiplayer"
            strTraining = "Training"
            strSettings = "Settings"
            strQuit = "Quit"

        multPlayerMenu = [
            (_("Face-Off"),     lambda: self.newLocalGame(players = 2,             maxplayers = 4)),
            (_("Pro Face-Off"), lambda: self.newLocalGame(players = 2, mode2p = 1, maxplayers = 4)),
            (_("Party Mode"),   lambda: self.newLocalGame(             mode2p = 2)),
            (_("FoFiX Co-Op"),  lambda: self.newLocalGame(players = 2, mode2p = 3, maxplayers = 4, allowMic = allowMic)),
            (_("RB Co-Op"),     lambda: self.newLocalGame(players = 2, mode2p = 4, maxplayers = 4, allowMic = allowMic)),
            (_("GH Co-Op"),     lambda: self.newLocalGame(players = 2, mode2p = 5, maxplayers = 4)),
            (_("GH Battle"),    lambda: self.newLocalGame(players = 2, mode2p = 6, allowDrum = False)), #akedrou- so you can block drums
          ]

        if not self.useSoloMenu:

            mainMenu = [
              (strCareer, lambda:   self.newLocalGame(mode1p = 2, allowMic = allowMic)),
              (strQuickplay, lambda:        self.newLocalGame(allowMic = allowMic)),
              ((strMultiplayer,"multiplayer"), multPlayerMenu),
              ((strTraining,"training"),    trainingMenu),
              ((strSettings,"settings"),  self.settingsMenu),
              (strQuit,        self.quit),
            ]

        else:

            soloMenu = [
              (_("Solo Tour"), lambda: self.newLocalGame(mode1p = 2, allowMic = allowMic)),
              (_("Quickplay"), lambda: self.newLocalGame(allowMic = allowMic)),
            ]

            mainMenu = [
              ((strSolo,"solo"), soloMenu),
              ((strMultiplayer,"multiplayer"), multPlayerMenu),
              ((strTraining,"training"),    trainingMenu),
              ((strSettings,"settings"),  self.settingsMenu),
              (strQuit,        self.quit),
            ]


        w, h, = self.engine.view.geometry[2:4]

        self.menu = Menu(self.engine, mainMenu, onClose = lambda: self.engine.view.popLayer(self), pos = (self.menux, .75-(.75*self.menuy)))

        engine.mainMenu = self    #Points engine.mainMenu to the one and only MainMenu object instance

        ## whether the main menu has come into view at least once
        self.shownOnce = False
Beispiel #19
0
from fofix.core import Config

Config.define("game", "language", str, "")

def getAvailableLanguages():
    return [os.path.basename(l).capitalize().replace(".mo", "").replace("_", " ") for l in glob.glob(os.path.join(Version.dataPath(), "translations", "*.mo"))]

def dummyTranslator(string):
    return unicodify(string)

language = Config.load(Version.PROGRAM_UNIXSTYLE_NAME + ".ini").get("game", "language")
_ = dummyTranslator

if language:
    try:
        trFile = os.path.join(Version.dataPath(), "translations", "%s.mo" % language.lower().replace(" ", "_"))
        catalog = gettext.GNUTranslations(open(trFile, "rb"))
        def translate(m):
            return catalog.ugettext(m)
        _ = translate
    except Exception as x:
        Log.warn("Unable to select language '%s': %s" % (language, x))
        language = None
        Config.set("game", "language", "")

# Define the config key again now that we have some options for it
langOptions = {"": "English"}
for lang in getAvailableLanguages():
    langOptions[lang] = _(lang)
Config.define("game", "language", str, "", _("Language"), langOptions, tipText = _("Change the game language!"))
Beispiel #20
0
    def set(self, dir):
        """Do all shader setup.
           dir = directory to load shaders from
        """

        #stump: check whether all needed extensions are actually supported
        if not glInitShaderObjectsARB():
            Log.warn('OpenGL extension ARB_shader_objects not supported - shaders disabled')
            return
        if not glInitVertexShaderARB():
            Log.warn('OpenGL extension ARB_vertex_shader not supported - shaders disabled')
            return
        if not glInitFragmentShaderARB():
            Log.warn('OpenGL extension ARB_fragment_shader not supported - shaders disabled')
            return
        if not glInitMultitextureARB():
            Log.warn('OpenGL extension ARB_multitexture not supported - shaders disabled')
            return
        if not glInitTexture3DEXT():
            if sys.platform != 'darwin':
                Log.warn('OpenGL extension EXT_texture3D not supported - shaders disabled')
                return

        self.workdir = dir

        # Load textures needed by the shaders.
        try:
            self.noise3D = self.loadTex3D("noise3d.dds")
            self.outline = self.loadTex2D("outline.tga")
        except:
            Log.error('Could not load shader textures - shaders disabled: ')
            return

        self.multiTex = (GL_TEXTURE0_ARB,GL_TEXTURE1_ARB,GL_TEXTURE2_ARB,GL_TEXTURE3_ARB)
        self.enabled = True
        self.turnon = True

        # Compile the shader objects that we are going to use.
        # Also set uniform shader variables to default values.
        try:
            self.make("lightning","stage")
        except:
            Log.error("Error compiling lightning shader: ")
        else:
            self.enable("stage")
            self.setVar("ambientGlowHeightScale",6.0)
            self.setVar("color",(0.0,0.0,0.0,0.0))
            self.setVar("glowFallOff",0.024)
            self.setVar("height",0.44)
            self.setVar("sampleDist",0.0076)
            self.setVar("speed",1.86)
            self.setVar("vertNoise",0.78)
            self.setVar("fading",1.0)
            self.setVar("solofx",False)
            self.setVar("scalexy",(5.0,2.4))
            self.setVar("fixalpha",True)
            self.setVar("offset",(0.0,-2.5))
            self.disable()

        try:
            self.make("lightning","sololight")
        except:
            Log.error("Error compiling lightning shader: ")
        else:
            self.enable("sololight")
            self.setVar("scalexy",(5.0,1.0))
            self.setVar("ambientGlow",0.5)
            self.setVar("ambientGlowHeightScale",6.0)
            self.setVar("solofx",True)
            self.setVar("height",0.3)
            self.setVar("glowFallOff",0.024)
            self.setVar("sampleDist",0.0076)
            self.setVar("fading",4.0)
            self.setVar("speed",1.86)
            self.setVar("vertNoise",0.78)
            self.setVar("solofx",True)
            self.setVar("color",(0.0,0.0,0.0,0.0))
            self.setVar("fixalpha",True)
            self.setVar("glowStrength",100.0)
            self.disable()

        try:
            self.make("lightning","tail")
        except:
            Log.error("Error compiling lightning shader: ")
        else:
            self.enable("tail")
            self.setVar("scalexy",(5.0,1.0))
            self.setVar("ambientGlow",0.1)
            self.setVar("ambientGlowHeightScale",6.0)
            self.setVar("solofx",True)
            self.setVar("fading",4.0)
            self.setVar("height",0.0)
            self.setVar("glowFallOff",0.024)
            self.setVar("sampleDist",0.0076)
            self.setVar("speed",1.86)
            self.setVar("vertNoise",0.78)
            self.setVar("solofx",True)
            self.setVar("color",(0.3,0.7,0.9,0.6))
            self.setVar("glowStrength",70.0)
            self.setVar("fixalpha",True)
            self.setVar("offset",(0.0,0.0))
            self.disable()

        try:
            self.make("rockbandtail","tail2")
        except:
            Log.error("Error compiling rockbandtail shader: ")
        else:
            self.enable("tail2")
            self.setVar("height",0.2)
            self.setVar("color",(0.0,0.6,1.0,1.0))
            self.setVar("speed",9.0)
            self.setVar("offset",(0.0,0.0))
            self.setVar("scalexy",(5.0,1.0))
            self.disable()

        try:
            self.make("metal","notes")
        except:
            Log.error("Error compiling metal shader: ")
        else:
            self.enable("notes")
            self.disable()

        try:
            self.make("neck","neck")
        except:
            Log.error("Error compiling neck shader: ")

        try:
            self.make("cd","cd")
        except:
            Log.error("Error compiling cd shader: ")
Beispiel #21
0
 def checkControls(self):
     if self.controls.isKeyMappingOK() == False:
         Log.warn("Conflicting player controls, resetting to defaults")
         self.controls.restoreDefaultKeyMappings()
         self.reloadControls()
Beispiel #22
0
    def set(self, dir):
        """Do all shader setup.
           dir = directory to load shaders from
        """

        #stump: check whether all needed extensions are actually supported
        if not glInitShaderObjectsARB():
            Log.warn(
                'OpenGL extension ARB_shader_objects not supported - shaders disabled'
            )
            return
        if not glInitVertexShaderARB():
            Log.warn(
                'OpenGL extension ARB_vertex_shader not supported - shaders disabled'
            )
            return
        if not glInitFragmentShaderARB():
            Log.warn(
                'OpenGL extension ARB_fragment_shader not supported - shaders disabled'
            )
            return
        if not glInitMultitextureARB():
            Log.warn(
                'OpenGL extension ARB_multitexture not supported - shaders disabled'
            )
            return
        if not glInitTexture3DEXT():
            if sys.platform != 'darwin':
                Log.warn(
                    'OpenGL extension EXT_texture3D not supported - shaders disabled'
                )
                return

        self.workdir = dir

        # Load textures needed by the shaders.
        try:
            self.noise3D = self.loadTex3D("noise3d.dds")
            self.outline = self.loadTex2D("outline.tga")
        except:
            Log.error('Could not load shader textures - shaders disabled: ')
            return

        self.multiTex = (GL_TEXTURE0_ARB, GL_TEXTURE1_ARB, GL_TEXTURE2_ARB,
                         GL_TEXTURE3_ARB)
        self.enabled = True
        self.turnon = True

        # Compile the shader objects that we are going to use.
        # Also set uniform shader variables to default values.
        try:
            self.make("lightning", "stage")
        except:
            Log.error("Error compiling lightning shader: ")
        else:
            self.enable("stage")
            self.setVar("ambientGlowHeightScale", 6.0)
            self.setVar("color", (0.0, 0.0, 0.0, 0.0))
            self.setVar("glowFallOff", 0.024)
            self.setVar("height", 0.44)
            self.setVar("sampleDist", 0.0076)
            self.setVar("speed", 1.86)
            self.setVar("vertNoise", 0.78)
            self.setVar("fading", 1.0)
            self.setVar("solofx", False)
            self.setVar("scalexy", (5.0, 2.4))
            self.setVar("fixalpha", True)
            self.setVar("offset", (0.0, -2.5))
            self.disable()

        try:
            self.make("lightning", "sololight")
        except:
            Log.error("Error compiling lightning shader: ")
        else:
            self.enable("sololight")
            self.setVar("scalexy", (5.0, 1.0))
            self.setVar("ambientGlow", 0.5)
            self.setVar("ambientGlowHeightScale", 6.0)
            self.setVar("solofx", True)
            self.setVar("height", 0.3)
            self.setVar("glowFallOff", 0.024)
            self.setVar("sampleDist", 0.0076)
            self.setVar("fading", 4.0)
            self.setVar("speed", 1.86)
            self.setVar("vertNoise", 0.78)
            self.setVar("solofx", True)
            self.setVar("color", (0.0, 0.0, 0.0, 0.0))
            self.setVar("fixalpha", True)
            self.setVar("glowStrength", 100.0)
            self.disable()

        try:
            self.make("lightning", "tail")
        except:
            Log.error("Error compiling lightning shader: ")
        else:
            self.enable("tail")
            self.setVar("scalexy", (5.0, 1.0))
            self.setVar("ambientGlow", 0.1)
            self.setVar("ambientGlowHeightScale", 6.0)
            self.setVar("solofx", True)
            self.setVar("fading", 4.0)
            self.setVar("height", 0.0)
            self.setVar("glowFallOff", 0.024)
            self.setVar("sampleDist", 0.0076)
            self.setVar("speed", 1.86)
            self.setVar("vertNoise", 0.78)
            self.setVar("solofx", True)
            self.setVar("color", (0.3, 0.7, 0.9, 0.6))
            self.setVar("glowStrength", 70.0)
            self.setVar("fixalpha", True)
            self.setVar("offset", (0.0, 0.0))
            self.disable()

        try:
            self.make("rockbandtail", "tail2")
        except:
            Log.error("Error compiling rockbandtail shader: ")
        else:
            self.enable("tail2")
            self.setVar("height", 0.2)
            self.setVar("color", (0.0, 0.6, 1.0, 1.0))
            self.setVar("speed", 9.0)
            self.setVar("offset", (0.0, 0.0))
            self.setVar("scalexy", (5.0, 1.0))
            self.disable()

        try:
            self.make("metal", "notes")
        except:
            Log.error("Error compiling metal shader: ")
        else:
            self.enable("notes")
            self.disable()

        try:
            self.make("neck", "neck")
        except:
            Log.error("Error compiling neck shader: ")

        try:
            self.make("cd", "cd")
        except:
            Log.error("Error compiling cd shader: ")
Beispiel #23
0
    def __init__(self, engine, choices, name = None, onClose = None, onCancel = None, pos = (.2, .31), viewSize = 6, fadeScreen = False, font = "font", mainMenu = None, textColor = None, selectedColor = None, append_submenu_char = True, selectedIndex = None, showTips = True, selectedBox = False):
        self.engine       = engine

        self.logClassInits = self.engine.config.get("game", "log_class_inits")
        if self.logClassInits == 1:
            Log.debug("Menu class init (Menu.py)...")

        #Get theme
        self.themename = self.engine.data.themeLabel
        self.theme = self.engine.data.theme

        self.choices      = []
        self.currentIndex = 0
        #MFH
        if selectedIndex:
            self.currentIndex = selectedIndex
        self.time         = 0
        self.onClose      = onClose
        self.onCancel     = onCancel
        self.viewOffset   = 0
        self.name     = name # akedrou - for graphical support
        self.mainMenu = False
        self.graphicMenu = False
        self.useSelectedBox = selectedBox
        self.useGraphics = self.engine.config.get("game", "use_graphical_submenu")
        self.gfxText = None

        self.scrolling = 0
        self.delay     = 0
        self.rate      = 0
        self.scroller  = [0, self.scrollUp, self.scrollDown, self.scrollLeft, self.scrollRight]

        self.textColor = textColor
        self.selectedColor = selectedColor
        self.tipColor = self.engine.theme.menuTipTextColor

        self.drumNav = self.engine.config.get("game", "drum_navigation")  #MFH

        if self.name and self.useGraphics > 0:
            try:
                if self.engine.loadImgDrawing(self, "menuBackground", os.path.join("themes",self.themename,"menu","%s.png" % self.name)):
                    if self.menuBackground.height1() == 1:
                        raise KeyError
                else:
                    raise KeyError
                self.gfxText = "%stext%d" % (self.name, len(choices))
                if not self.engine.loadImgDrawing(self, "menuText", os.path.join("themes",self.themename,"menu","%s.png" % self.gfxText)):
                    raise KeyError
                self.graphicMenu = True
                self.menux = self.engine.theme.submenuX[self.gfxText]
                self.menuy = self.engine.theme.submenuY[self.gfxText]
                self.menuScale = self.engine.theme.submenuScale[self.gfxText]
                self.vSpace = self.engine.theme.submenuVSpace[self.gfxText]
                if str(self.menux) != "None" and str(self.menuy) != "None":
                    self.menux = float(self.menux)
                    self.menuy = float(self.menuy)
                else:
                    self.menux = .4
                    self.menuy = .4
                if str(self.menuScale) != "None":
                    self.menuScale = float(self.menuScale)
                else:
                    self.menuScale = .5
                if str(self.vSpace) != "None":
                    self.vSpace = float(self.vSpace)
                else:
                    self.vSpace = .08
                Log.debug("Graphic menu enabled for submenu: %s" % self.name)
            except KeyError:
                Log.warn("Your theme does not appear to properly support the %s graphical submenu. Check to be sure you have the latest version of your theme." % self.name)
                self.menuBackground = None
                self.menuText = None


        if pos == (.2, .66 - .35):  #MFH - default position, not called with a special one - this is a submenu:
            self.sub_menu_x = self.engine.theme.sub_menu_xVar
            self.sub_menu_y = self.engine.theme.sub_menu_yVar

            if engine.data.theme == 0:
                if self.sub_menu_x is None:
                    self.sub_menu_x = .44
                if self.sub_menu_y is None:
                    self.sub_menu_y = .14
            elif engine.data.theme == 1:
                if self.sub_menu_x is None:
                    self.sub_menu_x = .38
                if self.sub_menu_y is None:
                    self.sub_menu_y = .15
            elif engine.data.theme == 2:
                if self.sub_menu_x is None:
                    self.sub_menu_x = .25
                if self.sub_menu_y is None:
                    self.sub_menu_y = .14

            pos = (self.sub_menu_x, self.sub_menu_y)

        if viewSize == 6:   #MFH - default viewsize
            if self.theme in [0, 1, 2]:#8bit
                viewSize = 10

        self.pos          = pos
        self.viewSize     = viewSize
        self.fadeScreen   = fadeScreen
        self.font         = font
        if self.font == "font":
            self.font = self.engine.data.font
        self.tipFont = self.engine.theme.menuTipTextFont
        if self.tipFont == "None":
            self.tipFont = self.font
        else:
            self.tipFont = self.engine.data.fontDict[self.tipFont]
        self.active = False
        self.mainMenu = mainMenu

        self.showTips = showTips
        if self.showTips:
            self.showTips = self.engine.theme.menuTipTextDisplay
        self.tipDelay = 700
        self.tipTimerEnabled = False
        self.tipScroll = 0
        self.tipScrollB = None
        self.tipScrollSpace = self.engine.theme.menuTipTextScrollSpace
        self.tipScale = self.engine.theme.menuTipTextScale
        self.tipDir = 0
        self.tipSize = 0
        self.tipY = self.engine.theme.menuTipTextY
        self.tipScrollMode = self.engine.theme.menuTipTextScrollMode # - 0 for constant scroll; 1 for back and forth

        for c in choices:
            try:
                text, callback = c
                if isinstance(text, tuple):
                    if len(text) == 2: # a submenu's name
                        c = Choice(text[0], callback, name = text[1], append_submenu_char = append_submenu_char)
                    else: # Dialogs menus - FileChooser, NeckChooser, ItemChooser - this last to be changed soon
                        c = Choice(text[0], callback, values = text[2], valueIndex = text[1], append_submenu_char = append_submenu_char)
                else:
                    c = Choice(text, callback, append_submenu_char = append_submenu_char)
            except ValueError:
                text, callback, tipText = c
                if isinstance(text, tuple):
                    if len(text) == 2: # a submenu's name
                        c = Choice(text[0], callback, name = text[1], append_submenu_char = append_submenu_char, tipText = tipText)
                    else: # Dialogs menus - FileChooser, NeckChooser, ItemChooser - this last to be changed soon
                        c = Choice(text[0], callback, values = text[2], valueIndex = text[1], append_submenu_char = append_submenu_char, tipText = tipText)
                else:
                    c = Choice(text, callback, append_submenu_char = append_submenu_char, tipText = tipText)
            except TypeError:
                pass
            self.choices.append(c)

        self.setTipScroll()
Beispiel #24
0
    def __init__(self, resource, svg):

        self.logClassInits = Config.get("game", "log_class_inits")
        if self.logClassInits == 1:
            Log.debug("Data class init (Data.py)...")
        self.logLoadings = Config.get("game", "log_loadings")

        self.logImageNotFound = Config.get("log", "log_image_not_found")

        self.resource = resource
        self.svg      = svg

        self.sfxVolume    = Config.get("audio", "SFX_volume")
        self.crowdVolume  = Config.get("audio", "crowd_volume")

        #Get theme
        themename = Config.get("coffee", "themename")
        self.themeLabel = themename
        self.themeCoOp  = False

        self.players = None
        self.players = Player.loadPlayers()

        #myfingershurt: check for existence of theme path
        themepath = os.path.join(Version.dataPath(), "themes")
        self.themepath = themepath
        self.path = Version.dataPath()

        if not self.checkImgDrawing(os.path.join("themes",themename,"notes","notes.png")):
            #myfingershurt: here need to ensure an existing theme is selected
            themes = []
            defaultTheme = None           #myfingershurt
            allthemes = os.listdir(themepath)
            for name in allthemes:
                if self.checkImgDrawing(os.path.join("themes",name,"notes","notes.png")):
                    themes.append(name)
                    if name == "MegaLight V4":         #myfingershurt
                        defaultTheme = name     #myfingershurt
            if defaultTheme != "MegaLight V4":     #myfingershurt
                defaultTheme = themes[0]    #myfingershurt
            #not a valid theme if notes.png isn't there!  Force default theme:
            Config.set("coffee", "themename",defaultTheme)
            #re-init Data with new default
            themename = defaultTheme
            self.themeLabel = themename


        if not os.path.exists(os.path.join(Version.dataPath(), "themes", themename, "vocals")):
            self.vocalPath = "vocals"
        else:
            self.vocalPath = os.path.join("themes",themename,"vocals")

        self.theme = 2
        self.themeCoOp = True

        self.fontScreenBottom = 0.75      #from our current viewport's constant 3:4 aspect ratio (which is always stretched to fill the video resolution)

        self.loadPartImages()
        #myfingershurt: multi-OS compatibility file access fixes using os.path.join()
        # load font customization images

        #Worldrave - Use new defined Star3 and star4. Using star1 and star2 as a fallback.

        #MFH - no more custom glyphs, these are wasting memory.
        #MFH - but we do need these star1-4 images anyway.  Leaving them loaded here in the Data object.
        self.loadImgDrawing(self, "star1",   os.path.join("themes",themename,"star1.png"), textureSize = (128, 128))
        self.loadImgDrawing(self, "star2",   os.path.join("themes",themename,"star2.png"), textureSize = (128, 128))

        #MFH - let's not rely on errors here if we don't have to...
        if not self.loadImgDrawing(self, "star3",   os.path.join("themes",themename,"star3.png"), textureSize = (128, 128)):
            self.star3 = self.star1
        if not self.loadImgDrawing(self, "star4",   os.path.join("themes",themename,"star4.png"), textureSize = (128, 128)):
            self.star4 = self.star2


        if self.loadImgDrawing(self, "starPerfect",   os.path.join("themes",themename,"starperfect.png"), textureSize = (128, 128)):
            self.perfectStars = True
            self.maskStars = False
        else:
            self.starPerfect = self.star2
            self.fcStars   = False
            self.starFC     = self.star2
            self.maskStars = True
            self.perfectStars = False

        if self.perfectStars:
            if self.loadImgDrawing(self, "starFC",   os.path.join("themes",themename,"starfc.png"), textureSize = (128, 128)):
                self.fcStars   = True
            else:
                self.starFC = self.starPerfect
                self.fcStars = False

        # load misc images
        self.loadImgDrawing(self, "loadingImage", os.path.join("themes",themename,"loadingbg.png"), textureSize = (256,256))
        self.loadImgDrawing(self, "optionsBG", os.path.join("themes",themename,"menu","optionsbg.png"))
        if self.loadImgDrawing(self, "submenuSelect", os.path.join("themes",themename,"submenuselect.png")):
            subSelectImgW = self.submenuSelect.width1()
            self.submenuSelectFound = True
            self.subSelectWFactor = 640.000/subSelectImgW
            self.subSelectImgH = self.submenuSelect.height1()
        else:
            self.submenuSelectFound = False
            self.loadImgDrawing(self, "submenuSelect", os.path.join("themes",themename,"menu","selected.png"))
            self.subSelectWFactor = 0
        # load all the data in parallel
        # asciiOnly = not bool(Language.language) or Language.language == "Custom"
        # reversed  = _("__lefttoright__") == "__righttoleft__" and True or False
        asciiOnly = True
        reversed  = False
        scale     = 1
        # evilynux - Load bigger fonts so they're nicer when scaled, scaling readjusted
        fontSize  = [44, 132, 34, 32, 30]
        w, h = [int(s) for s in Config.get("video", "resolution").split("x")]
        aspectRatio = float(w)/float(h)

        self.fontList = [
          ["font1","font","default.ttf",fontSize[4]],
          ["font2","bigFont","title.ttf",fontSize[1]],
          ["font3","pauseFont","pause.ttf",fontSize[2]],
          ["font4","scoreFont","score.ttf",fontSize[3]],
          ["font5","streakFont","streak.ttf",fontSize[3]],
          ["font6","loadingFont","loading.ttf",fontSize[3]],
          ["font7","songFont","song.ttf",fontSize[4]],
          ["font8","songListFont","songlist.ttf",fontSize[3]],
          ["font9","shadowFont","songlist.ttf",fontSize[3]],
          ["font10","streakFont2","streakphrase.ttf",fontSize[2]]
        ]
        for f in self.fontList:
            if self.fileExists(os.path.join("themes",themename,"fonts",f[2])):
                fn = resource.fileName(os.path.join("themes",themename,"fonts",f[2]))
                f[0] = lambda: Font(fn, f[3], scale = scale*.5, reversed = reversed, systemFont = not asciiOnly, outline = False, aspectRatio = aspectRatio)
                resource.load(self,f[1],f[0], synch = True)
            elif self.fileExists(os.path.join("themes",themename,"fonts","default.ttf")):
                Log.debug("Theme font not found: " + f[2])
                fn = resource.fileName(os.path.join("themes",themename,"fonts","default.ttf"))
                f[0] = lambda: Font(fn, f[3], scale = scale*.5, reversed = reversed, systemFont = not asciiOnly, outline = False, aspectRatio = aspectRatio)
                resource.load(self,f[1],f[0], synch = True)
            else:
                Log.debug("Default theme font not found: %s - using built-in default" % str(f[2]))
                fn = resource.fileName(os.path.join("fonts","default.ttf"))
                f[0] = lambda: Font(fn, f[3], scale = scale*.5, reversed = reversed, systemFont = not asciiOnly, outline = False, aspectRatio = aspectRatio)
                resource.load(self,f[1],f[0], synch = True)


        self.fontDict = {"font": self.font, "bigFont": self.bigFont, "pauseFont": self.pauseFont, "scoreFont": self.scoreFont, \
                         "streakFont": self.streakFont, "songFont": self.songFont, "streakFont2": self.streakFont2, \
                         "songListFont": self.songListFont, "shadowFont": self.shadowFont, "loadingFont": self.loadingFont}

        assert self.fontDict['font'] == self.font

        # load sounds asynchronously
        resource.load(self, "screwUpsounds", self.loadScrewUpsounds)
        resource.load(self, "screwUpsoundsBass", self.loadScrewUpsoundsBass)
        resource.load(self, "screwUpsoundsDrums", self.loadScrewUpsoundsDrums)
        resource.load(self, "acceptSounds", self.loadAcceptSounds)
        resource.load(self, "cancelSounds", self.loadBackSounds)

        # loadSoundEffect asynchronously
        self.syncSounds = [
          ["bassDrumSound","bassdrum.ogg"],
          ["battleUsedSound","battleused.ogg"],
          ["CDrumSound","crash.ogg"],
          ["clapSound","clapsound.ogg"],
          ["coOpFailSound","coopfail.ogg"],
          #["crowdSound","crowdcheers.ogg"],
          ["failSound","failsound.ogg"],
          ["rescueSound","rescue.ogg"],
          ["rockSound","rocksound.ogg"],
          ["selectSound1","select1.ogg"],
          ["selectSound2","select2.ogg"],
          ["selectSound3","select3.ogg"],
          ["starActivateSound","staractivate.ogg"],
          ["starDeActivateSound","stardeactivate.ogg"],
          ["starDingSound","starding.ogg"],
          ["starLostSound","starlost.ogg"],
          ["starReadySound","starpowerready.ogg"],
          ["starSound","starpower.ogg"],
          ["startSound","start.ogg"],
          ["T1DrumSound","tom01.ogg"],
          ["T2DrumSound","tom02.ogg"],
          ["T3DrumSound","tom03.ogg"]
        ]
        for self.sounds in self.syncSounds:
            if self.fileExists(os.path.join("themes",themename,"sounds",self.sounds[1])):
                self.loadSoundEffect(self, self.sounds[0], os.path.join("themes",themename,"sounds",self.sounds[1]))
            elif self.fileExists(os.path.join("sounds", self.sounds[1])):
                Log.debug("Theme sound not found: " + self.sounds[1])
                self.loadSoundEffect(self, self.sounds[0], os.path.join("sounds",self.sounds[1]))
            else:
                Log.warn("File " + self.sounds[1] + " not found using default instead.")
                self.loadSoundEffect(self, self.sounds[0], os.path.join("sounds","default.ogg"))

        #TODO: Simplify crowdSound stuff so it can join the rest of us.
        #MFH - fallback on sounds/crowdcheers.ogg, and then starpower.ogg. Note if the fallback crowdcheers was used or not.
        if self.fileExists(os.path.join("themes",themename,"sounds","crowdcheers.ogg")):
            self.loadSoundEffect(self, "crowdSound", os.path.join("themes",themename,"sounds","crowdcheers.ogg"), crowd = True)
            self.cheerSoundFound = 2
        elif self.fileExists(os.path.join("sounds","crowdcheers.ogg")):
            self.loadSoundEffect(self, "crowdSound", os.path.join("sounds","crowdcheers.ogg"), crowd = True)
            self.cheerSoundFound = 1
            Log.warn(themename + "/sounds/crowdcheers.ogg not found -- using data/sounds/crowdcheers.ogg instead.")
        else:
            self.cheerSoundFound = 0
            Log.warn("crowdcheers.ogg not found -- no crowd cheering.")
Beispiel #25
0
#####################################################################

import math
import numpy as np

from fofix.core import Log
from fofix.core import Audio
from fofix.core.Task import Task
from fofix.core.Language import _

try:
    import pyaudio
    from fofix.core import pypitch
    supported = True
except ImportError:
    Log.warn('Missing pyaudio or pypitch - microphone support will not be possible')
    supported = False

if supported:
    pa = pyaudio.PyAudio()

    # Precompute these in the interest of saving CPU time in the note analysis loop
    LN_2 = math.log(2.0)
    LN_440 = math.log(440.0)

    #stump: return dictionary mapping indices to device names
    # -1 is magic for the default device and will be replaced by None when actually opening the mic.
    def getAvailableMics():
        result = {-1: _('[Default Microphone]')}
        for devnum in range(pa.get_device_count()):
            devinfo = pa.get_device_info_by_index(devnum)
Beispiel #26
0
language = Config.load(Version.PROGRAM_UNIXSTYLE_NAME + ".ini").get(
    "game", "language")
_ = dummyTranslator

if language:
    try:
        trFile = os.path.join(Version.dataPath(), "translations",
                              "%s.mo" % language.lower().replace(" ", "_"))
        catalog = gettext.GNUTranslations(open(trFile, "rb"))

        def translate(m):
            return catalog.ugettext(m)

        _ = translate
    except Exception, x:
        Log.warn("Unable to select language '%s': %s" % (language, x))
        language = None
        Config.set("game", "language", "")

# Define the config key again now that we have some options for it
langOptions = {"": "English"}
for lang in getAvailableLanguages():
    langOptions[lang] = _(lang)
Config.define("game",
              "language",
              str,
              "",
              _("Language"),
              langOptions,
              tipText=_("Change the game language!"))
Beispiel #27
0
    def load(self, libraryName, songName, practiceMode=False):
        if self.scene.coOpType:
            rm = os.path.join("themes", self.themename, "rockmeter_coop.ini")
        elif self.scene.battle or self.scene.battleGH:
            rm = os.path.join("themes", self.themename,
                              "rockmeter_profaceoff.ini")
        elif self.scene.gamePlayers > 1:
            rm = os.path.join("themes", self.themename,
                              "rockmeter_faceoff.ini")
        else:
            rm = os.path.join("themes", self.themename, "rockmeter.ini")

        if os.path.exists(os.path.join("..", "data", rm)):
            rockmeter = self.engine.resource.fileName(rm)
        else:
            rockmeter = self.engine.resource.fileName(
                os.path.join("themes", self.themename, "rockmeter.ini"))

        self.rockmeter = Rockmeter.Rockmeter(self.scene, rockmeter,
                                             self.scene.coOpType)

        # evilynux - Fixes a self.background not defined crash
        self.background = None
        #MFH - new background stage logic:
        if self.mode == 2:  #blank / no stage
            self.songStage = 0
            self.rotationMode = 0
        elif practiceMode:  #check for existing practice stage; always disable stage rotation here
            self.songStage = 0
            self.rotationMode = 0
            self.mode = 1
            #separated practice stages for the instruments by k.i.d
            if self.scene.instruments[0].isDrum:
                background = "practicedrum"
            elif self.scene.instruments[0].isBassGuitar:
                background = "practicebass"
            else:
                background = "practice"
            if not self.engine.loadImgDrawing(
                    self, "background",
                    os.path.join("themes", self.themename, "backgrounds",
                                 background)):
                #MFH - must first fall back on the old practice.png before forcing blank stage mode!
                if not self.engine.loadImgDrawing(
                        self, "background",
                        os.path.join("themes", self.themename, "backgrounds",
                                     "practice")):
                    Log.warn(
                        "No practice stage, falling back on a forced Blank stage mode"
                    )  # evilynux
                    self.mode = 2  #if no practice stage, just fall back on a forced Blank stage mode

        elif self.songStage == 1:  #check for song-specific background
            test = True
            if not self.engine.loadImgDrawing(
                    self, "background",
                    os.path.join(libraryName, songName, "background")):
                Log.notice("No song-specific stage found")  # evilynux
                test = False
            if test:  #does a song-specific background exist?
                self.rotationMode = 0
                self.mode = 1
            else:
                self.songStage = 0

        #MFH - now, after the above logic, we can run the normal stage mode logic
        #      only worrying about checking for Blank, song-specific and
        #      practice stage modes
        if self.mode != 2 and self.mode != 3 and self.songStage == 0 and not practiceMode:  #still need to load stage(s)
            #myfingershurt: assign this first
            if self.mode == 1:  #just use Default.png
                if not self.engine.loadImgDrawing(
                        self, "background", os.path.join(self.path,
                                                         "default")):
                    Log.warn(
                        "No default stage; falling back on a forced Blank stage mode"
                    )  # evilynux
                    self.mode = 2  #if no practice stage, just fall back on a forced Blank stage mode

            ##This checks how many Stage-background we have to select from
            if self.mode == 0 and self.rotationMode == 0:  #MFH: just display a random stage
                files = []
                fileIndex = 0
                allfiles = os.listdir(self.pathfull)
                for name in allfiles:
                    if os.path.splitext(name)[0].lower(
                    ) != "practice" and os.path.splitext(name)[0].lower(
                    ) != "practicedrum" and os.path.splitext(name)[0].lower(
                    ) != "practicebass" and name != ".svn":
                        Log.debug("Valid background found, index (" +
                                  str(fileIndex) + "): " + name)
                        files.append(name)
                        fileIndex += 1
                    else:
                        Log.debug("Practice background filtered: " + name)

                # evilynux - improved error handling, fallback to blank background if no background are found
                if fileIndex == 0:
                    Log.warn("No valid stage found!")
                    self.mode = 2
                else:
                    i = random.randint(0, len(files) - 1)
                    filename = files[i]
                    ##End check number of Stage-backgrounds
                    if not self.engine.loadImgDrawing(
                            self, "background",
                            os.path.join(self.path, filename)):
                        self.mode = 2

            elif self.rotationMode > 0 and self.mode != 2:
                files = []
                fileIndex = 0

                if self.animatedFolder == "Random":  #Select one of the subfolders under stages\ to animate randomly
                    numAniStageFolders = len(self.engine.stageFolders)
                    if numAniStageFolders > 0:
                        self.animatedFolder = random.choice(
                            self.engine.stageFolders)
                    else:
                        self.animatedFolder = "Normal"

                elif self.animatedFolder == "None":
                    self.mode = 2

                if self.animatedFolder != "Normal" and self.mode != 2:  #just use the base Stages folder for rotation
                    self.path = os.path.join("themes", self.themename,
                                             "backgrounds",
                                             self.animatedFolder)
                    self.pathfull = self.engine.getPath(self.path)
                    self.animation = True

                allfiles = os.listdir(self.pathfull)
                for name in allfiles:

                    if os.path.splitext(
                            name)[1].lower() == ".png" or os.path.splitext(
                                name)[1].lower() == ".jpg" or os.path.splitext(
                                    name)[1].lower() == ".jpeg":
                        if os.path.splitext(name)[0].lower(
                        ) != "practice" and os.path.splitext(name)[0].lower(
                        ) != "practicedrum" and os.path.splitext(
                                name)[0].lower() != "practicebass":
                            Log.debug("Valid background found, index (" +
                                      str(fileIndex) + "): " + name)
                            files.append(name)
                            fileIndex += 1
                        else:
                            Log.debug("Practice background filtered: " + name)
                    files.sort()

            if self.rotationMode > 0 and self.mode != 2:  #alarian: blank stage option is not selected
                #myfingershurt: just populate the image array in order, they are pulled in whatever order requested:
                for j in range(len(files)):
                    self.engine.loadImgDrawing(
                        self, "backgroundA", os.path.join(self.path, files[j]))
                    self.imgArr.append(
                        getattr(self, "backgroundA",
                                os.path.join(self.path, files[j])))

        if self.rotationMode > 0 and len(self.imgArr) == 0:
            self.rotationMode = 0
Beispiel #28
0
    def __init__(self, engine):
        self.engine              = engine

        self.logClassInits = Config.get("game", "log_class_inits")
        if self.logClassInits == 1:
            Log.debug("MainMenu class init (MainMenu.py)...")

        self.time                = 0.0
        self.nextLayer           = None
        self.visibility          = 0.0
        self.active              = False

        self.showStartupMessages = False

        self.gfxVersionTag = Config.get("game", "gfx_version_tag")

        self.chosenNeck = Config.get("game", "default_neck")
        exists = 0

        if engine.loadImgDrawing(self, "ok", os.path.join("necks",self.chosenNeck+".png")):
            exists = 1
        elif engine.loadImgDrawing(self, "ok", os.path.join("necks","Neck_"+self.chosenNeck+".png")):
            exists = 1

        #MFH - fallback logic now supports a couple valid default neck filenames
        #MFH - check for Neck_1
        if exists == 0:
            if engine.loadImgDrawing(self, "ok", os.path.join("necks","Neck_1.png")):
                Config.set("game", "default_neck", "1")
                Log.warn("Default chosen neck not valid; fallback Neck_1.png forced.")
                exists = 1

        #MFH - check for defaultneck
        if exists == 0:
            if engine.loadImgDrawing(self, "ok", os.path.join("necks","defaultneck.png")):
                Log.warn("Default chosen neck not valid; fallback defaultneck.png forced.")
                Config.set("game", "default_neck", "defaultneck")
                exists = 1
            else:
                Log.error("Default chosen neck not valid; fallbacks Neck_1.png and defaultneck.png also not valid!")

        #Get theme
        self.theme       = self.engine.data.theme
        self.themeCoOp   = self.engine.data.themeCoOp
        self.themename   = self.engine.data.themeLabel
        self.useSoloMenu = self.engine.theme.use_solo_submenu

        allowMic = True

        self.menux = self.engine.theme.menuPos[0]
        self.menuy = self.engine.theme.menuPos[1]

        self.rbmenu = self.engine.theme.menuRB

        #MFH
        self.main_menu_scale = self.engine.theme.main_menu_scaleVar
        self.main_menu_vspacing = self.engine.theme.main_menu_vspacingVar

        if not self.engine.loadImgDrawing(self, "background", os.path.join("themes",self.themename,"menu","mainbg.png")):
            self.background = None
        self.engine.loadImgDrawing(self, "BGText", os.path.join("themes",self.themename,"menu","maintext.png"))
        self.engine.loadImgDrawing(self, "optionsBG", os.path.join("themes",self.themename,"menu","optionsbg.png"))
        self.engine.loadImgDrawing(self, "optionsPanel", os.path.join("themes",self.themename,"menu","optionspanel.png"))

        #racer: added version tag
        if self.gfxVersionTag or self.engine.theme.versiontag:
            if not self.engine.loadImgDrawing(self, "version", os.path.join("themes",self.themename,"menu","versiontag.png")):
                if not self.engine.loadImgDrawing(self, "version", "versiontag.png"): #falls back on default versiontag.png in data\ folder
                    self.version = None
        else:
            self.version = None

        #myfingershurt: random main menu music function, menu.ogg and menuXX.ogg (any filename with "menu" as the first 4 letters)
        self.files = None
        filepath = self.engine.getPath(os.path.join("themes",self.themename,"sounds"))
        if os.path.isdir(filepath):
            self.files = []
            allfiles = os.listdir(filepath)
            for name in allfiles:
                if os.path.splitext(name)[1] == ".ogg":
                    if string.find(name,"menu") > -1:
                        self.files.append(name)


        if self.files:
            i = random.randint(0,len(self.files)-1)
            filename = self.files[i]
            sound = os.path.join("themes",self.themename,"sounds",filename)
            self.menumusic = True
            engine.menuMusic = True

            self.song = Audio.Music(self.engine.resource.fileName(sound))
            self.song.setVolume(self.engine.config.get("audio", "menu_volume"))
            self.song.play(0)  #no loop
        else:
            self.menumusic = False

        self.opt_text_color     = self.engine.theme.opt_text_colorVar
        self.opt_selected_color = self.engine.theme.opt_selected_colorVar

        trainingMenu = [
          (_("Tutorials"), self.showTutorial),
          (_("Practice"), lambda: self.newLocalGame(mode1p = 1)),
        ]

        self.opt_bkg_size = [float(i) for i in self.engine.theme.opt_bkg_size]
        self.opt_text_color = self.engine.theme.opt_text_colorVar
        self.opt_selected_color = self.engine.theme.opt_selected_colorVar

        if self.BGText:
            strCareer = ""
            strQuickplay = ""
            strSolo = ""
            strMultiplayer = ""
            strTraining = ""
            strSettings = ""
            strQuit = ""
        else:
            strCareer = "Career"
            strQuickplay = "Quickplay"
            strSolo = "Solo"
            strMultiplayer = "Multiplayer"
            strTraining = "Training"
            strSettings = "Settings"
            strQuit = "Quit"

        multPlayerMenu = [
            (_("Face-Off"),     lambda: self.newLocalGame(players = 2,             maxplayers = 4)),
            (_("Pro Face-Off"), lambda: self.newLocalGame(players = 2, mode2p = 1, maxplayers = 4)),
            (_("FoFiX Co-Op"),  lambda: self.newLocalGame(players = 2, mode2p = 3, maxplayers = 4, allowMic = allowMic)),
            (_("RB Co-Op"),     lambda: self.newLocalGame(players = 2, mode2p = 4, maxplayers = 4, allowMic = allowMic)),
            (_("GH Co-Op"),     lambda: self.newLocalGame(players = 2, mode2p = 5, maxplayers = 4)),
            (_("GH Battle"),    lambda: self.newLocalGame(players = 2, mode2p = 6, allowDrum = False)), #akedrou- so you can block drums
          ]

        if not self.useSoloMenu:

            mainMenu = [
              (strCareer, lambda:   self.newLocalGame(mode1p = 2, allowMic = allowMic)),
              (strQuickplay, lambda:        self.newLocalGame(allowMic = allowMic)),
              ((strMultiplayer,"multiplayer"), multPlayerMenu),
              ((strTraining,"training"),    trainingMenu),
              ((strSettings,"settings"),  self.settingsMenu),
              (strQuit,        self.quit),
            ]

        else:

            soloMenu = [
              (_("Solo Tour"), lambda: self.newLocalGame(mode1p = 2, allowMic = allowMic)),
              (_("Quickplay"), lambda: self.newLocalGame(allowMic = allowMic)),
            ]

            mainMenu = [
              ((strSolo,"solo"), soloMenu),
              ((strMultiplayer,"multiplayer"), multPlayerMenu),
              ((strTraining,"training"),    trainingMenu),
              ((strSettings,"settings"),  self.settingsMenu),
              (strQuit,        self.quit),
            ]


        w, h, = self.engine.view.geometry[2:4]

        self.menu = Menu(self.engine, mainMenu, onClose = lambda: self.engine.view.popLayer(self), pos = (self.menux, .75-(.75*self.menuy)))

        engine.mainMenu = self    #Points engine.mainMenu to the one and only MainMenu object instance

        ## whether the main menu has come into view at least once
        self.shownOnce = False
Beispiel #29
0
    def load(self, libraryName, songName, practiceMode = False):
        if self.scene.coOpType:
            rm = os.path.join("themes", self.themename, "rockmeter_coop.ini")
        elif self.scene.battle or self.scene.battleGH:
            rm = os.path.join("themes", self.themename, "rockmeter_profaceoff.ini")
        elif self.scene.gamePlayers > 1:
            rm = os.path.join("themes", self.themename, "rockmeter_faceoff.ini")
        else:
            rm = os.path.join("themes", self.themename, "rockmeter.ini")

        if os.path.exists(os.path.join("..", "data", rm)):
            rockmeter = self.engine.resource.fileName(rm)
        else:
            rockmeter = self.engine.resource.fileName(os.path.join("themes", self.themename, "rockmeter.ini"))

        self.rockmeter = Rockmeter.Rockmeter(self.scene, rockmeter, self.scene.coOpType)

        # evilynux - Fixes a self.background not defined crash
        self.background = None
        #MFH - new background stage logic:
        if self.mode == 2:   #blank / no stage
            self.songStage = 0
            self.rotationMode = 0
        elif practiceMode:   #check for existing practice stage; always disable stage rotation here
            self.songStage = 0
            self.rotationMode = 0
            self.mode = 1
            #separated practice stages for the instruments by k.i.d
            if self.scene.instruments[0].isDrum:
                background = "practicedrum"
            elif self.scene.instruments[0].isBassGuitar:
                background = "practicebass"
            else:
                background = "practice"
            if not self.engine.loadImgDrawing(self, "background", os.path.join("themes",self.themename,"backgrounds",background)):
                #MFH - must first fall back on the old practice.png before forcing blank stage mode!
                if not self.engine.loadImgDrawing(self, "background", os.path.join("themes",self.themename,"backgrounds","practice")):
                    Log.warn("No practice stage, falling back on a forced Blank stage mode") # evilynux
                    self.mode = 2    #if no practice stage, just fall back on a forced Blank stage mode

        elif self.songStage == 1:    #check for song-specific background
            test = True
            if not self.engine.loadImgDrawing(self, "background", os.path.join(libraryName, songName, "background")):
                Log.notice("No song-specific stage found") # evilynux
                test = False
            if test:  #does a song-specific background exist?
                self.rotationMode = 0
                self.mode = 1
            else:
                self.songStage = 0

        #MFH - now, after the above logic, we can run the normal stage mode logic
        #      only worrying about checking for Blank, song-specific and
        #      practice stage modes
        if self.mode != 2 and self.mode != 3 and self.songStage == 0 and not practiceMode: #still need to load stage(s)
            #myfingershurt: assign this first
            if self.mode == 1:   #just use Default.png
                if not self.engine.loadImgDrawing(self, "background", os.path.join(self.path, "default")):
                    Log.warn("No default stage; falling back on a forced Blank stage mode") # evilynux
                    self.mode = 2    #if no practice stage, just fall back on a forced Blank stage mode

            ##This checks how many Stage-background we have to select from
            if self.mode == 0 and self.rotationMode == 0:  #MFH: just display a random stage
                files = []
                fileIndex = 0
                allfiles = os.listdir(self.pathfull)
                for name in allfiles:
                    if os.path.splitext(name)[0].lower() != "practice" and os.path.splitext(name)[0].lower() != "practicedrum" and os.path.splitext(name)[0].lower() != "practicebass" and name != ".svn":
                        Log.debug("Valid background found, index (" + str(fileIndex) + "): " + name)
                        files.append(name)
                        fileIndex += 1
                    else:
                        Log.debug("Practice background filtered: " + name)

                # evilynux - improved error handling, fallback to blank background if no background are found
                if fileIndex == 0:
                    Log.warn("No valid stage found!")
                    self.mode = 2;
                else:
                    i = random.randint(0,len(files)-1)
                    filename = files[i]
            ##End check number of Stage-backgrounds
                    if not self.engine.loadImgDrawing(self, "background", os.path.join(self.path, filename)):
                        self.mode = 2;

            elif self.rotationMode > 0 and self.mode != 2:
                files = []
                fileIndex = 0

                if self.animatedFolder == "Random": #Select one of the subfolders under stages\ to animate randomly
                    numAniStageFolders = len(self.engine.stageFolders)
                    if numAniStageFolders > 0:
                        self.animatedFolder = random.choice(self.engine.stageFolders)
                    else:
                        self.animatedFolder = "Normal"

                elif self.animatedFolder == "None":
                    self.mode = 2

                if self.animatedFolder != "Normal" and self.mode != 2: #just use the base Stages folder for rotation
                    self.path = os.path.join("themes",self.themename,"backgrounds",self.animatedFolder)
                    self.pathfull = self.engine.getPath(self.path)
                    self.animation = True

                allfiles = os.listdir(self.pathfull)
                for name in allfiles:

                    if os.path.splitext(name)[1].lower() == ".png" or os.path.splitext(name)[1].lower() == ".jpg" or os.path.splitext(name)[1].lower() == ".jpeg":
                        if os.path.splitext(name)[0].lower() != "practice" and os.path.splitext(name)[0].lower() != "practicedrum" and os.path.splitext(name)[0].lower() != "practicebass":
                            Log.debug("Valid background found, index (" + str(fileIndex) + "): " + name)
                            files.append(name)
                            fileIndex += 1
                        else:
                            Log.debug("Practice background filtered: " + name)
                    files.sort()

            if self.rotationMode > 0 and self.mode != 2:   #alarian: blank stage option is not selected
            #myfingershurt: just populate the image array in order, they are pulled in whatever order requested:
                for j in range(len(files)):
                    self.engine.loadImgDrawing(self, "backgroundA", os.path.join(self.path, files[j]))
                    self.imgArr.append(getattr(self, "backgroundA", os.path.join(self.path, files[j])))

        if self.rotationMode > 0 and len(self.imgArr) == 0:
            self.rotationMode = 0
Beispiel #30
0
    def parseText(self, filename):
        nf = self.engine.data.font
        ns = 0.002
        bs = 0.001
        hs = 0.003
        c1 = (1, 1, .5, 1)
        c2 = (1, .75, 0, 1)
        space = Text(nf, hs, c1, "center", " ")
        scale = 1

        path = filename
        if not hasattr(sys,"frozen"): #MFH - add ".." to path only if running from sources - not if running from EXE
            path = os.path.join("..", path)
        if not os.path.exists(path):
            return

        file = open(path)
        for line in file:
            line = line.strip("\n")
            if line.startswith("=====") or line.startswith("-----"):
                continue
            try:
                if line.startswith("!") and line.endswith("!"):
                    scale = float(line.strip("!"))
                    continue
            except ValueError:
                Log.warn("CREDITS file does not parse properly")
            if line == "":
                self.credits.append(space)
            elif line.startswith("`") and line.endswith("`"):
                line = line.strip("`")
                if line.startswith("%") and line.endswith("%"):
                    line = line.strip("%")
                    try:
                        for text in self.bank[line]:
                            self.credits.append( Text(nf, bs*scale, c1, "left", "%s" % text) )
                    except KeyError:
                        self.credits.append( Text(nf, bs*scale, c1, "left", "%s" % line) )
                else:
                    self.credits.append( Text(nf, bs*scale, c1, "left", "%s" % line) )
            elif line.startswith("_") and line.endswith("_"):
                line = line.strip("_")
                if line.startswith("%") and line.endswith("%"):
                    line = line.strip("%")
                    try:
                        for text in self.bank[line]:
                            self.credits.append( Text(nf, ns*scale, c2, "center", "%s" % text) )
                    except KeyError:
                        self.credits.append( Text(nf, ns*scale, c2, "center", "%s" % line) )
                else:
                    self.credits.append( Text(nf, ns*scale, c2, "center", "%s" % line) )
            elif line.startswith("=") and line.endswith("="):
                line = line.strip("=")
                if line.startswith("%") and line.endswith("%"):
                    line = line.strip("%")
                    try:
                        for text in self.bank[line]:
                            self.credits.append( Text(nf, ns*scale, c1, "left", "%s" % text) )
                    except KeyError:
                        self.credits.append( Text(nf, ns*scale, c1, "left", "%s" % line) )
                else:
                    self.credits.append( Text(nf, ns*scale, c1, "left", "%s" % line) )
            else:
                if line.startswith("%") and line.endswith("%"):
                    line = line.strip("%")
                    try:
                        for text in self.bank[line]:
                            self.credits.append( Text(nf, ns*scale, c2, "right", "%s" % text) )
                    except KeyError:
                        self.credits.append( Text(nf, ns*scale, c2, "right", "%s" % line) )
                else:
                    self.credits.append( Text(nf, ns*scale, c2, "right", "%s" % line) )
Beispiel #31
0
#####################################################################

import math
import numpy as np

from fofix.core import Log
from fofix.core import Audio
from fofix.core.Task import Task
from fofix.core.Language import _

try:
    import pyaudio
    from fofix.core import pypitch
    supported = True
except ImportError:
    Log.warn(
        'Missing pyaudio or pypitch - microphone support will not be possible')
    supported = False

if supported:
    pa = pyaudio.PyAudio()

    # Precompute these in the interest of saving CPU time in the note analysis loop
    LN_2 = math.log(2.0)
    LN_440 = math.log(440.0)

    #stump: return dictionary mapping indices to device names
    # -1 is magic for the default device and will be replaced by None when actually opening the mic.
    def getAvailableMics():
        result = {-1: _('[Default Microphone]')}
        for devnum in range(pa.get_device_count()):
            devinfo = pa.get_device_info_by_index(devnum)
Beispiel #32
0
    def parseText(self, filename):
        nf = self.engine.data.font
        ns = 0.002
        bs = 0.001
        hs = 0.003
        c1 = (1, 1, .5, 1)
        c2 = (1, .75, 0, 1)
        space = Text(nf, hs, c1, "center", " ")
        scale = 1

        path = filename
        if not hasattr(sys,"frozen"): #MFH - add ".." to path only if running from sources - not if running from EXE
            path = os.path.join("..", path)
        if not os.path.exists(path):
            return

        file = open(path)
        for line in file:
            line = line.strip("\n")
            if line.startswith("=====") or line.startswith("-----"):
                continue
            try:
                if line.startswith("!") and line.endswith("!"):
                    scale = float(line.strip("!"))
                    continue
            except ValueError:
                Log.warn("CREDITS file does not parse properly")
            if line == "":
                self.credits.append(space)
            elif line.startswith("`") and line.endswith("`"):
                line = line.strip("`")
                if line.startswith("%") and line.endswith("%"):
                    line = line.strip("%")
                    try:
                        for text in self.bank[line]:
                            self.credits.append( Text(nf, bs*scale, c1, "left", "%s" % text) )
                    except KeyError:
                        self.credits.append( Text(nf, bs*scale, c1, "left", "%s" % line) )
                else:
                    self.credits.append( Text(nf, bs*scale, c1, "left", "%s" % line) )
            elif line.startswith("_") and line.endswith("_"):
                line = line.strip("_")
                if line.startswith("%") and line.endswith("%"):
                    line = line.strip("%")
                    try:
                        for text in self.bank[line]:
                            self.credits.append( Text(nf, ns*scale, c2, "center", "%s" % text) )
                    except KeyError:
                        self.credits.append( Text(nf, ns*scale, c2, "center", "%s" % line) )
                else:
                    self.credits.append( Text(nf, ns*scale, c2, "center", "%s" % line) )
            elif line.startswith("=") and line.endswith("="):
                line = line.strip("=")
                if line.startswith("%") and line.endswith("%"):
                    line = line.strip("%")
                    try:
                        for text in self.bank[line]:
                            self.credits.append( Text(nf, ns*scale, c1, "left", "%s" % text) )
                    except KeyError:
                        self.credits.append( Text(nf, ns*scale, c1, "left", "%s" % line) )
                else:
                    self.credits.append( Text(nf, ns*scale, c1, "left", "%s" % line) )
            else:
                if line.startswith("%") and line.endswith("%"):
                    line = line.strip("%")
                    try:
                        for text in self.bank[line]:
                            self.credits.append( Text(nf, ns*scale, c2, "right", "%s" % text) )
                    except KeyError:
                        self.credits.append( Text(nf, ns*scale, c2, "right", "%s" % line) )
                else:
                    self.credits.append( Text(nf, ns*scale, c2, "right", "%s" % line) )
Beispiel #33
0
    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 not config:
            config = Config.load()

        self.config = config

        fps = self.config.get("video", "fps")

        self.fps = 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

        # evilynux - Check if theme icon exists first, then fallback on FoFiX icon.
        themename = self.config.get("coffee", "themename")
        themeicon = os.path.join(Version.dataPath(), "themes", themename,
                                 "icon.png")
        fofixicon = os.path.join(Version.dataPath(), "fofix_icon.png")
        icon = None
        if os.path.exists(themeicon):
            icon = themeicon
        elif os.path.exists(fofixicon):
            icon = fofixicon

        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.cmdPlay = 0
        self.cmdMode = None
        self.cmdDiff = None
        self.cmdPart = None

        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:
            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

        # 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)

        ##MFH: Animated stage folder selection option
        #<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 = themename

        stagespath = os.path.join(Version.dataPath(), "themes", currentTheme,
                                  "backgrounds")
        themepath = os.path.join(Version.dataPath(), "themes", currentTheme)
        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:
                self.config.set("game", "animated_stage_folder",
                                defaultAniStage)  #force 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

        try:
            fp, pathname, description = imp.find_module(
                "CustomTheme", [themepath])
            theme = imp.load_module("CustomTheme", fp, pathname, description)
            self.theme = theme.CustomTheme(themepath, themename)
        except ImportError:
            self.theme = Theme(themepath, themename)

        self.task.addTask(self.theme)

        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.")