From 20ad762470eedff104286d01dab3d63a80df3519 Mon Sep 17 00:00:00 2001 From: Matthew Sitton Date: Mon, 21 Sep 2015 00:08:24 -0500 Subject: [PATCH] Large commit, Update FoFiX to use version 0.1.1 of fretwork. Plus removes code that was moved into fretwork. --- FoFiX.py | 39 +- README.md | 24 +- fofix/core/Audio.py | 232 --------- fofix/core/Config.py | 15 +- fofix/core/Data.py | 36 +- fofix/core/GameEngine.py | 62 +-- fofix/core/Image.py | 5 +- fofix/core/Input.py | 30 +- fofix/core/Language.py | 7 +- fofix/core/LinedConfigParser.py | 3 +- fofix/core/Log.py | 128 ----- fofix/core/Microphone.py | 25 +- fofix/core/MixStream/MixStream.c | 473 ------------------ fofix/core/MixStream/MixStream.h | 57 --- fofix/core/MixStream/_MixStream.pyx | 103 ---- fofix/core/MixStream/__init__.py | 1 - fofix/core/MixStream/soundtouch-c.cpp | 128 ----- fofix/core/MixStream/soundtouch-c.h | 51 -- fofix/core/MixStream/vorbis.c | 135 ----- fofix/core/Mod.py | 5 +- fofix/core/Player.py | 9 +- fofix/core/Resource.py | 13 +- fofix/core/Settings.py | 53 +- fofix/core/Shader.py | 35 +- fofix/core/Task.py | 112 ----- fofix/core/Texture.py | 6 +- fofix/core/Theme.py | 27 +- fofix/core/Unicode.py | 56 --- fofix/core/Video.py | 13 +- fofix/core/View.py | 10 +- fofix/game/Credits.py | 7 +- fofix/game/Debug.py | 7 +- fofix/game/Dialogs.py | 31 +- fofix/game/GameResultsScene.py | 18 +- fofix/game/MainMenu.py | 19 +- fofix/game/Menu.py | 9 +- fofix/game/Scorekeeper.py | 5 +- fofix/game/Song.py | 183 +++---- fofix/game/SongChoosingScene.py | 13 +- fofix/game/guitarscene/GuitarScene.py | 92 ++-- fofix/game/guitarscene/Neck.py | 11 +- fofix/game/guitarscene/Rockmeter.py | 5 +- fofix/game/guitarscene/Stage.py | 31 +- fofix/game/guitarscene/instruments/Drum.py | 5 +- fofix/game/guitarscene/instruments/Guitar.py | 5 +- .../guitarscene/instruments/Instrument.py | 23 +- .../game/guitarscene/instruments/ProGuitar.py | 9 +- .../game/guitarscene/instruments/Vocalist.py | 10 +- setup.py | 14 - 49 files changed, 488 insertions(+), 1902 deletions(-) delete mode 100644 fofix/core/Audio.py delete mode 100644 fofix/core/Log.py delete mode 100644 fofix/core/MixStream/MixStream.c delete mode 100644 fofix/core/MixStream/MixStream.h delete mode 100644 fofix/core/MixStream/_MixStream.pyx delete mode 100644 fofix/core/MixStream/__init__.py delete mode 100644 fofix/core/MixStream/soundtouch-c.cpp delete mode 100644 fofix/core/MixStream/soundtouch-c.h delete mode 100644 fofix/core/MixStream/vorbis.c delete mode 100644 fofix/core/Task.py delete mode 100644 fofix/core/Unicode.py diff --git a/FoFiX.py b/FoFiX.py index f6366982a..39a5da048 100644 --- a/FoFiX.py +++ b/FoFiX.py @@ -110,12 +110,29 @@ def cmd_args(): import pygame + +from fretwork import log + +from fofix.core import Version +from fofix.core import VFS + +# setup the logfile +# File object representing the logfile. +if os.name == "posix": # evilynux - logfile in ~/.fofix/ for GNU/Linux and MacOS X + # evilynux - Under MacOS X, put the logs in ~/Library/Logs + if os.uname()[0] == "Darwin": + logFile = open(os.path.expanduser('~/Library/Logs/%s.log' % Version.PROGRAM_UNIXSTYLE_NAME), 'w') + else: # GNU/Linux et al. + logFile = VFS.open('/userdata/%s.log' % Version.PROGRAM_UNIXSTYLE_NAME, 'w') +else: + logFile = VFS.open('/userdata/%s.log' % Version.PROGRAM_UNIXSTYLE_NAME, 'w') + +log.setLogfile(logFile) + from fofix.core.VideoPlayer import VideoLayer, VideoPlayerError from fofix.core.GameEngine import GameEngine from fofix.game.MainMenu import MainMenu from fofix.core.Language import _ -from fofix.core import Version -from fofix.core import Log, VFS from fofix.core import Config class Main(): @@ -183,7 +200,7 @@ def init_oneshot(self): # Check for a valid invocation of one-shot mode. if self.playing is not None: - Log.debug('Validating song directory for one-shot mode.') + 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) @@ -197,12 +214,12 @@ def init_oneshot(self): 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) + 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.') + log.debug('Entering one-shot mode.') Config.set("setlist", "selected_song", playing) self.engine.cmdPlay = 1 @@ -218,7 +235,7 @@ def init_oneshot(self): self.engine.cmdMode = players, 0, mode def restart(self): - Log.notice("Restarting.") + log.notice("Restarting.") self.engine.audio.close() self.restartRequested = True @@ -234,7 +251,7 @@ def run(self): try: vidPlayer = VideoLayer(self.engine, vidSource, cancellable=True) except (IOError, VideoPlayerError): - Log.error("Error loading intro video:") + log.error("Error loading intro video:") else: vidPlayer.play() self.engine.view.pushLayer(vidPlayer) @@ -253,7 +270,7 @@ def run(self): while self.engine.run(): pass except KeyboardInterrupt: - Log.notice("Left mainloop due to KeyboardInterrupt.") + log.notice("Left mainloop due to KeyboardInterrupt.") # don't reraise # Restart the program if the engine is asking that we do so. @@ -275,8 +292,8 @@ def run(self): except (KeyboardInterrupt, SystemExit): raise except: - Log.error("Terminating due to unhandled exception: ") - _logname = os.path.abspath(Log.logFile.name) + log.error("Terminating due to unhandled exception: ") + _logname = os.path.abspath(log.logFile.name) _errmsg = "%s\n\n%s\n%s\n%s\n%s" % ( _("Terminating due to unhandled exception:"), traceback.format_exc(), @@ -289,7 +306,7 @@ def run(self): import win32api import win32con if win32api.MessageBox(0, "%s\n\n%s" % (_errmsg, _("Open the logfile now?")), "%s %s" % (Version.PROGRAM_NAME, Version.version()), win32con.MB_YESNO|win32con.MB_ICONSTOP) == win32con.IDYES: - Log.logFile.close() + log.logFile.close() os.startfile(_logname) if hasattr(sys, 'frozen'): sys.exit(1) # don't reraise if py2exe'd so the "Errors occurred" box won't appear after this and confuse the user as to which logfile we actually want diff --git a/README.md b/README.md index 471f389ec..e8ba8be7e 100644 --- a/README.md +++ b/README.md @@ -198,6 +198,18 @@ a subdirectory of the `win32/` directory.) Now you are ready to compile the native modules. +#### Installing fretwork +Fretwork is our new initiative to share some code with a fork of FoF called Frets on Fire: Reborn. +Some code from this repo has been move out into fretwork. To install fretwork download the following wheel: ([direct link to 0.1.1](https://github.com/fofix/fretwork/releases/download/0.1.1/fretwork-0.1.1-cp27-none-win32.whl)) +Then install it using the following command: +```pip install fretwork-0.1.1-cp27-none-win32.whl``` + +#### Upgrading fretwork +If you have previously installed fretwork make sure you download the latest release from above then following command: + +```pip install fretwork-0.1.1-cp27-none-win32.whl --upgrade``` + + ### Mac OS X Someone with a Mac will have to expand this section. @@ -234,6 +246,7 @@ The following are required: * Cython * pkg-config * cerealizer + * fretwork * The OpenGL, GLU, GLib, SDL, SDL_mixer, libogg, libvorbisfile, libtheora, libsoundtouch, and libswscale (part of ffmpeg) development headers @@ -248,7 +261,16 @@ following packages: `python-pygame`, `python-opengl`, `python-numpy`, `python-imaging`, `python-dev`, `build-essential`, `cython`, `pkg-config`, `libgl1-mesa-dev`, `libglu1-mesa-dev`, `libglib2.0-dev`, `libsdl1.2-dev`, `libsdl-mixer1.2-dev`, `libogg-dev`, `libvorbisfile-dev`, `libtheora-dev`, -`libswscale-dev`, `libsoundtouch-dev`, `python-cerealizer`, and if you want translations, `gettext`. +`libswscale-dev`, `libsoundtouch-dev`, and if you want translations, `gettext`. + +Cerealizer should be installed via pip + +For Fretwork you should download the sourcecode of the latest release ([over here](https://github.com/fofix/fretwork/releases/)), extract the files and run the following command: + +```pip2 install fretwork-0.1.1.tar.gz``` + +This command may depend on how your distribution provides pip, and what python versions you have installed. + Some packages can be troublesome, so we have notes below about certain packages. diff --git a/fofix/core/Audio.py b/fofix/core/Audio.py deleted file mode 100644 index 75763a60e..000000000 --- a/fofix/core/Audio.py +++ /dev/null @@ -1,232 +0,0 @@ -##################################################################### -# -*- coding: iso-8859-1 -*- # -# # -# Frets on Fire # -# Copyright (C) 2006 Sami Kyöstilä # -# 2008 myfingershurt # -# # -# This program is free software; you can redistribute it and/or # -# modify it under the terms of the GNU General Public License # -# as published by the Free Software Foundation; either version 2 # -# of the License, or (at your option) any later version. # -# # -# This program is distributed in the hope that it will be useful, # -# but WITHOUT ANY WARRANTY; without even the implied warranty of # -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # -# GNU General Public License for more details. # -# # -# You should have received a copy of the GNU General Public License # -# along with this program; if not, write to the Free Software # -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # -# MA 02110-1301, USA. # -##################################################################### - -import pygame -import numpy as np - -from fofix.core import Log -from fofix.core.Task import Task -from fofix.core.MixStream import VorbisFileMixStream - -#stump: get around some strangeness in pygame when py2exe'd... -if not hasattr(pygame.mixer, 'music'): - import sys - __import__('pygame.mixer_music') - pygame.mixer.music = sys.modules['pygame.mixer_music'] - - -class Audio: - def pre_open(self, frequency = 22050, bits = 16, stereo = True, bufferSize = 1024): - pygame.mixer.pre_init(frequency, -bits, stereo and 2 or 1, bufferSize) - return True - - 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 - - #myfingershurt: - def findChannel(self): - return pygame.mixer.find_channel() - - def getChannelCount(self): - return pygame.mixer.get_num_channels() - - def getChannel(self, n): - return Channel(n) - - def close(self): - try: - pygame.mixer.quit() - except: - pass - - def pause(self): - pygame.mixer.pause() - - def unpause(self): - pygame.mixer.unpause() - -class Music(object): - def __init__(self, fileName): - pygame.mixer.music.load(fileName) - - @staticmethod - def setEndEvent(event = None): - if event: - pygame.mixer.music.set_endevent(event) - else: - pygame.mixer.music.set_endevent() #MFH - to set NO event. - - def play(self, loops = -1, pos = 0.0): - pygame.mixer.music.play(loops, pos) - - def stop(self): - pygame.mixer.music.stop() - - def rewind(self): - pygame.mixer.music.rewind() - - def pause(self): - pygame.mixer.music.pause() - - def unpause(self): - pygame.mixer.music.unpause() - - def setVolume(self, volume): - pygame.mixer.music.set_volume(volume) - - def fadeout(self, time): - pygame.mixer.music.fadeout(time) - - def isPlaying(self): - return pygame.mixer.music.get_busy() - - def getPosition(self): - return pygame.mixer.music.get_pos() - - -class Channel(object): - def __init__(self, id): - self.channel = pygame.mixer.Channel(id) - self.id = id - - def play(self, sound): - self.channel.play(sound.sound) - - def stop(self): - self.channel.stop() - - def setVolume(self, volume): - self.channel.set_volume(volume) - - def fadeout(self, time): - self.channel.fadeout(time) - - -class Sound(object): - def __init__(self, fileName): - self.sound = pygame.mixer.Sound(fileName) - - def isPlaying(self): #MFH - adding function to check if sound is playing - return self.sound.get_num_channels() - - def play(self, loops = 0): - self.sound.play(loops) - - def stop(self): - self.sound.stop() - - def setVolume(self, volume): - self.sound.set_volume(volume) - - def fadeout(self, time): - self.sound.fadeout(time) - - -#stump: mic passthrough -class MicrophonePassthroughStream(Sound, Task): - def __init__(self, engine, mic): - Task.__init__(self) - self.engine = engine - self.channel = None - self.mic = mic - self.playing = False - self.volume = 1.0 - def __del__(self): - self.stop() - def play(self): - if not self.playing: - self.engine.addTask(self) - self.playing = True - def stop(self): - if self.playing: - self.channel.stop() - self.engine.removeTask(self) - self.playing = False - def setVolume(self, vol): - self.volume = vol - def run(self, ticks): - chunk = ''.join(self.mic.passthroughQueue) - self.mic.passthroughQueue = [] - if chunk == '': - return - data = np.frombuffer(chunk, dtype=np.float32) * 32767.0 - playbuf = np.zeros((len(data), 2), dtype=np.int16) - playbuf[:, 0] = data - playbuf[:, 1] = data - snd = pygame.mixer.Sound(buffer(playbuf)) - if self.channel is None or not self.channel.get_busy(): - self.channel = snd.play() - else: - self.channel.queue(snd) - self.channel.set_volume(self.volume) - - -class StreamingSound(object): - def __init__(self, channel, fileName): - self._mixstream = VorbisFileMixStream(fileName) - self._channel = channel - - def play(self): - self._mixstream.play(self._channel.id) - - def stop(self): - self._mixstream.stop() - self._channel.stop() - - def setVolume(self, volume): - self._channel.setVolume(volume) - - def isPlaying(self): - return self._mixstream.is_playing() - - def fadeout(self, time): - # TODO - self.stop() - - def getPosition(self): - return self._mixstream.get_position() - - def setPosition(self, position): - return self._mixstream.seek(position) - - def setPitchBendSemitones(self, semitones): - self._mixstream.set_pitch_semitones(semitones) - - def setSpeed(self, factor): - self._mixstream.set_speed(factor) diff --git a/fofix/core/Config.py b/fofix/core/Config.py index e393cf429..f53349543 100644 --- a/fofix/core/Config.py +++ b/fofix/core/Config.py @@ -26,9 +26,10 @@ import os from ConfigParser import RawConfigParser -from fofix.core import Log +from fretwork import log +from fretwork.unicode import utf8, unicodify + from fofix.core import VFS -from fofix.core.Unicode import utf8, unicodify config = None prototype = {} @@ -171,7 +172,7 @@ def get(self, section, option): type = self.prototype[section][option].type default = self.prototype[section][option].default except KeyError: - Log.error("Config key %s.%s not defined while reading %s." % (section, option, self.fileName)) + log.error("Config key %s.%s not defined while reading %s." % (section, option, self.fileName)) raise value = _convertValue(self.config.get(section, option) if self.config.has_option(section, option) else default, type, default) @@ -192,7 +193,7 @@ def getOptions(self, section, option): keys = self.prototype[section][option].options.keys() type = self.prototype[section][option].type except KeyError: - Log.error("Config key %s.%s not defined while reading %s." % (section, option, self.fileName)) + log.error("Config key %s.%s not defined while reading %s." % (section, option, self.fileName)) raise optionList = [] @@ -216,7 +217,7 @@ def getTipText(self, section, option): try: text = self.prototype[section][option].tipText except KeyError: - Log.error("Config key %s.%s not defined while reading %s." % (section, option, self.fileName)) + log.error("Config key %s.%s not defined while reading %s." % (section, option, self.fileName)) raise return text @@ -234,7 +235,7 @@ def getDefault(self, section, option): type = self.prototype[section][option].type default = self.prototype[section][option].default except KeyError: - Log.error("Config key %s.%s not defined while reading %s." % (section, option, self.fileName)) + log.error("Config key %s.%s not defined while reading %s." % (section, option, self.fileName)) raise value = _convertValue(default, type) @@ -253,7 +254,7 @@ def set(self, section, option, value): try: prototype[section][option] except KeyError: - Log.error("Config key %s.%s not defined while writing %s." % (section, option, self.fileName)) + log.error("Config key %s.%s not defined while writing %s." % (section, option, self.fileName)) raise if not self.config.has_section(section): diff --git a/fofix/core/Data.py b/fofix/core/Data.py index 045d7eb1e..5e0a24840 100644 --- a/fofix/core/Data.py +++ b/fofix/core/Data.py @@ -27,13 +27,15 @@ import glob import random +from fretwork import log +from fretwork.audio import Sound + from fofix.core.Font import Font from fofix.core.Image import ImgDrawing -from fofix.core.Audio import Sound + from fofix.core import Config from fofix.core import Version from fofix.core import Player -from fofix.core import Log # these constants define a few customized letters in the default font #MFH - with the new simplified Font.py, no more custom glyphs... let's do a simple replacement here for now... @@ -57,7 +59,7 @@ def __init__(self, resource, svg): self.logClassInits = Config.get("game", "log_class_inits") if self.logClassInits == 1: - Log.debug("Data class init (Data.py)...") + log.debug("Data class init (Data.py)...") self.logLoadings = Config.get("game", "log_loadings") self.logImageNotFound = Config.get("log", "log_image_not_found") @@ -186,12 +188,12 @@ def __init__(self, resource, svg): 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]) + 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])) + 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) @@ -239,10 +241,10 @@ def __init__(self, resource, svg): 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]) + 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.") + 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. @@ -253,10 +255,10 @@ def __init__(self, resource, svg): 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.") + 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.") + log.warn("crowdcheers.ogg not found -- no crowd cheering.") def loadPartImages(self): self.partImages = [] @@ -323,7 +325,7 @@ def determineNumSounds(self, soundPath, soundPrefix, soundExtension = ".ogg"): return soundNum-1 def getSoundObjectList(self, soundPath, soundPrefix, numSounds, soundExtension = ".ogg"): #MFH - Log.debug("{0}1{2} - {0}{1}{2} found in {3}".format(soundPrefix, numSounds, soundExtension, soundPath)) + log.debug("{0}1{2} - {0}{1}{2} found in {3}".format(soundPrefix, numSounds, soundExtension, soundPath)) sounds = [] for i in xrange(1, numSounds+1): @@ -401,9 +403,9 @@ def getImgDrawing(self, fileName, openImage=True): fileName1 = os.path.join(dataPath, fileName) if self.logLoadings == 1: if openImage: - Log.notice("Trying to load image: %s" % fileName1) + log.notice("Trying to load image: %s" % fileName1) else: - Log.notice("Checking image: %s" % fileName1) + log.notice("Checking image: %s" % fileName1) #check if fileName1 exists (has extension) if os.path.exists(fileName1): if openImage: @@ -411,9 +413,9 @@ def getImgDrawing(self, fileName, openImage=True): imgDrawing = ImgDrawing(self.svg, fileName1) return imgDrawing except IOError: - Log.warn("Unable to load image file: %s" % fileName1) + log.warn("Unable to load image file: %s" % fileName1) except OverflowError: - Log.warn("Unable to read image file: %s" % fileName1) + log.warn("Unable to read image file: %s" % fileName1) else: return True else: @@ -426,12 +428,12 @@ def getImgDrawing(self, fileName, openImage=True): imgDrawing = ImgDrawing(self.svg, files[i]) return imgDrawing except IOError: - Log.warn("Unable to load image file: %s" % files[i]) + 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) + log.debug("Image not found: %s" % fileName) return False def loadImgDrawing(self, target, name, fileName, textureSize = None): @@ -450,7 +452,7 @@ def loadImgDrawing(self, target, name, fileName, textureSize = None): if target and name: setattr(target, name, None) else: - Log.error("Image not found: " + fileName) + log.error("Image not found: " + fileName) return None if target: diff --git a/fofix/core/GameEngine.py b/fofix/core/GameEngine.py index ae0c94120..06c15955f 100644 --- a/fofix/core/GameEngine.py +++ b/fofix/core/GameEngine.py @@ -38,9 +38,13 @@ import sys import imp +from fretwork import log +from fretwork.audio import Audio +from fretwork.task import TaskEngine + from fofix.core.constants import * from fofix.core.Video import Video -from fofix.core.Audio import Audio + from fofix.core.View import View from fofix.core.Input import Input, KeyListener, SystemEventListener from fofix.core.Resource import Resource @@ -51,14 +55,12 @@ from fofix.core.Shader import shaders from fofix.core.Image import drawImage from fofix.core.timer import FpsTimer -from fofix.core.Task import TaskEngine from fofix.core import cmgl from fofix.core import Config from fofix.core import ConfigDefs from fofix.core import Version from fofix.core import Player -from fofix.core import Log from fofix.core import Mod from fofix.game import Dialogs @@ -82,11 +84,11 @@ i = len(themes) if i == 0: if os.name == 'posix': - Log.error("No valid theme found!\n" + + log.error("No valid theme found!\n" + "Make sure theme files are properly cased " + "e.g. notes.png works, Notes.png doesn't\n") else: - Log.error("No valid theme found!") + log.error("No valid theme found!") sys.exit(1) if defaultTheme is None: @@ -114,7 +116,7 @@ def keyPressed(self, key, unicode): self.altStatus = True elif key == pygame.K_RETURN and self.altStatus: if not self.engine.toggleFullscreen(): - Log.error("Unable to toggle fullscreen mode.") + log.error("Unable to toggle fullscreen mode.") return True elif key == pygame.K_d and self.altStatus: self.engine.setDebugModeEnabled(not self.engine.isDebugModeEnabled()) @@ -148,7 +150,7 @@ class GameEngine(object): """The main game engine.""" def __init__(self, config = None): - Log.debug("GameEngine class init (GameEngine.py)...") + log.debug("GameEngine class init (GameEngine.py)...") self.mainMenu = None #placeholder for main menu object - to prevent reinstantiation self.currentScene = None @@ -157,20 +159,20 @@ def __init__(self, config = None): 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) + 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))) + log.debug("win32api.GetVersionEx(1): " + repr(win32api.GetVersionEx(1))) elif os.name == 'posix': - Log.debug("os.uname(): " + repr(os.uname())) + log.debug("os.uname(): " + repr(os.uname())) """ Constructor. @@ -226,7 +228,7 @@ def __init__(self, config = None): self.scrollRate = self.config.get("game", "scroll_rate") self.scrollDelay = self.config.get("game", "scroll_delay") - Log.debug("Initializing audio.") + log.debug("Initializing audio.") frequency = self.config.get("audio", "frequency") bits = self.config.get("audio", "bits") stereo = self.config.get("audio", "stereo") @@ -243,7 +245,7 @@ def __init__(self, config = None): self.audioSpeedFactor = 1.0 - Log.debug("Initializing video.") + 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' @@ -251,10 +253,10 @@ def __init__(self, config = None): 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()))) + 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) @@ -265,7 +267,7 @@ def __init__(self, config = None): # Enable the high priority timer if configured if self.priority: - Log.debug("Enabling high priority timer.") + log.debug("Enabling high priority timer.") self.fps = 0 # High priority # evilynux - This was generating an error on the first pass (at least under @@ -334,7 +336,7 @@ def __init__(self, config = None): defaultAniStage = str(self.stageFolders[0]) else: defaultAniStage = "Normal" - Log.debug("Default animated stage for " + currentTheme + " theme = " + defaultAniStage) + 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 @@ -350,11 +352,11 @@ def __init__(self, config = None): 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.") + 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.") + 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 @@ -377,7 +379,7 @@ def __init__(self, config = None): self.loadingScreenShown = False self.graphicMenuShown = False - Log.debug("Ready.") + log.debug("Ready.") # evilynux - This stops the crowd cheers if they're still playing (issue 317). @@ -450,7 +452,7 @@ def startWorld(self, players, maxplayers = None, gameMode = 0, multiMode = 0, al def finishGame(self): if not self.world: - Log.notice("GameEngine.finishGame called before World created.") + log.notice("GameEngine.finishGame called before World created.") return self.world.finishGame() self.world = None diff --git a/fofix/core/Image.py b/fofix/core/Image.py index ccd0b0bfa..41771f771 100644 --- a/fofix/core/Image.py +++ b/fofix/core/Image.py @@ -27,9 +27,10 @@ from PIL import Image from OpenGL.GL import * +from fretwork import log + from fofix.core.Texture import Texture from fofix.core.constants import * -from fofix.core import Log from fofix.core import cmgl #stump: the last few stubs of DummyAmanith.py are inlined here since this @@ -212,7 +213,7 @@ def __init__(self, context, ImgData): e = "Unable to load texture for %s." % ImgData else: e = "Unable to load texture for SVG file." - Log.error(e) + log.error(e) raise RuntimeError(e) self.pixelSize = self.texture.pixelSize #the size of the image in pixels (from texture) diff --git a/fofix/core/Input.py b/fofix/core/Input.py index cde5c24fe..dd798cad0 100644 --- a/fofix/core/Input.py +++ b/fofix/core/Input.py @@ -31,12 +31,14 @@ haveMidi = False haveMidi = False + +from fretwork import log +from fretwork.audio import Music +from fretwork.task import Task + from fofix.core.Player import Controls -from fofix.core.Task import Task from fofix.core import Player from fofix.core import Config -from fofix.core import Audio -from fofix.core import Log class KeyListener: def keyPressed(self, key, unicode): @@ -81,7 +83,7 @@ def __init__(self): self.logClassInits = Config.get("game", "log_class_inits") if self.logClassInits == 1: - Log.debug("Input class init (Input.py)...") + log.debug("Input class init (Input.py)...") Task.__init__(self) self.mouse = pygame.mouse @@ -113,11 +115,11 @@ def __init__(self): self.joystickNames[j.get_id()] = j.get_name() self.joystickAxes[j.get_id()] = [0] * j.get_numaxes() self.joystickHats[j.get_id()] = [(0, 0)] * j.get_numhats() - Log.debug("%d joysticks found." % len(self.joysticks)) + log.debug("%d joysticks found." % len(self.joysticks)) # Enable music events - Audio.Music.setEndEvent(MusicFinished) - #Audio.Music.setEndEvent() #MFH - no event required? + Music.setEndEvent(MusicFinished) + #Music.setEndEvent() #MFH - no event required? # Custom key names self.getSystemKeyName = pygame.key.name @@ -128,19 +130,19 @@ def __init__(self): pygame.midi.init() for i in range(pygame.midi.get_count()): interface, name, is_input, is_output, is_opened = pygame.midi.get_device_info(i) - Log.debug("Found MIDI device: %s on %s" % (name, interface)) + log.debug("Found MIDI device: %s on %s" % (name, interface)) if not is_input: - Log.debug("MIDI device is not an input device.") + log.debug("MIDI device is not an input device.") continue try: self.midi.append(pygame.midi.Input(i)) - Log.debug("Device opened as device number %d." % len(self.midi)) + log.debug("Device opened as device number %d." % len(self.midi)) except pygame.midi.MidiException: - Log.error("Error opening device for input.") + log.error("Error opening device for input.") if len(self.midi) == 0: - Log.debug("No MIDI input ports found.") + log.debug("No MIDI input ports found.") else: - Log.notice("MIDI input support is not available; install at least pygame 1.9 to get it.") + log.notice("MIDI input support is not available; install at least pygame 1.9 to get it.") def showMouse(self): pygame.mouse.set_visible(True) @@ -428,7 +430,7 @@ def run(self, ticks): # glorandwarf: check that there are no control conflicts #FIXME def checkControls(self): if self.controls.isKeyMappingOK() is False: - Log.warn("Conflicting player controls, resetting to defaults") + log.warn("Conflicting player controls, resetting to defaults") self.controls.restoreDefaultKeyMappings() self.reloadControls() diff --git a/fofix/core/Language.py b/fofix/core/Language.py index a20a8e649..d6ab125ef 100644 --- a/fofix/core/Language.py +++ b/fofix/core/Language.py @@ -24,8 +24,9 @@ import os import glob -from fofix.core.Unicode import unicodify -from fofix.core import Log +from fretwork import log +from fretwork.unicode import unicodify + from fofix.core import Version from fofix.core import Config @@ -48,7 +49,7 @@ def translate(m): return catalog.ugettext(m) _ = translate except Exception as x: - Log.warn("Unable to select language '%s': %s" % (language, x)) + log.warn("Unable to select language '%s': %s" % (language, x)) language = None Config.set("game", "language", "") diff --git a/fofix/core/LinedConfigParser.py b/fofix/core/LinedConfigParser.py index 12d0acf9c..47c03eb70 100644 --- a/fofix/core/LinedConfigParser.py +++ b/fofix/core/LinedConfigParser.py @@ -94,7 +94,8 @@ _default_dict = dict import re -from fofix.core.Unicode import unicodify + +from fretwork.unicode import unicodify __all__ = ["NoSectionError", "NoOptionError", "ParsingError", "MissingSectionHeaderError", diff --git a/fofix/core/Log.py b/fofix/core/Log.py deleted file mode 100644 index d5152e3cc..000000000 --- a/fofix/core/Log.py +++ /dev/null @@ -1,128 +0,0 @@ -##################################################################### -# -*- coding: iso-8859-1 -*- # -# # -# Frets on Fire # -# Copyright (C) 2006 Sami Kyöstilä # -# 2009 John Stumpo # -# # -# This program is free software; you can redistribute it and/or # -# modify it under the terms of the GNU General Public License # -# as published by the Free Software Foundation; either version 2 # -# of the License, or (at your option) any later version. # -# # -# This program is distributed in the hope that it will be useful, # -# but WITHOUT ANY WARRANTY; without even the implied warranty of # -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # -# GNU General Public License for more details. # -# # -# You should have received a copy of the GNU General Public License # -# along with this program; if not, write to the Free Software # -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # -# MA 02110-1301, USA. # -##################################################################### - -''' -Functions for writing to the logfile. -''' - -import os -import sys -import time -import warnings -import traceback - -from fofix.core.Unicode import utf8 -from fofix.core import Version -from fofix.core import VFS - -# Whether to output log entries to stdout in addition to the logfile. -quiet = True - -# File object representing the logfile. -if os.name == "posix": # evilynux - logfile in ~/.fofix/ for GNU/Linux and MacOS X - # evilynux - Under MacOS X, put the logs in ~/Library/Logs - if os.uname()[0] == "Darwin": - logFile = open(os.path.expanduser('~/Library/Logs/%s.log' % Version.PROGRAM_UNIXSTYLE_NAME), 'w') - else: # GNU/Linux et al. - logFile = VFS.open('/userdata/%s.log' % Version.PROGRAM_UNIXSTYLE_NAME, 'w') -else: - logFile = VFS.open('/userdata/%s.log' % Version.PROGRAM_UNIXSTYLE_NAME, 'w') - -if "-v" in sys.argv or "--verbose" in sys.argv: - quiet = False - -# Labels for different priorities, as output to the logfile. -labels = { - "warn": "(W)", - "debug": "(D)", - "notice": "(N)", - "error": "(E)", -} - -# Labels for different priorities, as output to stdout. -if os.name == "posix": - displaylabels = { - "warn": "\033[1;33m(W)\033[0m", - "debug": "\033[1;34m(D)\033[0m", - "notice": "\033[1;32m(N)\033[0m", - "error": "\033[1;31m(E)\033[0m", - } -else: - displaylabels = labels - -def _log(cls, msg): - ''' - Generic logging function. - @param cls: Priority class for the message - @param msg: Log message text - ''' - msg = utf8(msg) - timeprefix = "[%12.6f] " % (time.time() - _initTime) - if not quiet: - print timeprefix + displaylabels[cls] + " " + msg - print >>logFile, timeprefix + labels[cls] + " " + msg - logFile.flush() #stump: truncated logfiles be gone! - -def error(msg): - ''' - Log a major error. - If this is called while handling an exception, the traceback will - be automatically included in the log. - @param msg: Error message text - ''' - if sys.exc_info() == (None, None, None): - #warnings.warn("Log.error() called without an active exception", UserWarning, 2) #stump: should we enforce this? - _log("error", msg) - else: - _log("error", msg + "\n" + traceback.format_exc()) - -def warn(msg): - ''' - Log a warning. - @param msg: Warning message text - ''' - _log("warn", msg) - -def notice(msg): - ''' - Log a notice. - @param msg: Notice message text - ''' - _log("notice", msg) - -def debug(msg): - ''' - Log a debug message. - @param msg: Debug message text - ''' - _log("debug", msg) - -def _showwarning(*args, **kw): - '''A hook to catch Python warnings.''' - warn("A Python warning was issued:\n" + warnings.formatwarning(*args, **kw)) - _old_showwarning(*args, **kw) -_old_showwarning = warnings.showwarning -warnings.showwarning = _showwarning - -_initTime = time.time() -debug("Logging initialized: " + time.asctime()) \ No newline at end of file diff --git a/fofix/core/Microphone.py b/fofix/core/Microphone.py index ba81f4c13..6b23877e9 100644 --- a/fofix/core/Microphone.py +++ b/fofix/core/Microphone.py @@ -24,9 +24,10 @@ import math import numpy as np -from fofix.core import Log -from fofix.core import Audio -from fofix.core.Task import Task +from fretwork import log +from fretwork.task import Task +from fretwork.audio import MicrophonePassthroughStream + from fofix.core.Language import _ try: @@ -34,7 +35,7 @@ from fofix.core import pypitch supported = True except ImportError: - Log.warn('Missing pyaudio or pypitch - microphone support will not be possible') + log.warn('Missing pyaudio or pypitch - microphone support will not be possible') supported = False if supported: @@ -75,11 +76,11 @@ def __init__(self, engine, controlnum, samprate=44100): self.passthroughQueue = [] passthroughVolume = self.engine.input.controls.micPassthroughVolume[controlnum] if passthroughVolume > 0.0: - Log.debug('Microphone: creating passthrough stream at %d%% volume' % round(passthroughVolume * 100)) - self.passthroughStream = Audio.MicrophonePassthroughStream(engine, self) + log.debug('Microphone: creating passthrough stream at %d%% volume' % round(passthroughVolume * 100)) + self.passthroughStream = MicrophonePassthroughStream(engine, self) self.passthroughStream.setVolume(passthroughVolume) else: - Log.debug('Microphone: not creating passthrough stream') + log.debug('Microphone: not creating passthrough stream') self.passthroughStream = None def __del__(self): @@ -91,20 +92,20 @@ def start(self): self.mic_started = True self.mic.start_stream() self.engine.addTask(self) - Log.debug('Microphone: started %s' % self.devname) + log.debug('Microphone: started %s' % self.devname) if self.passthroughStream is not None: - Log.debug('Microphone: starting passthrough stream') + log.debug('Microphone: starting passthrough stream') self.passthroughStream.play() def stop(self): if self.mic_started: if self.passthroughStream is not None: - Log.debug('Microphone: stopping passthrough stream') + log.debug('Microphone: stopping passthrough stream') self.passthroughStream.stop() self.engine.removeTask(self) self.mic.stop_stream() self.mic_started = False - Log.debug('Microphone: stopped %s' % self.devname) + log.debug('Microphone: stopped %s' % self.devname) # Called by the Task machinery: pump the mic and shove the data through the analyzer. def run(self, ticks): @@ -113,7 +114,7 @@ def run(self, ticks): chunk = self.mic.read(1024) except IOError as e: if e.args[1] == pyaudio.paInputOverflowed: - Log.notice('Microphone: ignoring input buffer overflow') + log.notice('Microphone: ignoring input buffer overflow') chunk = '\x00' * 4096 else: raise diff --git a/fofix/core/MixStream/MixStream.c b/fofix/core/MixStream/MixStream.c deleted file mode 100644 index 3391601a1..000000000 --- a/fofix/core/MixStream/MixStream.c +++ /dev/null @@ -1,473 +0,0 @@ -/* Frets on Fire X (FoFiX) - * Copyright (C) 2011-2012 FoFiX Team - * 2011-2012 John Stumpo - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - * MA 02110-1301, USA. - */ - -#include "MixStream.h" - -#include "soundtouch-c.h" -#include -#include - -#define FRAMES_PER_CHUNK 4096 - -struct _MixStream { - int samprate; - int channels; - mix_stream_read_cb read_cb; - mix_stream_seek_cb seek_cb; - mix_stream_length_cb length_cb; - mix_stream_free_cb free_cb; - void* cb_data; - int channel; - SoundTouch* soundtouch; - Mix_Chunk chunk; - gboolean input_eof; - gboolean eof; - int out_freq; - Uint16 out_format; - int out_channels; - int out_sample_size; - gboolean out_samples_signed; - gboolean byteswap_needed; - GMutex* st_mutex; - double next_read_time; - double out_speed; - double chunk_start_time; - Uint32 chunk_start_ticks; -}; - -static GHashTable* chan_table = NULL; -static GStaticMutex chan_table_mutex = G_STATIC_MUTEX_INIT; - -static void _mix_stream_soundtouchify(MixStream* stream); - - -/* Create a stream that will play data returned by read_cb. - * - samprate and channels specify the format returned by read_cb - * - seek_cb is called to attempt a seek (may be NULL if not implemented) - * - length_cb is called to get total length (may be NULL if not implemented) - * - free_cb is called on data when the stream is destroyed (may be NULL) - * - data is passed to the callbacks - */ -MixStream* mix_stream_new(int samprate, int channels, mix_stream_read_cb read_cb, - mix_stream_seek_cb seek_cb, mix_stream_length_cb length_cb, - mix_stream_free_cb free_cb, void* data, GError** err) -{ - MixStream* stream; - - if (!g_thread_supported()) - g_thread_init(NULL); - - stream = g_new0(MixStream, 1); - stream->samprate = samprate; - stream->channels = channels; - stream->read_cb = read_cb; - stream->seek_cb = seek_cb; - stream->length_cb = length_cb; - stream->free_cb = free_cb; - stream->cb_data = data; - stream->channel = -1; - stream->chunk.volume = MIX_MAX_VOLUME; - stream->out_speed = 1.0; - - if (!Mix_QuerySpec(&stream->out_freq, &stream->out_format, &stream->out_channels)) { - g_set_error(err, MIX_STREAM_ERROR, MIX_STREAM_MIXER_UNINIT, - "SDL_mixer is not initialized"); - g_free(stream); - return NULL; - } - - switch (stream->out_format) { - case AUDIO_S8: stream->out_sample_size = 1; stream->out_samples_signed = TRUE ; stream->byteswap_needed = FALSE; break; - case AUDIO_U8: stream->out_sample_size = 1; stream->out_samples_signed = FALSE; stream->byteswap_needed = FALSE; break; -#if G_BYTE_ORDER == G_LITTLE_ENDIAN - case AUDIO_S16LSB: stream->out_sample_size = 2; stream->out_samples_signed = TRUE ; stream->byteswap_needed = FALSE; break; - case AUDIO_U16LSB: stream->out_sample_size = 2; stream->out_samples_signed = FALSE; stream->byteswap_needed = FALSE; break; - case AUDIO_S16MSB: stream->out_sample_size = 2; stream->out_samples_signed = TRUE ; stream->byteswap_needed = TRUE ; break; - case AUDIO_U16MSB: stream->out_sample_size = 2; stream->out_samples_signed = FALSE; stream->byteswap_needed = TRUE ; break; -#else - case AUDIO_S16LSB: stream->out_sample_size = 2; stream->out_samples_signed = TRUE ; stream->byteswap_needed = TRUE ; break; - case AUDIO_U16LSB: stream->out_sample_size = 2; stream->out_samples_signed = FALSE; stream->byteswap_needed = TRUE ; break; - case AUDIO_S16MSB: stream->out_sample_size = 2; stream->out_samples_signed = TRUE ; stream->byteswap_needed = FALSE; break; - case AUDIO_U16MSB: stream->out_sample_size = 2; stream->out_samples_signed = FALSE; stream->byteswap_needed = FALSE; break; -#endif - default: g_assert_not_reached(); break; - } - - stream->st_mutex = g_mutex_new(); - - if (stream->samprate != stream->out_freq) { - _mix_stream_soundtouchify(stream); - soundtouch_set_rate(stream->soundtouch, (float)stream->samprate/(float)stream->out_freq); - } - - return stream; -} - - -/* Free a MixStream. */ -void mix_stream_destroy(MixStream* stream) -{ - if (stream->channel != -1) - mix_stream_stop(stream); - g_mutex_free(stream->st_mutex); - if (stream->soundtouch != NULL) - soundtouch_delete(stream->soundtouch); - if (stream->free_cb != NULL) - stream->free_cb(stream->cb_data); - g_free(stream); -} - - -/* Ensure the stream is using a soundtouch object. */ -static void _mix_stream_soundtouchify(MixStream* stream) -{ - g_mutex_lock(stream->st_mutex); - if (stream->soundtouch == NULL) { - stream->soundtouch = soundtouch_new(); - soundtouch_set_sample_rate(stream->soundtouch, stream->samprate); - soundtouch_set_channels(stream->soundtouch, stream->channels); - } - g_mutex_unlock(stream->st_mutex); -} - - -/* Fill a float buffer using a read callback and possibly a SoundTouch object. */ -static gsize _mix_stream_fill_floatbuf(MixStream* stream, float* buf, gsize numframes, guint channels) -{ - const gsize frame_size = sizeof(float) * channels; - gsize frames_obtained = 0; - gsize frames_read; - while (numframes > 0) { - - g_mutex_lock(stream->st_mutex); - if (stream->soundtouch == NULL) { - frames_read = stream->read_cb(buf, numframes * frame_size, stream->cb_data) / frame_size; - } else { - while (!stream->input_eof && soundtouch_num_samples(stream->soundtouch) < numframes) { - frames_read = stream->read_cb(buf, numframes * frame_size, stream->cb_data) / frame_size; - if (frames_read == 0) { - stream->input_eof = TRUE; - soundtouch_flush(stream->soundtouch); - break; - } - soundtouch_put_samples(stream->soundtouch, buf, frames_read); - } - frames_read = soundtouch_receive_samples(stream->soundtouch, buf, numframes); - } - g_mutex_unlock(stream->st_mutex); - - if (frames_read == 0) { - if (frames_obtained != 0) { - /* Fill up the rest of the buffer with silence. */ - memset(buf, 0, numframes * frame_size); - frames_obtained += numframes; - } - stream->eof = TRUE; - break; - } - - frames_obtained += frames_read; - buf += frames_read * channels; - numframes -= frames_read; - } - return frames_obtained; -} - - -/* Set the stream's audio chunk be the next size bytes of audio. */ -static gboolean _mix_stream_nextchunk(MixStream* stream, gsize size) -{ - // compute necessary number of samples - // if there's an active soundtouch object: - // while not enough samples in soundtouch output: - // call callback to get more samples - // feed new samples to soundtouch - // else: - // call callback to get samples - // perform any necessary conversions - int needed_frames; - int obtained_frames; - float* floatbuf; - guint8* out_buf; - - if (stream->eof) - return FALSE; - - if (stream->chunk.alen < size) { - stream->chunk.abuf = g_realloc(stream->chunk.abuf, size); - stream->chunk.alen = size; - } - out_buf = stream->chunk.abuf; - - needed_frames = size / (stream->out_channels * stream->out_sample_size); - - floatbuf = g_newa(float, needed_frames * stream->channels); - obtained_frames = _mix_stream_fill_floatbuf(stream, floatbuf, needed_frames, stream->channels); - if (obtained_frames == 0) - return FALSE; - - while (size > 0) { - float current_sample = *(floatbuf++); - /* If we're converting stereo to mono, average this sample with the other channel's. */ - if (stream->channels == 2 && stream->out_channels == 1) - current_sample = (float)(0.5 * (current_sample + *(floatbuf++))); - current_sample = CLAMP(current_sample, -1.0, 1.0); - -#define OUTPUT_SAMPLE(type, value) { *(type*)out_buf = (type)(value); out_buf += sizeof(type); size -= sizeof(type); } - - /* Convert and output the sample. */ - if (stream->out_samples_signed) { - if (stream->out_sample_size == 1) { - OUTPUT_SAMPLE(gint8, current_sample * G_MAXINT8); - } else if (!stream->byteswap_needed) { - OUTPUT_SAMPLE(gint16, current_sample * G_MAXINT16); - } else { - OUTPUT_SAMPLE(guint16, GUINT16_SWAP_LE_BE((guint16)(gint16)(current_sample * G_MAXINT16))); - } - } else { - current_sample = (float)(current_sample * 0.5 + 0.5); - if (stream->out_sample_size == 1) { - OUTPUT_SAMPLE(guint8, current_sample * G_MAXUINT8); - } else if (!stream->byteswap_needed) { - OUTPUT_SAMPLE(guint16, current_sample * G_MAXUINT16); - } else { - OUTPUT_SAMPLE(guint16, GUINT16_SWAP_LE_BE((guint16)(current_sample * G_MAXUINT16))); - } - } - - /* If we're converting mono to stereo, duplicate the sample. */ - if (stream->channels == 1 && stream->out_channels == 2) { - if (stream->out_sample_size == 1) { - OUTPUT_SAMPLE(guint8, *(guint8*)(out_buf - sizeof(guint8))); - } else { - OUTPUT_SAMPLE(guint16, *(guint16*)(out_buf - sizeof(guint16))); - } - } - -#undef OUTPUT_SAMPLE - - } - - stream->chunk_start_time = stream->next_read_time; - stream->next_read_time += (stream->out_speed * obtained_frames) / stream->out_freq; - - return TRUE; -} - - -static void _mix_stream_channel_finished(int channel) -{ - MixStream* stream; - - g_static_mutex_lock(&chan_table_mutex); - stream = g_hash_table_lookup(chan_table, &channel); - g_static_mutex_unlock(&chan_table_mutex); - - if (stream == NULL) - return; - - if (!_mix_stream_nextchunk(stream, FRAMES_PER_CHUNK)) { - g_static_mutex_lock(&chan_table_mutex); - g_hash_table_remove(chan_table, &stream->channel); - stream->channel = -1; - g_static_mutex_unlock(&chan_table_mutex); - return; - } - - Mix_PlayChannel(channel, &stream->chunk, 0); - stream->chunk_start_ticks = SDL_GetTicks(); -} - - -/* Begin playing a MixStream from its current position. */ -int mix_stream_play(MixStream* stream, int requested_channel) -{ - int real_channel; - - if (stream->channel != -1) - return -1; - - g_static_mutex_lock(&chan_table_mutex); - if (chan_table == NULL) - chan_table = g_hash_table_new_full(g_int_hash, g_int_equal, g_free, NULL); - g_static_mutex_unlock(&chan_table_mutex); - - _mix_stream_nextchunk(stream, FRAMES_PER_CHUNK); - - /* Sadly we can't call Mix_PlayChannel with the channel table lock held, as - * we have to take it in the channel-finished callback, which runs with - * the SDL audio lock held, but Mix_PlayChannel itself takes the SDL audio - * lock, so we'd risk deadlocking. - * - * So if we want SDL_mixer to pick a channel for us, just do it without the - * lock and deal with the possiblity that the chunk might finish before we - * record the channel-stream mapping in the channel table. - */ - Mix_ChannelFinished(_mix_stream_channel_finished); - if (requested_channel == -1) { - real_channel = Mix_PlayChannel(-1, &stream->chunk, 0); - if (real_channel == -1) - return -1; - } else { - real_channel = requested_channel; - } - - /* Now we know what channel we're on. Put it into the channel table. */ - g_static_mutex_lock(&chan_table_mutex); - stream->channel = real_channel; - g_hash_table_insert(chan_table, g_memdup(&stream->channel, sizeof(int)), stream); - g_static_mutex_unlock(&chan_table_mutex); - - stream->chunk_start_ticks = SDL_GetTicks(); - if (requested_channel == -1) - return real_channel; - else - return Mix_PlayChannel(real_channel, &stream->chunk, 0); -} - - -/* Check whether a MixStream is playing. */ -gboolean mix_stream_is_playing(const MixStream* stream) -{ - gboolean playing; - - /* Between SDL_mixer noticing that a chunk finished playing and when the - * callback plays the next chunk, the internal variable that Mix_Playing - * uses gets set to indicate not playing. That whole dance occurs with the - * SDL audio lock held, so take it when doing this check to prevent false - * indications that the stream is not playing. - */ - SDL_LockAudio(); - playing = ((stream->channel != -1) && Mix_Playing(stream->channel)); - SDL_UnlockAudio(); - return playing; -} - - -/* Stop playing a MixStream. */ -void mix_stream_stop(MixStream* stream) -{ - if (stream->channel != -1) { - /* Unregister the stream so the callback won't do anything more with the stream. - Again we have the channel table lock/SDL audio lock dilemma... */ - g_static_mutex_lock(&chan_table_mutex); - g_hash_table_remove(chan_table, &stream->channel); - stream->channel = -1; - g_static_mutex_unlock(&chan_table_mutex); - - Mix_HaltChannel(stream->channel); - /* It would seem like we should wait on a condition variable here, but - * it turns out that SDL_mixer calls the channel-finished callback from - * Mix_HaltChannel. Not that it's good to rely on implementation - * details like that, but it saves us a lot of extra trouble. - */ - } -} - - -/* Set pitch of a MixStream. */ -void mix_stream_set_pitch_semitones(MixStream* stream, float semitones) -{ - _mix_stream_soundtouchify(stream); - g_mutex_lock(stream->st_mutex); - soundtouch_set_pitch_semitones(stream->soundtouch, semitones); - g_mutex_unlock(stream->st_mutex); -} - - -/* Set speed of a MixStream without affecting pitch. */ -void mix_stream_set_speed(MixStream* stream, float speed) -{ - _mix_stream_soundtouchify(stream); - g_mutex_lock(stream->st_mutex); - soundtouch_set_tempo(stream->soundtouch, speed); - stream->out_speed = speed; - g_mutex_unlock(stream->st_mutex); -} - - -/* Seek to time (in seconds) from the beginning of a MixStream's - * underlying content and return the new time. Returns a negative - * value on error or if the content is unseekable. - */ -double mix_stream_seek(MixStream* stream, double time) -{ - double new_time; - if (stream->seek_cb == NULL) - return -1.0; - SDL_LockAudio(); - new_time = stream->seek_cb(time, stream->cb_data); - g_mutex_lock(stream->st_mutex); - if (stream->soundtouch != NULL) - soundtouch_clear(stream->soundtouch); - stream->eof = FALSE; - stream->input_eof = FALSE; - stream->next_read_time = new_time; - g_mutex_unlock(stream->st_mutex); - SDL_UnlockAudio(); - return new_time; -} - - -/* Get current playback position in seconds (with respect to the - * underlying content!) of a MixStream if this is well-defined for - * the underlying content. Returns a negative value on error. - */ -double mix_stream_get_position(MixStream* stream) -{ - /* This is one of the more critical functions to be sure we get right, as the - * notes on screen will be positioned based on whatever this function says. - */ - double chunk_time; - double time_since_chunk_start; - double position; - - if (!mix_stream_is_playing(stream)) - return -1.0; - - SDL_LockAudio(); - chunk_time = (double)FRAMES_PER_CHUNK/(double)stream->out_freq; - time_since_chunk_start = CLAMP((SDL_GetTicks() - stream->chunk_start_ticks) / 1000.0, 0.0, chunk_time); - position = stream->chunk_start_time + stream->out_speed * time_since_chunk_start; - SDL_UnlockAudio(); - return position; -} - - -/* Get total length in seconds of a MixStream's underlying content. - * Returns a negative value if this quantity is not defined. - */ -double mix_stream_get_length(MixStream* stream) -{ - double length; - if (stream->length_cb == NULL) - return -1.0; - SDL_LockAudio(); - length = stream->length_cb(stream->cb_data); - SDL_UnlockAudio(); - return length; -} - - -/* For GErrors we might return. */ -GQuark mix_stream_error_quark(void) -{ - return g_quark_from_static_string("mix-stream-error-quark"); -} diff --git a/fofix/core/MixStream/MixStream.h b/fofix/core/MixStream/MixStream.h deleted file mode 100644 index 27e38a7a6..000000000 --- a/fofix/core/MixStream/MixStream.h +++ /dev/null @@ -1,57 +0,0 @@ -/* Frets on Fire X (FoFiX) - * Copyright (C) 2011-2012 FoFiX Team - * 2011-2012 John Stumpo - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - * MA 02110-1301, USA. - */ - -#ifndef MIXSTREAM_H -#define MIXSTREAM_H - -#include - -typedef struct _MixStream MixStream; - -typedef gsize(*mix_stream_read_cb)(float* buf, gsize bufsize, void* data); -typedef double(*mix_stream_seek_cb)(double time, void* data); -typedef double(*mix_stream_length_cb)(void* data); -typedef void(*mix_stream_free_cb)(void* data); -MixStream* mix_stream_new(int samprate, int channels, mix_stream_read_cb read_cb, - mix_stream_seek_cb seek_cb, mix_stream_length_cb length_cb, - mix_stream_free_cb free_cb, void* data, GError** err); -MixStream* mix_stream_new_vorbisfile(const char* filename, GError** err); -void mix_stream_destroy(MixStream* stream); - -int mix_stream_play(MixStream* stream, int channel); -gboolean mix_stream_is_playing(const MixStream* stream); -void mix_stream_stop(MixStream* stream); -double mix_stream_seek(MixStream* stream, double time); -double mix_stream_get_position(MixStream* stream); -double mix_stream_get_length(MixStream* stream); - -void mix_stream_set_pitch_semitones(MixStream* stream, float semitones); -void mix_stream_set_speed(MixStream* stream, float speed); - -GQuark mix_stream_error_quark(void); -#define MIX_STREAM_ERROR mix_stream_error_quark() -GQuark mix_stream_ov_error_quark(void); -#define MIX_STREAM_OV_ERROR mix_stream_ov_error_quark() - -typedef enum { - MIX_STREAM_MIXER_UNINIT -} MixStreamError; - -#endif diff --git a/fofix/core/MixStream/_MixStream.pyx b/fofix/core/MixStream/_MixStream.pyx deleted file mode 100644 index 115d995eb..000000000 --- a/fofix/core/MixStream/_MixStream.pyx +++ /dev/null @@ -1,103 +0,0 @@ -##################################################################### -# -*- coding: iso-8859-1 -*- # -# # -# Frets on Fire X (FoFiX) # -# Copyright (C) 2011-2012 FoFiX Team # -# 2011-2012 John Stumpo # -# # -# This program is free software; you can redistribute it and/or # -# modify it under the terms of the GNU General Public License # -# as published by the Free Software Foundation; either version 2 # -# of the License, or (at your option) any later version. # -# # -# This program is distributed in the hope that it will be useful, # -# but WITHOUT ANY WARRANTY; without even the implied warranty of # -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # -# GNU General Public License for more details. # -# # -# You should have received a copy of the GNU General Public License # -# along with this program; if not, write to the Free Software # -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # -# MA 02110-1301, USA. # -##################################################################### - -cdef extern from "MixStream.h": - ctypedef struct CMixStream "MixStream": - pass - - ctypedef int GQuark - ctypedef struct GError: - GQuark domain - char* message - GQuark G_FILE_ERROR - GQuark MIX_STREAM_ERROR - GQuark MIX_STREAM_OV_ERROR - void g_error_free(GError*) - - CMixStream* mix_stream_new_vorbisfile(char*, GError**) - void mix_stream_destroy(CMixStream*) - int mix_stream_play(CMixStream*, int) - bint mix_stream_is_playing(CMixStream*) - void mix_stream_stop(CMixStream*) - double mix_stream_seek(CMixStream*, double) - double mix_stream_get_position(CMixStream*) - double mix_stream_get_length(CMixStream*) - void mix_stream_set_pitch_semitones(CMixStream*, float) - void mix_stream_set_speed(CMixStream*, float) - - -class MixStreamError(Exception): - pass - -class VorbisFileError(Exception): - pass - -cdef object raise_from_gerror(GError* err): - assert err is not NULL - if err.domain == MIX_STREAM_ERROR: - exc = MixStreamError(err.message) - elif err.domain == MIX_STREAM_OV_ERROR: - exc = VorbisFileError(err.message) - elif err.domain == G_FILE_ERROR: - exc = IOError(err.message) - else: - exc = Exception(err.message) - g_error_free(err) - raise exc - -cdef class VorbisFileMixStream(object): - cdef CMixStream* stream - - def __cinit__(self, char* filename): - cdef GError* err = NULL - self.stream = mix_stream_new_vorbisfile(filename, &err) - if self.stream is NULL: - raise_from_gerror(err) - - def __dealloc__(self): - if self.stream is not NULL: - mix_stream_destroy(self.stream) - - def play(self, int channel=-1): - return mix_stream_play(self.stream, channel) - - def is_playing(self): - return mix_stream_is_playing(self.stream) - - def stop(self): - mix_stream_stop(self.stream) - - def seek(self, double time): - return mix_stream_seek(self.stream, time) - - def get_position(self): - return mix_stream_get_position(self.stream) - - def get_length(self): - return mix_stream_get_length(self.stream) - - def set_pitch_semitones(self, float semitones): - mix_stream_set_pitch_semitones(self.stream, semitones) - - def set_speed(self, float speed): - mix_stream_set_speed(self.stream, speed) diff --git a/fofix/core/MixStream/__init__.py b/fofix/core/MixStream/__init__.py deleted file mode 100644 index ad17dc3a1..000000000 --- a/fofix/core/MixStream/__init__.py +++ /dev/null @@ -1 +0,0 @@ -from fofix.lib._MixStream import * diff --git a/fofix/core/MixStream/soundtouch-c.cpp b/fofix/core/MixStream/soundtouch-c.cpp deleted file mode 100644 index 792787667..000000000 --- a/fofix/core/MixStream/soundtouch-c.cpp +++ /dev/null @@ -1,128 +0,0 @@ -/* soundtouch-c: A C shim around most of the SoundTouch audio processor. - * Copyright (C) 2011 John Stumpo - * - * This program is covered by the same license as the SoundTouch library - * itself, namely (as of this writing) the GNU Lesser General Public - * License, version 2.1 or (at your option) any later version. See the - * license of the SoundTouch library for more information. - */ - -#include "soundtouch-c.h" -#include -#include -#include - -extern "C" -{ - -SoundTouch* soundtouch_new(void) -{ - // The reason we do a g_malloc and placement new here is so this - // object doesn't depend on anything C++-related beyond symbols from - // SoundTouch. This allows us to link it with MSVC tools on Windows and - // successfully bridge to the MinGW-compiled SoundTouch DLL. - // - // If SoundTouch itself wants to include this, it can just do ordinary - // new and delete here and in soundtouch_delete, as the constraint on - // linked-to symbols then no longer applies. - return new(g_malloc(sizeof(SoundTouch))) SoundTouch(); -} - -void soundtouch_delete(SoundTouch* st) -{ - // See comment in soundtouch_new(). - st->~SoundTouch(); - g_free(st); -} - -const char* soundtouch_get_version_string(void) -{ - return SoundTouch::getVersionString(); -} - -unsigned int soundtouch_get_version_id(void) -{ - return SoundTouch::getVersionId(); -} - -void soundtouch_set_rate(SoundTouch* st, float rate) -{ - st->setRate(rate); -} - -void soundtouch_set_tempo(SoundTouch* st, float tempo) -{ - st->setTempo(tempo); -} - -void soundtouch_set_rate_change(SoundTouch* st, float rate) -{ - st->setRateChange(rate); -} - -void soundtouch_set_tempo_change(SoundTouch* st, float tempo) -{ - st->setTempoChange(tempo); -} - -void soundtouch_set_pitch(SoundTouch* st, float pitch) -{ - st->setPitch(pitch); -} - -void soundtouch_set_pitch_octaves(SoundTouch* st, float pitch) -{ - st->setPitchOctaves(pitch); -} - -void soundtouch_set_pitch_semitones(SoundTouch* st, float pitch) -{ - st->setPitchSemiTones(pitch); -} - -void soundtouch_set_channels(SoundTouch* st, unsigned int channels) -{ - st->setChannels(channels); -} - -void soundtouch_set_sample_rate(SoundTouch* st, unsigned int rate) -{ - st->setSampleRate(rate); -} - -void soundtouch_flush(SoundTouch* st) -{ - st->flush(); -} - -void soundtouch_put_samples(SoundTouch* st, const float* input_buffer, unsigned int num_samples) -{ - st->putSamples(input_buffer, num_samples); -} - -void soundtouch_clear(SoundTouch* st) -{ - st->clear(); -} - -unsigned int soundtouch_num_unprocessed_samples(const SoundTouch* st) -{ - return st->numUnprocessedSamples(); -} - -unsigned int soundtouch_receive_samples(SoundTouch* st, float* output_buffer, unsigned int num_samples) -{ - return st->receiveSamples(output_buffer, num_samples); -} - -unsigned int soundtouch_num_samples(const SoundTouch* st) -{ - return st->numSamples(); -} - -int soundtouch_is_empty(const SoundTouch* st) -{ - return st->isEmpty(); -} - -} /* extern "C" */ diff --git a/fofix/core/MixStream/soundtouch-c.h b/fofix/core/MixStream/soundtouch-c.h deleted file mode 100644 index acdbc3400..000000000 --- a/fofix/core/MixStream/soundtouch-c.h +++ /dev/null @@ -1,51 +0,0 @@ -/* soundtouch-c: A C shim around most of the SoundTouch audio processor. - * Copyright (C) 2011 John Stumpo - * - * This program is covered by the same license as the SoundTouch library - * itself, namely (as of this writing) the GNU Lesser General Public - * License, version 2.1 or (at your option) any later version. See the - * license of the SoundTouch library for more information. - */ - -#ifndef SOUNDTOUCH_C_H -#define SOUNDTOUCH_C_H - -#ifdef __cplusplus -namespace soundtouch { struct SoundTouch; } -using soundtouch::SoundTouch; -extern "C" { -#else -typedef struct SoundTouch SoundTouch; -#endif - -SoundTouch* soundtouch_new(void); -void soundtouch_delete(SoundTouch*); - -const char* soundtouch_get_version_string(void); -unsigned int soundtouch_get_version_id(void); - -void soundtouch_set_rate(SoundTouch*, float); -void soundtouch_set_tempo(SoundTouch*, float); -void soundtouch_set_rate_change(SoundTouch*, float); -void soundtouch_set_tempo_change(SoundTouch*, float); - -void soundtouch_set_pitch(SoundTouch*, float); -void soundtouch_set_pitch_octaves(SoundTouch*, float); -void soundtouch_set_pitch_semitones(SoundTouch*, float); - -void soundtouch_set_channels(SoundTouch*, unsigned int); -void soundtouch_set_sample_rate(SoundTouch*, unsigned int); - -void soundtouch_flush(SoundTouch*); -void soundtouch_put_samples(SoundTouch*, const float*, unsigned int); -void soundtouch_clear(SoundTouch*); -unsigned int soundtouch_num_unprocessed_samples(const SoundTouch*); -unsigned int soundtouch_receive_samples(SoundTouch*, float*, unsigned int); -unsigned int soundtouch_num_samples(const SoundTouch*); -int soundtouch_is_empty(const SoundTouch*); - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/fofix/core/MixStream/vorbis.c b/fofix/core/MixStream/vorbis.c deleted file mode 100644 index dff397c3e..000000000 --- a/fofix/core/MixStream/vorbis.c +++ /dev/null @@ -1,135 +0,0 @@ -/* Frets on Fire X (FoFiX) - * Copyright (C) 2012 FoFiX Team - * 2012 John Stumpo - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - * MA 02110-1301, USA. - */ - -#include "MixStream.h" -#include -#include - - -/* strerror-like function for libvorbis{,file} error codes - * ...would be nice if libvorbis itself had something like this... - */ -static const char* vf_strerror(int vf_err) -{ - switch (vf_err) { - case 0: return "Success"; - case OV_EREAD: return "Read error"; - case OV_EFAULT: return "Internal fault in libvorbis"; - case OV_EIMPL: return "Feature not implemented"; - case OV_EINVAL: return "Invalid argument within libvorbis"; - case OV_ENOTVORBIS: return "Not Ogg Vorbis"; - case OV_EBADHEADER: return "Bad file header"; - case OV_EVERSION: return "Unsupported format revision"; - case OV_EBADLINK: return "Undecodable link"; - case OV_ENOSEEK: return "Stream is not seekable"; - default: return "General failure"; - } -} - - -/* Read callback for a libvorbisfile-backed stream. */ -static gsize vf_read_cb(float* buf, gsize bufsize, void* data) -{ - OggVorbis_File* vf = data; - int channels = ov_info(vf, -1)->channels; - int samples = bufsize / (channels * sizeof(float)); - float** pcm; - int streamno; - int i, j; - - /* Decode the samples. */ - samples = ov_read_float(vf, &pcm, samples, &streamno); - if (samples < 0) { - g_warning("Error in vorbisfile read callback: %s", vf_strerror(samples)); - return 0; - } - - /* Copy the samples into the buffer. */ - for (i = 0; i < samples; i++) - for (j = 0; j < channels; j++) - *(buf++) = pcm[j][i]; - - return samples * channels * sizeof(float); -} - - -/* Seek callback for a libvorbisfile-backed stream. */ -static double vf_seek_cb(double time, void* data) -{ - int result = ov_time_seek((OggVorbis_File*)data, time); - if (result == 0) - return time; - else - return -1.0; -} - - -/* Length callback for a libvorbisfile-backed stream. */ -static double vf_length_cb(void* data) -{ - return ov_time_total((OggVorbis_File*)data, -1); -} - - -/* Free callback for a libvorbisfile-backed stream. */ -static void vf_free_cb(void* data) -{ - ov_clear((OggVorbis_File*)data); - g_free(data); -} - - -/* Create a MixStream that plays Ogg Vorbis audio from the given file name. */ -MixStream* mix_stream_new_vorbisfile(const char* filename, GError** err) -{ - MixStream* stream; - OggVorbis_File* vf = g_new(OggVorbis_File, 1); - int vf_err; - vorbis_info* vi; - - errno = 0; - if ((vf_err = ov_fopen(filename, vf)) != 0) { - if (errno != 0) - g_set_error(err, G_FILE_ERROR, g_file_error_from_errno(errno), - "Failed to open file: %s", g_strerror(errno)); - else - g_set_error(err, MIX_STREAM_OV_ERROR, vf_err, - "Failed to initialize decoder: %s", vf_strerror(vf_err)); - g_free(vf); - return NULL; - } - - vi = ov_info(vf, -1); - - stream = mix_stream_new(vi->rate, vi->channels, vf_read_cb, vf_seek_cb, vf_length_cb, vf_free_cb, vf, err); - if (stream == NULL) { - ov_clear(vf); - g_free(vf); - return NULL; - } - return stream; -} - - -/* For GErrors we might return. */ -GQuark mix_stream_ov_error_quark(void) -{ - return g_quark_from_static_string("mix-stream-ov-error-quark"); -} diff --git a/fofix/core/Mod.py b/fofix/core/Mod.py index 5cb9fb9de..ce1c344c8 100644 --- a/fofix/core/Mod.py +++ b/fofix/core/Mod.py @@ -22,10 +22,11 @@ import os +from fretwork import log + from fofix.core.Language import _ from fofix.core import Config from fofix.core import Theme -from fofix.core import Log def _getModPath(engine): return engine.resource.fileName("mods") @@ -44,7 +45,7 @@ def getAvailableMods(engine): try: dirList = os.listdir(modPath) except OSError: - Log.warn("Could not find mods directory") + 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(".")] diff --git a/fofix/core/Player.py b/fofix/core/Player.py index 1b7db56df..bfb3d56d7 100644 --- a/fofix/core/Player.py +++ b/fofix/core/Player.py @@ -26,12 +26,13 @@ import pygame +from fretwork import log + from fofix.core.Language import _ from fofix.core import Microphone #stump from fofix.core import Config from fofix.game import Song from fofix.core import VFS -from fofix.core import Log class ConfigOption: def __init__(self, id, text): @@ -444,7 +445,7 @@ def __init__(self): self.logClassInits = Config.get("game", "log_class_inits") if self.logClassInits == 1: - Log.debug("Controls class init (Player.py)...") + log.debug("Controls class init (Player.py)...") self.controls = [] self.controls.append(Config.get("game", "control0")) self.controls.append(Config.get("game", "control1")) @@ -737,7 +738,7 @@ def keyName(value): else: return name + " " + guitarkeynames[j] else: - Log.notice("Key value not found.") + log.notice("Key value not found.") return "Error" if self.keyCheckerMode == 0: @@ -847,7 +848,7 @@ def __init__(self, name, number): self.logClassInits = Config.get("game", "log_class_inits") if self.logClassInits == 1: - Log.debug("Player class init (Player.py)...") + log.debug("Player class init (Player.py)...") self.name = name diff --git a/fofix/core/Resource.py b/fofix/core/Resource.py index bf7fe28c6..1bfa77992 100644 --- a/fofix/core/Resource.py +++ b/fofix/core/Resource.py @@ -30,11 +30,12 @@ from Queue import Queue, Empty from threading import Thread, BoundedSemaphore -from fofix.core.Task import Task +from fretwork import log +from fretwork.task import Task + from fofix.core.VFS import getWritableResourcePath from fofix.core import Version from fofix.core import Config -from fofix.core import Log class Loader(Thread): def __init__(self, target, name, function, resultQueue, loaderSemaphore, onLoad = None, onCancel = None): @@ -122,7 +123,7 @@ def finish(self): return if self.logLoadings == 1: - Log.notice("Loaded %s.%s in %.3f seconds" % (self.target.__class__.__name__, self.name, self.time)) + log.notice("Loaded %s.%s in %.3f seconds" % (self.target.__class__.__name__, self.name, self.time)) if self.exception: raise self.exception[0], self.exception[1], self.exception[2] @@ -209,7 +210,7 @@ def fileName(self, *name, **args): # read-write path. readWritePath = os.path.join(getWritableResourcePath(), *name) if not os.path.isfile(readWritePath) and os.path.isfile(readOnlyPath): - Log.notice("Copying '%s' to writable data directory." % "/".join(name)) + log.notice("Copying '%s' to writable data directory." % "/".join(name)) try: os.makedirs(os.path.dirname(readWritePath)) except: @@ -218,7 +219,7 @@ def fileName(self, *name, **args): self.makeWritable(readWritePath) # Create directories if needed if not os.path.isdir(readWritePath) and os.path.isdir(readOnlyPath): - Log.notice("Creating writable directory '%s'." % "/".join(name)) + log.notice("Creating writable directory '%s'." % "/".join(name)) os.makedirs(readWritePath) self.makeWritable(readWritePath) return readWritePath @@ -230,7 +231,7 @@ def makeWritable(self, path): def load(self, target = None, name = None, function = lambda: None, synch = False, onLoad = None, onCancel = None): if self.logLoadings == 1: - Log.notice("Loading %s.%s %s" % (target.__class__.__name__, name, synch and "synchronously" or "asynchronously")) + log.notice("Loading %s.%s %s" % (target.__class__.__name__, name, synch and "synchronously" or "asynchronously")) l = Loader(target, name, function, self.resultQueue, self.loaderSemaphore, onLoad = onLoad, onCancel = onCancel) if synch: diff --git a/fofix/core/Settings.py b/fofix/core/Settings.py index 3b99b03bf..45bc95099 100644 --- a/fofix/core/Settings.py +++ b/fofix/core/Settings.py @@ -33,6 +33,8 @@ import pygame +from fretwork import log + from fofix.core.Language import _ from fofix.core.View import BackgroundLayer from fofix.core.Input import KeyListener @@ -44,7 +46,6 @@ from fofix.core import Player from fofix.core import Mod from fofix.core import VFS -from fofix.core import Log class ConfigChoice(Menu.Choice): def __init__(self, engine, config, section, option, autoApply = False, isQuickset = 0): @@ -53,7 +54,7 @@ def __init__(self, engine, config, section, option, autoApply = False, isQuickse self.logClassInits = self.engine.config.get("game", "log_class_inits") if self.logClassInits == 1: - Log.debug("ConfigChoice class init (Settings.py)...") + log.debug("ConfigChoice class init (Settings.py)...") self.section = section self.option = option @@ -126,7 +127,7 @@ def __init__(self, engine, config, section, option, onChange, autoApply = True, self.logClassInits = self.engine.config.get("game", "log_class_inits") if self.logClassInits == 1: - Log.debug("ActiveConfigChoice class init (Settings.py)...") + log.debug("ActiveConfigChoice class init (Settings.py)...") def change(self, value): ConfigChoice.change(self, value) @@ -146,7 +147,7 @@ def __init__(self, engine, config, section, option, autoApply = False): self.logClassInits = self.engine.config.get("game", "log_class_inits") if self.logClassInits == 1: - Log.debug("VolumeConfigChoice class init (Settings.py)...") + log.debug("VolumeConfigChoice class init (Settings.py)...") def change(self, value): @@ -161,7 +162,7 @@ def __init__(self, engine, config, section, option, noneOK = False, shift = None self.logClassInits = self.engine.config.get("game", "log_class_inits") if self.logClassInits == 1: - Log.debug("KeyConfigChoice class init (Settings.py)...") + log.debug("KeyConfigChoice class init (Settings.py)...") self.config = config self.section = section @@ -303,7 +304,7 @@ def __init__(self, engine, mode, options): self.logClassInits = self.engine.config.get("game", "log_class_inits") if self.logClassInits == 1: - Log.debug("ControlChooser class init (Settings.py)...") + log.debug("ControlChooser class init (Settings.py)...") self.selected = None self.d = None @@ -341,7 +342,7 @@ def __init__(self, engine, control = "", edit = False): self.edit = edit self.logClassInits = self.engine.config.get("game", "log_class_inits") if self.logClassInits == 1: - Log.debug("ControlCreator class init (Settings.py)...") + log.debug("ControlCreator class init (Settings.py)...") self.time = 0.0 self.badname = ["defaultg", "defaultd", "defaultm"] #ensures that defaultm is included - duplicate is ok @@ -628,7 +629,7 @@ def __init__(self, engine): self.engine = engine self.logClassInits = self.engine.config.get("game", "log_class_inits") if self.logClassInits == 1: - Log.debug("SettingsMenu class init (Settings.py)...") + log.debug("SettingsMenu class init (Settings.py)...") self.keyCheckerMode = Config.get("game", "key_checker_mode") @@ -1085,13 +1086,13 @@ def scrollSet(self): self.engine.scrollDelay = self.engine.config.get("game", "scroll_delay") def resetLanguageToEnglish(self): - Log.debug("settings.resetLanguageToEnglish function call...") + log.debug("settings.resetLanguageToEnglish function call...") if self.engine.config.get("game", "language") != "": self.engine.config.set("game", "language", "") self.engine.restart() def baseLibrarySelect(self): - Log.debug("settings.baseLibrarySelect function call...") + log.debug("settings.baseLibrarySelect function call...") newPath = Dialogs.chooseFile(self.engine, masks = ["*/*"], prompt = _("Choose a new songs directory."), dirSelect = True) if newPath is not None: Config.set("setlist", "base_library", os.path.dirname(newPath)) @@ -1109,7 +1110,7 @@ def __init__(self, engine): self.logClassInits = self.engine.config.get("game", "log_class_inits") if self.logClassInits == 1: - Log.debug("BasicSettingsMenu class init (Settings.py)...") + log.debug("BasicSettingsMenu class init (Settings.py)...") self.opt_text_x = self.engine.theme.opt_text_xPos self.opt_text_y = self.engine.theme.opt_text_yPos @@ -1343,13 +1344,13 @@ def keyTest(self, controller): Dialogs.testKeys(self.engine, controller) def resetLanguageToEnglish(self): - Log.debug("settings.resetLanguageToEnglish function call...") + log.debug("settings.resetLanguageToEnglish function call...") if self.engine.config.get("game", "language") != "": self.engine.config.set("game", "language", "") self.engine.restart() def baseLibrarySelect(self): - Log.debug("settings.baseLibrarySelect function call...") + log.debug("settings.baseLibrarySelect function call...") newPath = Dialogs.chooseFile(self.engine, masks = ["*/*"], prompt = _("Choose a new songs directory."), dirSelect = True) if newPath is not None: Config.set("setlist", "base_library", os.path.dirname(newPath)) @@ -1368,14 +1369,14 @@ def quickset(config): config.set("game", "big_rock_endings", 1) config.set("game", "in_game_stars", 1) config.set("game", "mark_solo_sections", 2) - Log.debug("Quickset Gameplay - Theme-Based") + log.debug("Quickset Gameplay - Theme-Based") elif gameSetNum == 2: config.set("game", "sp_notes_while_active", 2) config.set("game", "bass_groove_enable", 2) config.set("game", "big_rock_endings", 2) config.set("game", "mark_solo_sections", 3) - Log.debug("Quickset Gameplay - MIDI-Based") + log.debug("Quickset Gameplay - MIDI-Based") elif gameSetNum == 3: config.set("game", "sp_notes_while_active", 3) @@ -1384,7 +1385,7 @@ def quickset(config): config.set("game", "in_game_stars", 2) config.set("game", "counting", True) config.set("game", "mark_solo_sections", 1) - Log.debug("Quickset Gameplay - RB style") + log.debug("Quickset Gameplay - RB style") elif gameSetNum == 4: config.set("game", "sp_notes_while_active", 0) @@ -1393,7 +1394,7 @@ def quickset(config): config.set("game", "in_game_stars", 0) config.set("game", "counting", False) config.set("game", "mark_solo_sections", 0) - Log.debug("Quickset Gameplay - GH style") + log.debug("Quickset Gameplay - GH style") elif gameSetNum == 5: # This needs work. config.set("game", "sp_notes_while_active", 0) @@ -1402,12 +1403,12 @@ def quickset(config): config.set("game", "in_game_stars", 0) config.set("game", "counting", True) config.set("game", "mark_solo_sections", 1) - Log.debug("Quickset Gameplay - WT style") + log.debug("Quickset Gameplay - WT style") # elif gameSetNum == 6: #FoFiX mode - perhaps soon. else: - Log.debug("Quickset Gameplay - Manual") + log.debug("Quickset Gameplay - Manual") if perfSetNum == 1: config.set("engine", "highpriority", False) @@ -1432,7 +1433,7 @@ def quickset(config): config.set("performance", "killfx", 2) config.set("performance", "star_score_updates", 0) config.set("performance", "cache_song_metadata", False) - Log.debug("Quickset Performance - Fastest") + log.debug("Quickset Performance - Fastest") elif perfSetNum == 2: config.set("engine", "highpriority", False) @@ -1457,7 +1458,7 @@ def quickset(config): config.set("performance", "killfx", 0) config.set("performance", "star_score_updates", 0) config.set("performance", "cache_song_metadata", True) - Log.debug("Quickset Performance - Fast") + log.debug("Quickset Performance - Fast") elif perfSetNum == 3: config.set("engine", "highpriority", False) @@ -1481,7 +1482,7 @@ def quickset(config): config.set("performance", "killfx", 0) config.set("performance", "star_score_updates", 1) config.set("performance", "cache_song_metadata", True) - Log.debug("Quickset Performance - Quality") + log.debug("Quickset Performance - Quality") elif perfSetNum == 4: config.set("engine", "highpriority", False) @@ -1506,17 +1507,17 @@ def quickset(config): config.set("performance", "killfx", 0) config.set("performance", "star_score_updates", 1) config.set("performance", "cache_song_metadata", True) - Log.debug("Quickset Performance - Highest Quality") + log.debug("Quickset Performance - Highest Quality") else: - Log.debug("Quickset Performance - Manual") + log.debug("Quickset Performance - Manual") class GameSettingsMenu(Menu.Menu): def __init__(self, engine, gTextColor, gSelectedColor, players): self.logClassInits = Config.get("game", "log_class_inits") if self.logClassInits == 1: - Log.debug("GameSettingsMenu class init (Settings.py)...") + log.debug("GameSettingsMenu class init (Settings.py)...") Cheats = [] @@ -1546,7 +1547,7 @@ def __init__(self, engine, gTextColor, gSelectedColor, players): self.logClassInits = Config.get("game", "log_class_inits") if self.logClassInits == 1: - Log.debug("GameSettingsMenu class init (Settings.py)...") + log.debug("GameSettingsMenu class init (Settings.py)...") settings = [ VolumeConfigChoice(engine, engine.config, "audio", "guitarvol", autoApply = True), VolumeConfigChoice(engine, engine.config, "audio", "songvol", autoApply = True), diff --git a/fofix/core/Shader.py b/fofix/core/Shader.py index 326352ba7..46fb5f3ae 100644 --- a/fofix/core/Shader.py +++ b/fofix/core/Shader.py @@ -34,8 +34,9 @@ from OpenGL.GL.ARB.multitexture import * from OpenGL.GL.EXT.texture3D import * +from fretwork import log + from fofix.core.constants import isTrue -from fofix.core import Log from fofix.core import Config from fofix.core import Version @@ -72,7 +73,7 @@ def make(self, fname, name = ""): name = fname fullname = os.path.join(self.workdir, fname) vertname, fragname = fullname+".vert", fullname+".frag" - Log.debug('Compiling shader "%s" from %s and %s.' % (name, vertname, fragname)) + log.debug('Compiling shader "%s" from %s and %s.' % (name, vertname, fragname)) program = self.compile(open(vertname), open(fragname)) sArray = {"program": program, "name": name, "textures": []} self.getVars(vertname, program, sArray) @@ -389,7 +390,7 @@ def loadTex3D(self, fname, type = GL_RED): noise = open(file).read() size = int(len(noise)**(1/3.0)) else: - Log.debug("Can't load %s; generating random 3D noise instead." % file) + log.debug("Can't load %s; generating random 3D noise instead." % file) return self.makeNoise3D(16) @@ -410,7 +411,7 @@ def loadTex2D(self, fname, type = GL_RGB): img = pygame.image.load(file) noise = pygame.image.tostring(img, "RGB") else: - Log.debug("Can't load %s; generating random 2D noise instead." % fname) + log.debug("Can't load %s; generating random 2D noise instead." % fname) return self.makeNoise2D(16) texture = 0 @@ -511,20 +512,20 @@ def set(self, dir): #stump: check whether all needed extensions are actually supported if not glInitShaderObjectsARB(): - Log.warn('OpenGL extension ARB_shader_objects not supported - shaders disabled') + 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') + 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') + 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') + 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') + log.warn('OpenGL extension EXT_texture3D not supported - shaders disabled') return self.workdir = dir @@ -534,7 +535,7 @@ def set(self, dir): self.noise3D = self.loadTex3D("noise3d.dds") self.outline = self.loadTex2D("outline.tga") except: - Log.error('Could not load shader textures - shaders disabled: ') + log.error('Could not load shader textures - shaders disabled: ') return self.multiTex = (GL_TEXTURE0_ARB,GL_TEXTURE1_ARB,GL_TEXTURE2_ARB,GL_TEXTURE3_ARB) @@ -546,7 +547,7 @@ def set(self, dir): try: self.make("lightning","stage") except: - Log.error("Error compiling lightning shader: ") + log.error("Error compiling lightning shader: ") else: self.enable("stage") self.setVar("ambientGlowHeightScale",6.0) @@ -566,7 +567,7 @@ def set(self, dir): try: self.make("lightning","sololight") except: - Log.error("Error compiling lightning shader: ") + log.error("Error compiling lightning shader: ") else: self.enable("sololight") self.setVar("scalexy",(5.0,1.0)) @@ -588,7 +589,7 @@ def set(self, dir): try: self.make("lightning","tail") except: - Log.error("Error compiling lightning shader: ") + log.error("Error compiling lightning shader: ") else: self.enable("tail") self.setVar("scalexy",(5.0,1.0)) @@ -611,7 +612,7 @@ def set(self, dir): try: self.make("rockbandtail","tail2") except: - Log.error("Error compiling rockbandtail shader: ") + log.error("Error compiling rockbandtail shader: ") else: self.enable("tail2") self.setVar("height",0.2) @@ -624,7 +625,7 @@ def set(self, dir): try: self.make("metal","notes") except: - Log.error("Error compiling metal shader: ") + log.error("Error compiling metal shader: ") else: self.enable("notes") self.disable() @@ -632,12 +633,12 @@ def set(self, dir): try: self.make("neck","neck") except: - Log.error("Error compiling neck shader: ") + log.error("Error compiling neck shader: ") try: self.make("cd","cd") except: - Log.error("Error compiling cd shader: ") + log.error("Error compiling cd shader: ") def mixColors(c1,c2,blend=0.5): c1 = list(c1) diff --git a/fofix/core/Task.py b/fofix/core/Task.py deleted file mode 100644 index a755b3951..000000000 --- a/fofix/core/Task.py +++ /dev/null @@ -1,112 +0,0 @@ -##################################################################### -# -*- coding: iso-8859-1 -*- # -# # -# Frets on Fire # -# Copyright (C) 2006 Sami Kyöstilä # -# 2013 FoFiX Team # -# # -# This program is free software; you can redistribute it and/or # -# modify it under the terms of the GNU General Public License # -# as published by the Free Software Foundation; either version 2 # -# of the License, or (at your option) any later version. # -# # -# This program is distributed in the hope that it will be useful, # -# but WITHOUT ANY WARRANTY; without even the implied warranty of # -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # -# GNU General Public License for more details. # -# # -# You should have received a copy of the GNU General Public License # -# along with this program; if not, write to the Free Software # -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # -# MA 02110-1301, USA. # -##################################################################### - -class Task(object): - def __init__(self): - pass - - def started(self): - pass - - def stopped(self): - pass - - def run(self, ticks): - pass - -class TaskEngine(object): - def __init__(self, engine): - - self.engine = engine - - # self.tasks contains a list of dictionaries. - # each contain: task instance, synced or not, and paused or not - self.tasks = [] - self.currentTask = None - - - def checkTask(self, task): - ''' Check if a task exists ''' - - for taskData in self.tasks: - if taskData['task'] is task: - return True - - return False - - def addTask(self, task, synced = True): - ''' Add a task ''' - - if not self.checkTask(task): - self.tasks.append({'task': task, 'synced': synced, 'paused': False}) - task.started() - - def removeTask(self, task): - ''' Remove a task ''' - - for taskData in self.tasks: - if taskData['task'] is task: - self.tasks.remove(taskData) - task.stopped() - break - - def pauseTask(self, task): - ''' Pause a task ''' - - for taskData in self.tasks: - if taskData['task'] is task: - taskData['paused'] = True - break - - def resumeTask(self, task): - ''' Resume a paused task ''' - - for taskData in self.tasks: - if taskData['task'] is task: - taskData['paused'] = False - break - - def runTask(self, task, tick=0): - self.currentTask = task - task.run(tick) - self.currentTask = None - - def run(self): - ''' Run one cycle of the task scheduler engine.''' - if not self.tasks: - return False - - # Synced tasks - for taskData in self.tasks: - if taskData['paused'] or not taskData['synced']: - continue - - self.runTask(taskData['task'], tick=self.engine.tickDelta) - - # Unsynced tasks - for taskData in self.tasks: - if taskData['paused']or taskData['synced']: - continue - - self.runTask(taskData['task']) - return True diff --git a/fofix/core/Texture.py b/fofix/core/Texture.py index fdd261b3e..8e3563c3b 100644 --- a/fofix/core/Texture.py +++ b/fofix/core/Texture.py @@ -27,7 +27,7 @@ from OpenGL.GL import * from OpenGL.GLU import * -from fofix.core import Log +from fretwork import log class TextureException(Exception): @@ -51,7 +51,7 @@ def __init__(self, name = None, target = GL_TEXTURE_2D, useMipmaps = True): except IndexError: pass except Exception as e: #MFH - to catch "did you call glewInit?" crashes - Log.error("Texture.py texture deletion exception: %s" % e) + log.error("Texture.py texture deletion exception: %s" % e) self.texture = glGenTextures(1) self.texEnv = GL_MODULATE @@ -85,7 +85,7 @@ def loadImage(self, image): else: try: image = image.convert('RGB') - Log.warn("Unsupported image mode '%s' converted to 'RGB'. May have unexpected results." % image.mode) + 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: diff --git a/fofix/core/Theme.py b/fofix/core/Theme.py index 6515e1e4a..d5e967aa1 100644 --- a/fofix/core/Theme.py +++ b/fofix/core/Theme.py @@ -32,13 +32,14 @@ from OpenGL.GL import * from OpenGL.GLU import * -from fofix.core import Log +from fretwork import log +from fretwork.task import Task + from fofix.core import Version from fofix.core import Config from fofix.core.Language import _ from fofix.core.Shader import shaders from fofix.core.Image import drawImage -from fofix.core.Task import Task from fofix.core.constants import * #Theme Constants. @@ -55,19 +56,19 @@ def halign(value, default='center'): 'center': CENTER, 'right': RIGHT}[value.lower()] except KeyError: - Log.warn('Invalid horizontal alignment value - defaulting to %s' % default) + log.warn('Invalid horizontal alignment value - defaulting to %s' % default) return halign(default) def valign(value, default='middle'): try: if value.lower() == 'center': - Log.notice('Use of "center" for vertical alignment is deprecated. Use "middle" instead.') + log.notice('Use of "center" for vertical alignment is deprecated. Use "middle" instead.') return {'top': TOP, 'middle': MIDDLE, # for consistency with HTML/CSS terminology 'center': MIDDLE, # for temporary backward compatibility 'bottom': BOTTOM}[value.lower()] except KeyError: - Log.warn('Invalid vertical alignment value - defaulting to %s' % default) + log.warn('Invalid vertical alignment value - defaulting to %s' % default) return valign(default) @@ -104,16 +105,16 @@ class Theme(Task): def __getattr__(self, attr): try: #getting to this function is kinda slow. Set it on the first get to keep renders from lagging. object.__getattribute__(self, '__dict__')[attr] = defaultDict[attr] - Log.debug("No theme variable for %s - Loading default..." % attr) + log.debug("No theme variable for %s - Loading default..." % attr) return object.__getattribute__(self, attr) except KeyError: if attr in classNames.keys(): - Log.warn("No theme class for %s - Loading default..." % attr) + log.warn("No theme class for %s - Loading default..." % attr) object.__getattribute__(self, '__dict__')[attr] = classNames[attr](self) return object.__getattribute__(self, attr) elif attr.startswith('__') and attr.endswith('__'): #for object's attributes (eg: __hash__, __eq__) return object.__getattribute__(self, attr) - Log.error("Attempted to load theme variable %s - no default found." % attr) + log.error("Attempted to load theme variable %s - no default found." % attr) def __init__(self, path, name): self.name = name @@ -121,21 +122,21 @@ def __init__(self, path, name): self.themePath = os.path.join(Version.dataPath(),"themes", name) if not os.path.exists(self.themePath): - Log.warn("Theme: %s does not exist!\n" % self.themePath) + log.warn("Theme: %s does not exist!\n" % self.themePath) name = Config.get("coffee", "themename") - Log.notice("Theme: Attempting fallback to default theme \"%s\"." % name) + log.notice("Theme: Attempting fallback to default theme \"%s\"." % name) self.themePath = os.path.join(Version.dataPath(),"themes", name) if not os.path.exists(self.themePath): - Log.error("Theme: %s does not exist!\nExiting.\n" % self.themePath) + log.error("Theme: %s does not exist!\nExiting.\n" % self.themePath) sys.exit(1) if os.path.exists(os.path.join(self.themePath, "theme.ini")): self.config = Config.MyConfigParser() self.config.read(os.path.join(self.themePath, "theme.ini")) - Log.debug("theme.ini loaded") + log.debug("theme.ini loaded") else: self.config = None - Log.debug("no theme.ini") + log.debug("no theme.ini") def get(value, type = str, default = None): if self.config: diff --git a/fofix/core/Unicode.py b/fofix/core/Unicode.py deleted file mode 100644 index 8b6d515bd..000000000 --- a/fofix/core/Unicode.py +++ /dev/null @@ -1,56 +0,0 @@ -##################################################################### -# Frets on Fire X (FoFiX) # -# Copyright (C) 2012 FoFiX Team # -# # -# This program is free software; you can redistribute it and/or # -# modify it under the terms of the GNU General Public License # -# as published by the Free Software Foundation; either version 2 # -# of the License, or (at your option) any later version. # -# # -# This program is distributed in the hope that it will be useful, # -# but WITHOUT ANY WARRANTY; without even the implied warranty of # -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # -# GNU General Public License for more details. # -# # -# You should have received a copy of the GNU General Public License # -# along with this program; if not, write to the Free Software # -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # -# MA 02110-1301, USA. # -##################################################################### - -''' -Miscellaneous functions for helping us handle Unicode correctly in -the face of what we've done in the past. -''' - -def unicodify(s): - ''' - Turns s into a Unicode string, interpreting it as UTF-8 if it is - valid UTF-8, or as ISO-8859-1 if it is not. Returns s itself if - it is already a Unicode string. - @param s: input - @return: Unicode version of s - ''' - if isinstance(s, unicode): - return s - - if not isinstance(s, basestring): - try: - return unicode(s) - except UnicodeDecodeError: - s = str(s) - - try: - return s.decode('utf-8') - except UnicodeDecodeError: - # Nothing is invalid ISO-8859-1, so this can't fail. - return s.decode('iso-8859-1') - - -def utf8(s): - ''' - Turns s into a valid UTF-8 bytestring. - @param s: input - @return: UTF-8-encoded version of s - ''' - return unicodify(s).encode('utf-8') diff --git a/fofix/core/Video.py b/fofix/core/Video.py index 41e186fda..f34991cd1 100644 --- a/fofix/core/Video.py +++ b/fofix/core/Video.py @@ -28,7 +28,8 @@ from OpenGL.GL import * from OpenGL.GL.ARB.multisample import * -from fofix.core import Log +from fretwork import log + from fofix.core.Language import _ class Video: @@ -145,11 +146,11 @@ def setMode(self, resolution, fullscreen = False, flags = pygame.OPENGL | pygame return bool(self.screen) def screenError(self): - Log.error("Video setup failed. Make sure your graphics card supports 32-bit display modes.") + log.error("Video setup failed. Make sure your graphics card supports 32-bit display modes.") raise def resolutionReset(self): - Log.warn("Video setup failed. Trying default windowed resolution.") + 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 @@ -164,7 +165,7 @@ def resolutionReset(self): self.screenError() def multisampleReset(self, resolution): - Log.warn("Video setup failed. Trying without antialiasing.") + 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 @@ -196,7 +197,7 @@ def disableScreensaver(self): import win32con import atexit - Log.debug('Disabling screensaver.') + log.debug('Disabling screensaver.') old_lowpowertimeout = win32gui.SystemParametersInfo(win32con.SPI_GETLOWPOWERTIMEOUT) if old_lowpowertimeout != 0: @@ -214,4 +215,4 @@ def disableScreensaver(self): win32gui.SystemParametersInfo(win32con.SPI_SETSCREENSAVETIMEOUT, 0) else: - Log.debug('Screensaver disabling is not implemented on this platform.') + log.debug('Screensaver disabling is not implemented on this platform.') diff --git a/fofix/core/View.py b/fofix/core/View.py index df48cef3c..0ed1fe2af 100644 --- a/fofix/core/View.py +++ b/fofix/core/View.py @@ -28,8 +28,8 @@ import numpy as np -from fofix.core.Task import Task -from fofix.core import Log +from fretwork import log +from fretwork.task import Task class Layer(Task): @@ -135,7 +135,7 @@ def setNormalizedGeometry(self): self.geometryNormalized[3] = h / w def pushLayer(self, layer): - Log.debug("View: Push: %s" % layer.__class__.__name__) + log.debug("View: Push: %s" % layer.__class__.__name__) if layer not in self.layers: self.layers.append(layer) @@ -153,7 +153,7 @@ def topLayer(self): return layer def popLayer(self, layer): - Log.debug("View: Pop: %s" % layer.__class__.__name__) + log.debug("View: Pop: %s" % layer.__class__.__name__) if layer in self.incoming: self.incoming.remove(layer) @@ -161,7 +161,7 @@ def popLayer(self, layer): self.outgoing.append(layer) def popAllLayers(self): - Log.debug("View: Pop all") + log.debug("View: Pop all") [self.popLayer(l) for l in list(self.layers)] def isTransitionInProgress(self): diff --git a/fofix/game/Credits.py b/fofix/game/Credits.py index 7a7526441..62cd5d762 100644 --- a/fofix/game/Credits.py +++ b/fofix/game/Credits.py @@ -30,6 +30,8 @@ from OpenGL.GL import OpenGL, glColor4f, glTranslatef +from fretwork import log + from fofix.core.VideoPlayer import VideoLayer, VideoPlayerError from fofix.core.Input import KeyListener from fofix.core.Image import drawImage @@ -39,7 +41,6 @@ from fofix.core import Version from fofix.core import Player from fofix.core import Config -from fofix.core import Log @@ -175,7 +176,7 @@ def __init__(self, engine, songName = None): try: self.vidPlayer = VideoLayer(self.engine, vidSource, mute = True, loop = True) except (IOError, VideoPlayerError): - Log.error('Error loading credits video:') + log.error('Error loading credits video:') else: self.vidPlayer.play() self.engine.view.pushLayer(self.vidPlayer) @@ -255,7 +256,7 @@ def parseText(self, filename): scale = float(line.strip("!")) continue except ValueError: - Log.warn("CREDITS file does not parse properly") + log.warn("CREDITS file does not parse properly") if line == "": self.credits.append(space) elif line.startswith("`") and line.endswith("`"): diff --git a/fofix/game/Debug.py b/fofix/game/Debug.py index 2a12c056f..d208c9d7d 100644 --- a/fofix/game/Debug.py +++ b/fofix/game/Debug.py @@ -29,8 +29,9 @@ from OpenGL.GL import glColor3f +from fretwork import log + from fofix.core.View import Layer -from fofix.core import Log @@ -114,7 +115,7 @@ def gcDump(self): before = len(gc.get_objects()) coll = gc.collect() after = len(gc.get_objects()) - Log.debug("%d GC objects collected, total %d -> %d." % (coll, before, after)) + log.debug("%d GC objects collected, total %d -> %d." % (coll, before, after)) fn = "gcdump.txt" f = open(fn, "w") n = 0 @@ -126,4 +127,4 @@ def gcDump(self): except: pass f.close() - Log.debug("Wrote a dump of %d GC garbage objects to %s." % (n, fn)) + log.debug("Wrote a dump of %d GC garbage objects to %s." % (n, fn)) diff --git a/fofix/game/Dialogs.py b/fofix/game/Dialogs.py index 939f3e2cb..07371e22d 100644 --- a/fofix/game/Dialogs.py +++ b/fofix/game/Dialogs.py @@ -37,16 +37,17 @@ import pygame from OpenGL.GL import * +from fretwork import log +from fretwork.unicode import unicodify + from fofix.core.View import Layer, BackgroundLayer from fofix.core.Input import KeyListener -from fofix.core.Unicode import unicodify from fofix.core.Image import drawImage from fofix.game.Credits import Credits from fofix.core.constants import * from fofix.core.Language import _ from fofix.game.Menu import Menu from fofix.core import Microphone -from fofix.core import Log from fofix.core import Player from fofix.core import Config @@ -157,7 +158,7 @@ def __init__(self, engine, prompt = "", text = ""): self.logClassInits = self.engine.config.get("game", "log_class_inits") if self.logClassInits == 1: - Log.debug("GetText class init (Dialogs.py)...") + log.debug("GetText class init (Dialogs.py)...") self.sfxVolume = self.engine.config.get("audio", "SFX_volume") @@ -292,7 +293,7 @@ def __init__(self, engine, prompt = "", key = None, noKey = False, specialKeyLis self.logClassInits = self.engine.config.get("game", "log_class_inits") if self.logClassInits == 1: - Log.debug("GetKey class init (Dialogs.py)...") + log.debug("GetKey class init (Dialogs.py)...") def shown(self): self.engine.input.addKeyListener(self, priority = True) @@ -358,7 +359,7 @@ def __init__(self, engine, condition, text, allowCancel = False): self.logClassInits = self.engine.config.get("game", "log_class_inits") if self.logClassInits == 1: - Log.debug("LoadingScreen class init (Dialogs.py)...") + log.debug("LoadingScreen class init (Dialogs.py)...") self.loadingx = self.engine.theme.loadingX self.loadingy = self.engine.theme.loadingY @@ -437,7 +438,7 @@ def __init__(self, engine, text, prompt = _("")): self.logClassInits = self.engine.config.get("game", "log_class_inits") if self.logClassInits == 1: - Log.debug("MessageScreen class init (Dialogs.py)...") + log.debug("MessageScreen class init (Dialogs.py)...") def shown(self): @@ -491,7 +492,7 @@ def __init__(self, engine, masks, path, prompt = "", dirSelect = False): self.logClassInits = self.engine.config.get("game", "log_class_inits") if self.logClassInits == 1: - Log.debug("FileChooser class init (Dialogs.py)...") + log.debug("FileChooser class init (Dialogs.py)...") self.dirSelect = dirSelect @@ -644,7 +645,7 @@ def __init__(self, engine, selected = None, prompt = _("Yellow (#3) / Blue (#4) self.logClassInits = self.engine.config.get("game", "log_class_inits") if self.logClassInits == 1: - Log.debug("%s NeckChooser class init (Dialogs.py)..." % (self.player)) + log.debug("%s NeckChooser class init (Dialogs.py)..." % (self.player)) splash = showLoadingSplashScreen(self.engine, _("Loading necks...")) @@ -897,7 +898,7 @@ def __init__(self, engine): self.logClassInits = self.engine.config.get("game", "log_class_inits") if self.logClassInits == 1: - Log.debug("AvatarChooser class init (Dialogs.py)...") + log.debug("AvatarChooser class init (Dialogs.py)...") splash = showLoadingSplashScreen(self.engine, _("Loading avatars...")) @@ -956,7 +957,7 @@ def __init__(self, engine): self.avatars.append(image) self.maxAv += 1 - Log.debug("%d Theme Avatars found; %d total." % (self.themeAvs, len(self.avatars))) + log.debug("%d Theme Avatars found; %d total." % (self.themeAvs, len(self.avatars))) self.avScale = [] for avatar in self.avatars: imgheight = avatar.height1() @@ -1164,7 +1165,7 @@ def __init__(self, engine, parts, info, players, back = False): self.logClassInits = self.engine.config.get("game", "log_class_inits") if self.logClassInits == 1: - Log.debug("PartDiffChooser class init (Dialogs.py)...") + log.debug("PartDiffChooser class init (Dialogs.py)...") self.time = 0.0 self.yes = [] @@ -1346,7 +1347,7 @@ def __init__(self, engine, items, selected = None, prompt = "", pos = None): self.logClassInits = self.engine.config.get("game", "log_class_inits") if self.logClassInits == 1: - Log.debug("ItemChooser class init (Dialogs.py)...") + log.debug("ItemChooser class init (Dialogs.py)...") self.accepted = False self.selectedItem = None @@ -1427,7 +1428,7 @@ def __init__(self, engine, control, prompt = ""): self.logClassInits = self.engine.config.get("game", "log_class_inits") if self.logClassInits == 1: - Log.debug("KeyTester class init (Dialogs.py)...") + log.debug("KeyTester class init (Dialogs.py)...") self.accepted = False @@ -1992,7 +1993,7 @@ def showMessage(engine, text): @param engine: Game engine @param text: Message text """ - Log.notice("%s" % text) + log.notice("%s" % text) d = MessageScreen(engine, text) _runDialog(engine, d) @@ -2014,7 +2015,7 @@ def __init__(self, engine, text): self.logClassInits = self.engine.config.get("game", "log_class_inits") if self.logClassInits == 1: - Log.debug("LoadingSplashScreen class init (Dialogs.py)...") + log.debug("LoadingSplashScreen class init (Dialogs.py)...") #Get theme self.theme = self.engine.data.theme diff --git a/fofix/game/GameResultsScene.py b/fofix/game/GameResultsScene.py index ee1931772..af38840ed 100644 --- a/fofix/game/GameResultsScene.py +++ b/fofix/game/GameResultsScene.py @@ -39,16 +39,18 @@ from OpenGL.GL import * +from fretwork import log +from fretwork.audio import Sound + from fofix.core.Image import drawImage from fofix.core.Scene import Scene -from fofix.core.Audio import Sound + from fofix.core.constants import * from fofix.core.Language import _ from fofix.game.Menu import Menu from fofix.game import Scorekeeper from fofix.game import Dialogs from fofix.game import Song -from fofix.core import Log from fofix.core import VFS @@ -61,7 +63,7 @@ def __init__(self, engine, libraryName, songName, scores = None, coOpType = Fals self.logClassInits = self.engine.config.get("game", "log_class_inits") if self.logClassInits == 1: - Log.debug("GameResultsScene class init...") + log.debug("GameResultsScene class init...") players = self.players if coOpType > 0: @@ -200,7 +202,7 @@ def __init__(self, engine, libraryName, songName, scores = None, coOpType = Fals self.cheerLoopDelay = self.engine.theme.crowdLoopDelay if self.cheerLoopDelay == None: self.cheerLoopDelay = self.engine.config.get("game", "cheer_loop_delay") - Log.debug("Cheer loop delay used: %d" % self.cheerLoopDelay) + log.debug("Cheer loop delay used: %d" % self.cheerLoopDelay) self.cheerLoopCounter = self.cheerLoopDelay @@ -544,10 +546,10 @@ def uploadHighscores(self, part = Song.parts[Song.GUITAR_PART], playerNum = 0, s d["scores_ext"] = binascii.hexlify(cerealizer.dumps(scores_ext)) url = self.engine.config.get("network", "uploadurl_w67_starpower") data = urllib.urlopen(url + "?" + urllib.urlencode(d)).read() - Log.debug("Score upload result: %s" % data) + log.debug("Score upload result: %s" % data) return data #MFH - want to return the actual result data. except Exception, e: - Log.error("Score upload error: %s" % e) + log.error("Score upload error: %s" % e) return False return True @@ -711,7 +713,7 @@ def run(self, ticks): count = 0 count += 1 if self.careerMode and not self.song.info.completed and self.scoring[0].stars >= self.careerStars: - Log.debug("Song completed") + log.debug("Song completed") self.song.info.completed = True self.song.info.count = "%d" % count self.song.info.save() @@ -1248,7 +1250,7 @@ def renderHighScores(self, visibility, topMost): try: notesHit, notesTotal, noteStreak, modVersion, handicap, handicapLong, originalScore = scoreExt except ValueError: - Log.warn("Old highscores found.") + log.warn("Old highscores found.") notesHit, notesTotal, noteStreak, modVersion, oldScores1, oldScores2 = scoreExt for j,player in enumerate(self.playerList): if (self.time % 10.0) < 5.0 and i == self.highscoreIndex[j] and self.scoreDifficulty == player.difficulty and self.scorePart == player.part: diff --git a/fofix/game/MainMenu.py b/fofix/game/MainMenu.py index a24738de9..46b91cee1 100644 --- a/fofix/game/MainMenu.py +++ b/fofix/game/MainMenu.py @@ -29,6 +29,9 @@ import sys import os +from fretwork import log +from fretwork.audio import Music + from fofix.core.View import BackgroundLayer from fofix.core.Image import drawImage from fofix.core.Shader import shaders @@ -38,11 +41,9 @@ from fofix.game.Menu import Menu from fofix.core import Config from fofix.game import Dialogs -from fofix.core import Audio from fofix.core import Settings from fofix.core import Version from fofix.core import VFS -from fofix.core import Log class MainMenu(BackgroundLayer): @@ -51,7 +52,7 @@ def __init__(self, engine): self.logClassInits = Config.get("game", "log_class_inits") if self.logClassInits == 1: - Log.debug("MainMenu class init (MainMenu.py)...") + log.debug("MainMenu class init (MainMenu.py)...") self.time = 0.0 self.nextLayer = None @@ -75,17 +76,17 @@ def __init__(self, engine): 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.") + 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.") + 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!") + 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 @@ -137,7 +138,7 @@ def __init__(self, engine): self.menumusic = True engine.menuMusic = True - self.song = Audio.Music(self.engine.resource.fileName(sound)) + self.song = Music(self.engine.resource.fileName(sound)) self.song.setVolume(self.engine.config.get("audio", "menu_volume")) self.song.play(0) #no loop else: @@ -261,7 +262,7 @@ def runMusic(self): self.menumusic = True self.engine.menuMusic = True - self.song = Audio.Music(self.engine.resource.fileName(sound)) + self.song = Music(self.engine.resource.fileName(sound)) self.song.setVolume(self.engine.config.get("audio", "menu_volume")) self.song.play(0) else: @@ -298,7 +299,7 @@ def showTutorial(self): # evilynux - Make sure tutorial exists before launching tutorialpath = self.engine.tutorialFolder if not os.path.isdir(self.engine.resource.fileName(tutorialpath)): - Log.debug("No folder found: %s" % tutorialpath) + log.debug("No folder found: %s" % tutorialpath) Dialogs.showMessage(self.engine, _("No tutorials found!")) return diff --git a/fofix/game/Menu.py b/fofix/game/Menu.py index 6896e1424..2fb255f26 100644 --- a/fofix/game/Menu.py +++ b/fofix/game/Menu.py @@ -30,12 +30,13 @@ from OpenGL.GL import * import pygame +from fretwork import log + from fofix.core.Input import KeyListener from fofix.core.Image import drawImage from fofix.core.View import Layer from fofix.core import Player from fofix.core import Data -from fofix.core import Log class Choice: def __init__(self, text, callback, name = None, values = None, valueIndex = 0, append_submenu_char = True, tipText = None): @@ -96,7 +97,7 @@ def __init__(self, engine, choices, name = None, onClose = None, onCancel = None self.logClassInits = self.engine.config.get("game", "log_class_inits") if self.logClassInits == 1: - Log.debug("Menu class init (Menu.py)...") + log.debug("Menu class init (Menu.py)...") #Get theme self.themename = self.engine.data.themeLabel @@ -158,9 +159,9 @@ def __init__(self, engine, choices, name = None, onClose = None, onCancel = None self.vSpace = float(self.vSpace) else: self.vSpace = .08 - Log.debug("Graphic menu enabled for submenu: %s" % self.name) + 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) + 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 diff --git a/fofix/game/Scorekeeper.py b/fofix/game/Scorekeeper.py index e835f31d7..dc958e7b7 100644 --- a/fofix/game/Scorekeeper.py +++ b/fofix/game/Scorekeeper.py @@ -29,9 +29,10 @@ # MA 02110-1301, USA. # ##################################################################### +from fretwork import log + from fofix.core.Language import _ from fofix.game import Song -from fofix.core import Log from fofix.core import Config HANDICAPS = [.75, 1.0, .8, .9, .75, .8, 1.05, 1.1, 1.03, 1.02, 1.01, .95, .9, .85, .7, .95, 0.0, .5, .7, .7] @@ -49,7 +50,7 @@ def __init__(self, instrument, coOpType = False): self.coOpType = coOpType logClassInits = Config.get("game", "log_class_inits") if logClassInits == 1: - Log.debug("ScoreCard class init...") + log.debug("ScoreCard class init...") self.starScoring = Config.get("game", "star_scoring") self.updateOnScore = Config.get("performance", "star_score_updates") self.avMult = 0.0 diff --git a/fofix/game/Song.py b/fofix/game/Song.py index a836569db..b0e92b47e 100644 --- a/fofix/game/Song.py +++ b/fofix/game/Song.py @@ -33,13 +33,14 @@ import binascii import cerealizer +from fretwork import log +from fretwork.audio import StreamingSound +from fretwork.unicode import utf8 + from fofix.core.Theme import hexToColor, colorToHex -from fofix.core.Unicode import utf8 from fofix.core.Language import _ from fofix.core.Theme import * from fofix.core import midi -from fofix.core import Log -from fofix.core import Audio from fofix.core import Config from fofix.core import Version from fofix.core import VFS @@ -172,7 +173,7 @@ def __repr__(self): try: _dbversion = _songDB.execute("SELECT `value` FROM `config` WHERE `key` = 'version'").fetchone()[0] if int(_dbversion) == 6: - Log.debug('Upgrading song cache schema version 6 to 7.') + log.debug('Upgrading song cache schema version 6 to 7.') _songDB.execute('ALTER TABLE `songinfo` ADD `seen` INT') _songDB.execute('UPDATE `songinfo` SET `seen` = 0') _songDB.execute("UPDATE `config` SET `value` = '7' WHERE `key` = 'version'") @@ -182,7 +183,7 @@ def __repr__(self): # able to upgrade starting at *any* schema version we support # upgrading from, like so.) #if _dbversion == 7: - # Log.debug('Upgrading song cache schema version 7 to 8.') + # log.debug('Upgrading song cache schema version 7 to 8.') # _songDB.execute(sql needed to do the update) # _songDB.commit() # _dbversion = 8 @@ -190,11 +191,11 @@ def __repr__(self): _mustReinitialize = False else: _mustReinitialize = True - Log.debug('Song cache has incompatible schema version; forcing reinitialization.') + log.debug('Song cache has incompatible schema version; forcing reinitialization.') except: _mustReinitialize = True if _mustReinitialize: - Log.debug('Initializing song cache.') + log.debug('Initializing song cache.') # Clean out the database, then make our tables. for tbl in _songDB.execute("SELECT `name` FROM `sqlite_master` WHERE `type` = 'table'").fetchall(): _songDB.execute('DROP TABLE `%s`' % tbl) @@ -231,7 +232,7 @@ def __init__(self, infoFileName, songLibrary = DEFAULT_LIBRARY): self.logClassInits = Config.get("game", "log_class_inits") if self.logClassInits == 1: - Log.debug("SongInfo class init (song.py): " + self.name) + log.debug("SongInfo class init (song.py): " + self.name) self.logSections = Config.get("game", "log_sections") @@ -242,15 +243,15 @@ def __init__(self, infoFileName, songLibrary = DEFAULT_LIBRARY): if os.path.isfile(os.path.join(os.path.dirname(self.fileName), "notes-unedited.mid")): notefile = "notes-unedited.mid" if self.logUneditedMidis == 1: - Log.debug("notes-unedited.mid found, using instead of notes.mid! - " + self.name) + log.debug("notes-unedited.mid found, using instead of notes.mid! - " + self.name) else: notefile = "notes.mid" if self.logUneditedMidis == 1: - Log.debug("notes-unedited.mid not found, using notes.mid - " + self.name) + log.debug("notes-unedited.mid not found, using notes.mid - " + self.name) else: notefile = "notes.mid" if self.logUneditedMidis == 1: - Log.debug("notes-unedited.mid not found, using notes.mid - " + self.name) + log.debug("notes-unedited.mid not found, using notes.mid - " + self.name) self.noteFileName = os.path.join(os.path.dirname(self.fileName), notefile) for part in parts.values(): @@ -262,21 +263,21 @@ def __init__(self, infoFileName, songLibrary = DEFAULT_LIBRARY): try: #MFH - it crashes here on previews! result = _songDB.execute('SELECT `info` FROM `songinfo` WHERE `hash` = ?', [songhash]).fetchone() if result is None: - Log.debug('Song %s was not found in the cache.' % infoFileName) + log.debug('Song %s was not found in the cache.' % infoFileName) except Exception: - Log.error('Cache retrieval failed for %s: ' % infoFileName) + log.error('Cache retrieval failed for %s: ' % infoFileName) result = None if result is not None: try: self.__dict__.update(cPickle.loads(str(result[0]))) _songDB.execute('UPDATE `songinfo` SET `seen` = 1 WHERE `hash` = ?', [songhash]) - Log.debug('Song %s successfully loaded from cache.' % infoFileName) + log.debug('Song %s successfully loaded from cache.' % infoFileName) return except: # The entry is there but could not be loaded. # Nuke it and let it be rebuilt. - Log.error('Song %s has invalid cache data (will rebuild): ' % infoFileName) + log.error('Song %s has invalid cache data (will rebuild): ' % infoFileName) _songDB.execute('DELETE FROM `songinfo` WHERE `hash` = ?', [songhash]) #stump: preload this stuff... @@ -284,7 +285,7 @@ def __init__(self, infoFileName, songLibrary = DEFAULT_LIBRARY): self.getSections() #stump: Write this song's info into the cache. - Log.debug('Writing out cache for song %s.' % self.fileName) + log.debug('Writing out cache for song %s.' % self.fileName) pdict = {} for key in ('_parts', '_partDifficulties', '_midiStyle', '_sections'): pdict[key] = getattr(self, key) @@ -349,7 +350,7 @@ def getScores(self, part): else: self.addHighscore(difficulty, score, stars, name, part) else: - Log.warn("Weak hack attempt detected. Better luck next time.") + log.warn("Weak hack attempt detected. Better luck next time.") def _set(self, attr, value): if not self.info.has_section("song"): @@ -429,18 +430,18 @@ def getParts(self): # See which parts are available try: noteFileName = self.noteFileName - Log.debug("Retrieving parts from: " + noteFileName) + log.debug("Retrieving parts from: " + noteFileName) info = MidiPartsDiffReader() midiIn = midi.MidiInFile(info, noteFileName) midiIn.read() if info.parts == []: - Log.debug("Improperly named tracks. Attempting to force first track guitar.") + log.debug("Improperly named tracks. Attempting to force first track guitar.") info = MidiPartsDiffReader(forceGuitar = True) midiIn = midi.MidiInFile(info, noteFileName) midiIn.read() if info.parts == []: - Log.warn("No tracks found!") + log.warn("No tracks found!") raise Exception self._midiStyle = info.midiStyle info.parts.sort(lambda b, a: cmp(b.id, a.id)) @@ -452,7 +453,7 @@ def getParts(self): info.difficulties[part.id].sort(lambda a, b: cmp(a.id, b.id)) self._partDifficulties[part.id] = info.difficulties[part.id] except: - Log.warn("Note file not parsed correctly. Selected part and/or difficulty may not be available.") + log.warn("Note file not parsed correctly. Selected part and/or difficulty may not be available.") self._parts = parts.values() for part in self._parts: self._partDifficulties[part.id] = difficulties.values() @@ -587,10 +588,10 @@ def uploadHighscores(self, url, songHash, part = parts[GUITAR_PART]): "songPart": part } data = urllib.urlopen(url + "?" + urllib.urlencode(d)).read() - Log.debug("Score upload result: %s" % data) + log.debug("Score upload result: %s" % data) return data #MFH - want to return the actual result data. except Exception as e: - Log.error("Score upload error: %s" % e) + log.error("Score upload error: %s" % e) return False return True @@ -615,7 +616,7 @@ def getSections(self): #MFH # See which sections are available try: noteFileName = self.noteFileName - Log.debug("Retrieving sections from: " + noteFileName) + log.debug("Retrieving sections from: " + noteFileName) info = MidiSectionReader() midiIn = midi.MidiInFile(info, noteFileName) try: @@ -628,19 +629,19 @@ def getSections(self): #MFH self._sections.insert(0,["0:00 -> Start", 0.0]) #MFH - only log if enabled - Log.warn("Song.py: Using auto-generated note count sections...") + log.warn("Song.py: Using auto-generated note count sections...") if self.logSections == 1: - Log.debug("Practice sections: " + str(self._sections)) + log.debug("Practice sections: " + str(self._sections)) else: self._sections.insert(0,["0:00 -> Start", 0.0]) #MFH - only log if enabled if self.logSections == 1: - Log.debug("Practice sections: " + str(self._sections)) + log.debug("Practice sections: " + str(self._sections)) except Exception as e: - Log.warn("Song.py: Unable to retrieve section names for practice mode selection: %s" % e) + log.warn("Song.py: Unable to retrieve section names for practice mode selection: %s" % e) self._sections = None return self._sections @@ -707,7 +708,7 @@ def __init__(self, libraryName, infoFileName): self.logClassInits = Config.get("game", "log_class_inits") if self.logClassInits == 1: - Log.debug("LibraryInfo class init (song.py)...") + log.debug("LibraryInfo class init (song.py)...") try: @@ -776,7 +777,7 @@ def __init__(self, nameToDisplay = ""): self.logClassInits = Config.get("game", "log_class_inits") if self.logClassInits == 1: - Log.debug("BlankSpaceInfo class init (song.py)...") + log.debug("BlankSpaceInfo class init (song.py)...") self.name = nameToDisplay self.color = None @@ -791,7 +792,7 @@ def __init__(self): self.logClassInits = Config.get("game", "log_class_inits") if self.logClassInits == 1: - Log.debug("CareerResetterInfo class init (song.py)...") + log.debug("CareerResetterInfo class init (song.py)...") self.name = _("Reset Career") self.color = None @@ -802,7 +803,7 @@ class RandomSongInfo(object): #MFH def __init__(self): self.logClassInits = Config.get("game", "log_class_inits") if self.logClassInits == 1: - Log.debug("RandomSongInfo class init (song.py)...") + log.debug("RandomSongInfo class init (song.py)...") self.name = _(" (Random Song)") self.color = None @@ -817,7 +818,7 @@ def __init__(self, config, section): self.logClassInits = Config.get("game", "log_class_inits") if self.logClassInits == 1: - Log.debug("TitleInfo class init (song.py)...") + log.debug("TitleInfo class init (song.py)...") self.artist = None #MFH - prevents search errors @@ -859,7 +860,7 @@ def __init__(self, nameToDisplay): self.logClassInits = Config.get("game", "log_class_inits") if self.logClassInits == 1: - Log.debug("TitleInfo class init (song.py)...") + log.debug("TitleInfo class init (song.py)...") self.name = nameToDisplay self.color = None @@ -964,7 +965,7 @@ def __init__(self, engine): if engine is not None: self.logClassInits = Config.get("game", "log_class_inits") if self.logClassInits == 1: - Log.debug("Track class init (song.py)...") + log.debug("Track class init (song.py)...") def __getitem__(self, index): return self.allEvents[index] @@ -1079,7 +1080,7 @@ def removeTempoEvents(self): if isinstance(event, Tempo): self.allEvents.remove((time, event)) if self.logTempoEvents == 1: - Log.debug("Tempo event removed from VocalTrack during cleanup: " + str(event.bpm) + "bpm") + log.debug("Tempo event removed from VocalTrack during cleanup: " + str(event.bpm) + "bpm") def markPhrases(self): phraseId = 0 @@ -1087,13 +1088,13 @@ def markPhrases(self): markStars = False if len(self.starTimes) < 2: markStars = True - Log.warn("This song does not appear to have any vocal star power events - falling back on auto-generation.") + log.warn("This song does not appear to have any vocal star power events - falling back on auto-generation.") for time, event in self.getAllEvents(): if isinstance(event, VocalPhrase): if time in self.starTimes and not markStars: event.star = True if time in phraseTimes: - Log.warn("Phrase repeated - some lyric phrase errors may occur.") + log.warn("Phrase repeated - some lyric phrase errors may occur.") phraseId += 1 continue if markStars and phraseId+1 % 7 == 0: @@ -1222,7 +1223,7 @@ def removeTempoEvents(self): if isinstance(event, Tempo): self.allEvents.remove((time, event)) if self.logTempoEvents == 1: - Log.debug("Tempo event removed from NoteTrack during cleanup: " + str(event.bpm) + "bpm") + log.debug("Tempo event removed from NoteTrack during cleanup: " + str(event.bpm) + "bpm") def flipDrums(self): for time, event in self.allEvents: @@ -1241,9 +1242,9 @@ def markHopoRF(self, eighthNH, songHopoFreq): songHopoFreq = int(songHopoFreq) except Exception: songHopoFreq = None - # Log.warn("Song.ini HOPO Frequency setting is invalid -- forcing Normal (value 1)") + # log.warn("Song.ini HOPO Frequency setting is invalid -- forcing Normal (value 1)") if self.songHopoFreq == 1 and songHopoFreq in [0, 1, 2, 3, 4, 5]: - Log.debug("markHopoRF: song-specific HOPO frequency %d forced" % songHopoFreq) + log.debug("markHopoRF: song-specific HOPO frequency %d forced" % songHopoFreq) self.hopoTick = songHopoFreq #dtb file says 170 ticks @@ -1476,7 +1477,7 @@ def markHopoGH2(self, eighthNH, HoposAfterChords, songHopoFreq): except Exception: songHopoFreq = None if self.songHopoFreq == 1 and songHopoFreq in [0, 1, 2, 3, 4, 5]: - Log.debug("markHopoGH2: song-specific HOPO frequency %d forced" % songHopoFreq) + log.debug("markHopoGH2: song-specific HOPO frequency %d forced" % songHopoFreq) self.hopoTick = songHopoFreq @@ -2013,7 +2014,7 @@ def __init__(self, engine, infoFileName, songTrackName, guitarTrackName, rhythmT self.logClassInits = self.engine.config.get("game", "log_class_inits") if self.logClassInits == 1: - Log.debug("Song class init (song.py)...") + log.debug("Song class init (song.py)...") self.info = SongInfo(infoFileName) self.tracks = [] @@ -2086,34 +2087,34 @@ def __init__(self, engine, infoFileName, songTrackName, guitarTrackName, rhythmT try: if songTrackName: - self.songTrack = Audio.StreamingSound(self.engine.audio.getChannel(0), songTrackName) + self.songTrack = StreamingSound(self.engine.audio.getChannel(0), songTrackName) except Exception as e: - Log.warn("Unable to load song track: %s" % e) + log.warn("Unable to load song track: %s" % e) try: if guitarTrackName: - self.guitarTrack = Audio.StreamingSound(self.engine.audio.getChannel(1), guitarTrackName) + self.guitarTrack = StreamingSound(self.engine.audio.getChannel(1), guitarTrackName) except Exception as e: - Log.warn("Unable to load guitar track: %s" % e) + log.warn("Unable to load guitar track: %s" % e) try: if rhythmTrackName: - self.rhythmTrack = Audio.StreamingSound(self.engine.audio.getChannel(2), rhythmTrackName) + self.rhythmTrack = StreamingSound(self.engine.audio.getChannel(2), rhythmTrackName) except Exception as e: - Log.warn("Unable to load rhythm track: %s" % e) + log.warn("Unable to load rhythm track: %s" % e) try: if drumTrackName: - self.drumTrack = Audio.StreamingSound(self.engine.audio.getChannel(3), drumTrackName) + self.drumTrack = StreamingSound(self.engine.audio.getChannel(3), drumTrackName) except Exception as e: - Log.warn("Unable to load drum track: %s" % e) + log.warn("Unable to load drum track: %s" % e) try: if crowdTrackName: - self.crowdTrack = Audio.StreamingSound(self.engine.audio.getChannel(4), crowdTrackName) + self.crowdTrack = StreamingSound(self.engine.audio.getChannel(4), crowdTrackName) except Exception as e: - Log.warn("Unable to load crowd track: %s" % e) + log.warn("Unable to load crowd track: %s" % e) #MFH - single audio track song detection self.singleTrackSong = False @@ -2121,12 +2122,12 @@ def __init__(self, engine, infoFileName, songTrackName, guitarTrackName, rhythmT if self.songTrack or self.guitarTrack or self.rhythmTrack or self.drumTrack: self.singleTrackSong = True self.missVolume = self.engine.config.get("audio", "single_track_miss_volume") #MFH - force single-track miss volume setting instead - Log.debug("Song with only a single audio track identified - single-track miss volume applied: " + str(self.missVolume)) + log.debug("Song with only a single audio track identified - single-track miss volume applied: " + str(self.missVolume)) # load the notes if noteFileName: - Log.debug("Retrieving notes from: " + noteFileName) + log.debug("Retrieving notes from: " + noteFileName) midiIn = midi.MidiInFile(MidiReader(self), noteFileName) midiIn.read() @@ -2467,7 +2468,7 @@ def __init__(self, song, scriptFile): self.logClassInits = Config.get("game", "log_class_inits") if self.logClassInits == 1: - Log.debug("ScriptReader class init (song.py)...") + log.debug("ScriptReader class init (song.py)...") def read(self): @@ -2503,7 +2504,7 @@ def __init__(self, song): self.logClassInits = Config.get("game", "log_class_inits") if self.logClassInits == 1: - Log.debug("MidiReader class init (song.py)...") + log.debug("MidiReader class init (song.py)...") self.logMarkerNotes = Config.get("game", "log_marker_notes") @@ -2594,7 +2595,7 @@ def addTempoEvent(self, event, time = None): #MFH - universal Tempo track han #add tempo events to the universal tempo track self.song.tempoEventTrack.addEvent(time, event) if self.logTempoEvents == 1: - Log.debug("Tempo event added to Tempo track: " + str(time) + " - " + str(event.bpm) + "BPM" ) + log.debug("Tempo event added to Tempo track: " + str(time) + " - " + str(event.bpm) + "BPM" ) def addSpecialMidiEvent(self, track, event, time = None): #MFH if self.partnumber == -1: @@ -2675,7 +2676,7 @@ def sequence_name(self, text): self.useVocalTrack = False if self.logSections == 1: - Log.debug(tempText + tempText2) + log.debug(tempText + tempText2) self.guitarSoloIndex = 0 self.guitarSoloActive = False @@ -2724,7 +2725,7 @@ def note_off(self, channel, note, velocity): self.addSpecialMidiEvent(diff, MarkerNote(note, endTime - startTime), time = startTime) self.addSpecialMidiEvent(diff, MarkerNote(note, 1, endMarker = True), time = endTime+1) #ending marker note if self.logMarkerNotes == 1: - Log.debug("RB Overdrive MarkerNote at %f added to part: %s and difficulty: %s" % ( startTime, self.partnumber, difficulties[diff] ) ) + log.debug("RB Overdrive MarkerNote at %f added to part: %s and difficulty: %s" % ( startTime, self.partnumber, difficulties[diff] ) ) elif note == starPowerMarkingNote: #MFH self.song.hasStarpowerPaths = True @@ -2732,18 +2733,18 @@ def note_off(self, channel, note, velocity): self.addSpecialMidiEvent(diff, MarkerNote(note, endTime - startTime), time = startTime) self.addSpecialMidiEvent(diff, MarkerNote(note, 1, endMarker = True), time = endTime+1) #ending marker note if self.logMarkerNotes == 1: - Log.debug("GH Starpower (or RB Solo) MarkerNote at %f added to part: %s and difficulty: %s" % ( startTime, self.partnumber, difficulties[diff] ) ) + log.debug("GH Starpower (or RB Solo) MarkerNote at %f added to part: %s and difficulty: %s" % ( startTime, self.partnumber, difficulties[diff] ) ) elif note == freestyleMarkingNote: #MFH - for drum fills and big rock endings self.song.hasFreestyleMarkings = True for diff in difficulties: self.addSpecialMidiEvent(diff, MarkerNote(note, endTime - startTime), time = startTime) if self.logMarkerNotes == 1: - Log.debug("RB freestyle section (drum fill or BRE) at %f added to part: %s and difficulty: %s" % ( startTime, self.partnumber, difficulties[diff] ) ) + log.debug("RB freestyle section (drum fill or BRE) at %f added to part: %s and difficulty: %s" % ( startTime, self.partnumber, difficulties[diff] ) ) else: pass except KeyError: - Log.warn("MIDI note 0x%x on channel %d ending at %d was never started." % (note, channel, self.abs_time())) + log.warn("MIDI note 0x%x on channel %d ending at %d was never started." % (note, channel, self.abs_time())) #MFH - OK - this needs to be optimized. @@ -2786,7 +2787,7 @@ def text(self, text): event = TextEvent(text, 250.0) if text.lower().find("big rock ending") >= 0: curTime = self.abs_time() - Log.debug("Big Rock Ending section event marker found at " + str(curTime) ) + log.debug("Big Rock Ending section event marker found at " + str(curTime) ) self.song.breMarkerTime = curTime if text.lower().find("solo") >= 0 and text.lower().find("drum") < 0 and text.lower().find("outro") < 0 and text.lower().find("organ") < 0 and text.lower().find("synth") < 0 and text.lower().find("bass") < 0 and text.lower().find("harmonica") < 0: @@ -2829,7 +2830,7 @@ def text(self, text): if not self.guitarSoloActive: self.guitarSoloActive = True soloEvent = TextEvent("GSOLO ON", 250.0) - Log.debug("GSOLO ON event " + event.text + " found at time " + str(self.abs_time()) ) + log.debug("GSOLO ON event " + event.text + " found at time " + str(self.abs_time()) ) self.song.eventTracks[TK_GUITAR_SOLOS].addEvent(self.abs_time(), soloEvent) #MFH - add an event to the guitar solos track else: #this is the cue to end solos... if self.guitarSoloActive: @@ -2838,7 +2839,7 @@ def text(self, text): if self.song.eventTracks[TK_GUITAR_SOLOS][-1][0] < curTime: self.guitarSoloActive = False soloEvent = TextEvent("GSOLO OFF", 250.0) - Log.debug("GSOLO OFF event " + event.text + " found at time " + str(curTime) ) + log.debug("GSOLO OFF event " + event.text + " found at time " + str(curTime) ) self.guitarSoloIndex += 1 self.song.eventTracks[TK_GUITAR_SOLOS].addEvent(curTime, soloEvent) #MFH - add an event to the guitar solos track @@ -2870,7 +2871,7 @@ def __init__(self): self.logClassInits = Config.get("game", "log_class_inits") if self.logClassInits == 1: - Log.debug("MidiSectionReader class init (song.py)...") + log.debug("MidiSectionReader class init (song.py)...") self.logSections = Config.get("game", "log_sections") @@ -2919,7 +2920,7 @@ def note_on(self, channel, note, velocity): #MFH - only log if enabled if self.logSections == 1: - Log.debug("Found potential default practice section: " + str(pos) + " - " + text) + log.debug("Found potential default practice section: " + str(pos) + " - " + text) self.noteCountSections.append([text,pos]) @@ -2946,7 +2947,7 @@ def text(self, text): #MFH - only log if enabled if self.logSections == 1: - Log.debug("Found
potential RB-style practice section: " + str(pos) + " - " + text) + log.debug("Found
potential RB-style practice section: " + str(pos) + " - " + text) text = "%d:%02d -> " % (pos / 60000, (pos % 60000) / 1000) + text self.sections.append([text,pos]) @@ -2956,7 +2957,7 @@ def text(self, text): #MFH - only log if enabled if self.logSections == 1: - Log.debug("Found potential GH1-style practice section: " + str(pos) + " - " + text) + log.debug("Found potential GH1-style practice section: " + str(pos) + " - " + text) text = "%d:%02d -> " % (pos / 60000, (pos % 60000) / 1000) + text self.sections.append([text,pos]) @@ -2964,7 +2965,7 @@ def text(self, text): #MFH - only log if enabled if self.logSections == 1: - Log.debug("Found potential GH1-style practice section: " + str(pos) + " - " + text) + log.debug("Found potential GH1-style practice section: " + str(pos) + " - " + text) text = "%d:%02d -> " % (pos / 60000, (pos % 60000) / 1000) + text self.sections.append([text,pos]) @@ -2974,7 +2975,7 @@ def text(self, text): #MFH - only log if enabled if self.logSections == 1: - Log.debug("Found potential GH1-style practice section: " + str(pos) + " - " + text) + log.debug("Found potential GH1-style practice section: " + str(pos) + " - " + text) text = "%d:%02d -> " % (pos / 60000, (pos % 60000) / 1000) + text self.sections.append([text,pos]) @@ -2982,7 +2983,7 @@ def text(self, text): #MFH - only log if enabled if self.logSections == 1: - Log.debug("Found potential GH1-style practice section: " + str(pos) + " - " + text) + log.debug("Found potential GH1-style practice section: " + str(pos) + " - " + text) text = "%d:%02d -> " % (pos / 60000, (pos % 60000) / 1000) + text self.sections.append([text,pos]) @@ -3005,7 +3006,7 @@ def __init__(self): self.logClassInits = Config.get("game", "log_class_inits") if self.logClassInits == 1: - Log.debug("SongQueue class init (song.py)...") + log.debug("SongQueue class init (song.py)...") def __len__(self): return len(self.songName) @@ -3046,7 +3047,7 @@ def replayFullQueue(self): def getSong(self): if len(self.songName) == 0 or len(self.library) == 0: - Log.warn("SongQueue.getSong: Empty queue get.") + log.warn("SongQueue.getSong: Empty queue get.") return False song = self.songName.pop(0) library = self.library.pop(0) @@ -3054,7 +3055,7 @@ def getSong(self): def getRandomSong(self): if len(self.songName) == 0 or len(self.library) == 0: - Log.warn("SongQueue.getRandomSong: Empty queue get.") + log.warn("SongQueue.getRandomSong: Empty queue get.") return False n = random.randint(0,len(self.songName)-1) song = self.songName.pop(n) @@ -3096,19 +3097,19 @@ def __init__(self, forceGuitar = False): self.logClassInits = Config.get("game", "log_class_inits") if self.logClassInits == 1: - Log.debug("MidiPartsDiffReader class init (song.py)...") + log.debug("MidiPartsDiffReader class init (song.py)...") self.logSections = Config.get("game", "log_sections") def getMidiStyle(self): if self._ODNoteFound: - Log.debug("MIDI Type identified as RB") + log.debug("MIDI Type identified as RB") return MIDI_TYPE_RB elif self._drumFound and self._SPNoteFound: - Log.debug("MIDI Type identified as WT") + log.debug("MIDI Type identified as WT") return MIDI_TYPE_WT else: - Log.debug("MIDI Type identified as GH") + log.debug("MIDI Type identified as GH") return MIDI_TYPE_GH midiStyle = property(getMidiStyle) @@ -3125,10 +3126,10 @@ def start_of_track(self, n_track=0): if self.logSections == 1: tempText = "No recognized tracks found. Using first track, and identifying it as " tempText2 = "GUITAR_PART" - Log.debug(tempText + tempText2) + log.debug(tempText + tempText2) self.firstTrack = True else: - Log.notice("This song has multiple tracks, none properly named. Behavior may be erratic.") + log.notice("This song has multiple tracks, none properly named. Behavior may be erratic.") def sequence_name(self, text): @@ -3152,7 +3153,7 @@ def sequence_name(self, text): self._drumFound = True if self.logSections == 1: tempText2 = part.trackName[0].replace(" ", "_") - Log.debug(tempText + tempText2) + log.debug(tempText + tempText2) return self.currentPart = -1 @@ -3187,7 +3188,7 @@ def note_on(self, channel, note, velocity): def loadSong(engine, name, library = DEFAULT_LIBRARY, seekable = False, playbackOnly = False, notesOnly = False, part = [parts[GUITAR_PART]], practiceMode = False, practiceSpeed = .5): - Log.debug("loadSong function call (song.py)...") + log.debug("loadSong function call (song.py)...") crowdsEnabled = engine.config.get("audio", "enable_crowd_tracks") #RF-mod (not needed?) @@ -3203,15 +3204,15 @@ def loadSong(engine, name, library = DEFAULT_LIBRARY, seekable = False, playback noteFile = engine.resource.fileName(library, name, "notes-unedited.mid", writable = True) if os.path.isfile(noteFile): if logUneditedMidis == 1: - Log.debug("notes-unedited.mid found, using instead of notes.mid! - " + name) + log.debug("notes-unedited.mid found, using instead of notes.mid! - " + name) else: noteFile = engine.resource.fileName(library, name, "notes.mid", writable = True) if logUneditedMidis == 1: - Log.debug("notes-unedited.mid not found, using notes.mid - " + name) + log.debug("notes-unedited.mid not found, using notes.mid - " + name) else: noteFile = engine.resource.fileName(library, name, "notes.mid", writable = True) if logUneditedMidis == 1: - Log.debug("notes-unedited.mid not found, using notes.mid - " + name) + log.debug("notes-unedited.mid not found, using notes.mid - " + name) infoFile = engine.resource.fileName(library, name, "song.ini", writable = True) scriptFile = engine.resource.fileName(library, name, "script.txt") @@ -3296,7 +3297,7 @@ def getDefaultLibrary(engine): return LibraryInfo(DEFAULT_LIBRARY, engine.resource.fileName(DEFAULT_LIBRARY, "library.ini")) def getAvailableLibraries(engine, library = DEFAULT_LIBRARY): - Log.debug("Song.getAvailableLibraries function call...library = " + str(library) ) + log.debug("Song.getAvailableLibraries function call...library = " + str(library) ) # Search for libraries in both the read-write and read-only directories songRoots = [engine.resource.fileName(library), engine.resource.fileName(library, writable = True)] @@ -3523,7 +3524,7 @@ def getAvailableTitles(engine, library = DEFAULT_LIBRARY): titles.append(BlankSpaceInfo(_("End of Career"))) except: - Log.debug("titles.ini could not be read (song.py)") + log.debug("titles.ini could not be read (song.py)") return [] return titles @@ -3734,7 +3735,7 @@ def removeSongOrderPrefixFromName(name): #stump def updateSongDatabase(engine): from fofix.game import Dialogs # putting it at the top causes circular-import-related problems... - Log.debug('Updating song cache.') + log.debug('Updating song cache.') _songDB.execute('UPDATE `songinfo` SET `seen` = 0') lastScreenUpdateTime = [time.time()] # one-element list to avoid having to throw this into the global namespace for updatePhase's sake loadingScreen = Dialogs.showLoadingSplashScreen(engine, _('Checking song database...')) @@ -3756,6 +3757,6 @@ def updatePhase(text): prunecount = _songDB.execute('DELETE FROM `songinfo` WHERE `seen` = 0').rowcount if prunecount != 0: _songDB.execute('VACUUM') - Log.debug('Pruned %d cache entries.' % prunecount) + log.debug('Pruned %d cache entries.' % prunecount) _songDB.commit() Dialogs.hideLoadingSplashScreen(engine, loadingScreen) diff --git a/fofix/game/SongChoosingScene.py b/fofix/game/SongChoosingScene.py index f569a4ed7..00ee00c0b 100644 --- a/fofix/game/SongChoosingScene.py +++ b/fofix/game/SongChoosingScene.py @@ -28,6 +28,8 @@ import time import pygame +from fretwork import log + from fofix.core.Scene import Scene from fofix.core.Settings import ConfigChoice, ActiveConfigChoice @@ -42,7 +44,6 @@ from fofix.core import Config from fofix.core import Version from fofix.game.Menu import Menu -from fofix.core import Log from fofix.core.constants import * PRACTICE = 1 @@ -271,7 +272,7 @@ def resetQueueVars(self): self.loadLibrary() def loadLibrary(self): - Log.debug("Loading libraries in %s" % self.library) + log.debug("Loading libraries in %s" % self.library) self.loaded = False self.tiersPresent = False if self.splash: @@ -282,7 +283,7 @@ def loadLibrary(self): self.engine.resource.load(self, "libraries", lambda: Song.getAvailableLibraries(self.engine, self.library), onLoad = self.loadSongs, synch = True) def loadSongs(self, libraries): - Log.debug("Loading songs in %s" % self.library) + log.debug("Loading songs in %s" % self.library) self.engine.resource.load(self, "songs", lambda: Song.getAvailableSongsAndTitles(self.engine, self.library, progressCallback=self.progressCallback), onLoad = self.prepareSetlist, synch = True) def progressCallback(self, percent): @@ -363,7 +364,7 @@ def prepareSetlist(self, songs): self.loadLibrary() return - Log.debug("Setlist loaded.") + log.debug("Setlist loaded.") self.loaded = True @@ -421,7 +422,7 @@ def checkCmdPlay(self): guitars.append(part) if self.engine.cmdPlay == 2 and self.engine.cmdPart is not None and len(self.playerList) == 1: if self.engine.cmdPart == part.id: - Log.debug("Command-line mode: Part found!") + log.debug("Command-line mode: Part found!") if part.id == 4 and self.engine.input.gameDrums > 0: autoPart = part.id elif part.id == 5 and self.engine.input.gameMics > 0: @@ -827,7 +828,7 @@ def keyPressed(self, key, unicode): if isinstance(self.selectedItem, Song.LibraryInfo): self.library = self.selectedItem.libraryName self.startingSelected = None - Log.debug("New library selected: " + str(self.library) ) + log.debug("New library selected: " + str(self.library) ) self.loadLibrary() elif isinstance(self.selectedItem, Song.SongInfo) and not self.selectedItem.getLocked(): if self.listingMode == 1 and not self.careerMode: diff --git a/fofix/game/guitarscene/GuitarScene.py b/fofix/game/guitarscene/GuitarScene.py index a1d565cf2..6dab30135 100644 --- a/fofix/game/guitarscene/GuitarScene.py +++ b/fofix/game/guitarscene/GuitarScene.py @@ -38,6 +38,9 @@ from OpenGL.GL import * + +from fretwork import log + from fofix.game.Song import Note, TextEvent, PictureEvent, loadSong, Bars, VocalPhrase from fofix.core.Player import STAR, KILL, CANCEL, KEY1A from fofix.game.guitarscene.instruments import * @@ -53,7 +56,6 @@ from fofix.core import Settings from fofix.game import Song from fofix.core import Player -from fofix.core import Log import random @@ -64,7 +66,7 @@ def __init__(self, engine, libraryName, songName): superClass.__init__(engine) - Log.debug("BandPlayBaseScene init...") + log.debug("BandPlayBaseScene init...") self.engine.world.sceneName = "GuitarScene" self.ready = False @@ -141,7 +143,7 @@ def __init__(self, engine, libraryName, songName): if None not in [self.targetX, self.targetY, self.targetZ, self.originX, self.originY, self.originZ]: self.customPOV = True - Log.debug("All theme POV set. Using custom camera POV.") + log.debug("All theme POV set. Using custom camera POV.") #weirdpeople - sets the distances the neck has to move in the animation if self.neckintroAnimationType == 0: #Original @@ -201,7 +203,7 @@ def loadmages(self, w, h): if self.engine.loadImgDrawing(self, "breScoreBackground", os.path.join("themes",self.themeName,"brescorebackground.png")): self.breScoreBackgroundWFactor = (w * self.engine.theme.breScoreBackgroundScale) / self.breScoreBackground.width1() else: - Log.debug("BRE score background image loading problem!") + log.debug("BRE score background image loading problem!") self.breScoreBackground = None self.breScoreBackgroundWFactor = None @@ -657,7 +659,7 @@ def __init__(self, engine, libraryName, songName): self.practiceMode = False self.bossBattle = False - Log.debug("GuitarScene init...") + log.debug("GuitarScene init...") self.coOpPlayerMeter = 0 @@ -778,7 +780,7 @@ def __init__(self, engine, libraryName, songName): self.soloKeysList.append([]) self.soloShifts.append([]) - Log.debug("GuitarScene keysList: %s" % str(self.keysList)) + log.debug("GuitarScene keysList: %s" % str(self.keysList)) self.aiSkill = [0 for i in self.players] self.aiHitPercentage = [0 for i in self.players] @@ -1344,7 +1346,7 @@ def __init__(self, engine, libraryName, songName): for i in range(self.numOfPlayers): #MFH - count number of drum fills if self.instruments[i].isDrum: #MFH - count number of drum fill markers self.numDrumFills = len([1 for time, event in self.song.midiEventTrack[i].getAllEvents() if (isinstance(event, Song.MarkerNote) and (event.number == Song.freestyleMarkingNote) ) ]) - Log.debug("Drum part found, scanning for drum fills.... %d freestyle markings found (the last one may be a Big Rock Ending)." % self.numDrumFills) + log.debug("Drum part found, scanning for drum fills.... %d freestyle markings found (the last one may be a Big Rock Ending)." % self.numDrumFills) #MFH - handle early hit window automatic type determination, and how it compares to the forced handicap if not auto @@ -1352,7 +1354,7 @@ def __init__(self, engine, libraryName, songName): self.automaticEarlyHitWindow = Song.EARLY_HIT_WINDOW_HALF self.forceEarlyHitWindowSetting = self.engine.config.get("handicap", "early_hit_window") if self.song.info.early_hit_window_size: - Log.debug("song.ini setting found specifying early_hit_window_size - %s" % self.song.info.early_hit_window_size) + log.debug("song.ini setting found specifying early_hit_window_size - %s" % self.song.info.early_hit_window_size) if self.song.info.early_hit_window_size.lower() == "none": self.automaticEarlyHitWindow = Song.EARLY_HIT_WINDOW_NONE elif self.song.info.early_hit_window_size.lower() == "half": @@ -1361,10 +1363,10 @@ def __init__(self, engine, libraryName, songName): self.automaticEarlyHitWindow = Song.EARLY_HIT_WINDOW_FULL else: - Log.debug("No song.ini setting found specifying early_hit_window_size - using automatic detection...") + log.debug("No song.ini setting found specifying early_hit_window_size - using automatic detection...") if self.song.midiStyle == Song.MIDI_TYPE_RB: - Log.debug("Basic RB1/RB2 type MIDI found - early hitwindow of NONE is set as handicap base.") + log.debug("Basic RB1/RB2 type MIDI found - early hitwindow of NONE is set as handicap base.") self.automaticEarlyHitWindow = Song.EARLY_HIT_WINDOW_NONE if self.forceEarlyHitWindowSetting > 0: #MFH - if user is specifying a specific early hitwindow, then calculate handicap... @@ -1456,19 +1458,19 @@ def __init__(self, engine, libraryName, songName): spEvent.finalStar = True oneLastSpNoteMarked = True if self.logMarkerNotes == 1: - Log.debug("GuitarScene: P%d overdrive / starpower phrase marked between %f and %f" % ( i+1, time, time+event.length ) ) + log.debug("GuitarScene: P%d overdrive / starpower phrase marked between %f and %f" % ( i+1, time, time+event.length ) ) if lastSpNoteTime == 0: - Log.warn("This starpower phrase doesn't appear to have any finalStar notes marked... probably will not reward starpower!") + log.warn("This starpower phrase doesn't appear to have any finalStar notes marked... probably will not reward starpower!") self.midiSP = True unisonCheck.extend(self.spTimes[i]) elif self.starpowerMode == 2: #this particular instrument only has one starpower path marked! Force auto-generation of SP paths. - Log.warn("Instrument %s only has one starpower path marked! ...falling back on auto-generated paths for this instrument." % self.players[i].part.text) + log.warn("Instrument %s only has one starpower path marked! ...falling back on auto-generated paths for this instrument." % self.players[i].part.text) guitar.starNotesSet = False #fallback on auto generation. elif self.starpowerMode == 2: if self.numberOfGuitars > 0: - Log.warn("This song does not appear to have any starpower or overdrive paths marked, falling back on auto-generated paths.") + log.warn("This song does not appear to have any starpower or overdrive paths marked, falling back on auto-generated paths.") for instrument in self.instruments: if instrument.isVocal: continue @@ -1567,7 +1569,7 @@ def __init__(self, engine, libraryName, songName): lastDrumNoteEvent = event if instrument.isDrum: self.lastDrumNoteTime = lastDrumNoteTime - Log.debug("Last drum note located at time = " + str(self.lastDrumNoteTime) ) + log.debug("Last drum note located at time = " + str(self.lastDrumNoteTime) ) self.scoring[i].totalStreakNotes = len([1 for time, event in self.song.track[i].getEvents(self.players[i].startPos,self.lastEvent) if isinstance(event, Note)]) elif instrument.isVocal: self.scoring[i].totalStreakNotes = len([1 for time, event in self.song.track[i].getEvents(self.players[i].startPos,self.lastEvent) if isinstance(event, VocalPhrase)]) @@ -1578,11 +1580,11 @@ def __init__(self, engine, libraryName, songName): self.lastNoteTimes[i] = lastDrumNoteTime if lastDrumNoteEvent: if isinstance(lastDrumNoteEvent, Note): - Log.debug("Last note (number %d) found for player %d at time %f" % (lastDrumNoteEvent.number, i, lastDrumNoteTime) ) + log.debug("Last note (number %d) found for player %d at time %f" % (lastDrumNoteEvent.number, i, lastDrumNoteTime) ) elif isinstance(lastDrumNoteEvent, VocalPhrase): - Log.debug("Last vocal phrase found for player %d at time %f" % (i, lastDrumNoteTime) ) + log.debug("Last vocal phrase found for player %d at time %f" % (i, lastDrumNoteTime) ) else: - Log.debug("Last note event not found and is None!") + log.debug("Last note event not found and is None!") if instrument.isVocal: self.scoring[i].totalNotes = self.scoring[i].totalStreakNotes - len(instrument.tapNoteTotals) @@ -1606,7 +1608,7 @@ def __init__(self, engine, libraryName, songName): breEnd = time + event.length numBreStreakNotes = len(set(time for time, event in self.song.track[i].getEvents(breStart, breEnd) if isinstance(event, Note))) self.scoring[i].totalStreakNotes -= numBreStreakNotes #MFH - remove BRE notes correctly from streak count. - Log.debug("Removed %d streak notes from player %d" % (numBreStreakNotes, i) ) + log.debug("Removed %d streak notes from player %d" % (numBreStreakNotes, i) ) totalBreNotes += numBreStreakNotes @@ -1619,7 +1621,7 @@ def __init__(self, engine, libraryName, songName): endTime = time + event.length guitarSoloNoteCount = len([1 for Gtime, Gevent in self.song.track[i].getEvents(startTime, endTime) if isinstance(Gevent, Note)]) self.guitarSolos[i].append(guitarSoloNoteCount - 1) - Log.debug("P" + str(i+1) + " MIDI " + self.players[i].part.text + " Solo found from: " + str(startTime) + " to: " + str(endTime) + ", containing " + str(guitarSoloNoteCount) + " notes." ) + log.debug("P" + str(i+1) + " MIDI " + self.players[i].part.text + " Solo found from: " + str(startTime) + " to: " + str(endTime) + ", containing " + str(guitarSoloNoteCount) + " notes." ) elif instrument.markSolos == 1: #mark using the old text-based system @@ -1635,7 +1637,7 @@ def __init__(self, engine, libraryName, songName): isGuitarSoloNow = False guitarSoloNoteCount = len([1 for Gtime, Gevent in self.song.track[i].getEvents(guitarSoloStartTime, time) if isinstance(Gevent, Note)]) self.guitarSolos[i].append(guitarSoloNoteCount - 1) - Log.debug("GuitarScene: Guitar Solo found: " + str(guitarSoloStartTime) + "-" + str(time) + " = " + str(guitarSoloNoteCount) ) + log.debug("GuitarScene: Guitar Solo found: " + str(guitarSoloStartTime) + "-" + str(time) + " = " + str(guitarSoloNoteCount) ) if isGuitarSoloNow: #open solo until end - needs end event! isGuitarSoloNow = False #MFH - must find the real "last note" time, requires another iteration... @@ -1647,7 +1649,7 @@ def __init__(self, engine, libraryName, songName): self.guitarSolos[i].append(guitarSoloNoteCount - 1) newEvent = TextEvent("GSOLO OFF", 100.0) self.song.eventTracks[Song.TK_GUITAR_SOLOS].addEvent(Ntime, newEvent) #adding the missing GSOLO OFF event - Log.debug("GuitarScene: Guitar Solo until end of song found - (guitarSoloStartTime - Ntime = guitarSoloNoteCount): " + str(guitarSoloStartTime) + "-" + str(Ntime) + " = " + str(guitarSoloNoteCount) ) + log.debug("GuitarScene: Guitar Solo until end of song found - (guitarSoloStartTime - Ntime = guitarSoloNoteCount): " + str(guitarSoloStartTime) + "-" + str(Ntime) + " = " + str(guitarSoloNoteCount) ) @@ -1665,8 +1667,8 @@ def __init__(self, engine, libraryName, songName): for j in range(len(self.spTimes)): if self.unisonConfirm[i] in self.spTimes[j]: self.unisonPlayers[i].append(j) - Log.debug("Unisons confirmed: " + str(self.unisonConfirm)) - Log.debug("Unisons between: " + str(self.unisonPlayers)) + log.debug("Unisons confirmed: " + str(self.unisonConfirm)) + log.debug("Unisons between: " + str(self.unisonPlayers)) #MFH - handle gathering / sizing / grouping line-by-line lyric display here, during initialization: @@ -1716,15 +1718,15 @@ def __init__(self, engine, libraryName, songName): #MFH - test unpacking / decoding the lyrical lines: for midiLyricSubList in self.midiLyricLineEvents: if self.logLyricEvents == 1: - Log.debug("...New MIDI lyric line:") + log.debug("...New MIDI lyric line:") for lyricTuple in midiLyricSubList: time, event = lyricTuple if self.logLyricEvents == 1: - Log.debug("MIDI Line-by-line lyric unpack test - time, event = " + str(time) + ", " + event.text ) + log.debug("MIDI Line-by-line lyric unpack test - time, event = " + str(time) + ", " + event.text ) for lineStartTime, midiLyricSimpleLineText in self.midiLyricLines: if self.logLyricEvents == 1: - Log.debug("MIDI Line-by-line simple lyric line starting at time: " + str(lineStartTime) + ", " + midiLyricSimpleLineText) + log.debug("MIDI Line-by-line simple lyric line starting at time: " + str(lineStartTime) + ", " + midiLyricSimpleLineText) self.numMidiLyricLines = len(self.midiLyricLines) @@ -1733,7 +1735,7 @@ def __init__(self, engine, libraryName, songName): self.coOpTotalNotes = 0 if self.coOpScoreCard: self.coOpScoreCard.lastNoteTime = max(self.lastNoteTimes) - Log.debug("Last note for co-op mode found at %.2f" % self.coOpScoreCard.lastNoteTime) + log.debug("Last note for co-op mode found at %.2f" % self.coOpScoreCard.lastNoteTime) for i, scoreCard in enumerate(self.scoring): #accumulate base scoring values for co-op if self.coOpScoreCard: self.coOpScoreCard.totalStreakNotes += scoreCard.totalStreakNotes @@ -1827,7 +1829,7 @@ def __init__(self, engine, libraryName, songName): settingsMenu.fadeScreen = False careerSettingsMenu.fadeScreen = False - Log.debug("Pause text / selected colors: " + str(self.pause_text_color) + " / " + str(self.pause_selected_color)) + log.debug("Pause text / selected colors: " + str(self.pause_text_color) + " / " + str(self.pause_selected_color)) @@ -3175,7 +3177,7 @@ def run(self, ticks): #QQstarS: Fix this funcion else: count = 0 count += 1 - Log.debug("Song completed") + log.debug("Song completed") self.song.info.completed = True self.song.info.count = "%d" % count self.song.info.save() @@ -3272,7 +3274,7 @@ def run(self, ticks): #QQstarS: Fix this funcion if guitar.battleStatus[1]: if self.songTime - guitar.battleDrainStart > guitar.battleDrainLength: - Log.debug("Drain for Player %d disabled" % i) + log.debug("Drain for Player %d disabled" % i) guitar.battleStatus[1] = False for k, nowUsed in enumerate(guitar.battleBeingUsed): if guitar.battleBeingUsed[k] == 1: @@ -3286,7 +3288,7 @@ def run(self, ticks): #QQstarS: Fix this funcion if guitar.battleStatus[6]: if self.songTime - guitar.battleStartTimes[6] > guitar.battleLeftyLength: - Log.debug("Lefty Mode for Player %d disabled" % i) + log.debug("Lefty Mode for Player %d disabled" % i) guitar.battleStatus[6] = False for k, nowUsed in enumerate(guitar.battleBeingUsed): if guitar.battleBeingUsed[k] == 6: @@ -3294,7 +3296,7 @@ def run(self, ticks): #QQstarS: Fix this funcion if guitar.battleStatus[8]: if self.songTime - guitar.battleStartTimes[8] > guitar.battleAmpLength: - Log.debug("Diff Up Mode for Player %d disabled" % i) + log.debug("Diff Up Mode for Player %d disabled" % i) guitar.battleStatus[8] = False for k, nowUsed in enumerate(guitar.battleBeingUsed): if guitar.battleBeingUsed[k] == 8: @@ -3303,7 +3305,7 @@ def run(self, ticks): #QQstarS: Fix this funcion if guitar.battleStatus[7]: if self.songTime - guitar.battleStartTimes[7] > guitar.battleDoubleLength: - Log.debug("Diff Up Mode for Player %d disabled" % i) + log.debug("Diff Up Mode for Player %d disabled" % i) guitar.battleStatus[7] = False for k, nowUsed in enumerate(guitar.battleBeingUsed): if guitar.battleBeingUsed[k] == 7: @@ -3319,7 +3321,7 @@ def run(self, ticks): #QQstarS: Fix this funcion if guitar.battleStatus[2]: if self.songTime - guitar.battleStartTimes[2] > guitar.battleDiffUpLength: - Log.debug("Diff Up Mode for Player %d disabled" % i) + log.debug("Diff Up Mode for Player %d disabled" % i) guitar.battleStatus[2] = False self.song.difficulty[i] = Song.difficulties[guitar.battleDiffUpValue] guitar.difficulty = guitar.battleDiffUpValue @@ -3339,7 +3341,7 @@ def run(self, ticks): #QQstarS: Fix this funcion scoreCard = self.coOpScoreCard if scoreCard.freestyleWasJustActive and not scoreCard.endingAwarded: if scoreCard.lastNoteTime < self.songTime and not scoreCard.endingStreakBroken: - Log.debug("Big Rock Ending bonus awarded for co-op players! %d points." % scoreCard.endingScore) + log.debug("Big Rock Ending bonus awarded for co-op players! %d points." % scoreCard.endingScore) if scoreCard.endingScore > 0: scoreCard.addEndingScore() self.engine.data.starActivateSound.play() @@ -3349,7 +3351,7 @@ def run(self, ticks): #QQstarS: Fix this funcion if scoreCard.freestyleWasJustActive and not scoreCard.endingAwarded: if scoreCard.lastNoteEvent and not scoreCard.endingStreakBroken: if scoreCard.lastNoteEvent.played or scoreCard.lastNoteEvent.hopod: - Log.debug("Big Rock Ending bonus awarded for player %d: %d points" % (playerNum, scoreCard.endingScore) ) + log.debug("Big Rock Ending bonus awarded for player %d: %d points" % (playerNum, scoreCard.endingScore) ) if scoreCard.endingScore > 0: scoreCard.addEndingScore() self.engine.data.starActivateSound.play() @@ -3434,7 +3436,7 @@ def run(self, ticks): #QQstarS: Fix this funcion self.coOpScoreCard.notesMissed += 1 if theNote.star or theNote.finalStar: if self.logStarpowerMisses == 1: - Log.debug("SP Miss: run(), note: %d, gameTime: %s" % (theNote.number, self.timeLeft) ) + log.debug("SP Miss: run(), note: %d, gameTime: %s" % (theNote.number, self.timeLeft) ) self.starNotesMissed[i] = True if self.unisonActive: self.inUnison[i] = False @@ -3458,7 +3460,7 @@ def run(self, ticks): #QQstarS: Fix this funcion self.scoring[playerNum].endingStreakBroken = True #MFH if self.hopoDebugDisp == 1: missedNoteNums = [noat.number for time, noat in missedNotes] - Log.debug("Miss: run(), found missed note(s)... %(missedNotes)s, Song time=%(songTime)s" % \ + log.debug("Miss: run(), found missed note(s)... %(missedNotes)s, Song time=%(songTime)s" % \ {'missedNotes': str(missedNoteNums), 'songTime': str(self.timeLeft)}) guitar.hopoActive = 0 @@ -3997,14 +3999,14 @@ def doPick3GH2(self, num, hopo = False, pullOff = False): #MFH - so DoPick knows for tym, theNote in missedNotes: #MFH if theNote.star or theNote.finalStar: if self.logStarpowerMisses == 1: - Log.debug("SP Miss: doPick3GH2(), foundMissedCatchupNote: %d, gameTime: %s" % (theNote.number, self.timeLeft) ) + log.debug("SP Miss: doPick3GH2(), foundMissedCatchupNote: %d, gameTime: %s" % (theNote.number, self.timeLeft) ) self.starNotesMissed[num] = True if self.unisonActive: self.inUnison[num] = False if self.hopoDebugDisp == 1: missedNoteNums = [noat.number for time, noat in missedNotes] - Log.debug("Miss: dopick3gh2(), found missed note(s)... %(missedNotes)s, Song time=%(songTime)s" % \ + log.debug("Miss: dopick3gh2(), found missed note(s)... %(missedNotes)s, Song time=%(songTime)s" % \ {'missedNotes': str(missedNoteNums), 'songTime': str(self.timeLeft)}) if hopo == True: @@ -4187,7 +4189,7 @@ def doPick3GH2(self, num, hopo = False, pullOff = False): #MFH - so DoPick knows self.stage.triggerMiss(self.songTime) if self.hopoDebugDisp == 1 and not self.instruments[num].isDrum: problemNoteMatchingList = [(int(tym), noat.number, noat.played) for tym, noat in self.instruments[num].matchingNotes] - Log.debug("Miss: dopick3gh2(), fail-startpick3()...HigherFretsHeld: %(higherFrets)s, LastHopoFretHeld: %(lastHopoFret)s, lastStrumWasChord: %(lastStrumChord)s, sameNoteHopoStringFlag: %(sameNoteHopoFlag)s, notesToMatch: %(matchNotes)s, activeFrets: %(activeFrets)s, Song time=%(songTime)s" % \ + log.debug("Miss: dopick3gh2(), fail-startpick3()...HigherFretsHeld: %(higherFrets)s, LastHopoFretHeld: %(lastHopoFret)s, lastStrumWasChord: %(lastStrumChord)s, sameNoteHopoStringFlag: %(sameNoteHopoFlag)s, notesToMatch: %(matchNotes)s, activeFrets: %(activeFrets)s, Song time=%(songTime)s" % \ {'higherFrets': str(HigherFretsHeld), 'lastHopoFret': str(LastHopoFretStillHeld), 'lastStrumChord': str(lastStrumWasChordWas), 'sameNoteHopoFlag': str(sameNoteHopoFlagWas), 'matchNotes': str(problemNoteMatchingList), 'activeFrets': str(activeKeyList), 'songTime': str(self.timeLeft)}) self.notesMissed[num] = True #QQstarS:Set [0] to [i] @@ -4197,7 +4199,7 @@ def doPick3GH2(self, num, hopo = False, pullOff = False): #MFH - so DoPick knows for tym, noat in noteList: if (noat.star or noat.finalStar) and isFirst: if self.logStarpowerMisses == 1: - Log.debug("SP Miss: doPick3GH2(), afterStartPick3Fail, matchingNote: %d, gameTime: %s" % (noat.number, self.timeLeft) ) + log.debug("SP Miss: doPick3GH2(), afterStartPick3Fail, matchingNote: %d, gameTime: %s" % (noat.number, self.timeLeft) ) self.starNotesMissed[num] = True if self.unisonActive: self.inUnison[num] = False @@ -4262,7 +4264,7 @@ def activateSP(self, num): #QQstarS: Fix this function, add a element "num" elif self.coOpGH: #akedrou also says don't let vocal players in GH Co-Op. if self.coOpStarPower >= (50 * self.numOfPlayers) and self.instruments[num].starPowerActive == False: - Log.debug("Star Power Activated at: " + str(self.songTime)) + log.debug("Star Power Activated at: " + str(self.songTime)) self.coOpStarPowerActive[num] = self.songTime if self.songTime - min(self.coOpStarPowerActive) < 300.0 and not self.instruments[num].starPowerActive: self.engine.data.starActivateSound.play() @@ -4274,7 +4276,7 @@ def activateSP(self, num): #QQstarS: Fix this function, add a element "num" else: if self.songTime - self.coOpStarPowerTimer > 1000.0: for i in range(self.numOfPlayers): - Log.debug(str(self.songTime - self.coOpStarPowerActive[i])) + log.debug(str(self.songTime - self.coOpStarPowerActive[i])) if self.songTime - self.coOpStarPowerActive[i] < 300.0: continue if self.instruments[i].isDrum and self.autoDrumStarpowerActivate == 0 and self.numDrumFills < 2: diff --git a/fofix/game/guitarscene/Neck.py b/fofix/game/guitarscene/Neck.py index 099b50740..b97971bc1 100644 --- a/fofix/game/guitarscene/Neck.py +++ b/fofix/game/guitarscene/Neck.py @@ -27,11 +27,12 @@ from OpenGL.GL import * import numpy as np +from fretwork import log + from fofix.core.Shader import shaders, mixColors from fofix.game.Song import Bars from fofix.game import Song from fofix.core import cmgl -from fofix.core import Log class Neck: def __init__(self, engine, instrument, playerObj): @@ -267,9 +268,9 @@ def __init__(self, engine, instrument, playerObj): i = random.randint(0,len(themeNeck)-1) if engine.loadImgDrawing(self, "neckDrawing", os.path.join("themes", themename, "necks", themeNeck[i]), textureSize = (256, 256)): neckFind = False - Log.debug("Random theme neck chosen: " + themeNeck[i]) + log.debug("Random theme neck chosen: " + themeNeck[i]) else: - Log.error("Unable to load theme neck: " + themeNeck[i]) + log.error("Unable to load theme neck: " + themeNeck[i]) # fall back to defaultneck self.neck = "defaultneck" if neckFind: @@ -289,9 +290,9 @@ def __init__(self, engine, instrument, playerObj): i = random.randint(0,len(self.neck)-1) if engine.loadImgDrawing(self, "neckDrawing", os.path.join("necks",self.neck[i]+".png"), textureSize = (256, 256)): - Log.debug("Random neck chosen: " + self.neck[i]) + log.debug("Random neck chosen: " + self.neck[i]) else: - Log.error("Unable to load neck: " + self.neck[i]) + log.error("Unable to load neck: " + self.neck[i]) self.neck = "defaultneck" engine.loadImgDrawing(self, "neckDrawing", os.path.join("necks",self.neck+".png"), textureSize = (256, 256)) else: diff --git a/fofix/game/guitarscene/Rockmeter.py b/fofix/game/guitarscene/Rockmeter.py index fa3ebd2be..d8d0cc315 100644 --- a/fofix/game/guitarscene/Rockmeter.py +++ b/fofix/game/guitarscene/Rockmeter.py @@ -36,6 +36,8 @@ from PIL import Image, ImageDraw from OpenGL.GL import * +from fretwork import log + from fofix.core.LinedConfigParser import LinedConfigParser from fofix.core.Theme import halign, valign from fofix.core.Image import ImgDrawing @@ -44,7 +46,6 @@ from fofix.core.constants import * from fofix.core import Version from fofix.core import cmgl -from fofix.core import Log #these are the variables for setting the alignment of text and images #when setting them up in the rockmeter.ini you do not have @@ -907,7 +908,7 @@ def __init__(self, guitarScene, configFileName, coOp = False): self.customRMLayers = imp.load_module("CustomRMLayers", fp, pathname, description) except ImportError: self.customRMLayers = None - Log.notice("Custom Rockmeter layers are not available") + log.notice("Custom Rockmeter layers are not available") # Build the layers for i in range(Rockmeter._layerLimit): diff --git a/fofix/game/guitarscene/Stage.py b/fofix/game/guitarscene/Stage.py index 72a9bff10..ead470928 100644 --- a/fofix/game/guitarscene/Stage.py +++ b/fofix/game/guitarscene/Stage.py @@ -31,6 +31,8 @@ from OpenGL.GL import * +from fretwork import log + from fofix.core.VideoPlayer import VideoLayer, VideoPlayerError from fofix.core.LinedConfigParser import LinedConfigParser from fofix.game.guitarscene import Rockmeter @@ -38,7 +40,6 @@ from fofix.core.Shader import shaders from fofix.core.constants import * from fofix.core.Language import _ -from fofix.core import Log @@ -288,7 +289,7 @@ def __init__(self, guitarScene, configFileName): 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) + log.warn("Stage folder does not exist: %s" % self.pathfull) self.mode = 1 # Fallback to song-specific stage self.loadLayers(configFileName) @@ -361,26 +362,26 @@ def loadVideo(self, libraryName, songName): vidSource = songBackgroundVideoPath loop = False else: - Log.warn("Video not found: %s" % songBackgroundVideoPath) + 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.") + 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) + 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):") + log.error("Failed to load song video (falling back to default stage mode):") def restartVideo(self): if not self.mode == 3: @@ -424,13 +425,13 @@ def load(self, libraryName, songName, practiceMode = False): 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 + 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 + log.notice("No song-specific stage found") # evilynux test = False if test: #does a song-specific background exist? self.rotationMode = 0 @@ -445,7 +446,7 @@ def load(self, libraryName, songName, practiceMode = False): #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 + 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 @@ -455,15 +456,15 @@ def load(self, libraryName, songName, practiceMode = False): 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) + log.debug("Valid background found, index (" + str(fileIndex) + "): " + name) files.append(name) fileIndex += 1 else: - Log.debug("Practice background filtered: " + name) + 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!") + log.warn("No valid stage found!") self.mode = 2; else: i = random.randint(0,len(files)-1) @@ -496,11 +497,11 @@ def load(self, libraryName, songName, practiceMode = False): 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) + log.debug("Valid background found, index (" + str(fileIndex) + "): " + name) files.append(name) fileIndex += 1 else: - Log.debug("Practice background filtered: " + name) + log.debug("Practice background filtered: " + name) files.sort() if self.rotationMode > 0 and self.mode != 2: #alarian: blank stage option is not selected diff --git a/fofix/game/guitarscene/instruments/Drum.py b/fofix/game/guitarscene/instruments/Drum.py index b69ce6019..9c1a678c8 100644 --- a/fofix/game/guitarscene/instruments/Drum.py +++ b/fofix/game/guitarscene/instruments/Drum.py @@ -32,6 +32,8 @@ import numpy as np from OpenGL.GL import * +from fretwork import log + from fofix.game.guitarscene.instruments.Instrument import Instrument from fofix.game.guitarscene.Neck import Neck from fofix.game.Song import Note, Tempo @@ -40,7 +42,6 @@ from fofix.core.Mesh import Mesh from fofix.game import Song from fofix.core import cmgl -from fofix.core import Log #Normal guitar key color order: Green, Red, Yellow, Blue, Orange #Drum fret color order: Red, Yellow, Blue, Green @@ -104,7 +105,7 @@ def __init__(self, engine, playerObj, scene, player = 0): self.logClassInits = self.engine.config.get("game", "log_class_inits") if self.logClassInits == 1: - Log.debug("Drum class initialization!") + log.debug("Drum class initialization!") self.freestyleHitFlameCounts = [0 for n in range(self.strings+1)] #MFH diff --git a/fofix/game/guitarscene/instruments/Guitar.py b/fofix/game/guitarscene/instruments/Guitar.py index 859655c0a..5929927fa 100644 --- a/fofix/game/guitarscene/instruments/Guitar.py +++ b/fofix/game/guitarscene/instruments/Guitar.py @@ -34,6 +34,8 @@ from OpenGL.GL import * import numpy as np +from fretwork import log + from fofix.game.guitarscene.instruments.Instrument import Instrument from fofix.game.guitarscene.Neck import Neck from fofix.game.Song import Note, Tempo @@ -42,7 +44,6 @@ from fofix.core.Mesh import Mesh from fofix.game import Song from fofix.core import cmgl -from fofix.core import Log class Guitar(Instrument): def __init__(self, engine, playerObj, scene, player = 0, bass = False): @@ -61,7 +62,7 @@ def __init__(self, engine, playerObj, scene, player = 0, bass = False): self.logClassInits = self.engine.config.get("game", "log_class_inits") if self.logClassInits == 1: - Log.debug("Guitar class init...") + log.debug("Guitar class init...") self.lastPlayedNotes = [] #MFH - for reverting when game discovers it implied incorrectly diff --git a/fofix/game/guitarscene/instruments/Instrument.py b/fofix/game/guitarscene/instruments/Instrument.py index 8f7a91923..688f99d4b 100644 --- a/fofix/game/guitarscene/instruments/Instrument.py +++ b/fofix/game/guitarscene/instruments/Instrument.py @@ -26,13 +26,14 @@ from OpenGL.GL import * import numpy as np +from fretwork import log + from fofix.game.Song import Note, Tempo from fofix.core.Image import draw3Dtex from fofix.core.Shader import shaders from fofix.core.Mesh import Mesh from fofix.game import Song from fofix.core import cmgl -from fofix.core import Log class Instrument(object): @@ -147,7 +148,7 @@ def __init__(self, engine, playerObj, scene, player = 0): if self.engine.config.get("game", "battle_Steal") == 1: self.battleObjectsEnabled.append(5) - Log.debug("Battle Objects Enabled: "+str(self.battleObjectsEnabled)) + log.debug("Battle Objects Enabled: "+str(self.battleObjectsEnabled)) self.battleNextObject = 0 self.battleObjects = [0] * 3 self.battleBeingUsed = [0] * 2 @@ -394,7 +395,7 @@ def checkPath(self, subdirectory, file, lastResort = False): else: if lastResort and not self.engine.fileExists(os.path.join(defaultpath, file)): return file - Log.debug("Image not found: " + themepath + "/" + file) + log.debug("Image not found: " + themepath + "/" + file) return os.path.join(defaultpath, file) def loadFlames(self): @@ -575,7 +576,7 @@ def loadTails(self): break if self.simpleTails: - Log.debug("Simple tails used; complex tail loading error...") + log.debug("Simple tails used; complex tail loading error...") engine.loadImgDrawing(self, "tail1", getD("tail1.png"), textureSize = (128, 128)) engine.loadImgDrawing(self, "tail2", getD("tail2.png"), textureSize = (128, 128)) engine.loadImgDrawing(self, "bigTail1", getD("bigtail1.png"), textureSize = (128, 128)) @@ -720,7 +721,7 @@ def getMissedNotes(self, song, pos, catchup = False): def getRequiredNotesForRender(self, song, pos): if self.battleStatus[2] and self.difficulty != 0: - Log.debug(self.battleDiffUpValue) + log.debug(self.battleDiffUpValue) song.difficulty[self.player] = Song.difficulties[self.battleDiffUpValue] track0 = song.track[self.player] notes0 = [(time, event) for time, event in track0.getEvents(pos - self.currentPeriod * 2, pos + self.currentPeriod * self.beatsPerBoard)] @@ -754,7 +755,7 @@ def coOpRescue(self, pos): self.coOpRestart = True #initializes Restart Timer self.coOpRescueTime = pos self.starPower = 0 - Log.debug("Rescued at " + str(pos)) + log.debug("Rescued at " + str(pos)) def noteBeingHeld(self): noteHeld = False @@ -1238,7 +1239,7 @@ def renderNotes(self, visibility, song, pos): elif self.coOpRescueTime + (self.currentPeriod * self.beatsPerBoard * 2) < pos: self.coOpFailed = False self.coOpRestart = False - Log.debug("Turning off coOpFailed. Rescue successful.") + log.debug("Turning off coOpFailed. Rescue successful.") else: continue #can't break. Tempo. @@ -1315,7 +1316,7 @@ def renderNotes(self, visibility, song, pos): if self.starPower < 50 and self.isDrum: #not enough starpower to activate yet, kill existing drumfills for dfEvent in self.drumFillEvents: dfEvent.happened = True - Log.debug("star power added") + log.debug("star power added") if self.gameMode2p == 6 and not self.isDrum: if self.battleSuddenDeath: self.battleObjects = [1] + self.battleObjects[:2] @@ -1323,7 +1324,7 @@ def renderNotes(self, visibility, song, pos): self.battleObjects = [self.battleObjectsEnabled[random.randint(0,len(self.battleObjectsEnabled)-1)]] + self.battleObjects[:2] self.battleGetTime = pos self.battleObjectGained = True - Log.debug("Battle Object Gained, Objects %s" % str(self.battleObjects)) + log.debug("Battle Object Gained, Objects %s" % str(self.battleObjects)) else: if self.starPower < 100: @@ -1433,7 +1434,7 @@ def renderOpenNotes(self, visibility, song, pos): elif self.coOpRescueTime + (self.currentPeriod * self.beatsPerBoard * 2) < pos: self.coOpFailed = False self.coOpRestart = False - Log.debug("Turning off coOpFailed. Rescue successful.") + log.debug("Turning off coOpFailed. Rescue successful.") else: continue #can't break. Tempo. @@ -1986,7 +1987,7 @@ def renderTails(self, visibility, song, pos, killswitch): elif self.coOpRescueTime + (self.currentPeriod * self.beatsPerBoard * 2) < pos: self.coOpFailed = False self.coOpRestart = False - Log.debug("Turning off coOpFailed. Rescue successful.") + log.debug("Turning off coOpFailed. Rescue successful.") else: continue diff --git a/fofix/game/guitarscene/instruments/ProGuitar.py b/fofix/game/guitarscene/instruments/ProGuitar.py index 78eca1878..f3cc9d7a0 100644 --- a/fofix/game/guitarscene/instruments/ProGuitar.py +++ b/fofix/game/guitarscene/instruments/ProGuitar.py @@ -25,12 +25,13 @@ from OpenGL.GL import * +from fretwork import log + from fofix.game.guitarscene.instruments.Guitar import Guitar from fofix.game.Song import Note, Tempo from fofix.core.Image import draw3Dtex from fofix.core.Shader import shaders from fofix.core.Mesh import Mesh -from fofix.core import Log class ProGuitar(Guitar): @@ -240,7 +241,7 @@ def renderNotes(self, visibility, song, pos): elif self.coOpRescueTime + (self.currentPeriod * self.beatsPerBoard * 2) < pos: self.coOpFailed = False self.coOpRestart = False - Log.debug("Turning off coOpFailed. Rescue successful.") + log.debug("Turning off coOpFailed. Rescue successful.") else: continue #can't break. Tempo. @@ -302,7 +303,7 @@ def renderNotes(self, visibility, song, pos): if self.starPower < 50: #not enough starpower to activate yet, kill existing drumfills for dfEvent in self.drumFillEvents: dfEvent.happened = True - Log.debug("star power added") + log.debug("star power added") if self.gameMode2p == 6 and not self.isDrum: if self.battleSuddenDeath: self.battleObjects = [1] + self.battleObjects[:2] @@ -310,7 +311,7 @@ def renderNotes(self, visibility, song, pos): self.battleObjects = [self.battleObjectsEnabled[random.randint(0,len(self.battleObjectsEnabled)-1)]] + self.battleObjects[:2] self.battleGetTime = pos self.battleObjectGained = True - Log.debug("Battle Object Gained, Objects %s" % str(self.battleObjects)) + log.debug("Battle Object Gained, Objects %s" % str(self.battleObjects)) else: if self.starPower < 100: self.starPower += 25 diff --git a/fofix/game/guitarscene/instruments/Vocalist.py b/fofix/game/guitarscene/instruments/Vocalist.py index d5f151d97..0c6b476ba 100644 --- a/fofix/game/guitarscene/instruments/Vocalist.py +++ b/fofix/game/guitarscene/instruments/Vocalist.py @@ -28,14 +28,14 @@ from OpenGL.GL import * import numpy as np +from fretwork import log + from fofix.core.Microphone import Microphone from fofix.core.Image import ImgDrawing from fofix.game.Song import VocalNote from fofix.core.constants import * from fofix.core.Language import _ from fofix.core import cmgl -from fofix.core import Log - diffMod = {0: 1.4, 1: 1.6, 2: 1.75, 3: 1.9} baseScores = {0: 1000, 1: 800, 2: 400, 3: 200} @@ -216,7 +216,7 @@ def __init__(self, engine, playerObj, scene, player = 0): dispOverlay = ImgDrawing(self.engine.data.svg, overlay) self.drawnVocalOverlays[degrees] = dispOverlay except: - Log.error('Could not prebuild vocal overlay textures: ') + log.error('Could not prebuild vocal overlay textures: ') self.vocalContinuousAvailable = False self.vocalLaneSize = self.engine.theme.vocalLaneSize @@ -409,7 +409,7 @@ def coOpRescue(self, pos): self.coOpRestart = True #initializes Restart Timer self.coOpRescueTime = 3000 self.starPower = 0 - Log.debug("Rescued at " + str(pos)) + log.debug("Rescued at " + str(pos)) def render(self, visibility, song, pos, players): font = self.engine.data.font @@ -452,7 +452,7 @@ def render(self, visibility, song, pos, players): if self.coOpRestart: self.coOpFailed = False self.coOpRestart = False - Log.debug("Turning off coOpFailed. Rescue successful.") + log.debug("Turning off coOpFailed. Rescue successful.") else: return if self.useOld: diff --git a/setup.py b/setup.py index e28dc3a5e..afadab1d7 100644 --- a/setup.py +++ b/setup.py @@ -294,22 +294,14 @@ def def_split(x): ogg_info = pc_info('ogg') -vorbisfile_info = pc_info('vorbisfile') -sdl_info = pc_info('sdl') -sdl_mixer_info = pc_info('SDL_mixer') theoradec_info = pc_info('theoradec') glib_info = pc_info('glib-2.0') -gthread_info = pc_info('gthread-2.0') swscale_info = pc_info('libswscale') -soundtouch_info = pc_info('soundtouch', ['soundtouch-1.4', 'soundtouch-1.0']) if os.name == 'nt': # Windows systems: we just know what the OpenGL library is. gl_info = {'libraries': ['opengl32']} # And glib needs a slight hack to work correctly. glib_info['define_macros'].append(('inline', '__inline')) - # And we use the prebuilt soundtouch-c. - soundtouch_info['libraries'].append('soundtouch-c') - extra_soundtouch_src = [] else: # Other systems: we ask pkg-config. try: @@ -324,8 +316,6 @@ def def_split(x): 'libraries': [], 'library_dirs': [], } - # And build our own soundtouch-c. - extra_soundtouch_src = ['fofix/core/MixStream/soundtouch-c.cpp'] # Build a similar info record for the numpy headers. numpy_info = {'include_dirs': [np.get_include()]} @@ -442,10 +432,6 @@ def run(self): ['fofix/core/VideoPlayer/_VideoPlayer.pyx', 'fofix/core/VideoPlayer/VideoPlayer.c'], **combine_info(gl_info, ogg_info, theoradec_info, glib_info, swscale_info, {'include_dirs': ['.']})), - Extension('fofix.lib._MixStream', - ['fofix/core/MixStream/_MixStream.pyx', 'fofix/core/MixStream/MixStream.c', - 'fofix/core/MixStream/vorbis.c'] + extra_soundtouch_src, - **combine_info(vorbisfile_info, soundtouch_info, glib_info, gthread_info, sdl_info, sdl_mixer_info)), ], 'cmdclass': {'build_ext': build_ext, 'install': install, 'msgfmt': msgfmt, 'xgettext': xgettext}, })