code
stringlengths
1
1.72M
language
stringclasses
1 value
##################################################################### # -*- coding: iso-8859-1 -*- # # # # FoFiX # # Copyright (C) 2009 Pascal Giard <evilynux@gmail.com> # # # # 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 unittest try: import hashlib except ImportError: import sha class hashlib: sha1 = sha.sha import Cerealizer import binascii import urllib class CerealizerTest(unittest.TestCase): def setUp(self): difficulty = 0 # Expert score = 123456 # Final score nbrStars = 4 # Number of stars name = "SomePlayer" # Player name scoreHash = hashlib.sha1("%d%d%d%s" % (difficulty, score, nbrStars, name) ).hexdigest() self.scores = {} self.scores[difficulty] = [(score, nbrStars, name, scoreHash)] def testIntegrity(self): expected = self.scores scoresSerial = binascii.hexlify(Cerealizer.dumps(self.scores)) result = Cerealizer.loads(binascii.unhexlify(scoresSerial)) self.assertEqual(result, expected) def testHash(self): # For the record, the worldchart rejects those hashes: scoresHash = "63657265616c310a330a646963740a6c6973740a7475706c650a340a"\ "6936333834360a69350a7531310a50617363616c4769617264733430"\ "0a343839666538656632343239646564373637363835373930303936"\ "31323531633136303662373863310a72310a69310a310a72320a72300a" scores = Cerealizer.loads(binascii.unhexlify(scoresHash)) #print scores[1][0][2] self.assertEqual(scores[1][0][2], "PascalGiard") #scoreExtHash = "63657265616c310a330a646963740a6c6973740a7475706c650a"\ # "390a7334300a3438396665386566323432396465643736373638"\ # "353739303039363132353163313630366237386369350a693236"\ # "310a693237300a6937320a7331310a466f4669582d332e313030"\ # "69300a73300a6936333834360a310a72310a69310a310a72320a"\ # "72300a" #songHash = "6551c0f99efddfd3c5c7ef2d407c81b8e3001a43" if __name__ == "__main__": unittest.main()
Python
##################################################################### # -*- coding: iso-8859-1 -*- # # # # Frets on Fire X (FoFiX) # # Copyright (C) 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. # ##################################################################### # Most of this code is derived from the pitch analyzer in Performous, # which is licensed under the GPL version 2 or later. # This code performs very close to as well as pypitch did; it started as # a direct Python translation of the C++ code (except for stuff like the # fast Fourier transform) and was then optimized by hand to remove quite # a bit of unnecessary stuff and to make numpy do all the heavy lifting. # (Four lines of commentary that align perfectly... what about a fifth?) import math import numpy FORMANT_RANGE = [(300, 1300), (700, 2400), (1800, 3300), (3000, 4400)] try: # This is only guaranteed to do the right thing under Python 2.6 or later # (see PEP 754). Otherwise, we must hope that the underlying C runtime # will let this work... NEGINF = float('-inf') except: # Another way to do it, but it's not anywhere near as elegant. NEGINF = -1e300000 # Limit range to avoid noise and useless computation FFT_MINFREQ = 45.0 FFT_MAXFREQ = 5000.0 class Tone(object): MAXHARM = 48 # maximum harmonics MINAGE = 2 # minimum age def __init__(self): self.freq = 0.0 self.db = NEGINF self.stabledb = NEGINF self.harmonics = [NEGINF] * self.MAXHARM self.age = 0 def __str__(self): if self.age >= self.MINAGE: return '%.1f Hz, age %f, dB: %f %f %f %f %f %f %f %f' % ([self.freq, self.age, self.db] + self.harmonics[:8]) else: return '' def __cmp__(self, rhs): if isinstance(rhs, float): diff = self.freq / rhs - 1.0 if abs(diff) < 0.05: return 0 elif diff < 0.0: return -1 else: return 1 elif isinstance(rhs, Tone): return self.__cmp__(rhs.freq) else: return NotImplemented FFT_P = 10 FFT_N = 1 << FFT_P class Analyzer(object): def __init__(self, rate, step=200): self.step = step self.rate = rate self.peak = 0.0 self.oldfreq = 0.0 self.inputBuffer = [] self.tones = [] # Use a Hamming window. # The numpy function to make one isn't this precise. self.window = numpy.array([0.53836 - 0.46164 * math.cos(2.0 * math.pi * i / (FFT_N - 1)) for i in range(FFT_N)]) # Precalculate some constants used in the analysis code. self.freqPerBin = self.rate / FFT_N self.phaseStep = 2.0 * math.pi * self.step / FFT_N self.normCoeff = 1.0 / FFT_N self.minMagnitude = pow(10, -100.0 / 20.0) / self.normCoeff # -100 dB # Limit the frequency range processed. self.kMin = max(1, int(FFT_MINFREQ / self.freqPerBin)) self.kMax = min(FFT_N / 2, int(FFT_MAXFREQ / self.freqPerBin)) self.fftLastPhase = numpy.zeros(self.kMax) self.peakDecayFactor = numpy.power(0.999, numpy.arange(4096, -1, -1)) # 4097 elements on purpose def input(self, ary): '''Add input data to buffer.''' if len(ary) > 4096: raise ValueError, 'Input array is too long (4096 samples max)' # Update the peak dB level. peakary = numpy.concatenate((numpy.array([self.peak]), numpy.square(ary))) self.peak = (peakary * self.peakDecayFactor[-len(peakary):]).max() if len(self.inputBuffer) > 0 and len(self.inputBuffer[0]) < FFT_N: deficit = FFT_N - len(self.inputBuffer[0]) if len(ary) <= deficit: self.inputBuffer[0] = numpy.concatenate((self.inputBuffer[0], ary)) return else: self.inputBuffer[0] = numpy.concatenate((self.inputBuffer[0], ary[:deficit])) remainingInput = ary[deficit:] else: remainingInput = ary[:] while len(remainingInput) >= FFT_N: self.inputBuffer.insert(0, remainingInput[:FFT_N]) remainingInput = remainingInput[FFT_N:] if len(remainingInput) > 0: self.inputBuffer.insert(0, remainingInput[:]) def getPeak(self): '''Get the peak level in dB (negative value; 0.0 = clipping).''' try: return 10.0 * math.log10(self.peak) except (OverflowError, ValueError): return NEGINF def getTones(self): '''Get a list of all tones detected.''' return self.tones def getFormants(self): if len(self.tones) == 0: return [None] *3 formants = [0] for fNum in range(3): minfreq = FORMANT_RANGE[fNum][0] maxfreq = FORMANT_RANGE[fNum][1] maxtone = None for t in self.tones: if t.freq < minfreq or t.freq > maxfreq or t.age < Tone.MINAGE: continue if t.freq < formants[fNum]: continue if maxtone: if t.db > maxtone.db: maxtone = t else: maxtone = t if maxtone: formants.append(maxtone.freq) else: formants.append(None) formants.remove(0) return formants def findTone(self, minfreq=70.0, maxfreq=700.0): '''Find a tone within the singing range; prefer strong tones around 200-400 Hz.''' if len(self.tones) == 0: self.oldfreq = 0.0 return None db = max(tone.db for tone in self.tones) best = None bestscore = 0.0 for t in self.tones: if t.db < db - 20.0 or t.freq < minfreq or t.age < Tone.MINAGE: continue if t.freq > maxfreq: break score = t.db - max(180.0, abs(t.freq - 300.0)) / 10.0 if self.oldfreq != 0.0 and abs(t.freq / self.oldfreq - 1.0) < 0.05: score += 10.0 if best is not None and bestscore > score: break best = t bestscore = score if best is not None: self.oldfreq = best.freq else: self.oldfreq = 0.0 return best def process(self): '''Process all data input so far.''' # Instead of Peak objects, two numpy arrays (peakFreqs and peakDbs) are used. def match(peakDbs, pos): best = pos if peakDbs[pos-1] > peakDbs[best]: best = pos - 1 if peakDbs[pos+1] > peakDbs[best]: best = pos + 1 return best while len(self.inputBuffer) > 0 and len(self.inputBuffer[-1]) == FFT_N: self.fft = numpy.fft.fft(self.inputBuffer.pop() * self.window) magnitudes = numpy.absolute(self.fft[1:self.kMax+1]) phases = numpy.angle(self.fft[1:self.kMax+1]) # Process the phase difference. deltas = phases - self.fftLastPhase self.fftLastPhase = phases deltas -= numpy.arange(1, self.kMax+1) * self.phaseStep # expected phase difference deltas = numpy.fmod(deltas, 2.0 * math.pi) # map into (-2pi,2pi) deltas /= self.phaseStep # difference from bin center frequency peakFreqs = numpy.zeros(self.kMax+1) peakDbs = numpy.zeros(self.kMax+1) # Also prefilter peaks. prevdb = 0.0 for k in range(1, self.kMax+1): freq = (k + deltas[k-1]) * self.freqPerBin # true frequency db = magnitudes[k-1] # 20.0 * log10(this value * self.normCoeff) comes a bit later if freq > 1.0 and magnitudes[k-1] > self.minMagnitude: if db > prevdb: peakFreqs[k-1], peakDbs[k-1] = 0.0, 0.0 peakFreqs[k], peakDbs[k] = freq, db else: peakFreqs[k], peakDbs[k] = 0.0, 0.0 prevdb = db else: peakFreqs[k], peakDbs[k] = 0.0, 0.0 prevdb = 0.0 peakDbs = numpy.log10(peakDbs * self.normCoeff) * 20.0 # Find the tones (collections of harmonics) from the array of peaks. tones = [] for k in range(self.kMax-1, self.kMin-1, -1): if peakDbs[k] < -70.0: continue # Find the best divisor for getting the fundamental from peaks[k]. bestDiv = 1 bestScore = 0 for div in range(2, Tone.MAXHARM + 1): if k / div > 1: break freq = peakFreqs[k] / div # fundamental score = 0 for n in range(1, min(div, 8)): p = match(peakDbs, k * n / div) score -= 1 if peakDbs[p] < -90.0 or abs(peakFreqs[p] / n / freq - 1.0) > 0.03: continue if n == 1: # bonus for fundamental score += 4 score += 2 if score > bestScore: bestScore = score bestDiv = div # Make the Tone object from the fundamental (freq) and all harmonics. t = Tone() count = 0 freq = peakFreqs[k] / bestDiv t.db = peakDbs[k] for n in range(1, bestDiv+1): # Find the peak for the nth harmonic. p = match(peakDbs, k * n / bestDiv) if abs(peakFreqs[p] / n / freq - 1.0) > 0.03: # fundamental? continue if peakDbs[p] > t.db - 10.0: t.db = max(t.db, peakDbs[p]) count += 1 t.freq += peakFreqs[p] / n t.harmonics[n-1] = peakDbs[p] peakFreqs[p], peakDbs[p] = 0.0, NEGINF t.freq /= count # If the tone seems strong enough, add it. # (-3 dB compensation for each harmonic) if t.db > -50.0 - 3.0 * count: t.stabledb = t.db tones.append(t) tones.sort() i = 0 for oldtone in self.tones: while i < len(tones) and tones[i] < oldtone: i += 1 if i == len(tones) or tones[i] != oldtone: if oldtone.db > -80.0: tones.insert(i, oldtone) tones[i].db -= 5.0 tones[i].stabledb -= 0.1 i += 1 elif tones[i] == oldtone: tones[i].age = oldtone.age + 1 tones[i].stabledb = 0.8 * oldtone.stabledb + 0.2 * tones[i].db tones[i].freq = (oldtone.freq + tones[i].freq) / 2.0 self.tones = tones
Python
# pitchbend - pitch-bend the output of the SDL mixer # Copyright (C) 2008-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, see <http://www.gnu.org/licenses/>. #__version__ = '$Id: svntag.py 5 2009-01-01 05:00:35Z stump $' import os def get_svn_info(path='.'): f = open(os.path.join(path, '.svn', 'entries')) f.readline(200) f.readline(200) f.readline(200) num_str = f.readline(200).strip() repo_str = f.readline(200).strip() f.readline(200) f.readline(200) f.readline(200) f.readline(200) #date_str, time_str = f.readline(200).strip().partition('T')[::2] #return {'revnum': num_str, 'repo': repo_str, 'date': date_str, 'time': time_str} return {'revnum': num_str, 'repo': repo_str} if __name__ == '__main__': import sys try: print repr(get_svn_info(sys.argv[1])) except IndexError: print repr(get_svn_info())
Python
##################################################################### # -*- coding: iso-8859-1 -*- # # # # Frets on Fire X (FoFiX) # # Copyright (C) 2009 Team FoFiX # # 2009 akedrou # # # # 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 Log import os from Language import _ from Microphone import Microphone, getNoteName from Song import VocalNote, VocalPhrase from OpenGL.GL import * from numpy import array, float32 from random import random import Theme #stump: needed for continuous star fillup (akedrou - stealing for vocals) import Image import ImageDraw from Svg import ImgDrawing diffMod = {0: 1.4, 1: 1.6, 2: 1.75, 3: 1.9} class Vocalist: def __init__(self, engine, playerObj, editorMode = False, player = 0): self.engine = engine self.mic = Microphone(self.engine, playerObj.controller) #Get theme themename = self.engine.data.themeLabel #now theme determination logic is only in data.py: self.theme = self.engine.data.theme self.showData = self.engine.config.get("debug", "show_raw_vocal_data") #unused variables for compatibility with other instrument classes self.isDrum = False self.isBassGuitar = False self.isVocal = True self.canGuitarSolo = False self.guitarSolo = False self.useMidiSoloMarkers = False self.neckrender = None self.earlyHitWindowSizeFactor = 0 self.starNotesSet = True self.spEnabled = False self.bigRockEndingMarkerSeen = False self.freestyleStart = 0 self.freestyleFirstHit = 0 self.freestyleLength = 0 self.freestyleBonusFret = 0 self.freestyleLastFretHitTime = [0 for i in range(5)] self.twoChord = False self.leftyMode = False self.drumFlip = False self.keys = [] self.actions = [] self.neckSpeed = 0.0 self.hitw = 1.4 self.lateMargin = 100.0 self.earlyMargin = 100.0 self.oldNote = 2.0 self.pitchFudge = 0 self.barFudge = 600 self.stayEnd = 0 self.awardEnd = True self.formants = [None] * 3 self.currentNote = None self.currentNoteItem = None self.currentNoteTime = 0 self.currentLyric = None self.requiredNote = None self.lastPhrase = None self.phrase = None self.tapping = False self.activePhrase = None self.nextPhrase = None self.currentPhraseTime = 0 self.currentPhraseLength = 0 self.phraseMin = 0 self.phraseMax = 0 self.phraseTimes = [] self.doneLastPhrase = False #scoring variables self.allowedDeviation = 1.4 self.scoreThresholds = [.95, .80, .60, .40, .20, 0] self.scoredPhrases = [0 for i in self.scoreThresholds] self.scoreMultiplier = 1 self.totalPhrases = 0 self.starPhrases = [] self.phraseInTune = 0 self.phraseNoteTime = 0 self.phraseTaps = 0 self.phraseTapsHit = 0 self.lastPos = 0 self.showText = 0 self.textTrans = 0 self.scoreBox = (0,1) self.scorePhrases = [_("Amazing!"), _("Great!"), _("Decent"), _("Average"), _("Meh"), _("Bad"), _("Terrible...")] self.textScore = -1 self.lastScore = -1 self.coOpRB = False self.phraseIndex = 0 self.lyricMode = self.engine.config.get("game", "midi_lyric_mode") self.nstype = self.engine.config.get("game", "vocal_scroll") self.speed = self.engine.config.get("game", "vocal_speed")*0.01 self.actualBpm = 0 self.currentBpm = 120.0 self.lastBpmChange = -1.0 self.baseBeat = 0.0 self.currentPeriod = 60000.0 self.oldTime = 0 self.oldLength = 0 self.useOld = False self.arrowVis = 0 self.minPitch = 0 self.maxPitch = 0 self.pitchRange = 0 #akedrou self.coOpFailed = False self.coOpRestart = False self.coOpRescueTime = 0 self.lyricScale = .00170 self.engine.loadImgDrawing(self, "vocalLyricSheet", os.path.join(self.engine.data.vocalPath,"lyricsheet.png")) imgwidth = self.vocalLyricSheet.width1() self.vocalLyricSheetWFactor = 640.000/imgwidth try: self.engine.loadImgDrawing(self, "vocalLyricSheetGlow", os.path.join(self.engine.data.vocalPath,"lyricsheetglow.png")) imgwidth = self.vocalLyricSheetGlow.width1() self.vocalLyricSheetGlowWFactor = 640.000/imgwidth except: self.vocalLyricSheetGlow = None try: self.engine.loadImgDrawing(self, "vocalLyricSheetSP", os.path.join(self.engine.data.vocalPath,"lyricsheetactivate.png")) self.vocalSheetSPWidth = float(self.vocalLyricSheetSP.width1()*self.vocalLyricSheetWFactor)*(self.engine.view.geometry[2]/640.0) except: self.vocalLyricSheetSP = None self.engine.loadImgDrawing(self, "vocalArrow", os.path.join(self.engine.data.vocalPath,"arrow.png")) try: self.engine.loadImgDrawing(self, "vocalSplitArrow", os.path.join(self.engine.data.vocalPath,"split_arrow.png")) except IOError: self.vocalSplitArrow = self.vocalArrow self.engine.loadImgDrawing(self, "vocalBar", os.path.join(self.engine.data.vocalPath,"beatline.png")) self.arrowW = self.vocalArrow.width1() self.engine.loadImgDrawing(self, "vocalMult", os.path.join(self.engine.data.vocalPath,"mult.png")) self.engine.loadImgDrawing(self, "vocalMeter", os.path.join(self.engine.data.vocalPath,"meter.png")) try: self.engine.loadImgDrawing(self, "vocalFill", os.path.join(self.engine.data.vocalPath,"meter_fill.png")) except IOError: self.vocalFill = self.vocalMeter try: self.engine.loadImgDrawing(self, "vocalGlow", os.path.join(self.engine.data.vocalPath,"meter_glow.png")) except IOError: self.vocalGlow = None self.engine.loadImgDrawing(self, "vocalTap", os.path.join(self.engine.data.vocalPath,"tap.png")) self.engine.loadImgDrawing(self, "vocalTapNote", os.path.join(self.engine.data.vocalPath,"tap_note.png")) try: self.engine.loadImgDrawing(self, "vocalText", os.path.join(self.engine.data.vocalPath,"text.png")) except IOError: self.vocalText = None self.engine.loadImgDrawing(self, "vocalODBottom", os.path.join(self.engine.data.vocalPath,"bottom.png")) self.engine.loadImgDrawing(self, "vocalODFill", os.path.join(self.engine.data.vocalPath,"fill.png")) self.vocalODFillWidth = self.vocalODFill.width1()/1280.000 try: self.engine.loadImgDrawing(self, "vocalODTop", os.path.join(self.engine.data.vocalPath,"top.png")) except IOError: self.vocalODTop = None try: self.engine.loadImgDrawing(self, "vocalODGlow", os.path.join(self.engine.data.vocalPath,"glow.png")) except IOError: self.vocalODGlow = None height = self.vocalMeter.height1() vocalSize = Theme.vocalMeterSize self.vocalMeterScale = (vocalSize/height)*.5 self.vocalFillWidth = self.vocalFill.width1()*self.vocalMeterScale/640.000 olFactor = height/Theme.vocalFillupFactor self.vocalFillupCenterX = int(Theme.vocalFillupCenterX*olFactor) self.vocalFillupCenterY = int(Theme.vocalFillupCenterY*olFactor) self.vocalFillupInRadius = int(Theme.vocalFillupInRadius*olFactor) self.vocalFillupOutRadius = int(Theme.vocalFillupOutRadius*olFactor) self.vocalFillupColor = Theme.vocalFillupColor self.vocalContinuousAvailable = Theme.vocalCircularFillup and \ None not in (self.vocalFillupCenterX, self.vocalFillupCenterY, self.vocalFillupInRadius, self.vocalFillupOutRadius, self.vocalFillupColor) if self.vocalContinuousAvailable: try: self.drawnVocalOverlays = {} baseVocalFillImageSize = Image.open(self.vocalMeter.texture.name).size for degrees in range(0, 361, 5): overlay = Image.new('RGBA', baseVocalFillImageSize) draw = ImageDraw.Draw(overlay) draw.pieslice((self.vocalFillupCenterX-self.vocalFillupOutRadius, self.vocalFillupCenterY-self.vocalFillupOutRadius, self.vocalFillupCenterX+self.vocalFillupOutRadius, self.vocalFillupCenterY+self.vocalFillupOutRadius), -90, degrees-90, outline=self.vocalFillupColor, fill=self.vocalFillupColor) draw.ellipse((self.vocalFillupCenterX-self.vocalFillupInRadius, self.vocalFillupCenterY-self.vocalFillupInRadius, self.vocalFillupCenterX+self.vocalFillupInRadius, self.vocalFillupCenterY+self.vocalFillupInRadius), outline=(0, 0, 0, 0), fill=(0, 0, 0, 0)) dispOverlay = ImgDrawing(self.engine.data.svg, overlay) self.drawnVocalOverlays[degrees] = dispOverlay except: Log.error('Could not prebuild vocal overlay textures: ') self.vocalContinuousAvailable = False self.vocalLaneSize = Theme.vocalLaneSize self.vocalGlowSize = Theme.vocalGlowSize self.vocalGlowFade = Theme.vocalGlowFade self.vocalLaneColor = list(Theme.vocalLaneColor) self.vocalShadowColor = list(Theme.vocalShadowColor) self.vocalGlowColor = list(Theme.vocalGlowColor) self.vocalLaneColorStar = list(Theme.vocalLaneColorStar) self.vocalShadowColorStar = list(Theme.vocalShadowColorStar) self.vocalGlowColorStar = list(Theme.vocalGlowColorStar) self.lastVal = 0 self.vocalMeterX = Theme.vocalMeterX self.vocalMeterY = Theme.vocalMeterY self.vocalMultX = Theme.vocalMultX self.vocalMultY = Theme.vocalMultY self.vocalPowerX = Theme.vocalPowerX self.vocalPowerY = Theme.vocalPowerY self.time = 0.0 self.tap = 0 self.tapBuffer = 0 self.peak = -100.0 self.starPowerDecreaseDivisor = 400.0/self.engine.audioSpeedFactor self.starPower = 0 self.starPowerActive = False self.starPowerGained = False self.starPowerEnable = False self.starPowerCountdown = False self.starPowerTimer = 200 self.starPowerActivate = False self.paused = False self.player = player self.tapPartStart = [] self.tapPartLength = [] self.tapNoteTotals = [] self.tapNoteHits = [] self.tapPhraseActive = False self.currentTapPhrase = -1 self.difficulty = playerObj.getDifficultyInt() self.tapMargin = 100 + (100 * self.difficulty) self.tapBufferMargin = 300 - (50 * self.difficulty) self.accuracy = 5000 - (self.difficulty * 1000) self.difficultyModifier = diffMod[self.difficulty] #Controls Jurgen in vocal parts self.jurgenEnabled = False self.jurgenSkill = 5 def setBPM(self, bpm): if bpm > 200: bpm = 200 self.currentBpm = bpm if self.nstype == 0: #BPM mode self.currentPeriod = (60000.0/bpm)/self.speed elif self.nstype == 1: #Difficulty mode if self.difficulty == 0: #expert self.currentPeriod = 333/self.speed elif self.difficulty == 1: self.currentPeriod = 417/self.speed elif self.difficulty == 2: self.currentPeriod = 500/self.speed else: #easy self.currentPeriod = 583/self.speed elif self.nstype == 2: #BPM & Diff mode if self.difficulty == 0: #expert self.currentPeriod = (40000.0/bpm)/self.speed elif self.difficulty == 1: self.currentPeriod = (50000.0/bpm)/self.speed elif self.difficulty == 2: self.currentPeriod = (60000.0/bpm)/self.speed else: #easy self.currentPeriod = (70000.0/bpm)/self.speed self.neckSpeed = self.currentPeriod self.earlyMargin = 250 - bpm/5 - 70*self.hitw self.lateMargin = 250 - bpm/5 - 70*self.hitw def getMultVals(self): if not self.starPowerActive: return (self.scoreMultiplier-1, self.scoreMultiplier) elif not self.coOpRB: multDict = {1: (4,5), 2: (6,7), 3: (7,8), 4: (8,9)} return multDict[self.scoreMultiplier] else: multDict = {1: (0,1), 2: (4,5), 3: (5,6), 4: (6,7)} return multDict[self.scoreMultiplier] def getScoreChange(self): if self.lastScore > -1: score = 5 - self.lastScore self.lastScore = -1 return score else: return None def getJurgenPct(self): #Controls Jurgen in vocal parts j = self.jurgenSkill if not self.jurgenEnabled: return 1 if j == 0: return min((.70 + (.05*self.difficulty*random())), 1) elif j == 1: return min((.80 + (.05*self.difficulty*random())), 1) elif j == 2: return min((.85 + (.05*self.difficulty*random())), 1) elif j == 3: return min((.90 + (.05*self.difficulty*random())), 1) elif j == 4: return min((.95 + (.05*self.difficulty*random())), 1) else: return 1 def getCurrentNote(self, pos): if not self.mic.mic_started: return if self.tapPhraseActive: if self.requiredNote is not None: if (self.tap > 0 or self.jurgenEnabled) and not self.currentNoteItem.played: self.tapNoteHits[self.currentTapPhrase] += 1 self.phraseTapsHit += 1 self.currentNoteItem.played = True self.lastPos = pos self.currentNote = self.tap return if not self.jurgenEnabled: self.peak = self.mic.getPeak() self.formants = self.mic.getFormants() else: self.peak = -10 self.formants = [100, 600] if self.currentNote is not None: if abs(self.currentNote) < self.allowedDeviation: self.oldNote = self.currentNote if self.peak < -15: self.starPowerCountdown = False self.starPowerTimer = 200 elif self.requiredNote is not None: if self.jurgenEnabled: self.currentNote = 0.0 else: self.currentNote = self.mic.getDeviation(self.requiredNote) #if self.awardEnd: # mult = .8 #else: mult = 1 if self.currentNote is not None: if self.currentNoteItem.speak or self.currentNoteItem.extra: self.currentNote = 0 if abs(self.currentNote) < self.allowedDeviation and self.formants[1] is not None: duration = pos - self.lastPos self.currentNoteItem.accuracy += duration*mult*self.getJurgenPct() self.phraseInTune += duration*self.difficultyModifier*mult*self.getJurgenPct() self.pitchFudge = 70.0 # elif self.currentNoteItem.played and self.stayEnd <= 0 and self.awardEnd: # self.currentNoteItem.accuracy += self.currentNoteItem.length * (1-mult) # self.phraseInTune += self.currentNoteItem.length * (1-mult) *self.difficultyModifier # self.pitchFudge = 0.0 elif abs(self.oldNote) < self.allowedDeviation and self.pitchFudge > 0: duration = pos - self.lastPos self.currentNoteItem.accuracy += duration * (self.pitchFudge/100.0) self.phraseInTune += duration*self.difficultyModifier else: if self.starPowerEnable: self.starPowerCountdown = True self.currentNote = self.mic.getDeviation(6) self.lastPos = pos #stump: draw a vocal note lane, vaguely RB2-style def drawNoteLane(self, colors, xStartPos, xEndPos, yStartPos, yEndPos): colorArray = array([colors[i] for i in (4, 5, 6, 6, 0, 1, 1, 0, 2, 3, 3, 2, 6, 6, 5, 4)], dtype=float32) vertexArray = array([[xStartPos, yStartPos-self.vocalLaneSize, 0], [xEndPos, yEndPos -self.vocalLaneSize, 0], [xEndPos, yEndPos -self.vocalGlowSize, 0], [xStartPos, yStartPos-self.vocalGlowSize, 0], [xStartPos-self.vocalLaneSize, yStartPos, 0], [xEndPos +self.vocalLaneSize, yEndPos, 0], [xEndPos, yEndPos -self.vocalLaneSize, 0], [xStartPos, yStartPos-self.vocalLaneSize, 0], [xStartPos, yStartPos+self.vocalLaneSize, 0], [xEndPos, yEndPos +self.vocalLaneSize, 0], [xEndPos +self.vocalLaneSize, yEndPos, 0], [xStartPos-self.vocalLaneSize, yStartPos, 0], [xStartPos, yStartPos+self.vocalGlowSize, 0], [xEndPos, yEndPos +self.vocalGlowSize, 0], [xEndPos, yEndPos +self.vocalLaneSize, 0], [xStartPos, yStartPos+self.vocalLaneSize, 0]], dtype=float32) glEnableClientState(GL_VERTEX_ARRAY) glEnableClientState(GL_COLOR_ARRAY) glVertexPointerf(vertexArray) glColorPointerf(colorArray) glDrawArrays(GL_QUADS, 0, len(colorArray)) glDisableClientState(GL_COLOR_ARRAY) glDisableClientState(GL_VERTEX_ARRAY) def coOpRescue(self, pos): self.coOpRestart = True #initializes Restart Timer self.coOpRescueTime = 3000 self.starPower = 0 Log.debug("Rescued at " + str(pos)) def render(self, visibility, song, pos, players): font = self.engine.data.font w, h = self.engine.view.geometry[2:4] height = (self.vocalLyricSheet.height1())/480.000 if players == 1: addY = .7 addYText = .725*self.engine.data.fontScreenBottom vsheetpos = (h*(1-addY))-(h*(height/2)) tappos = (h*(1-(addY-.02)))-(h*(height/2)) else: addY = 0 addYText = .025*self.engine.data.fontScreenBottom vsheetpos = (h*(1-addY))-(h*(height/2)) tappos = (h*(1-(addY-.02)))-(h*(height/2)) if not song: return glColor4f(1,1,1,1) if self.showData: if self.currentNote is None: font.render(_('None'), (.55, .25)) else: if abs(self.currentNote) < .5 and not self.tapPhraseActive: glColor3f(0,1,0) font.render(str(self.currentNote), (.55, .25)) if self.requiredNote is None: font.render(_('None'), (.25, .25)) else: if self.tapPhraseActive: if self.tap > 0: glColor3f(0,1,0) font.render(_("Tap!"), (.25, .25)) else: font.render("MIDI note %d" % self.requiredNote, (.25, .25)) if self.formants[1] is not None: font.render("Second Formant: %.2f Hz" % self.formants[1], (.35, .4)) self.engine.drawImage(self.vocalLyricSheet, scale = (self.vocalLyricSheetWFactor,-self.vocalLyricSheetWFactor), coord = (w*.5,vsheetpos)) if self.coOpFailed: return if self.useOld: phraseTime = self.oldTime phraseLength = self.oldLength else: phraseTime = self.currentPhraseTime phraseLength = self.currentPhraseLength if self.activePhrase: if self.lastPhrase and not self.coOpRestart: lastnotes = self.lastPhrase[1].getAllEvents() else: lastnotes = [] if self.coOpRestart: notes = [] else: notes = self.activePhrase.getAllEvents() if self.nextPhrase: if self.nextPhrase[0]-pos > self.coOpRescueTime: nextnotes = self.nextPhrase[1].getAllEvents() else: nextnotes = [] else: nextnotes = [] lastNoteEnd = None #stump for time, event in notes: if self.activePhrase.tapPhrase: if not event.played: if self.lyricMode == 0: x = time - pos if x < self.currentPeriod * 6 and x > -(self.currentPeriod * 2): noteX = (x/(self.currentPeriod * 8))+.25 self.engine.drawImage(self.vocalTapNote, scale = (.5,-.5), coord = (w*noteX,tappos)) elif self.lyricMode == 1 or self.lyricMode == 2: noteX = (.75*(time - phraseTime)/phraseLength)+.12 self.engine.drawImage(self.vocalTapNote, scale = (.5,-.5), coord = (w*noteX,tappos)) else: now = False if time <= pos and time + event.length > pos: now = True elif time > pos: if self.activePhrase.star: glColor4f(1,1,0,1) else: glColor4f(1,1,1,1) if self.lyricMode == 0: #scrolling xStart = time - pos xEnd = time + event.length - pos if xStart < self.currentPeriod * 6 and xEnd > -(self.currentPeriod * 2): xStartPos = (xStart/(self.currentPeriod * 8))+.25 xEndPos = (xEnd/(self.currentPeriod * 8))+.25 if event.speak or event.extra: val = .5 else: val = float(event.note-self.minPitch)/float(self.pitchRange) vStart = (xStartPos*4) vEnd = (xEndPos*4) if time < pos: if now: glColor4f(0,1,0,vStart) else: glColor4f(.5,.5,.5,vStart) font.render(event.lyric, (xStartPos, .085+addYText), scale = self.lyricScale) if not (event.speak or event.extra): #font.render("X", (xStartPos, .057-(.05*val)+addYText), scale = self.lyricScale) #stump: note lanes with RB2-like glow if players == 1: baseY = -.1-(.05*val)+addY else: baseY = .075-(.05*val)+addY if self.activePhrase.star: colors = [self.vocalLaneColorStar + [vStart], self.vocalLaneColorStar + [vEnd], self.vocalShadowColorStar + [vStart], self.vocalShadowColorStar + [vEnd], self.vocalGlowColorStar + [vStart*self.vocalGlowFade], self.vocalGlowColorStar + [vEnd*self.vocalGlowFade], self.vocalGlowColorStar + [0.0]] else: colors = [self.vocalLaneColor + [vStart], self.vocalLaneColor + [vEnd], self.vocalShadowColor + [vStart], self.vocalShadowColor + [vEnd], self.vocalGlowColor + [vStart*self.vocalGlowFade], self.vocalGlowColor + [vEnd*self.vocalGlowFade], self.vocalGlowColor + [0.0]] #stump: apparently we don't necessarily get the notes in strict chronological order. # This lane-connecting code would work nicely if not for that, but under these conditions it tends to make a big mess. # (Seriously, uncomment it and see for yourself.) if event.lyric is None and lastNoteEnd is not None: self.drawNoteLane(colors, lastNoteEnd[0], xStartPos, lastNoteEnd[1], baseY) self.drawNoteLane(colors, xStartPos, xEndPos, baseY, baseY) lastNoteEnd = (xEndPos, baseY) elif self.lyricMode == 1 or self.lyricMode == 2: #line-by-line xStart = time - phraseTime xEnd = time - phraseTime + event.length if xStart < self.currentPeriod * 6 and xEnd > -(self.currentPeriod * 2): xStartPos = (.75*(xStart/phraseLength))+.12 xEndPos = (.75*xEnd/phraseLength)+.12 if event.speak or event.extra: val = .5 else: val = float(event.note-self.minPitch)/float(self.pitchRange) vStart = (xStartPos*4) vEnd = (xEndPos*4) if time < pos: if now: glColor4f(0,1,0,vStart) else: glColor4f(.5,.5,.5,vStart) font.render(event.lyric, (xStartPos, .085+addYText), scale = self.lyricScale) if not (event.speak or event.extra): #font.render("X", (xStartPos, .057-(.05*val)+addYText), scale = self.lyricScale) #stump: note lanes with RB2-like glow if players == 1: baseY = -.1-(.05*val)+addY else: baseY = .075-(.05*val)+addY if self.activePhrase.star: colors = [self.vocalLaneColorStar + [vStart], self.vocalLaneColorStar + [vEnd], self.vocalShadowColorStar + [vStart], self.vocalShadowColorStar + [vEnd], self.vocalGlowColorStar + [vStart*self.vocalGlowFade], self.vocalGlowColorStar + [vEnd*self.vocalGlowFade], self.vocalGlowColorStar + [0.0]] else: colors = [self.vocalLaneColor + [vStart], self.vocalLaneColor + [vEnd], self.vocalShadowColor + [vStart], self.vocalShadowColor + [vEnd], self.vocalGlowColor + [vStart*self.vocalGlowFade], self.vocalGlowColor + [vEnd*self.vocalGlowFade], self.vocalGlowColor + [0.0]] if event.lyric is None and lastNoteEnd is not None: self.drawNoteLane(colors, lastNoteEnd[0], xStartPos, lastNoteEnd[1], baseY) self.drawNoteLane(colors, xStartPos, xEndPos, baseY, baseY) lastNoteEnd = (xEndPos, baseY) if self.lyricMode == 0: lastNoteEnd = None for time, event in lastnotes: if self.lastPhrase[1].tapPhrase: if not event.played: x = time - pos if x > -(self.currentPeriod * 2): noteX = (x/(self.currentPeriod * 8))+.25 self.engine.drawImage(self.vocalTapNote, scale = (.5,-.5), coord = (w*noteX,tappos)) else: xStart = time - pos xEnd = time + event.length - pos if xEnd > -(self.currentPeriod * 2): xStartPos = (xStart/(self.currentPeriod * 8))+.25 xEndPos = (xEnd/(self.currentPeriod * 8))+.25 if event.speak or event.extra: val = .5 else: val = float(event.note-self.minPitch)/float(self.pitchRange) vStart = (xStartPos*4) vEnd = (xEndPos*4) glColor4f(.5,.5,.5,vStart) font.render(event.lyric, (xStartPos, .085+addYText), scale = self.lyricScale) if not (event.speak or event.extra): #font.render("X", (xStartPos, .057-(.05*val)+addYText), scale = self.lyricScale) #stump: note lanes with RB2-like glow if players == 1: baseY = -.1-(.05*val)+addY else: baseY = .075-(.05*val)+addY if self.lastPhrase[1].star: colors = [self.vocalLaneColorStar + [vStart], self.vocalLaneColorStar + [vEnd], self.vocalShadowColorStar + [vStart], self.vocalShadowColorStar + [vEnd], self.vocalGlowColorStar + [vStart*self.vocalGlowFade], self.vocalGlowColorStar + [vEnd*self.vocalGlowFade], self.vocalGlowColorStar + [0.0]] else: colors = [self.vocalLaneColor + [vStart], self.vocalLaneColor + [vEnd], self.vocalShadowColor + [vStart], self.vocalShadowColor + [vEnd], self.vocalGlowColor + [vStart*self.vocalGlowFade], self.vocalGlowColor + [vEnd*self.vocalGlowFade], self.vocalGlowColor + [0.0]] if event.lyric is None and lastNoteEnd is not None: self.drawNoteLane(colors, lastNoteEnd[0], xStartPos, lastNoteEnd[1], baseY) self.drawNoteLane(colors, xStartPos, xEndPos, baseY, baseY) lastNoteEnd = (xEndPos, baseY) lastNoteEnd = None for time, event in nextnotes: if self.nextPhrase[1].tapPhrase: x = time - pos if x < self.currentPeriod * 6: noteX = (x/(self.currentPeriod * 8))+.25 self.engine.drawImage(self.vocalTapNote, scale = (.5,-.5), coord = (w*noteX,tappos)) else: if self.nextPhrase[1].star: glColor4f(1,1,0,1) else: glColor4f(1,1,1,1) xStart = time - pos xEnd = time + event.length - pos if xStart < self.currentPeriod * 6: xStartPos = (xStart/(self.currentPeriod * 8))+.25 xEndPos = (xEnd/(self.currentPeriod * 8))+.25 if event.speak or event.extra: val = .5 else: val = float(event.note-self.minPitch)/float(self.pitchRange) vStart = (xStartPos*4) vEnd = (xEndPos*4) font.render(event.lyric, (xStartPos, .085+addYText), scale = self.lyricScale) if not (event.speak or event.extra): #stump: note lanes with RB2-like glow if players == 1: baseY = -.1-(.05*val)+addY else: baseY = .075-(.05*val)+addY if self.nextPhrase[1].star: colors = [self.vocalLaneColorStar + [vStart], self.vocalLaneColorStar + [vEnd], self.vocalShadowColorStar + [vStart], self.vocalShadowColorStar + [vEnd], self.vocalGlowColorStar + [vStart*self.vocalGlowFade], self.vocalGlowColorStar + [vEnd*self.vocalGlowFade], self.vocalGlowColorStar + [0.0]] else: colors = [self.vocalLaneColor + [vStart], self.vocalLaneColor + [vEnd], self.vocalShadowColor + [vStart], self.vocalShadowColor + [vEnd], self.vocalGlowColor + [vStart*self.vocalGlowFade], self.vocalGlowColor + [vEnd*self.vocalGlowFade], self.vocalGlowColor + [0.0]] if event.lyric is None and lastNoteEnd is not None: self.drawNoteLane(colors, lastNoteEnd[0], xStartPos, lastNoteEnd[1], baseY) self.drawNoteLane(colors, xStartPos, xEndPos, baseY, baseY) lastNoteEnd = (xEndPos, baseY) if self.currentNote is not None: rotate = 0 if self.requiredNote: val = float(self.requiredNote-self.minPitch)/(self.pitchRange) self.lastVal = val else: val = self.lastVal if abs(self.currentNote) < self.allowedDeviation: currentOffset = 0 rotate = 0 elif self.pitchFudge > 0: if self.currentNote > self.oldNote: rotate = .2 currentOffset = .005 else: rotate = -.2 currentOffset = -.005 else: currentOffset = (self.currentNote/12.0) val += currentOffset if val > 1: val -= 1 elif val < 0: val += 1 else: val = .5 rotate = 0 if players == 1: baseY = .89+(.05*val)-addY else: baseY = .92+(.05*val)-addY if self.lyricMode == 1 or self.lyricMode == 2: self.engine.drawImage(self.vocalBar, scale = (.5,-.5), coord = (w*.87,tappos)) if self.activePhrase: #this checks the previous phrase or the current noteX = (.75*(pos - phraseTime)/phraseLength)+.12 if self.activePhrase.tapPhrase: self.engine.drawImage(self.vocalTap, scale = (.5,-.5), coord = (w*noteX,tappos)) else: self.engine.drawImage(self.vocalArrow, scale = (self.vocalLyricSheetWFactor,-self.vocalLyricSheetWFactor), coord = (w*noteX-(self.arrowW/2),h*baseY), color = (1,1,1,self.arrowVis/500.0)) self.engine.drawImage(self.vocalBar, scale = (.5,-.5), coord = (w*noteX,tappos)) elif self.lyricMode == 0: if self.phrase and self.tapPhraseActive: #this checks the next phrase /or/ the current self.engine.drawImage(self.vocalTap, scale = (.5,-.5), coord = (w*.25,tappos)) else: if self.currentNoteItem and (self.currentNoteItem.speak or self.currentNoteItem.extra): self.engine.drawImage(self.vocalSplitArrow, scale = (self.vocalLyricSheetWFactor,-self.vocalLyricSheetWFactor), coord = (w*.25-(self.arrowW/2),h*(.8355-addY)), color = (1,1,1,self.arrowVis/500.0)) else: self.engine.drawImage(self.vocalArrow, scale = (self.vocalLyricSheetWFactor,-self.vocalLyricSheetWFactor), coord = (w*.25-(self.arrowW/2),h*baseY), rot = rotate, color = (1,1,1,self.arrowVis/500.0)) a = [0] #this sticks a bar in at the beginning, so at least you know the vocal code is aware the song started. if self.lastPhrase: a.extend([self.lastPhrase[0], self.lastPhrase[0]+self.lastPhrase[1].length]) if self.phrase: a.extend([self.phrase[0], self.phrase[0]+self.phrase[1].length]) if self.nextPhrase: a.extend([self.nextPhrase[0], self.nextPhrase[0]+self.nextPhrase[1].length]) tLast = -1001 #needs to be further negative than barfudge for t in a: if t-tLast<self.barFudge: #prevents ending/starting phrase bars from appearing too close together continue tLast = t x = t - pos if x < self.currentPeriod * 6 and x > -(self.currentPeriod * 2): xPos = (x/(self.currentPeriod * 8))+.25 if t < pos: v = (xPos*4) else: v = 1 self.engine.drawImage(self.vocalBar, scale = (.5,-.5), coord = (w*xPos,tappos), color = (1,1,1,v)) spActPhrases = [] if self.starPower >= 50 and not self.starPowerActive: if self.lastPhrase and self.phrase: if not self.lastPhrase[1].tapPhrase and not self.phrase[1].tapPhrase: spActPhrases.append((self.lastPhrase[0]+self.lastPhrase[1].length,self.phrase[0])) if self.phrase and self.nextPhrase: if not self.phrase[1].tapPhrase and not self.nextPhrase[1].tapPhrase: spActPhrases.append((self.phrase[0]+self.phrase[1].length,self.nextPhrase[0])) self.starPowerEnable = False for startTime,endTime in spActPhrases: if endTime - startTime < 1000: continue xStart = startTime - pos xEnd = endTime - pos if pos > startTime and pos < endTime: self.starPowerEnable = True else: if self.lyricMode == 1 or self.lyricMode == 2: continue if self.lyricMode == 1 or self.lyricMode == 2: xStart = -(self.currentPeriod*2) xEnd = self.currentPeriod*6 noteX = (.75*(pos - startTime)/(endTime - startTime))+.12 if xStart < self.currentPeriod * 6 or xEnd > -(self.currentPeriod*2): xStartPos = (xStart/(self.currentPeriod*8))+.25 xEndPos = (xEnd/(self.currentPeriod*8))+.25 if self.vocalLyricSheetSP: width = (xEndPos-xStartPos)*w widthImg = self.vocalSheetSPWidth if width > widthImg*50: width = widthImg*50 #prevents too many loops. theme makers should make sure this image is reasonably sized. (note: 'light' themes) xStartPos *= w while width > 0: if xStartPos > w: break if xStartPos < -widthImg: xStartPos += widthImg width -= widthImg continue if widthImg < width: partUsed = 1 width -= widthImg else: partUsed = float(width)/float(widthImg) width = 0 self.engine.drawImage(self.vocalLyricSheetSP, scale = (self.vocalLyricSheetWFactor*partUsed,-self.vocalLyricSheetWFactor), coord = (xStartPos+(widthImg*partUsed/2),vsheetpos), rect = (0,partUsed,0,1)) xStartPos += widthImg if self.lyricMode == 1 or self.lyricMode == 2: self.engine.drawImage(self.vocalBar, scale = (.5,-.5), coord = (w*noteX,tappos)) if self.showText > 0: if self.vocalText: self.engine.drawImage(self.vocalText, scale = (.5, (-.5/6.0)*(1-self.textTrans)), coord = (w*self.vocalMeterX,h*(self.vocalMeterY-addY)), rect = (0, 1, self.scoreBox[0], self.scoreBox[1]-(self.textTrans/6.0)), color = (1,1,1,1-self.textTrans)) else: glColor4f(1,1,1,1-self.textTrans) font.render(self.scorePhrases[self.textScore],(self.vocalMeterX,((1-self.vocalMeterY)*self.engine.data.fontScreenBottom+addYText)), .002) if self.showText <= 0 or self.textTrans > 0: val1,val2 = self.getMultVals() self.engine.drawImage(self.vocalMeter, scale = (self.vocalMeterScale,-self.vocalMeterScale), coord = (w*self.vocalMeterX,h*(self.vocalMeterY-addY)), color = (1,1,1,self.textTrans)) if self.vocalGlow and self.starPowerActive: self.engine.drawImage(self.vocalGlow, scale = (self.vocalMeterScale,-self.vocalMeterScale), coord = (w*self.vocalMeterX,h*(self.vocalMeterY-addY)), color = (1,1,1,self.textTrans)) self.engine.drawImage(self.vocalMult, scale = (.5,-.5/8.0), coord = (w*self.vocalMultX,h*(self.vocalMultY-addY)), rect = (0, 1, float(val1)/9.0, float(val2)/9.0), color = (1,1,1,self.textTrans)) if self.phraseNoteTime > 0 and self.phraseInTune > 0 and not self.tapPhraseActive: ratio = self.phraseInTune/float(self.phraseNoteTime) if ratio > 1: ratio = 1 if self.vocalContinuousAvailable: degrees = int(360*ratio) - (int(360*ratio) % 5) self.engine.drawImage(self.drawnVocalOverlays[degrees], scale = (self.vocalMeterScale,-self.vocalMeterScale), coord = (w*self.vocalMeterX,h*(self.vocalMeterY-addY)), color = (1,1,1,self.textTrans)) else: self.engine.drawImage(self.vocalFill, scale = (self.vocalFillWidth*ratio, -self.vocalFillWidth), coord = (w*self.vocalMeterX-(ratio*self.vocalFillWidth*w*.5), h*(self.vocalMeterY-addY)), rect = (0,ratio,0,1), color = (1,1,1,self.textTrans), stretched = 11) self.engine.drawImage(self.vocalODBottom, scale = (.5,-.5), coord = (w*self.vocalPowerX,h*(self.vocalPowerY-addY))) if self.starPower > 0: currentSP = self.starPower/100.0 self.engine.drawImage(self.vocalODFill, scale = (self.vocalODFillWidth*currentSP,-self.vocalODFillWidth), coord = (w*self.vocalPowerX-((1-currentSP)*self.vocalODFillWidth*w*.5),h*(self.vocalPowerY-addY)), rect = (0,currentSP,0,1), stretched = 11) if self.vocalODTop: self.engine.drawImage(self.vocalODTop, scale = (.5,-.5), coord = (w*self.vocalPowerX,h*(self.vocalPowerY-addY))) if self.starPowerActive: if self.vocalLyricSheetGlow: self.engine.drawImage(self.vocalLyricSheetGlow, scale = (self.vocalLyricSheetWFactor,-self.vocalLyricSheetWFactor), coord = (w*.5,vsheetpos)) if self.vocalODGlow: self.engine.drawImage(self.vocalODGlow, scale = (.5,-.5), coord = (w*self.vocalPowerX,h*(self.vocalPowerY-addY))) if self.tapPhraseActive: font.render("%d / %d" % (self.tapNoteHits[self.currentTapPhrase], self.tapNoteTotals[self.currentTapPhrase]), (.25, .065+addYText), scale = self.lyricScale) def stopMic(self): self.mic.stop() def startMic(self): self.mic.start() def addMult(self): if self.scoreMultiplier < 4: self.scoreMultiplier += 1 def resetMult(self): self.scoreMultiplier = 1 def getRequiredNote(self, pos, song, lyric = False): track = song.track[self.player] if self.doneLastPhrase: return if pos > self.currentPhraseTime + self.currentPhraseLength - 20: if self.phraseIndex < len(track): if self.phraseIndex > 0: self.lastPhrase = track.allEvents[self.phraseIndex-1] self.phraseNoteTime = max(self.phraseNoteTime, 1) if self.activePhrase.tapPhrase: score = float(self.phraseTapsHit)/float(self.phraseTaps) else: score = (self.phraseInTune/self.phraseNoteTime) if not self.coOpRestart and not self.coOpFailed: for i, thresh in enumerate(self.scoreThresholds): if score >= thresh: if i < 2: if self.phrase[1].star: self.starPower += 25 self.starPowerGained = True if self.starPower > 100: self.starPower = 100 self.addMult() if i >= 2: self.resetMult() self.lastScore = i self.textScore = i self.scoredPhrases[i] += 1 self.showText = 1000 self.scoreBox = (i/6.0, float(i+1)/6.0) break else: self.minPitch = track.minPitch self.maxPitch = track.maxPitch self.pitchRange = self.maxPitch-self.minPitch self.phrase = track.allEvents[self.phraseIndex] self.phraseInTune = 0 self.phraseNoteTime = 0 self.phraseTaps = 0 self.phraseTapsHit = 0 if self.phrase[1].tapPhrase: for note in self.phrase[1]: self.phraseTaps += 1 if not self.tapPhraseActive: self.mic.detectTaps = True self.tapPhraseActive = True self.currentTapPhrase += 1 else: self.tapPhraseActive = False self.mic.detectTaps = False self.mic.getTap() for time, note in self.phrase[1]: self.phraseNoteTime += note.length self.phraseIndex += 1 if self.phraseIndex < len(track): self.nextPhrase = track.allEvents[self.phraseIndex] else: self.nextPhrase = None elif self.phraseIndex == len(track): self.phraseNoteTime = max(self.phraseNoteTime, 1) if self.activePhrase.tapPhrase: score = float(self.phraseTapsHit)/float(self.phraseTaps) else: score = (self.phraseInTune/self.phraseNoteTime) if not self.coOpFailed and not self.coOpRestart: for i, thresh in enumerate(self.scoreThresholds): if score >= thresh: if i < 2: if self.phrase[1].star: self.starPower += 25 self.starPowerGained = True if self.starPower > 100: self.starPower = 100 self.addMult() if i >= 2: self.resetMult() self.lastScore = i self.textScore = i self.scoredPhrases[i] += 1 self.showText = 1000 self.scoreBox = (i/6.0, float(i+1)/6.0) break self.phraseInTune = 0 self.phraseNoteTime = 0 self.phraseTaps = 0 self.phraseTapsHit = 0 self.doneLastPhrase = True if self.coOpFailed and self.coOpRestart: self.coOpFailed = False if self.coOpRestart and self.coOpRescueTime == 0: self.coOpRestart = False self.currentPhraseTime = self.phrase[0] self.currentPhraseLength = self.phrase[1].length self.useOld = False if self.lyricMode == 1 or self.lyricMode == 2: if pos >= self.currentPhraseTime and pos < self.currentPhraseTime + self.currentPhraseLength: self.activePhrase = self.phrase[1] else: oldPhraseNum = self.phraseIndex - 2 if oldPhraseNum >= 0: oldPhrase = track.allEvents[oldPhraseNum] if pos < oldPhrase[0] + oldPhrase[1].length + (self.currentPeriod/2): self.activePhrase = oldPhrase[1] self.oldTime = oldPhrase[0] self.oldLength = oldPhrase[1].length self.useOld = True else: self.activePhrase = None else: self.activePhrase = None elif self.lyricMode == 0: if self.phrase: self.activePhrase = self.phrase[1] else: self.activePhrase = None if self.activePhrase: lateMargin = 0 if self.activePhrase.tapPhrase: lateMargin = self.lateMargin notes = [(time, event) for time, event in self.activePhrase.getAllEvents() if isinstance(event, VocalNote)] retval = None for note in notes: if retval is not None: #this checks if the note is a held note - if it is, do not award points based on cutting off. if note[1].heldNote: self.awardEnd = False else: self.awardEnd = True break if note[0] <= pos and note[0] + note[1].length + lateMargin > pos: self.currentNoteTime = note[0] self.currentNoteItem = note[1] if not note[1].heldNote: self.currentLyric = note[1].lyric if note[1].tap: retval = 1 elif note[1].speak or note[1].extra: # with # or ^ markers retval = 0 else: retval = note[1].note else: self.currentNoteItem = None else: self.awardEnd = True if retval is None: self.currentLyric = None self.currentNoteItem = None return retval else: self.awardEnd = True self.currentLyric = None self.currentNoteItem = None return None def run(self, ticks, pos): if not self.paused: self.time += ticks if self.tap > 0: self.tap -= ticks if self.tap < 0: self.tap = 0 if self.tapBuffer > 0: self.tapBuffer -= ticks if self.tapBuffer < 0: self.tapBuffer = 0 if self.pitchFudge > 0: self.pitchFudge -= ticks if self.stayEnd > 0 and self.formants[1] is None: self.stayEnd -= ticks if self.showText > 0: self.showText -= ticks if self.showText < 0: self.showText = 0 if self.textTrans > 0: self.textTrans -= ticks/400.0 if self.textTrans < 0: self.textTrans = 0 else: self.textTrans = 1 if self.coOpRescueTime > 0: self.coOpRescueTime -= ticks if self.coOpRescueTime < 0: self.coOpRescueTime = 0 if not self.starPowerEnable: self.starPowerCountdown = False self.starPowerTimer = 200 if self.starPowerCountdown: self.starPowerTimer -= ticks if self.starPowerTimer <= 0: self.starPowerActivate = True if self.currentNote is None or (self.formants[1] is None and self.pitchFudge <= 0): self.arrowVis -= ticks if self.arrowVis < 0: self.arrowVis = 0 else: self.arrowVis = 500 if self.activePhrase: if self.activePhrase.tapPhrase: if self.mic.getTap() and self.tapBuffer == 0: self.tap = self.earlyMargin #test only self.tapBuffer = 0 #(self.tapBufferMargin*120)/self.currentBpm #myfingershurt: must not decrease SP if paused. if self.starPowerActive == True and self.paused == False: self.starPower -= ticks/self.starPowerDecreaseDivisor if self.starPower <= 0: self.starPower = 0 self.starPowerActive = False #MFH - call to play star power deactivation sound, if it exists (if not play nothing) if self.engine.data.starDeActivateSoundFound: #self.engine.data.starDeActivateSound.setVolume(self.sfxVolume) self.engine.data.starDeActivateSound.play() self.getCurrentNote(pos) return True
Python
# Copyright (c) 2004 Python Software Foundation. # All rights reserved. # Written by Eric Price <eprice at tjhsst.edu> # and Facundo Batista <facundo at taniquetil.com.ar> # and Raymond Hettinger <python at rcn.com> # and Aahz <aahz at pobox.com> # and Tim Peters # This module is currently Py2.3 compatible and should be kept that way # unless a major compelling advantage arises. IOW, 2.3 compatibility is # strongly preferred, but not guaranteed. # Also, this module should be kept in sync with the latest updates of # the IBM specification as it evolves. Those updates will be treated # as bug fixes (deviation from the spec is a compatibility, usability # bug) and will be backported. At this point the spec is stabilizing # and the updates are becoming fewer, smaller, and less significant. """ This is a Py2.3 implementation of decimal floating point arithmetic based on the General Decimal Arithmetic Specification: www2.hursley.ibm.com/decimal/decarith.html and IEEE standard 854-1987: www.cs.berkeley.edu/~ejr/projects/754/private/drafts/854-1987/dir.html Decimal floating point has finite precision with arbitrarily large bounds. The purpose of the module is to support arithmetic using familiar "schoolhouse" rules and to avoid the some of tricky representation issues associated with binary floating point. The package is especially useful for financial applications or for contexts where users have expectations that are at odds with binary floating point (for instance, in binary floating point, 1.00 % 0.1 gives 0.09999999999999995 instead of the expected Decimal("0.00") returned by decimal floating point). Here are some examples of using the decimal module: >>> from decimal import * >>> setcontext(ExtendedContext) >>> Decimal(0) Decimal("0") >>> Decimal("1") Decimal("1") >>> Decimal("-.0123") Decimal("-0.0123") >>> Decimal(123456) Decimal("123456") >>> Decimal("123.45e12345678901234567890") Decimal("1.2345E+12345678901234567892") >>> Decimal("1.33") + Decimal("1.27") Decimal("2.60") >>> Decimal("12.34") + Decimal("3.87") - Decimal("18.41") Decimal("-2.20") >>> dig = Decimal(1) >>> print dig / Decimal(3) 0.333333333 >>> getcontext().prec = 18 >>> print dig / Decimal(3) 0.333333333333333333 >>> print dig.sqrt() 1 >>> print Decimal(3).sqrt() 1.73205080756887729 >>> print Decimal(3) ** 123 4.85192780976896427E+58 >>> inf = Decimal(1) / Decimal(0) >>> print inf Infinity >>> neginf = Decimal(-1) / Decimal(0) >>> print neginf -Infinity >>> print neginf + inf NaN >>> print neginf * inf -Infinity >>> print dig / 0 Infinity >>> getcontext().traps[DivisionByZero] = 1 >>> print dig / 0 Traceback (most recent call last): ... ... ... DivisionByZero: x / 0 >>> c = Context() >>> c.traps[InvalidOperation] = 0 >>> print c.flags[InvalidOperation] 0 >>> c.divide(Decimal(0), Decimal(0)) Decimal("NaN") >>> c.traps[InvalidOperation] = 1 >>> print c.flags[InvalidOperation] 1 >>> c.flags[InvalidOperation] = 0 >>> print c.flags[InvalidOperation] 0 >>> print c.divide(Decimal(0), Decimal(0)) Traceback (most recent call last): ... ... ... InvalidOperation: 0 / 0 >>> print c.flags[InvalidOperation] 1 >>> c.flags[InvalidOperation] = 0 >>> c.traps[InvalidOperation] = 0 >>> print c.divide(Decimal(0), Decimal(0)) NaN >>> print c.flags[InvalidOperation] 1 >>> """ __all__ = [ # Two major classes 'Decimal', 'Context', # Contexts 'DefaultContext', 'BasicContext', 'ExtendedContext', # Exceptions 'DecimalException', 'Clamped', 'InvalidOperation', 'DivisionByZero', 'Inexact', 'Rounded', 'Subnormal', 'Overflow', 'Underflow', # Constants for use in setting up contexts 'ROUND_DOWN', 'ROUND_HALF_UP', 'ROUND_HALF_EVEN', 'ROUND_CEILING', 'ROUND_FLOOR', 'ROUND_UP', 'ROUND_HALF_DOWN', # Functions for manipulating contexts 'setcontext', 'getcontext', 'localcontext' ] import copy as _copy #Rounding ROUND_DOWN = 'ROUND_DOWN' ROUND_HALF_UP = 'ROUND_HALF_UP' ROUND_HALF_EVEN = 'ROUND_HALF_EVEN' ROUND_CEILING = 'ROUND_CEILING' ROUND_FLOOR = 'ROUND_FLOOR' ROUND_UP = 'ROUND_UP' ROUND_HALF_DOWN = 'ROUND_HALF_DOWN' #Rounding decision (not part of the public API) NEVER_ROUND = 'NEVER_ROUND' # Round in division (non-divmod), sqrt ONLY ALWAYS_ROUND = 'ALWAYS_ROUND' # Every operation rounds at end. #Errors class DecimalException(ArithmeticError): """Base exception class. Used exceptions derive from this. If an exception derives from another exception besides this (such as Underflow (Inexact, Rounded, Subnormal) that indicates that it is only called if the others are present. This isn't actually used for anything, though. handle -- Called when context._raise_error is called and the trap_enabler is set. First argument is self, second is the context. More arguments can be given, those being after the explanation in _raise_error (For example, context._raise_error(NewError, '(-x)!', self._sign) would call NewError().handle(context, self._sign).) To define a new exception, it should be sufficient to have it derive from DecimalException. """ def handle(self, context, *args): pass class Clamped(DecimalException): """Exponent of a 0 changed to fit bounds. This occurs and signals clamped if the exponent of a result has been altered in order to fit the constraints of a specific concrete representation. This may occur when the exponent of a zero result would be outside the bounds of a representation, or when a large normal number would have an encoded exponent that cannot be represented. In this latter case, the exponent is reduced to fit and the corresponding number of zero digits are appended to the coefficient ("fold-down"). """ class InvalidOperation(DecimalException): """An invalid operation was performed. Various bad things cause this: Something creates a signaling NaN -INF + INF 0 * (+-)INF (+-)INF / (+-)INF x % 0 (+-)INF % x x._rescale( non-integer ) sqrt(-x) , x > 0 0 ** 0 x ** (non-integer) x ** (+-)INF An operand is invalid """ def handle(self, context, *args): if args: if args[0] == 1: #sNaN, must drop 's' but keep diagnostics return Decimal( (args[1]._sign, args[1]._int, 'n') ) return NaN class ConversionSyntax(InvalidOperation): """Trying to convert badly formed string. This occurs and signals invalid-operation if an string is being converted to a number and it does not conform to the numeric string syntax. The result is [0,qNaN]. """ def handle(self, context, *args): return (0, (0,), 'n') #Passed to something which uses a tuple. class DivisionByZero(DecimalException, ZeroDivisionError): """Division by 0. This occurs and signals division-by-zero if division of a finite number by zero was attempted (during a divide-integer or divide operation, or a power operation with negative right-hand operand), and the dividend was not zero. The result of the operation is [sign,inf], where sign is the exclusive or of the signs of the operands for divide, or is 1 for an odd power of -0, for power. """ def handle(self, context, sign, double = None, *args): if double is not None: return (Infsign[sign],)*2 return Infsign[sign] class DivisionImpossible(InvalidOperation): """Cannot perform the division adequately. This occurs and signals invalid-operation if the integer result of a divide-integer or remainder operation had too many digits (would be longer than precision). The result is [0,qNaN]. """ def handle(self, context, *args): return (NaN, NaN) class DivisionUndefined(InvalidOperation, ZeroDivisionError): """Undefined result of division. This occurs and signals invalid-operation if division by zero was attempted (during a divide-integer, divide, or remainder operation), and the dividend is also zero. The result is [0,qNaN]. """ def handle(self, context, tup=None, *args): if tup is not None: return (NaN, NaN) #for 0 %0, 0 // 0 return NaN class Inexact(DecimalException): """Had to round, losing information. This occurs and signals inexact whenever the result of an operation is not exact (that is, it needed to be rounded and any discarded digits were non-zero), or if an overflow or underflow condition occurs. The result in all cases is unchanged. The inexact signal may be tested (or trapped) to determine if a given operation (or sequence of operations) was inexact. """ pass class InvalidContext(InvalidOperation): """Invalid context. Unknown rounding, for example. This occurs and signals invalid-operation if an invalid context was detected during an operation. This can occur if contexts are not checked on creation and either the precision exceeds the capability of the underlying concrete representation or an unknown or unsupported rounding was specified. These aspects of the context need only be checked when the values are required to be used. The result is [0,qNaN]. """ def handle(self, context, *args): return NaN class Rounded(DecimalException): """Number got rounded (not necessarily changed during rounding). This occurs and signals rounded whenever the result of an operation is rounded (that is, some zero or non-zero digits were discarded from the coefficient), or if an overflow or underflow condition occurs. The result in all cases is unchanged. The rounded signal may be tested (or trapped) to determine if a given operation (or sequence of operations) caused a loss of precision. """ pass class Subnormal(DecimalException): """Exponent < Emin before rounding. This occurs and signals subnormal whenever the result of a conversion or operation is subnormal (that is, its adjusted exponent is less than Emin, before any rounding). The result in all cases is unchanged. The subnormal signal may be tested (or trapped) to determine if a given or operation (or sequence of operations) yielded a subnormal result. """ pass class Overflow(Inexact, Rounded): """Numerical overflow. This occurs and signals overflow if the adjusted exponent of a result (from a conversion or from an operation that is not an attempt to divide by zero), after rounding, would be greater than the largest value that can be handled by the implementation (the value Emax). The result depends on the rounding mode: For round-half-up and round-half-even (and for round-half-down and round-up, if implemented), the result of the operation is [sign,inf], where sign is the sign of the intermediate result. For round-down, the result is the largest finite number that can be represented in the current precision, with the sign of the intermediate result. For round-ceiling, the result is the same as for round-down if the sign of the intermediate result is 1, or is [0,inf] otherwise. For round-floor, the result is the same as for round-down if the sign of the intermediate result is 0, or is [1,inf] otherwise. In all cases, Inexact and Rounded will also be raised. """ def handle(self, context, sign, *args): if context.rounding in (ROUND_HALF_UP, ROUND_HALF_EVEN, ROUND_HALF_DOWN, ROUND_UP): return Infsign[sign] if sign == 0: if context.rounding == ROUND_CEILING: return Infsign[sign] return Decimal((sign, (9,)*context.prec, context.Emax-context.prec+1)) if sign == 1: if context.rounding == ROUND_FLOOR: return Infsign[sign] return Decimal( (sign, (9,)*context.prec, context.Emax-context.prec+1)) class Underflow(Inexact, Rounded, Subnormal): """Numerical underflow with result rounded to 0. This occurs and signals underflow if a result is inexact and the adjusted exponent of the result would be smaller (more negative) than the smallest value that can be handled by the implementation (the value Emin). That is, the result is both inexact and subnormal. The result after an underflow will be a subnormal number rounded, if necessary, so that its exponent is not less than Etiny. This may result in 0 with the sign of the intermediate result and an exponent of Etiny. In all cases, Inexact, Rounded, and Subnormal will also be raised. """ # List of public traps and flags _signals = [Clamped, DivisionByZero, Inexact, Overflow, Rounded, Underflow, InvalidOperation, Subnormal] # Map conditions (per the spec) to signals _condition_map = {ConversionSyntax:InvalidOperation, DivisionImpossible:InvalidOperation, DivisionUndefined:InvalidOperation, InvalidContext:InvalidOperation} ##### Context Functions ####################################### # The getcontext() and setcontext() function manage access to a thread-local # current context. Py2.4 offers direct support for thread locals. If that # is not available, use threading.currentThread() which is slower but will # work for older Pythons. If threads are not part of the build, create a # mock threading object with threading.local() returning the module namespace. try: import threading except ImportError: # Python was compiled without threads; create a mock object instead import sys class MockThreading: def local(self, sys=sys): return sys.modules[__name__] threading = MockThreading() del sys, MockThreading try: threading.local except AttributeError: #To fix reloading, force it to create a new context #Old contexts have different exceptions in their dicts, making problems. if hasattr(threading.currentThread(), '__decimal_context__'): del threading.currentThread().__decimal_context__ def setcontext(context): """Set this thread's context to context.""" if context in (DefaultContext, BasicContext, ExtendedContext): context = context.copy() context.clear_flags() threading.currentThread().__decimal_context__ = context def getcontext(): """Returns this thread's context. If this thread does not yet have a context, returns a new context and sets this thread's context. New contexts are copies of DefaultContext. """ try: return threading.currentThread().__decimal_context__ except AttributeError: context = Context() threading.currentThread().__decimal_context__ = context return context else: local = threading.local() if hasattr(local, '__decimal_context__'): del local.__decimal_context__ def getcontext(_local=local): """Returns this thread's context. If this thread does not yet have a context, returns a new context and sets this thread's context. New contexts are copies of DefaultContext. """ try: return _local.__decimal_context__ except AttributeError: context = Context() _local.__decimal_context__ = context return context def setcontext(context, _local=local): """Set this thread's context to context.""" if context in (DefaultContext, BasicContext, ExtendedContext): context = context.copy() context.clear_flags() _local.__decimal_context__ = context del threading, local # Don't contaminate the namespace def localcontext(ctx=None): """Return a context manager for a copy of the supplied context Uses a copy of the current context if no context is specified The returned context manager creates a local decimal context in a with statement: def sin(x): with localcontext() as ctx: ctx.prec += 2 # Rest of sin calculation algorithm # uses a precision 2 greater than normal return +s # Convert result to normal precision def sin(x): with localcontext(ExtendedContext): # Rest of sin calculation algorithm # uses the Extended Context from the # General Decimal Arithmetic Specification return +s # Convert result to normal context """ # The string below can't be included in the docstring until Python 2.6 # as the doctest module doesn't understand __future__ statements """ >>> from __future__ import with_statement >>> print getcontext().prec 28 >>> with localcontext(): ... ctx = getcontext() ... ctx.prec() += 2 ... print ctx.prec ... 30 >>> with localcontext(ExtendedContext): ... print getcontext().prec ... 9 >>> print getcontext().prec 28 """ if ctx is None: ctx = getcontext() return _ContextManager(ctx) ##### Decimal class ########################################### class Decimal(object): """Floating point class for decimal arithmetic.""" __slots__ = ('_exp','_int','_sign', '_is_special') # Generally, the value of the Decimal instance is given by # (-1)**_sign * _int * 10**_exp # Special values are signified by _is_special == True # We're immutable, so use __new__ not __init__ def __new__(cls, value="0", context=None): """Create a decimal point instance. >>> Decimal('3.14') # string input Decimal("3.14") >>> Decimal((0, (3, 1, 4), -2)) # tuple input (sign, digit_tuple, exponent) Decimal("3.14") >>> Decimal(314) # int or long Decimal("314") >>> Decimal(Decimal(314)) # another decimal instance Decimal("314") """ self = object.__new__(cls) self._is_special = False # From an internal working value if isinstance(value, _WorkRep): self._sign = value.sign self._int = tuple(map(int, str(value.int))) self._exp = int(value.exp) return self # From another decimal if isinstance(value, Decimal): self._exp = value._exp self._sign = value._sign self._int = value._int self._is_special = value._is_special return self # From an integer if isinstance(value, (int,long)): if value >= 0: self._sign = 0 else: self._sign = 1 self._exp = 0 self._int = tuple(map(int, str(abs(value)))) return self # tuple/list conversion (possibly from as_tuple()) if isinstance(value, (list,tuple)): if len(value) != 3: raise ValueError, 'Invalid arguments' if value[0] not in (0,1): raise ValueError, 'Invalid sign' for digit in value[1]: if not isinstance(digit, (int,long)) or digit < 0: raise ValueError, "The second value in the tuple must be composed of non negative integer elements." self._sign = value[0] self._int = tuple(value[1]) if value[2] in ('F','n','N'): self._exp = value[2] self._is_special = True else: self._exp = int(value[2]) return self if isinstance(value, float): raise TypeError("Cannot convert float to Decimal. " + "First convert the float to a string") # Other argument types may require the context during interpretation if context is None: context = getcontext() # From a string # REs insist on real strings, so we can too. if isinstance(value, basestring): if _isinfinity(value): self._exp = 'F' self._int = (0,) self._is_special = True if _isinfinity(value) == 1: self._sign = 0 else: self._sign = 1 return self if _isnan(value): sig, sign, diag = _isnan(value) self._is_special = True if len(diag) > context.prec: #Diagnostic info too long self._sign, self._int, self._exp = \ context._raise_error(ConversionSyntax) return self if sig == 1: self._exp = 'n' #qNaN else: #sig == 2 self._exp = 'N' #sNaN self._sign = sign self._int = tuple(map(int, diag)) #Diagnostic info return self try: self._sign, self._int, self._exp = _string2exact(value) except ValueError: self._is_special = True self._sign, self._int, self._exp = context._raise_error(ConversionSyntax) return self raise TypeError("Cannot convert %r to Decimal" % value) def _isnan(self): """Returns whether the number is not actually one. 0 if a number 1 if NaN 2 if sNaN """ if self._is_special: exp = self._exp if exp == 'n': return 1 elif exp == 'N': return 2 return 0 def _isinfinity(self): """Returns whether the number is infinite 0 if finite or not a number 1 if +INF -1 if -INF """ if self._exp == 'F': if self._sign: return -1 return 1 return 0 def _check_nans(self, other = None, context=None): """Returns whether the number is not actually one. if self, other are sNaN, signal if self, other are NaN return nan return 0 Done before operations. """ self_is_nan = self._isnan() if other is None: other_is_nan = False else: other_is_nan = other._isnan() if self_is_nan or other_is_nan: if context is None: context = getcontext() if self_is_nan == 2: return context._raise_error(InvalidOperation, 'sNaN', 1, self) if other_is_nan == 2: return context._raise_error(InvalidOperation, 'sNaN', 1, other) if self_is_nan: return self return other return 0 def __nonzero__(self): """Is the number non-zero? 0 if self == 0 1 if self != 0 """ if self._is_special: return 1 return sum(self._int) != 0 def __cmp__(self, other, context=None): other = _convert_other(other) if other is NotImplemented: return other if self._is_special or other._is_special: ans = self._check_nans(other, context) if ans: return 1 # Comparison involving NaN's always reports self > other # INF = INF return cmp(self._isinfinity(), other._isinfinity()) if not self and not other: return 0 #If both 0, sign comparison isn't certain. #If different signs, neg one is less if other._sign < self._sign: return -1 if self._sign < other._sign: return 1 self_adjusted = self.adjusted() other_adjusted = other.adjusted() if self_adjusted == other_adjusted and \ self._int + (0,)*(self._exp - other._exp) == \ other._int + (0,)*(other._exp - self._exp): return 0 #equal, except in precision. ([0]*(-x) = []) elif self_adjusted > other_adjusted and self._int[0] != 0: return (-1)**self._sign elif self_adjusted < other_adjusted and other._int[0] != 0: return -((-1)**self._sign) # Need to round, so make sure we have a valid context if context is None: context = getcontext() context = context._shallow_copy() rounding = context._set_rounding(ROUND_UP) #round away from 0 flags = context._ignore_all_flags() res = self.__sub__(other, context=context) context._regard_flags(*flags) context.rounding = rounding if not res: return 0 elif res._sign: return -1 return 1 def __eq__(self, other): if not isinstance(other, (Decimal, int, long)): return NotImplemented return self.__cmp__(other) == 0 def __ne__(self, other): if not isinstance(other, (Decimal, int, long)): return NotImplemented return self.__cmp__(other) != 0 def compare(self, other, context=None): """Compares one to another. -1 => a < b 0 => a = b 1 => a > b NaN => one is NaN Like __cmp__, but returns Decimal instances. """ other = _convert_other(other) if other is NotImplemented: return other #compare(NaN, NaN) = NaN if (self._is_special or other and other._is_special): ans = self._check_nans(other, context) if ans: return ans return Decimal(self.__cmp__(other, context)) def __hash__(self): """x.__hash__() <==> hash(x)""" # Decimal integers must hash the same as the ints # Non-integer decimals are normalized and hashed as strings # Normalization assures that hash(100E-1) == hash(10) if self._is_special: if self._isnan(): raise TypeError('Cannot hash a NaN value.') return hash(str(self)) i = int(self) if self == Decimal(i): return hash(i) assert self.__nonzero__() # '-0' handled by integer case return hash(str(self.normalize())) def as_tuple(self): """Represents the number as a triple tuple. To show the internals exactly as they are. """ return (self._sign, self._int, self._exp) def __repr__(self): """Represents the number as an instance of Decimal.""" # Invariant: eval(repr(d)) == d return 'Decimal("%s")' % str(self) def __str__(self, eng = 0, context=None): """Return string representation of the number in scientific notation. Captures all of the information in the underlying representation. """ if self._is_special: if self._isnan(): minus = '-'*self._sign if self._int == (0,): info = '' else: info = ''.join(map(str, self._int)) if self._isnan() == 2: return minus + 'sNaN' + info return minus + 'NaN' + info if self._isinfinity(): minus = '-'*self._sign return minus + 'Infinity' if context is None: context = getcontext() tmp = map(str, self._int) numdigits = len(self._int) leftdigits = self._exp + numdigits if eng and not self: #self = 0eX wants 0[.0[0]]eY, not [[0]0]0eY if self._exp < 0 and self._exp >= -6: #short, no need for e/E s = '-'*self._sign + '0.' + '0'*(abs(self._exp)) return s #exp is closest mult. of 3 >= self._exp exp = ((self._exp - 1)// 3 + 1) * 3 if exp != self._exp: s = '0.'+'0'*(exp - self._exp) else: s = '0' if exp != 0: if context.capitals: s += 'E' else: s += 'e' if exp > 0: s += '+' #0.0e+3, not 0.0e3 s += str(exp) s = '-'*self._sign + s return s if eng: dotplace = (leftdigits-1)%3+1 adjexp = leftdigits -1 - (leftdigits-1)%3 else: adjexp = leftdigits-1 dotplace = 1 if self._exp == 0: pass elif self._exp < 0 and adjexp >= 0: tmp.insert(leftdigits, '.') elif self._exp < 0 and adjexp >= -6: tmp[0:0] = ['0'] * int(-leftdigits) tmp.insert(0, '0.') else: if numdigits > dotplace: tmp.insert(dotplace, '.') elif numdigits < dotplace: tmp.extend(['0']*(dotplace-numdigits)) if adjexp: if not context.capitals: tmp.append('e') else: tmp.append('E') if adjexp > 0: tmp.append('+') tmp.append(str(adjexp)) if eng: while tmp[0:1] == ['0']: tmp[0:1] = [] if len(tmp) == 0 or tmp[0] == '.' or tmp[0].lower() == 'e': tmp[0:0] = ['0'] if self._sign: tmp.insert(0, '-') return ''.join(tmp) def to_eng_string(self, context=None): """Convert to engineering-type string. Engineering notation has an exponent which is a multiple of 3, so there are up to 3 digits left of the decimal place. Same rules for when in exponential and when as a value as in __str__. """ return self.__str__(eng=1, context=context) def __neg__(self, context=None): """Returns a copy with the sign switched. Rounds, if it has reason. """ if self._is_special: ans = self._check_nans(context=context) if ans: return ans if not self: # -Decimal('0') is Decimal('0'), not Decimal('-0') sign = 0 elif self._sign: sign = 0 else: sign = 1 if context is None: context = getcontext() if context._rounding_decision == ALWAYS_ROUND: return Decimal((sign, self._int, self._exp))._fix(context) return Decimal( (sign, self._int, self._exp)) def __pos__(self, context=None): """Returns a copy, unless it is a sNaN. Rounds the number (if more then precision digits) """ if self._is_special: ans = self._check_nans(context=context) if ans: return ans sign = self._sign if not self: # + (-0) = 0 sign = 0 if context is None: context = getcontext() if context._rounding_decision == ALWAYS_ROUND: ans = self._fix(context) else: ans = Decimal(self) ans._sign = sign return ans def __abs__(self, round=1, context=None): """Returns the absolute value of self. If the second argument is 0, do not round. """ if self._is_special: ans = self._check_nans(context=context) if ans: return ans if not round: if context is None: context = getcontext() context = context._shallow_copy() context._set_rounding_decision(NEVER_ROUND) if self._sign: ans = self.__neg__(context=context) else: ans = self.__pos__(context=context) return ans def __add__(self, other, context=None): """Returns self + other. -INF + INF (or the reverse) cause InvalidOperation errors. """ other = _convert_other(other) if other is NotImplemented: return other if context is None: context = getcontext() if self._is_special or other._is_special: ans = self._check_nans(other, context) if ans: return ans if self._isinfinity(): #If both INF, same sign => same as both, opposite => error. if self._sign != other._sign and other._isinfinity(): return context._raise_error(InvalidOperation, '-INF + INF') return Decimal(self) if other._isinfinity(): return Decimal(other) #Can't both be infinity here shouldround = context._rounding_decision == ALWAYS_ROUND exp = min(self._exp, other._exp) negativezero = 0 if context.rounding == ROUND_FLOOR and self._sign != other._sign: #If the answer is 0, the sign should be negative, in this case. negativezero = 1 if not self and not other: sign = min(self._sign, other._sign) if negativezero: sign = 1 return Decimal( (sign, (0,), exp)) if not self: exp = max(exp, other._exp - context.prec-1) ans = other._rescale(exp, watchexp=0, context=context) if shouldround: ans = ans._fix(context) return ans if not other: exp = max(exp, self._exp - context.prec-1) ans = self._rescale(exp, watchexp=0, context=context) if shouldround: ans = ans._fix(context) return ans op1 = _WorkRep(self) op2 = _WorkRep(other) op1, op2 = _normalize(op1, op2, shouldround, context.prec) result = _WorkRep() if op1.sign != op2.sign: # Equal and opposite if op1.int == op2.int: if exp < context.Etiny(): exp = context.Etiny() context._raise_error(Clamped) return Decimal((negativezero, (0,), exp)) if op1.int < op2.int: op1, op2 = op2, op1 #OK, now abs(op1) > abs(op2) if op1.sign == 1: result.sign = 1 op1.sign, op2.sign = op2.sign, op1.sign else: result.sign = 0 #So we know the sign, and op1 > 0. elif op1.sign == 1: result.sign = 1 op1.sign, op2.sign = (0, 0) else: result.sign = 0 #Now, op1 > abs(op2) > 0 if op2.sign == 0: result.int = op1.int + op2.int else: result.int = op1.int - op2.int result.exp = op1.exp ans = Decimal(result) if shouldround: ans = ans._fix(context) return ans __radd__ = __add__ def __sub__(self, other, context=None): """Return self + (-other)""" other = _convert_other(other) if other is NotImplemented: return other if self._is_special or other._is_special: ans = self._check_nans(other, context=context) if ans: return ans # -Decimal(0) = Decimal(0), which we don't want since # (-0 - 0 = -0 + (-0) = -0, but -0 + 0 = 0.) # so we change the sign directly to a copy tmp = Decimal(other) tmp._sign = 1-tmp._sign return self.__add__(tmp, context=context) def __rsub__(self, other, context=None): """Return other + (-self)""" other = _convert_other(other) if other is NotImplemented: return other tmp = Decimal(self) tmp._sign = 1 - tmp._sign return other.__add__(tmp, context=context) def _increment(self, round=1, context=None): """Special case of add, adding 1eExponent Since it is common, (rounding, for example) this adds (sign)*one E self._exp to the number more efficiently than add. For example: Decimal('5.624e10')._increment() == Decimal('5.625e10') """ if self._is_special: ans = self._check_nans(context=context) if ans: return ans return Decimal(self) # Must be infinite, and incrementing makes no difference L = list(self._int) L[-1] += 1 spot = len(L)-1 while L[spot] == 10: L[spot] = 0 if spot == 0: L[0:0] = [1] break L[spot-1] += 1 spot -= 1 ans = Decimal((self._sign, L, self._exp)) if context is None: context = getcontext() if round and context._rounding_decision == ALWAYS_ROUND: ans = ans._fix(context) return ans def __mul__(self, other, context=None): """Return self * other. (+-) INF * 0 (or its reverse) raise InvalidOperation. """ other = _convert_other(other) if other is NotImplemented: return other if context is None: context = getcontext() resultsign = self._sign ^ other._sign if self._is_special or other._is_special: ans = self._check_nans(other, context) if ans: return ans if self._isinfinity(): if not other: return context._raise_error(InvalidOperation, '(+-)INF * 0') return Infsign[resultsign] if other._isinfinity(): if not self: return context._raise_error(InvalidOperation, '0 * (+-)INF') return Infsign[resultsign] resultexp = self._exp + other._exp shouldround = context._rounding_decision == ALWAYS_ROUND # Special case for multiplying by zero if not self or not other: ans = Decimal((resultsign, (0,), resultexp)) if shouldround: #Fixing in case the exponent is out of bounds ans = ans._fix(context) return ans # Special case for multiplying by power of 10 if self._int == (1,): ans = Decimal((resultsign, other._int, resultexp)) if shouldround: ans = ans._fix(context) return ans if other._int == (1,): ans = Decimal((resultsign, self._int, resultexp)) if shouldround: ans = ans._fix(context) return ans op1 = _WorkRep(self) op2 = _WorkRep(other) ans = Decimal( (resultsign, map(int, str(op1.int * op2.int)), resultexp)) if shouldround: ans = ans._fix(context) return ans __rmul__ = __mul__ def __div__(self, other, context=None): """Return self / other.""" return self._divide(other, context=context) __truediv__ = __div__ def _divide(self, other, divmod = 0, context=None): """Return a / b, to context.prec precision. divmod: 0 => true division 1 => (a //b, a%b) 2 => a //b 3 => a%b Actually, if divmod is 2 or 3 a tuple is returned, but errors for computing the other value are not raised. """ other = _convert_other(other) if other is NotImplemented: if divmod in (0, 1): return NotImplemented return (NotImplemented, NotImplemented) if context is None: context = getcontext() sign = self._sign ^ other._sign if self._is_special or other._is_special: ans = self._check_nans(other, context) if ans: if divmod: return (ans, ans) return ans if self._isinfinity() and other._isinfinity(): if divmod: return (context._raise_error(InvalidOperation, '(+-)INF // (+-)INF'), context._raise_error(InvalidOperation, '(+-)INF % (+-)INF')) return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF') if self._isinfinity(): if divmod == 1: return (Infsign[sign], context._raise_error(InvalidOperation, 'INF % x')) elif divmod == 2: return (Infsign[sign], NaN) elif divmod == 3: return (Infsign[sign], context._raise_error(InvalidOperation, 'INF % x')) return Infsign[sign] if other._isinfinity(): if divmod: return (Decimal((sign, (0,), 0)), Decimal(self)) context._raise_error(Clamped, 'Division by infinity') return Decimal((sign, (0,), context.Etiny())) # Special cases for zeroes if not self and not other: if divmod: return context._raise_error(DivisionUndefined, '0 / 0', 1) return context._raise_error(DivisionUndefined, '0 / 0') if not self: if divmod: otherside = Decimal(self) otherside._exp = min(self._exp, other._exp) return (Decimal((sign, (0,), 0)), otherside) exp = self._exp - other._exp if exp < context.Etiny(): exp = context.Etiny() context._raise_error(Clamped, '0e-x / y') if exp > context.Emax: exp = context.Emax context._raise_error(Clamped, '0e+x / y') return Decimal( (sign, (0,), exp) ) if not other: if divmod: return context._raise_error(DivisionByZero, 'divmod(x,0)', sign, 1) return context._raise_error(DivisionByZero, 'x / 0', sign) #OK, so neither = 0, INF or NaN shouldround = context._rounding_decision == ALWAYS_ROUND #If we're dividing into ints, and self < other, stop. #self.__abs__(0) does not round. if divmod and (self.__abs__(0, context) < other.__abs__(0, context)): if divmod == 1 or divmod == 3: exp = min(self._exp, other._exp) ans2 = self._rescale(exp, context=context, watchexp=0) if shouldround: ans2 = ans2._fix(context) return (Decimal( (sign, (0,), 0) ), ans2) elif divmod == 2: #Don't round the mod part, if we don't need it. return (Decimal( (sign, (0,), 0) ), Decimal(self)) op1 = _WorkRep(self) op2 = _WorkRep(other) op1, op2, adjust = _adjust_coefficients(op1, op2) res = _WorkRep( (sign, 0, (op1.exp - op2.exp)) ) if divmod and res.exp > context.prec + 1: return context._raise_error(DivisionImpossible) prec_limit = 10 ** context.prec while 1: while op2.int <= op1.int: res.int += 1 op1.int -= op2.int if res.exp == 0 and divmod: if res.int >= prec_limit and shouldround: return context._raise_error(DivisionImpossible) otherside = Decimal(op1) frozen = context._ignore_all_flags() exp = min(self._exp, other._exp) otherside = otherside._rescale(exp, context=context, watchexp=0) context._regard_flags(*frozen) if shouldround: otherside = otherside._fix(context) return (Decimal(res), otherside) if op1.int == 0 and adjust >= 0 and not divmod: break if res.int >= prec_limit and shouldround: if divmod: return context._raise_error(DivisionImpossible) shouldround=1 # Really, the answer is a bit higher, so adding a one to # the end will make sure the rounding is right. if op1.int != 0: res.int *= 10 res.int += 1 res.exp -= 1 break res.int *= 10 res.exp -= 1 adjust += 1 op1.int *= 10 op1.exp -= 1 if res.exp == 0 and divmod and op2.int > op1.int: #Solves an error in precision. Same as a previous block. if res.int >= prec_limit and shouldround: return context._raise_error(DivisionImpossible) otherside = Decimal(op1) frozen = context._ignore_all_flags() exp = min(self._exp, other._exp) otherside = otherside._rescale(exp, context=context) context._regard_flags(*frozen) return (Decimal(res), otherside) ans = Decimal(res) if shouldround: ans = ans._fix(context) return ans def __rdiv__(self, other, context=None): """Swaps self/other and returns __div__.""" other = _convert_other(other) if other is NotImplemented: return other return other.__div__(self, context=context) __rtruediv__ = __rdiv__ def __divmod__(self, other, context=None): """ (self // other, self % other) """ return self._divide(other, 1, context) def __rdivmod__(self, other, context=None): """Swaps self/other and returns __divmod__.""" other = _convert_other(other) if other is NotImplemented: return other return other.__divmod__(self, context=context) def __mod__(self, other, context=None): """ self % other """ other = _convert_other(other) if other is NotImplemented: return other if self._is_special or other._is_special: ans = self._check_nans(other, context) if ans: return ans if self and not other: return context._raise_error(InvalidOperation, 'x % 0') return self._divide(other, 3, context)[1] def __rmod__(self, other, context=None): """Swaps self/other and returns __mod__.""" other = _convert_other(other) if other is NotImplemented: return other return other.__mod__(self, context=context) def remainder_near(self, other, context=None): """ Remainder nearest to 0- abs(remainder-near) <= other/2 """ other = _convert_other(other) if other is NotImplemented: return other if self._is_special or other._is_special: ans = self._check_nans(other, context) if ans: return ans if self and not other: return context._raise_error(InvalidOperation, 'x % 0') if context is None: context = getcontext() # If DivisionImpossible causes an error, do not leave Rounded/Inexact # ignored in the calling function. context = context._shallow_copy() flags = context._ignore_flags(Rounded, Inexact) #keep DivisionImpossible flags (side, r) = self.__divmod__(other, context=context) if r._isnan(): context._regard_flags(*flags) return r context = context._shallow_copy() rounding = context._set_rounding_decision(NEVER_ROUND) if other._sign: comparison = other.__div__(Decimal(-2), context=context) else: comparison = other.__div__(Decimal(2), context=context) context._set_rounding_decision(rounding) context._regard_flags(*flags) s1, s2 = r._sign, comparison._sign r._sign, comparison._sign = 0, 0 if r < comparison: r._sign, comparison._sign = s1, s2 #Get flags now self.__divmod__(other, context=context) return r._fix(context) r._sign, comparison._sign = s1, s2 rounding = context._set_rounding_decision(NEVER_ROUND) (side, r) = self.__divmod__(other, context=context) context._set_rounding_decision(rounding) if r._isnan(): return r decrease = not side._iseven() rounding = context._set_rounding_decision(NEVER_ROUND) side = side.__abs__(context=context) context._set_rounding_decision(rounding) s1, s2 = r._sign, comparison._sign r._sign, comparison._sign = 0, 0 if r > comparison or decrease and r == comparison: r._sign, comparison._sign = s1, s2 context.prec += 1 if len(side.__add__(Decimal(1), context=context)._int) >= context.prec: context.prec -= 1 return context._raise_error(DivisionImpossible)[1] context.prec -= 1 if self._sign == other._sign: r = r.__sub__(other, context=context) else: r = r.__add__(other, context=context) else: r._sign, comparison._sign = s1, s2 return r._fix(context) def __floordiv__(self, other, context=None): """self // other""" return self._divide(other, 2, context)[0] def __rfloordiv__(self, other, context=None): """Swaps self/other and returns __floordiv__.""" other = _convert_other(other) if other is NotImplemented: return other return other.__floordiv__(self, context=context) def __float__(self): """Float representation.""" return float(str(self)) def __int__(self): """Converts self to an int, truncating if necessary.""" if self._is_special: if self._isnan(): context = getcontext() return context._raise_error(InvalidContext) elif self._isinfinity(): raise OverflowError, "Cannot convert infinity to long" if self._exp >= 0: s = ''.join(map(str, self._int)) + '0'*self._exp else: s = ''.join(map(str, self._int))[:self._exp] if s == '': s = '0' sign = '-'*self._sign return int(sign + s) def __long__(self): """Converts to a long. Equivalent to long(int(self)) """ return long(self.__int__()) def _fix(self, context): """Round if it is necessary to keep self within prec precision. Rounds and fixes the exponent. Does not raise on a sNaN. Arguments: self - Decimal instance context - context used. """ if self._is_special: return self if context is None: context = getcontext() prec = context.prec ans = self._fixexponents(context) if len(ans._int) > prec: ans = ans._round(prec, context=context) ans = ans._fixexponents(context) return ans def _fixexponents(self, context): """Fix the exponents and return a copy with the exponent in bounds. Only call if known to not be a special value. """ folddown = context._clamp Emin = context.Emin ans = self ans_adjusted = ans.adjusted() if ans_adjusted < Emin: Etiny = context.Etiny() if ans._exp < Etiny: if not ans: ans = Decimal(self) ans._exp = Etiny context._raise_error(Clamped) return ans ans = ans._rescale(Etiny, context=context) #It isn't zero, and exp < Emin => subnormal context._raise_error(Subnormal) if context.flags[Inexact]: context._raise_error(Underflow) else: if ans: #Only raise subnormal if non-zero. context._raise_error(Subnormal) else: Etop = context.Etop() if folddown and ans._exp > Etop: context._raise_error(Clamped) ans = ans._rescale(Etop, context=context) else: Emax = context.Emax if ans_adjusted > Emax: if not ans: ans = Decimal(self) ans._exp = Emax context._raise_error(Clamped) return ans context._raise_error(Inexact) context._raise_error(Rounded) return context._raise_error(Overflow, 'above Emax', ans._sign) return ans def _round(self, prec=None, rounding=None, context=None): """Returns a rounded version of self. You can specify the precision or rounding method. Otherwise, the context determines it. """ if self._is_special: ans = self._check_nans(context=context) if ans: return ans if self._isinfinity(): return Decimal(self) if context is None: context = getcontext() if rounding is None: rounding = context.rounding if prec is None: prec = context.prec if not self: if prec <= 0: dig = (0,) exp = len(self._int) - prec + self._exp else: dig = (0,) * prec exp = len(self._int) + self._exp - prec ans = Decimal((self._sign, dig, exp)) context._raise_error(Rounded) return ans if prec == 0: temp = Decimal(self) temp._int = (0,)+temp._int prec = 1 elif prec < 0: exp = self._exp + len(self._int) - prec - 1 temp = Decimal( (self._sign, (0, 1), exp)) prec = 1 else: temp = Decimal(self) numdigits = len(temp._int) if prec == numdigits: return temp # See if we need to extend precision expdiff = prec - numdigits if expdiff > 0: tmp = list(temp._int) tmp.extend([0] * expdiff) ans = Decimal( (temp._sign, tmp, temp._exp - expdiff)) return ans #OK, but maybe all the lost digits are 0. lostdigits = self._int[expdiff:] if lostdigits == (0,) * len(lostdigits): ans = Decimal( (temp._sign, temp._int[:prec], temp._exp - expdiff)) #Rounded, but not Inexact context._raise_error(Rounded) return ans # Okay, let's round and lose data this_function = getattr(temp, self._pick_rounding_function[rounding]) #Now we've got the rounding function if prec != context.prec: context = context._shallow_copy() context.prec = prec ans = this_function(prec, expdiff, context) context._raise_error(Rounded) context._raise_error(Inexact, 'Changed in rounding') return ans _pick_rounding_function = {} def _round_down(self, prec, expdiff, context): """Also known as round-towards-0, truncate.""" return Decimal( (self._sign, self._int[:prec], self._exp - expdiff) ) def _round_half_up(self, prec, expdiff, context, tmp = None): """Rounds 5 up (away from 0)""" if tmp is None: tmp = Decimal( (self._sign,self._int[:prec], self._exp - expdiff)) if self._int[prec] >= 5: tmp = tmp._increment(round=0, context=context) if len(tmp._int) > prec: return Decimal( (tmp._sign, tmp._int[:-1], tmp._exp + 1)) return tmp def _round_half_even(self, prec, expdiff, context): """Round 5 to even, rest to nearest.""" tmp = Decimal( (self._sign, self._int[:prec], self._exp - expdiff)) half = (self._int[prec] == 5) if half: for digit in self._int[prec+1:]: if digit != 0: half = 0 break if half: if self._int[prec-1] & 1 == 0: return tmp return self._round_half_up(prec, expdiff, context, tmp) def _round_half_down(self, prec, expdiff, context): """Round 5 down""" tmp = Decimal( (self._sign, self._int[:prec], self._exp - expdiff)) half = (self._int[prec] == 5) if half: for digit in self._int[prec+1:]: if digit != 0: half = 0 break if half: return tmp return self._round_half_up(prec, expdiff, context, tmp) def _round_up(self, prec, expdiff, context): """Rounds away from 0.""" tmp = Decimal( (self._sign, self._int[:prec], self._exp - expdiff) ) for digit in self._int[prec:]: if digit != 0: tmp = tmp._increment(round=1, context=context) if len(tmp._int) > prec: return Decimal( (tmp._sign, tmp._int[:-1], tmp._exp + 1)) else: return tmp return tmp def _round_ceiling(self, prec, expdiff, context): """Rounds up (not away from 0 if negative.)""" if self._sign: return self._round_down(prec, expdiff, context) else: return self._round_up(prec, expdiff, context) def _round_floor(self, prec, expdiff, context): """Rounds down (not towards 0 if negative)""" if not self._sign: return self._round_down(prec, expdiff, context) else: return self._round_up(prec, expdiff, context) def __pow__(self, n, modulo = None, context=None): """Return self ** n (mod modulo) If modulo is None (default), don't take it mod modulo. """ n = _convert_other(n) if n is NotImplemented: return n if context is None: context = getcontext() if self._is_special or n._is_special or n.adjusted() > 8: #Because the spot << doesn't work with really big exponents if n._isinfinity() or n.adjusted() > 8: return context._raise_error(InvalidOperation, 'x ** INF') ans = self._check_nans(n, context) if ans: return ans if not n._isinteger(): return context._raise_error(InvalidOperation, 'x ** (non-integer)') if not self and not n: return context._raise_error(InvalidOperation, '0 ** 0') if not n: return Decimal(1) if self == Decimal(1): return Decimal(1) sign = self._sign and not n._iseven() n = int(n) if self._isinfinity(): if modulo: return context._raise_error(InvalidOperation, 'INF % x') if n > 0: return Infsign[sign] return Decimal( (sign, (0,), 0) ) #with ludicrously large exponent, just raise an overflow and return inf. if not modulo and n > 0 and (self._exp + len(self._int) - 1) * n > context.Emax \ and self: tmp = Decimal('inf') tmp._sign = sign context._raise_error(Rounded) context._raise_error(Inexact) context._raise_error(Overflow, 'Big power', sign) return tmp elength = len(str(abs(n))) firstprec = context.prec if not modulo and firstprec + elength + 1 > DefaultContext.Emax: return context._raise_error(Overflow, 'Too much precision.', sign) mul = Decimal(self) val = Decimal(1) context = context._shallow_copy() context.prec = firstprec + elength + 1 if n < 0: #n is a long now, not Decimal instance n = -n mul = Decimal(1).__div__(mul, context=context) spot = 1 while spot <= n: spot <<= 1 spot >>= 1 #Spot is the highest power of 2 less than n while spot: val = val.__mul__(val, context=context) if val._isinfinity(): val = Infsign[sign] break if spot & n: val = val.__mul__(mul, context=context) if modulo is not None: val = val.__mod__(modulo, context=context) spot >>= 1 context.prec = firstprec if context._rounding_decision == ALWAYS_ROUND: return val._fix(context) return val def __rpow__(self, other, context=None): """Swaps self/other and returns __pow__.""" other = _convert_other(other) if other is NotImplemented: return other return other.__pow__(self, context=context) def normalize(self, context=None): """Normalize- strip trailing 0s, change anything equal to 0 to 0e0""" if self._is_special: ans = self._check_nans(context=context) if ans: return ans dup = self._fix(context) if dup._isinfinity(): return dup if not dup: return Decimal( (dup._sign, (0,), 0) ) end = len(dup._int) exp = dup._exp while dup._int[end-1] == 0: exp += 1 end -= 1 return Decimal( (dup._sign, dup._int[:end], exp) ) def quantize(self, exp, rounding=None, context=None, watchexp=1): """Quantize self so its exponent is the same as that of exp. Similar to self._rescale(exp._exp) but with error checking. """ if self._is_special or exp._is_special: ans = self._check_nans(exp, context) if ans: return ans if exp._isinfinity() or self._isinfinity(): if exp._isinfinity() and self._isinfinity(): return self #if both are inf, it is OK if context is None: context = getcontext() return context._raise_error(InvalidOperation, 'quantize with one INF') return self._rescale(exp._exp, rounding, context, watchexp) def same_quantum(self, other): """Test whether self and other have the same exponent. same as self._exp == other._exp, except NaN == sNaN """ if self._is_special or other._is_special: if self._isnan() or other._isnan(): return self._isnan() and other._isnan() and True if self._isinfinity() or other._isinfinity(): return self._isinfinity() and other._isinfinity() and True return self._exp == other._exp def _rescale(self, exp, rounding=None, context=None, watchexp=1): """Rescales so that the exponent is exp. exp = exp to scale to (an integer) rounding = rounding version watchexp: if set (default) an error is returned if exp is greater than Emax or less than Etiny. """ if context is None: context = getcontext() if self._is_special: if self._isinfinity(): return context._raise_error(InvalidOperation, 'rescale with an INF') ans = self._check_nans(context=context) if ans: return ans if watchexp and (context.Emax < exp or context.Etiny() > exp): return context._raise_error(InvalidOperation, 'rescale(a, INF)') if not self: ans = Decimal(self) ans._int = (0,) ans._exp = exp return ans diff = self._exp - exp digits = len(self._int) + diff if watchexp and digits > context.prec: return context._raise_error(InvalidOperation, 'Rescale > prec') tmp = Decimal(self) tmp._int = (0,) + tmp._int digits += 1 if digits < 0: tmp._exp = -digits + tmp._exp tmp._int = (0,1) digits = 1 tmp = tmp._round(digits, rounding, context=context) if tmp._int[0] == 0 and len(tmp._int) > 1: tmp._int = tmp._int[1:] tmp._exp = exp tmp_adjusted = tmp.adjusted() if tmp and tmp_adjusted < context.Emin: context._raise_error(Subnormal) elif tmp and tmp_adjusted > context.Emax: return context._raise_error(InvalidOperation, 'rescale(a, INF)') return tmp def to_integral(self, rounding=None, context=None): """Rounds to the nearest integer, without raising inexact, rounded.""" if self._is_special: ans = self._check_nans(context=context) if ans: return ans if self._exp >= 0: return self if context is None: context = getcontext() flags = context._ignore_flags(Rounded, Inexact) ans = self._rescale(0, rounding, context=context) context._regard_flags(flags) return ans def sqrt(self, context=None): """Return the square root of self. Uses a converging algorithm (Xn+1 = 0.5*(Xn + self / Xn)) Should quadratically approach the right answer. """ if self._is_special: ans = self._check_nans(context=context) if ans: return ans if self._isinfinity() and self._sign == 0: return Decimal(self) if not self: #exponent = self._exp / 2, using round_down. #if self._exp < 0: # exp = (self._exp+1) // 2 #else: exp = (self._exp) // 2 if self._sign == 1: #sqrt(-0) = -0 return Decimal( (1, (0,), exp)) else: return Decimal( (0, (0,), exp)) if context is None: context = getcontext() if self._sign == 1: return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0') tmp = Decimal(self) expadd = tmp._exp // 2 if tmp._exp & 1: tmp._int += (0,) tmp._exp = 0 else: tmp._exp = 0 context = context._shallow_copy() flags = context._ignore_all_flags() firstprec = context.prec context.prec = 3 if tmp.adjusted() & 1 == 0: ans = Decimal( (0, (8,1,9), tmp.adjusted() - 2) ) ans = ans.__add__(tmp.__mul__(Decimal((0, (2,5,9), -2)), context=context), context=context) ans._exp -= 1 + tmp.adjusted() // 2 else: ans = Decimal( (0, (2,5,9), tmp._exp + len(tmp._int)- 3) ) ans = ans.__add__(tmp.__mul__(Decimal((0, (8,1,9), -3)), context=context), context=context) ans._exp -= 1 + tmp.adjusted() // 2 #ans is now a linear approximation. Emax, Emin = context.Emax, context.Emin context.Emax, context.Emin = DefaultContext.Emax, DefaultContext.Emin half = Decimal('0.5') maxp = firstprec + 2 rounding = context._set_rounding(ROUND_HALF_EVEN) while 1: context.prec = min(2*context.prec - 2, maxp) ans = half.__mul__(ans.__add__(tmp.__div__(ans, context=context), context=context), context=context) if context.prec == maxp: break #round to the answer's precision-- the only error can be 1 ulp. context.prec = firstprec prevexp = ans.adjusted() ans = ans._round(context=context) #Now, check if the other last digits are better. context.prec = firstprec + 1 # In case we rounded up another digit and we should actually go lower. if prevexp != ans.adjusted(): ans._int += (0,) ans._exp -= 1 lower = ans.__sub__(Decimal((0, (5,), ans._exp-1)), context=context) context._set_rounding(ROUND_UP) if lower.__mul__(lower, context=context) > (tmp): ans = ans.__sub__(Decimal((0, (1,), ans._exp)), context=context) else: upper = ans.__add__(Decimal((0, (5,), ans._exp-1)),context=context) context._set_rounding(ROUND_DOWN) if upper.__mul__(upper, context=context) < tmp: ans = ans.__add__(Decimal((0, (1,), ans._exp)),context=context) ans._exp += expadd context.prec = firstprec context.rounding = rounding ans = ans._fix(context) rounding = context._set_rounding_decision(NEVER_ROUND) if not ans.__mul__(ans, context=context) == self: # Only rounded/inexact if here. context._regard_flags(flags) context._raise_error(Rounded) context._raise_error(Inexact) else: #Exact answer, so let's set the exponent right. #if self._exp < 0: # exp = (self._exp +1)// 2 #else: exp = self._exp // 2 context.prec += ans._exp - exp ans = ans._rescale(exp, context=context) context.prec = firstprec context._regard_flags(flags) context.Emax, context.Emin = Emax, Emin return ans._fix(context) def max(self, other, context=None): """Returns the larger value. like max(self, other) except if one is not a number, returns NaN (and signals if one is sNaN). Also rounds. """ other = _convert_other(other) if other is NotImplemented: return other if self._is_special or other._is_special: # if one operand is a quiet NaN and the other is number, then the # number is always returned sn = self._isnan() on = other._isnan() if sn or on: if on == 1 and sn != 2: return self if sn == 1 and on != 2: return other return self._check_nans(other, context) ans = self c = self.__cmp__(other) if c == 0: # if both operands are finite and equal in numerical value # then an ordering is applied: # # if the signs differ then max returns the operand with the # positive sign and min returns the operand with the negative sign # # if the signs are the same then the exponent is used to select # the result. if self._sign != other._sign: if self._sign: ans = other elif self._exp < other._exp and not self._sign: ans = other elif self._exp > other._exp and self._sign: ans = other elif c == -1: ans = other if context is None: context = getcontext() if context._rounding_decision == ALWAYS_ROUND: return ans._fix(context) return ans def min(self, other, context=None): """Returns the smaller value. like min(self, other) except if one is not a number, returns NaN (and signals if one is sNaN). Also rounds. """ other = _convert_other(other) if other is NotImplemented: return other if self._is_special or other._is_special: # if one operand is a quiet NaN and the other is number, then the # number is always returned sn = self._isnan() on = other._isnan() if sn or on: if on == 1 and sn != 2: return self if sn == 1 and on != 2: return other return self._check_nans(other, context) ans = self c = self.__cmp__(other) if c == 0: # if both operands are finite and equal in numerical value # then an ordering is applied: # # if the signs differ then max returns the operand with the # positive sign and min returns the operand with the negative sign # # if the signs are the same then the exponent is used to select # the result. if self._sign != other._sign: if other._sign: ans = other elif self._exp > other._exp and not self._sign: ans = other elif self._exp < other._exp and self._sign: ans = other elif c == 1: ans = other if context is None: context = getcontext() if context._rounding_decision == ALWAYS_ROUND: return ans._fix(context) return ans def _isinteger(self): """Returns whether self is an integer""" if self._exp >= 0: return True rest = self._int[self._exp:] return rest == (0,)*len(rest) def _iseven(self): """Returns 1 if self is even. Assumes self is an integer.""" if self._exp > 0: return 1 return self._int[-1+self._exp] & 1 == 0 def adjusted(self): """Return the adjusted exponent of self""" try: return self._exp + len(self._int) - 1 #If NaN or Infinity, self._exp is string except TypeError: return 0 # support for pickling, copy, and deepcopy def __reduce__(self): return (self.__class__, (str(self),)) def __copy__(self): if type(self) == Decimal: return self # I'm immutable; therefore I am my own clone return self.__class__(str(self)) def __deepcopy__(self, memo): if type(self) == Decimal: return self # My components are also immutable return self.__class__(str(self)) ##### Context class ########################################### # get rounding method function: rounding_functions = [name for name in Decimal.__dict__.keys() if name.startswith('_round_')] for name in rounding_functions: #name is like _round_half_even, goes to the global ROUND_HALF_EVEN value. globalname = name[1:].upper() val = globals()[globalname] Decimal._pick_rounding_function[val] = name del name, val, globalname, rounding_functions class _ContextManager(object): """Context manager class to support localcontext(). Sets a copy of the supplied context in __enter__() and restores the previous decimal context in __exit__() """ def __init__(self, new_context): self.new_context = new_context.copy() def __enter__(self): self.saved_context = getcontext() setcontext(self.new_context) return self.new_context def __exit__(self, t, v, tb): setcontext(self.saved_context) class Context(object): """Contains the context for a Decimal instance. Contains: prec - precision (for use in rounding, division, square roots..) rounding - rounding type. (how you round) _rounding_decision - ALWAYS_ROUND, NEVER_ROUND -- do you round? traps - If traps[exception] = 1, then the exception is raised when it is caused. Otherwise, a value is substituted in. flags - When an exception is caused, flags[exception] is incremented. (Whether or not the trap_enabler is set) Should be reset by user of Decimal instance. Emin - Minimum exponent Emax - Maximum exponent capitals - If 1, 1*10^1 is printed as 1E+1. If 0, printed as 1e1 _clamp - If 1, change exponents if too high (Default 0) """ def __init__(self, prec=None, rounding=None, traps=None, flags=None, _rounding_decision=None, Emin=None, Emax=None, capitals=None, _clamp=0, _ignored_flags=None): if flags is None: flags = [] if _ignored_flags is None: _ignored_flags = [] if not isinstance(flags, dict): flags = dict([(s,s in flags) for s in _signals]) del s if traps is not None and not isinstance(traps, dict): traps = dict([(s,s in traps) for s in _signals]) del s for name, val in locals().items(): if val is None: setattr(self, name, _copy.copy(getattr(DefaultContext, name))) else: setattr(self, name, val) del self.self def __repr__(self): """Show the current context.""" s = [] s.append('Context(prec=%(prec)d, rounding=%(rounding)s, Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d' % vars(self)) s.append('flags=[' + ', '.join([f.__name__ for f, v in self.flags.items() if v]) + ']') s.append('traps=[' + ', '.join([t.__name__ for t, v in self.traps.items() if v]) + ']') return ', '.join(s) + ')' def clear_flags(self): """Reset all flags to zero""" for flag in self.flags: self.flags[flag] = 0 def _shallow_copy(self): """Returns a shallow copy from self.""" nc = Context(self.prec, self.rounding, self.traps, self.flags, self._rounding_decision, self.Emin, self.Emax, self.capitals, self._clamp, self._ignored_flags) return nc def copy(self): """Returns a deep copy from self.""" nc = Context(self.prec, self.rounding, self.traps.copy(), self.flags.copy(), self._rounding_decision, self.Emin, self.Emax, self.capitals, self._clamp, self._ignored_flags) return nc __copy__ = copy def _raise_error(self, condition, explanation = None, *args): """Handles an error If the flag is in _ignored_flags, returns the default response. Otherwise, it increments the flag, then, if the corresponding trap_enabler is set, it reaises the exception. Otherwise, it returns the default value after incrementing the flag. """ error = _condition_map.get(condition, condition) if error in self._ignored_flags: #Don't touch the flag return error().handle(self, *args) self.flags[error] += 1 if not self.traps[error]: #The errors define how to handle themselves. return condition().handle(self, *args) # Errors should only be risked on copies of the context #self._ignored_flags = [] raise error, explanation def _ignore_all_flags(self): """Ignore all flags, if they are raised""" return self._ignore_flags(*_signals) def _ignore_flags(self, *flags): """Ignore the flags, if they are raised""" # Do not mutate-- This way, copies of a context leave the original # alone. self._ignored_flags = (self._ignored_flags + list(flags)) return list(flags) def _regard_flags(self, *flags): """Stop ignoring the flags, if they are raised""" if flags and isinstance(flags[0], (tuple,list)): flags = flags[0] for flag in flags: self._ignored_flags.remove(flag) def __hash__(self): """A Context cannot be hashed.""" # We inherit object.__hash__, so we must deny this explicitly raise TypeError, "Cannot hash a Context." def Etiny(self): """Returns Etiny (= Emin - prec + 1)""" return int(self.Emin - self.prec + 1) def Etop(self): """Returns maximum exponent (= Emax - prec + 1)""" return int(self.Emax - self.prec + 1) def _set_rounding_decision(self, type): """Sets the rounding decision. Sets the rounding decision, and returns the current (previous) rounding decision. Often used like: context = context._shallow_copy() # That so you don't change the calling context # if an error occurs in the middle (say DivisionImpossible is raised). rounding = context._set_rounding_decision(NEVER_ROUND) instance = instance / Decimal(2) context._set_rounding_decision(rounding) This will make it not round for that operation. """ rounding = self._rounding_decision self._rounding_decision = type return rounding def _set_rounding(self, type): """Sets the rounding type. Sets the rounding type, and returns the current (previous) rounding type. Often used like: context = context.copy() # so you don't change the calling context # if an error occurs in the middle. rounding = context._set_rounding(ROUND_UP) val = self.__sub__(other, context=context) context._set_rounding(rounding) This will make it round up for that operation. """ rounding = self.rounding self.rounding= type return rounding def create_decimal(self, num='0'): """Creates a new Decimal instance but using self as context.""" d = Decimal(num, context=self) return d._fix(self) #Methods def abs(self, a): """Returns the absolute value of the operand. If the operand is negative, the result is the same as using the minus operation on the operand. Otherwise, the result is the same as using the plus operation on the operand. >>> ExtendedContext.abs(Decimal('2.1')) Decimal("2.1") >>> ExtendedContext.abs(Decimal('-100')) Decimal("100") >>> ExtendedContext.abs(Decimal('101.5')) Decimal("101.5") >>> ExtendedContext.abs(Decimal('-101.5')) Decimal("101.5") """ return a.__abs__(context=self) def add(self, a, b): """Return the sum of the two operands. >>> ExtendedContext.add(Decimal('12'), Decimal('7.00')) Decimal("19.00") >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4')) Decimal("1.02E+4") """ return a.__add__(b, context=self) def _apply(self, a): return str(a._fix(self)) def compare(self, a, b): """Compares values numerically. If the signs of the operands differ, a value representing each operand ('-1' if the operand is less than zero, '0' if the operand is zero or negative zero, or '1' if the operand is greater than zero) is used in place of that operand for the comparison instead of the actual operand. The comparison is then effected by subtracting the second operand from the first and then returning a value according to the result of the subtraction: '-1' if the result is less than zero, '0' if the result is zero or negative zero, or '1' if the result is greater than zero. >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3')) Decimal("-1") >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1')) Decimal("0") >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10')) Decimal("0") >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1')) Decimal("1") >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3')) Decimal("1") >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1')) Decimal("-1") """ return a.compare(b, context=self) def divide(self, a, b): """Decimal division in a specified context. >>> ExtendedContext.divide(Decimal('1'), Decimal('3')) Decimal("0.333333333") >>> ExtendedContext.divide(Decimal('2'), Decimal('3')) Decimal("0.666666667") >>> ExtendedContext.divide(Decimal('5'), Decimal('2')) Decimal("2.5") >>> ExtendedContext.divide(Decimal('1'), Decimal('10')) Decimal("0.1") >>> ExtendedContext.divide(Decimal('12'), Decimal('12')) Decimal("1") >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2')) Decimal("4.00") >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0')) Decimal("1.20") >>> ExtendedContext.divide(Decimal('1000'), Decimal('100')) Decimal("10") >>> ExtendedContext.divide(Decimal('1000'), Decimal('1')) Decimal("1000") >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2')) Decimal("1.20E+6") """ return a.__div__(b, context=self) def divide_int(self, a, b): """Divides two numbers and returns the integer part of the result. >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3')) Decimal("0") >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3')) Decimal("3") >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3')) Decimal("3") """ return a.__floordiv__(b, context=self) def divmod(self, a, b): return a.__divmod__(b, context=self) def max(self, a,b): """max compares two values numerically and returns the maximum. If either operand is a NaN then the general rules apply. Otherwise, the operands are compared as as though by the compare operation. If they are numerically equal then the left-hand operand is chosen as the result. Otherwise the maximum (closer to positive infinity) of the two operands is chosen as the result. >>> ExtendedContext.max(Decimal('3'), Decimal('2')) Decimal("3") >>> ExtendedContext.max(Decimal('-10'), Decimal('3')) Decimal("3") >>> ExtendedContext.max(Decimal('1.0'), Decimal('1')) Decimal("1") >>> ExtendedContext.max(Decimal('7'), Decimal('NaN')) Decimal("7") """ return a.max(b, context=self) def min(self, a,b): """min compares two values numerically and returns the minimum. If either operand is a NaN then the general rules apply. Otherwise, the operands are compared as as though by the compare operation. If they are numerically equal then the left-hand operand is chosen as the result. Otherwise the minimum (closer to negative infinity) of the two operands is chosen as the result. >>> ExtendedContext.min(Decimal('3'), Decimal('2')) Decimal("2") >>> ExtendedContext.min(Decimal('-10'), Decimal('3')) Decimal("-10") >>> ExtendedContext.min(Decimal('1.0'), Decimal('1')) Decimal("1.0") >>> ExtendedContext.min(Decimal('7'), Decimal('NaN')) Decimal("7") """ return a.min(b, context=self) def minus(self, a): """Minus corresponds to unary prefix minus in Python. The operation is evaluated using the same rules as subtract; the operation minus(a) is calculated as subtract('0', a) where the '0' has the same exponent as the operand. >>> ExtendedContext.minus(Decimal('1.3')) Decimal("-1.3") >>> ExtendedContext.minus(Decimal('-1.3')) Decimal("1.3") """ return a.__neg__(context=self) def multiply(self, a, b): """multiply multiplies two operands. If either operand is a special value then the general rules apply. Otherwise, the operands are multiplied together ('long multiplication'), resulting in a number which may be as long as the sum of the lengths of the two operands. >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3')) Decimal("3.60") >>> ExtendedContext.multiply(Decimal('7'), Decimal('3')) Decimal("21") >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8')) Decimal("0.72") >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0')) Decimal("-0.0") >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321')) Decimal("4.28135971E+11") """ return a.__mul__(b, context=self) def normalize(self, a): """normalize reduces an operand to its simplest form. Essentially a plus operation with all trailing zeros removed from the result. >>> ExtendedContext.normalize(Decimal('2.1')) Decimal("2.1") >>> ExtendedContext.normalize(Decimal('-2.0')) Decimal("-2") >>> ExtendedContext.normalize(Decimal('1.200')) Decimal("1.2") >>> ExtendedContext.normalize(Decimal('-120')) Decimal("-1.2E+2") >>> ExtendedContext.normalize(Decimal('120.00')) Decimal("1.2E+2") >>> ExtendedContext.normalize(Decimal('0.00')) Decimal("0") """ return a.normalize(context=self) def plus(self, a): """Plus corresponds to unary prefix plus in Python. The operation is evaluated using the same rules as add; the operation plus(a) is calculated as add('0', a) where the '0' has the same exponent as the operand. >>> ExtendedContext.plus(Decimal('1.3')) Decimal("1.3") >>> ExtendedContext.plus(Decimal('-1.3')) Decimal("-1.3") """ return a.__pos__(context=self) def power(self, a, b, modulo=None): """Raises a to the power of b, to modulo if given. The right-hand operand must be a whole number whose integer part (after any exponent has been applied) has no more than 9 digits and whose fractional part (if any) is all zeros before any rounding. The operand may be positive, negative, or zero; if negative, the absolute value of the power is used, and the left-hand operand is inverted (divided into 1) before use. If the increased precision needed for the intermediate calculations exceeds the capabilities of the implementation then an Invalid operation condition is raised. If, when raising to a negative power, an underflow occurs during the division into 1, the operation is not halted at that point but continues. >>> ExtendedContext.power(Decimal('2'), Decimal('3')) Decimal("8") >>> ExtendedContext.power(Decimal('2'), Decimal('-3')) Decimal("0.125") >>> ExtendedContext.power(Decimal('1.7'), Decimal('8')) Decimal("69.7575744") >>> ExtendedContext.power(Decimal('Infinity'), Decimal('-2')) Decimal("0") >>> ExtendedContext.power(Decimal('Infinity'), Decimal('-1')) Decimal("0") >>> ExtendedContext.power(Decimal('Infinity'), Decimal('0')) Decimal("1") >>> ExtendedContext.power(Decimal('Infinity'), Decimal('1')) Decimal("Infinity") >>> ExtendedContext.power(Decimal('Infinity'), Decimal('2')) Decimal("Infinity") >>> ExtendedContext.power(Decimal('-Infinity'), Decimal('-2')) Decimal("0") >>> ExtendedContext.power(Decimal('-Infinity'), Decimal('-1')) Decimal("-0") >>> ExtendedContext.power(Decimal('-Infinity'), Decimal('0')) Decimal("1") >>> ExtendedContext.power(Decimal('-Infinity'), Decimal('1')) Decimal("-Infinity") >>> ExtendedContext.power(Decimal('-Infinity'), Decimal('2')) Decimal("Infinity") >>> ExtendedContext.power(Decimal('0'), Decimal('0')) Decimal("NaN") """ return a.__pow__(b, modulo, context=self) def quantize(self, a, b): """Returns a value equal to 'a' (rounded) and having the exponent of 'b'. The coefficient of the result is derived from that of the left-hand operand. It may be rounded using the current rounding setting (if the exponent is being increased), multiplied by a positive power of ten (if the exponent is being decreased), or is unchanged (if the exponent is already equal to that of the right-hand operand). Unlike other operations, if the length of the coefficient after the quantize operation would be greater than precision then an Invalid operation condition is raised. This guarantees that, unless there is an error condition, the exponent of the result of a quantize is always equal to that of the right-hand operand. Also unlike other operations, quantize will never raise Underflow, even if the result is subnormal and inexact. >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001')) Decimal("2.170") >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01')) Decimal("2.17") >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1')) Decimal("2.2") >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0')) Decimal("2") >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1')) Decimal("0E+1") >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity')) Decimal("-Infinity") >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity')) Decimal("NaN") >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1')) Decimal("-0") >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5')) Decimal("-0E+5") >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2')) Decimal("NaN") >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2')) Decimal("NaN") >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1')) Decimal("217.0") >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0')) Decimal("217") >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1')) Decimal("2.2E+2") >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2')) Decimal("2E+2") """ return a.quantize(b, context=self) def remainder(self, a, b): """Returns the remainder from integer division. The result is the residue of the dividend after the operation of calculating integer division as described for divide-integer, rounded to precision digits if necessary. The sign of the result, if non-zero, is the same as that of the original dividend. This operation will fail under the same conditions as integer division (that is, if integer division on the same two operands would fail, the remainder cannot be calculated). >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3')) Decimal("2.1") >>> ExtendedContext.remainder(Decimal('10'), Decimal('3')) Decimal("1") >>> ExtendedContext.remainder(Decimal('-10'), Decimal('3')) Decimal("-1") >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1')) Decimal("0.2") >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3')) Decimal("0.1") >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3')) Decimal("1.0") """ return a.__mod__(b, context=self) def remainder_near(self, a, b): """Returns to be "a - b * n", where n is the integer nearest the exact value of "x / b" (if two integers are equally near then the even one is chosen). If the result is equal to 0 then its sign will be the sign of a. This operation will fail under the same conditions as integer division (that is, if integer division on the same two operands would fail, the remainder cannot be calculated). >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3')) Decimal("-0.9") >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6')) Decimal("-2") >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3')) Decimal("1") >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3')) Decimal("-1") >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1')) Decimal("0.2") >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3')) Decimal("0.1") >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3')) Decimal("-0.3") """ return a.remainder_near(b, context=self) def same_quantum(self, a, b): """Returns True if the two operands have the same exponent. The result is never affected by either the sign or the coefficient of either operand. >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001')) False >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01')) True >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1')) False >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf')) True """ return a.same_quantum(b) def sqrt(self, a): """Returns the square root of a non-negative number to context precision. If the result must be inexact, it is rounded using the round-half-even algorithm. >>> ExtendedContext.sqrt(Decimal('0')) Decimal("0") >>> ExtendedContext.sqrt(Decimal('-0')) Decimal("-0") >>> ExtendedContext.sqrt(Decimal('0.39')) Decimal("0.624499800") >>> ExtendedContext.sqrt(Decimal('100')) Decimal("10") >>> ExtendedContext.sqrt(Decimal('1')) Decimal("1") >>> ExtendedContext.sqrt(Decimal('1.0')) Decimal("1.0") >>> ExtendedContext.sqrt(Decimal('1.00')) Decimal("1.0") >>> ExtendedContext.sqrt(Decimal('7')) Decimal("2.64575131") >>> ExtendedContext.sqrt(Decimal('10')) Decimal("3.16227766") >>> ExtendedContext.prec 9 """ return a.sqrt(context=self) def subtract(self, a, b): """Return the difference between the two operands. >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07')) Decimal("0.23") >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30')) Decimal("0.00") >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07')) Decimal("-0.77") """ return a.__sub__(b, context=self) def to_eng_string(self, a): """Converts a number to a string, using scientific notation. The operation is not affected by the context. """ return a.to_eng_string(context=self) def to_sci_string(self, a): """Converts a number to a string, using scientific notation. The operation is not affected by the context. """ return a.__str__(context=self) def to_integral(self, a): """Rounds to an integer. When the operand has a negative exponent, the result is the same as using the quantize() operation using the given operand as the left-hand-operand, 1E+0 as the right-hand-operand, and the precision of the operand as the precision setting, except that no flags will be set. The rounding mode is taken from the context. >>> ExtendedContext.to_integral(Decimal('2.1')) Decimal("2") >>> ExtendedContext.to_integral(Decimal('100')) Decimal("100") >>> ExtendedContext.to_integral(Decimal('100.0')) Decimal("100") >>> ExtendedContext.to_integral(Decimal('101.5')) Decimal("102") >>> ExtendedContext.to_integral(Decimal('-101.5')) Decimal("-102") >>> ExtendedContext.to_integral(Decimal('10E+5')) Decimal("1.0E+6") >>> ExtendedContext.to_integral(Decimal('7.89E+77')) Decimal("7.89E+77") >>> ExtendedContext.to_integral(Decimal('-Inf')) Decimal("-Infinity") """ return a.to_integral(context=self) class _WorkRep(object): __slots__ = ('sign','int','exp') # sign: 0 or 1 # int: int or long # exp: None, int, or string def __init__(self, value=None): if value is None: self.sign = None self.int = 0 self.exp = None elif isinstance(value, Decimal): self.sign = value._sign cum = 0 for digit in value._int: cum = cum * 10 + digit self.int = cum self.exp = value._exp else: # assert isinstance(value, tuple) self.sign = value[0] self.int = value[1] self.exp = value[2] def __repr__(self): return "(%r, %r, %r)" % (self.sign, self.int, self.exp) __str__ = __repr__ def _normalize(op1, op2, shouldround = 0, prec = 0): """Normalizes op1, op2 to have the same exp and length of coefficient. Done during addition. """ # Yes, the exponent is a long, but the difference between exponents # must be an int-- otherwise you'd get a big memory problem. numdigits = int(op1.exp - op2.exp) if numdigits < 0: numdigits = -numdigits tmp = op2 other = op1 else: tmp = op1 other = op2 if shouldround and numdigits > prec + 1: # Big difference in exponents - check the adjusted exponents tmp_len = len(str(tmp.int)) other_len = len(str(other.int)) if numdigits > (other_len + prec + 1 - tmp_len): # If the difference in adjusted exps is > prec+1, we know # other is insignificant, so might as well put a 1 after the precision. # (since this is only for addition.) Also stops use of massive longs. extend = prec + 2 - tmp_len if extend <= 0: extend = 1 tmp.int *= 10 ** extend tmp.exp -= extend other.int = 1 other.exp = tmp.exp return op1, op2 tmp.int *= 10 ** numdigits tmp.exp -= numdigits return op1, op2 def _adjust_coefficients(op1, op2): """Adjust op1, op2 so that op2.int * 10 > op1.int >= op2.int. Returns the adjusted op1, op2 as well as the change in op1.exp-op2.exp. Used on _WorkRep instances during division. """ adjust = 0 #If op1 is smaller, make it larger while op2.int > op1.int: op1.int *= 10 op1.exp -= 1 adjust += 1 #If op2 is too small, make it larger while op1.int >= (10 * op2.int): op2.int *= 10 op2.exp -= 1 adjust -= 1 return op1, op2, adjust ##### Helper Functions ######################################## def _convert_other(other): """Convert other to Decimal. Verifies that it's ok to use in an implicit construction. """ if isinstance(other, Decimal): return other if isinstance(other, (int, long)): return Decimal(other) return NotImplemented _infinity_map = { 'inf' : 1, 'infinity' : 1, '+inf' : 1, '+infinity' : 1, '-inf' : -1, '-infinity' : -1 } def _isinfinity(num): """Determines whether a string or float is infinity. +1 for negative infinity; 0 for finite ; +1 for positive infinity """ num = str(num).lower() return _infinity_map.get(num, 0) def _isnan(num): """Determines whether a string or float is NaN (1, sign, diagnostic info as string) => NaN (2, sign, diagnostic info as string) => sNaN 0 => not a NaN """ num = str(num).lower() if not num: return 0 #get the sign, get rid of trailing [+-] sign = 0 if num[0] == '+': num = num[1:] elif num[0] == '-': #elif avoids '+-nan' num = num[1:] sign = 1 if num.startswith('nan'): if len(num) > 3 and not num[3:].isdigit(): #diagnostic info return 0 return (1, sign, num[3:].lstrip('0')) if num.startswith('snan'): if len(num) > 4 and not num[4:].isdigit(): return 0 return (2, sign, num[4:].lstrip('0')) return 0 ##### Setup Specific Contexts ################################ # The default context prototype used by Context() # Is mutable, so that new contexts can have different default values DefaultContext = Context( prec=28, rounding=ROUND_HALF_EVEN, traps=[DivisionByZero, Overflow, InvalidOperation], flags=[], _rounding_decision=ALWAYS_ROUND, Emax=999999999, Emin=-999999999, capitals=1 ) # Pre-made alternate contexts offered by the specification # Don't change these; the user should be able to select these # contexts and be able to reproduce results from other implementations # of the spec. BasicContext = Context( prec=9, rounding=ROUND_HALF_UP, traps=[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow], flags=[], ) ExtendedContext = Context( prec=9, rounding=ROUND_HALF_EVEN, traps=[], flags=[], ) ##### Useful Constants (internal use only) #################### #Reusable defaults Inf = Decimal('Inf') negInf = Decimal('-Inf') #Infsign[sign] is infinity w/ that sign Infsign = (Inf, negInf) NaN = Decimal('NaN') ##### crud for parsing strings ################################# import re # There's an optional sign at the start, and an optional exponent # at the end. The exponent has an optional sign and at least one # digit. In between, must have either at least one digit followed # by an optional fraction, or a decimal point followed by at least # one digit. Yuck. _parser = re.compile(r""" # \s* (?P<sign>[-+])? ( (?P<int>\d+) (\. (?P<frac>\d*))? | \. (?P<onlyfrac>\d+) ) ([eE](?P<exp>[-+]? \d+))? # \s* $ """, re.VERBOSE).match #Uncomment the \s* to allow leading or trailing spaces. del re # return sign, n, p s.t. float string value == -1**sign * n * 10**p exactly def _string2exact(s): m = _parser(s) if m is None: raise ValueError("invalid literal for Decimal: %r" % s) if m.group('sign') == "-": sign = 1 else: sign = 0 exp = m.group('exp') if exp is None: exp = 0 else: exp = int(exp) intpart = m.group('int') if intpart is None: intpart = "" fracpart = m.group('onlyfrac') else: fracpart = m.group('frac') if fracpart is None: fracpart = "" exp -= len(fracpart) mantissa = intpart + fracpart tmp = map(int, mantissa) backup = tmp while tmp and tmp[0] == 0: del tmp[0] # It's a zero if not tmp: if backup: return (sign, tuple(backup), exp) return (sign, (0,), exp) mantissa = tuple(tmp) return (sign, mantissa, exp) if __name__ == '__main__': import doctest, sys doctest.testmod(sys.modules[__name__])
Python
# Cerealizer # Copyright (C) 2005-2006 Jean-Baptiste LAMY # # This program is free software. # It is available under the Python licence. try: set except: import sets set = sets.Set class frozenset(set): pass """Cerealizer -- A secure Pickle-like module The interface of the Cerealizer module is similar to Pickle, and it supports __getstate__, __setstate__, __getinitargs__ and __getnewargs__. Cerealizer supports int, long, float, bool, complex, string, unicode, tuple, list, set, frozenset, dict, old-style and new-style class instances. C-defined types are supported but saving the C-side data may require to write e.g. a specific Handler or a __getstate__ and __setstate__ pair. Objects with __slots__ are supported too. You have to register the class you want to serialize, by calling cerealizer.register(YourClass). Cerealizer can be considered as secure AS LONG AS the following methods of 'YourClass' are secure: - __new__ - __del__ - __getstate__ - __setstate__ - __init__ (ONLY if __getinitargs__ is used for the class) These methods are the only one Cerealizer may call. For a higher security, Cerealizer maintains its own reference to these method (exepted __del__ that can only be called indirectly). Cerealizer doesn't aim at producing Human-readable files. About performances, Cerealizer is really fast and, when powered by Psyco, it may even beat cPickle! Although Cerealizer is implemented in less than 500 lines of pure-Python code (which is another reason for Cerealizer to be secure, since less code means less bugs :-). Compared to Pickle (cPickle): - Cerealizer is secure - Cerealizer achieves similar performances (using Psyco) - Cerealizer requires you to declare the serializable classes Compared to Jelly (from TwistedMatrix): - Cerealizer is faster - Cerealizer does a better job with object cycles, C-defined types and tuples (*) - Cerealizer files are not Human readable (*) Jelly handles them, but tuples and objects in a cycle are first created as _Tuple or _Dereference objects; this works for Python classes, but not with C-defined types which expects a precise type (e.g. tuple and not _Tuple). IMPLEMENTATION DETAILS GENERAL FILE FORMAT STRUCTURE Cerealizer format is simple but quite surprising. It uses a "double flat list" format. It looks like that : <magic code (currently cereal1)>\\n <number of objects>\\n <classname of object #0>\\n <optional data for creating object #0 (currently nothing except for tuples)> <classname of object #0>\\n <optional data for creating object #0 (currently nothing except for tuples)> [...] <data of object #0 (format depend of the type of object #1)> <data of object #0 (format depend of the type of object #1)> [...] <reference to the 'root' object> As you can see, the information for a given object is splitted in two parts, the first one for object's class, and the second one for the object's data. To avoid problems, the order of the objects is the following: <list, dict, set> <object, instance> <tuple, sorted by depth (=max number of folded tuples)> Objects are put after basic types (list,...), since object's __setstate__ might rely on a list, and thus the list must be fully loaded BEFORE calling the object's __setstate__. DATA (<data of object #n> above) The part <data of object #n> saves the data of object #n. It may contains reference to other data (see below, in Cerealizer references include reference to other objects but also raw data like int). - an object is saved by : <reference to the object state (the value returned by object.__getstate__() or object.__dict__)> e.g. 'r7\\n' (object #7 being e.g. the __dict__). - a list or a set is saved by : <number of item>\\n <reference to item #0> <reference to item #1> [...] e.g. '3\\ni0\\ni1\\ni2\\n' for [0, 1, 2] - a dict is saved by : <number of item>\\n <reference to value #0> <reference to key #0> <reference to value #1> <reference to key #1> [...] REFERENCES (<reference to XXX> above) In Cerealizer a reference can be either a reference to another object beign serialized in the same file, or a raw value (e.g. an integer). - an int is saved by e.g. 'i187\\n' - a long is saved by e.g. 'l10000000000\\n' - a float is saved by e.g. 'f1.07\\n' - a bool is saved by 'b0' or 'b1' - a string is saved by e.g. 's5\\nascii' (where 5 is the number of characters) - an unicode is saved by e.g. 'u4\\nutf8' (where 4 is the number of characters) - an object reference is saved by e.g. 'r3\\n' (where 3 means reference to object #3) - None is saved by 'n' """ __alls__ = ["load", "dump", "loads", "dumps", "freeze_configuration", "register"] VERSION = "0.5" import logging logger = logging.getLogger("cerealizer") #logging.basicConfig(level=logging.INFO) from cStringIO import StringIO from new import instance class NotCerealizerFileError(StandardError): pass class NonCerealizableObjectError(StandardError): pass def _priority_sorter(a, b): return cmp(a[0], b[0]) class Dumper(object): def dump(self, root_obj, s): self.objs = [] self.objs_id = set() self.priorities_objs = [] # [(priority1, obj1), (priority2, obj2),...] self.obj2state = {} self.obj2newargs = {} self.id2id = {} self.collect(root_obj) self.priorities_objs.sort(_priority_sorter) self.objs.extend([o for (priority, o) in self.priorities_objs]) s.write("cereal1\n%s\n" % len(self.objs)) i = 0 for obj in self.objs: self.id2id[id(obj)] = i i += 1 for obj in self.objs: _HANDLERS_[obj.__class__].dump_obj (obj, self, s) for obj in self.objs: _HANDLERS_[obj.__class__].dump_data(obj, self, s) _HANDLERS_[root_obj.__class__].dump_ref(root_obj, self, s) def undump(self, s): if s.read(8) != "cereal1\n": raise NotCerealizerFileError("Not a cerealizer file!") nb = int(s.readline()) self.id2obj = [ None ] * nb # DO NOT DO self.id2obj = [comprehension list], since undump_ref may access id2obj during its construction for i in range(nb): classname = s.readline() handler = _HANDLERS.get(classname) if not handler: raise NonCerealizableObjectError("Object of class/type '%s' cannot be de-cerealized! Use cerealizer.register to extend Cerealizer support to other classes." % classname[:-1]) self.id2obj[i] = handler.undump_obj(self, s) for obj in self.id2obj: _HANDLERS_[obj.__class__].undump_data(obj, self, s) return self.undump_ref(s) def collect(self, obj): """Dumper.collect(OBJ) -> bool Collects OBJ for serialization. Returns false is OBJ is already collected; else returns true.""" handler = _HANDLERS_.get(obj.__class__) if not handler: raise NonCerealizableObjectError("Object of class/type '%s' cannot be cerealized! Use cerealizer.register to extend Cerealizer support to other classes." % obj.__class__) handler.collect(obj, self) def dump_ref (self, obj, s): """Dumper.dump_ref(OBJ, S) Writes a reference to OBJ in file S.""" _HANDLERS_[obj.__class__].dump_ref(obj, self, s) def undump_ref(self, s): """Dumper.undump_ref(S) -> obj Reads a reference from file S.""" c = s.read(1) if c == "i": return int (s.readline()) elif c == "f": return float(s.readline()) elif c == "s": return s.read(int(s.readline())) elif c == "u": return s.read(int(s.readline())).decode("utf8") elif c == "r": return self.id2obj[int(s.readline())] elif c == "n": return None elif c == "b": return bool(int(s.read(1))) elif c == "l": return long(s.readline()) elif c == "c": return complex(s.readline()) raise ValueError("Unknown ref code '%s'!" % c) def immutable_depth(self, t): depth = 0 for i in t: i2 = self.obj2newargs.get(id(i)) if not i2 is None: i = i2 if isinstance(i, tuple) or isinstance(i, frozenset): x = self.immutable_depth(i) if x > depth: depth = x return depth + 1 class Handler(object): """Handler A customized handler for serialization and deserialization. You can subclass it to extend cerealization support to new object. See also ObjHandler.""" def collect(self, obj, dumper): """Handler.collect(obj, dumper) -> bool Collects all the objects referenced by OBJ. For each objects ROBJ referenced by OBJ, calls collect method of the Handler for ROBJ's class, i.e._HANDLERS_[ROBJ.__class__].collect(ROBJ, dumper). Returns false if OBJ is already referenced (and thus no collection should occur); else returns true. """ i = id(obj) if not i in dumper.objs_id: dumper.objs.append(obj) dumper.objs_id.add(i) return 1 def dump_obj (self, obj, dumper, s): """Handler.dump_obj(obj, dumper, s) Dumps OBJ classname in file S.""" s.write(self.classname) def dump_data(self, obj, dumper, s): """Handler.dump_data(obj, dumper, s) Dumps OBJ data in file S.""" def dump_ref (self, obj, dumper, s): """Handler.dump_ref(obj, dumper, s) Write a reference to OBJ in file S. You should not override dump_ref, since they is no corresponding 'undump_ref' that you can override.""" s.write("r%s\n" % dumper.id2id[id(obj)]) def undump_obj(self, dumper, s): """Handler.undump_obj(dumper, s) Returns a new uninitialized (=no __init__'ed) instance of the class. If you override undump_obj, DUMPER and file S can be used to read additional data saved by Handler.dump_obj().""" def undump_data(self, obj, dumper, s): """Handler.undump_data(obj, dumper, s) Reads the data for OBJ, from DUMPER and file S. If you override undump_data, you should use DUMPER.undump_ref(S) to read a reference or a basic type (=a string, an int,...).""" class RefHandler(object): def collect (self, obj, dumper) : pass def dump_obj (self, obj, dumper, s): pass def dump_data(self, obj, dumper, s): pass class NoneHandler(RefHandler): def dump_ref (self, obj, dumper, s): s.write("n") class StrHandler(RefHandler): def dump_ref (self, obj, dumper, s): s.write("s%s\n%s" % (len(obj), obj)) class UnicodeHandler(RefHandler): def dump_ref (self, obj, dumper, s): obj = obj.encode("utf8") s.write("u%s\n%s" % (len(obj), obj)) class BoolHandler(RefHandler): def dump_ref (self, obj, dumper, s): s.write("b%s" % int(obj)) class IntHandler(RefHandler): def dump_ref (self, obj, dumper, s): s.write("i%s\n" % obj) class LongHandler(RefHandler): def dump_ref (self, obj, dumper, s): s.write("l%s\n" % obj) class FloatHandler(RefHandler): def dump_ref (self, obj, dumper, s): s.write("f%s\n" % obj) class ComplexHandler(RefHandler): def dump_ref (self, obj, dumper, s): c = str(obj) if c.startswith("("): c = c[1:-1] # complex("(1+2j)") doesn't work s.write("c%s\n" % c) class TupleHandler(Handler): classname = "tuple\n" def collect(self, obj, dumper): if not id(obj) in dumper.objs_id: dumper.priorities_objs.append((dumper.immutable_depth(obj), obj)) dumper.objs_id.add(id(obj)) for i in obj: dumper.collect(i) return 1 def dump_obj(self, obj, dumper, s): s.write("%s%s\n" % (self.classname, len(obj))) for i in obj: _HANDLERS_[i.__class__].dump_ref(i, dumper, s) def undump_obj(self, dumper, s): return tuple([dumper.undump_ref(s) for i in range(int(s.readline()))]) class FrozensetHandler(TupleHandler): classname = "frozenset\n" def undump_obj(self, dumper, s): return frozenset([dumper.undump_ref(s) for i in range(int(s.readline()))]) class ListHandler(Handler): classname = "list\n" def collect(self, obj, dumper): if Handler.collect(self, obj, dumper): for i in obj: dumper.collect(i) return 1 def dump_data(self, obj, dumper, s): s.write("%s\n" % len(obj)) for i in obj: _HANDLERS_[i.__class__].dump_ref(i, dumper, s) def undump_obj(self, dumper, s): return [] def undump_data(self, obj, dumper, s): for i in range(int(s.readline())): obj.append(dumper.undump_ref(s)) class SetHandler(ListHandler): classname = "set\n" def undump_obj(self, dumper, s): return set() def undump_data(self, obj, dumper, s): for i in range(int(s.readline())): obj.add(dumper.undump_ref(s)) class DictHandler(Handler): classname = "dict\n" def collect(self, obj, dumper): if Handler.collect(self, obj, dumper): for i in obj.iterkeys (): dumper.collect(i) # Collect is not ordered for i in obj.itervalues(): dumper.collect(i) return 1 def dump_data(self, obj, dumper, s): s.write("%s\n" % len(obj)) for k, v in obj.iteritems(): _HANDLERS_[v.__class__].dump_ref(v, dumper, s) # Value is saved fist _HANDLERS_[k.__class__].dump_ref(k, dumper, s) def undump_obj(self, dumper, s): return {} def undump_data(self, obj, dumper, s): for i in range(int(s.readline())): obj[dumper.undump_ref(s)] = dumper.undump_ref(s) # Value is read fist class ObjHandler(Handler): """ObjHandler A Cerealizer Handler that can support any new-style class instances, old-style class instances as well as C-defined types (although it may not save the C-side data).""" def __init__(self, Class, classname = ""): self.Class = Class self.Class_new = getattr(Class, "__new__" , instance) self.Class_getstate = getattr(Class, "__getstate__", None) # Check for and store __getstate__ and __setstate__ now self.Class_setstate = getattr(Class, "__setstate__", None) # so we are are they are not modified in the class or the object if classname: self.classname = "%s\n" % classname else: self.classname = "%s.%s\n" % (Class.__module__, Class.__name__) def collect(self, obj, dumper): i = id(obj) if not i in dumper.objs_id: dumper.priorities_objs.append((-1, obj)) dumper.objs_id.add(i) if self.Class_getstate: state = self.Class_getstate(obj) else: state = obj.__dict__ dumper.obj2state[i] = state dumper.collect(state) return 1 def dump_data(self, obj, dumper, s): i = dumper.obj2state[id(obj)] _HANDLERS_[i.__class__].dump_ref(i, dumper, s) def undump_obj(self, dumper, s): return self.Class_new(self.Class) def undump_data(self, obj, dumper, s): if self.Class_setstate: self.Class_setstate(obj, dumper.undump_ref(s)) else: obj.__dict__ = dumper.undump_ref(s) class SlotedObjHandler(ObjHandler): """SlotedObjHandler A Cerealizer Handler that can support new-style class instances with __slot__.""" def __init__(self, Class, classname = ""): ObjHandler.__init__(self, Class, classname) self.Class_slots = Class.__slots__ def collect(self, obj, dumper): i = id(obj) if not i in dumper.objs_id: dumper.priorities_objs.append((-1, obj)) dumper.objs_id.add(i) if self.Class_getstate: state = self.Class_getstate(obj) else: state = dict([(slot, getattr(obj, slot, None)) for slot in self.Class_slots]) dumper.obj2state[i] = state dumper.collect(state) return 1 def undump_data(self, obj, dumper, s): if self.Class_setstate: self.Class_setstate(obj, dumper.undump_ref(s)) else: state = dumper.undump_ref(s) for slot in self.Class_slots: setattr(obj, slot, state[slot]) class InitArgsObjHandler(ObjHandler): """InitArgsObjHandler A Cerealizer Handler that can support class instances with __getinitargs__.""" def __init__(self, Class, classname = ""): ObjHandler.__init__(self, Class, classname) self.Class_getinitargs = Class.__getinitargs__ self.Class_init = Class.__init__ def collect(self, obj, dumper): i = id(obj) if not i in dumper.objs_id: dumper.priorities_objs.append((-1, obj)) dumper.objs_id.add(i) dumper.obj2state[i] = state = self.Class_getinitargs(obj) dumper.collect(state) return 1 def undump_data(self, obj, dumper, s): self.Class_init(obj, *dumper.undump_ref(s)) class NewArgsObjHandler(ObjHandler): """NewArgsObjHandler A Cerealizer Handler that can support class instances with __getnewargs__.""" def __init__(self, Class, classname = ""): ObjHandler.__init__(self, Class, classname) self.Class_getnewargs = Class.__getnewargs__ def collect(self, obj, dumper): i = id(obj) if not i in dumper.objs_id: dumper.obj2newargs[i] = newargs = self.Class_getnewargs(obj) dumper.collect(newargs) dumper.priorities_objs.append((dumper.immutable_depth(newargs), obj)) dumper.objs_id.add(i) if self.Class_getstate: state = self.Class_getstate(obj) else: state = obj.__dict__ dumper.obj2state[i] = state dumper.collect(state) return 1 def dump_obj (self, obj, dumper, s): s.write(self.classname) newargs = dumper.obj2newargs[id(obj)] _HANDLERS_[newargs.__class__].dump_ref(newargs, dumper, s) def undump_obj(self, dumper, s): return self.Class_new(self.Class, *dumper.undump_ref(s)) _configurable = 1 _HANDLERS = {} _HANDLERS_ = {} def register(Class, handler = None, classname = ""): """register(Class, handler = None, classname = "") Registers CLASS as a serializable and secure class. By calling register, YOU HAVE TO ASSUME THAT THE FOLLOWING METHODS ARE SECURE: - CLASS.__new__ - CLASS.__del__ - CLASS.__getstate__ - CLASS.__setstate__ - CLASS.__getinitargs__ - CLASS.__init__ (only if CLASS.__getinitargs__ exists) HANDLER is the Cerealizer Handler object that handles serialization and deserialization for Class. If not given, Cerealizer create an instance of ObjHandler, which is suitable for old-style and new_style Python class, and also C-defined types (although if it has some C-side data, you may have to write a custom Handler or a __getstate__ and __setstate__ pair). CLASSNAME is the classname used in Cerealizer files. It defaults to the full classname (module.class) but you may choose something shorter -- as long as there is no risk of name clash.""" if not _configurable: raise StandardError("Cannot register new classes after freeze_configuration has been called!") if "\n" in classname: raise ValueError("CLASSNAME cannot have \\n (Cerealizer automatically add a trailing \\n for performance reason)!") if not handler: if hasattr(Class, "__getnewargs__" ): handler = NewArgsObjHandler (Class, classname) elif hasattr(Class, "__getinitargs__"): handler = InitArgsObjHandler(Class, classname) elif hasattr(Class, "__slots__" ): handler = SlotedObjHandler (Class, classname) else: handler = ObjHandler (Class, classname) if _HANDLERS_.has_key(Class): raise ValueError("Class %s has already been registred!" % Class) if not isinstance(handler, RefHandler): if _HANDLERS .has_key(handler.classname): raise ValueError("A class has already been registred under the name %s!" % handler.classname[:-1]) _HANDLERS [handler.classname] = handler if handler.__class__ is ObjHandler: logger.info("Registring class %s as '%s'" % (Class, handler.classname[:-1])) else: logger.info("Registring class %s as '%s' (using %s)" % (Class, handler.classname[:-1], handler.__class__.__name__)) else: logger.info("Registring reference '%s'" % Class) _HANDLERS_[Class] = handler register_class = register # For backward compatibility def register_alias(Class, alias): """register_alias(Class, alias) Registers ALIAS as an alias classname for CLASS. Usefull for keeping backward compatibility in files: e.g. if you have renamed OldClass to NewClass, just do: cerealizer.register_alias(NewClass, "OldClass") and you'll be able to open old files containing OldClass serialized.""" handler = _HANDLERS_.get(Class) if not handler: raise ValueError("Cannot register alias '%s' to Class %s: the class is not yet registred!" % (alias, Class)) if _HANDLERS.has_key(alias): raise ValueError("Cannot register alias '%s' to Class %s: another class is already registred under the alias name!" % (alias, Class)) logger.info("Registring alias '%s' for %s" % (alias, Class)) _HANDLERS[alias + "\n"] = handler def freeze_configuration(): """freeze_configuration() Ends Cerealizer configuration. When freeze_configuration() is called, it is no longer possible to register classes, using register(). Calling freeze_configuration() is not mandatory, but it may enforce security, by forbidding unexpected calls to register().""" global _configurable _configurable = 0 logger.info("Configuration frozen") register(type(None), NoneHandler ()) register(str , StrHandler ()) register(unicode , UnicodeHandler ()) register(bool , BoolHandler ()) register(int , IntHandler ()) register(long , LongHandler ()) register(float , FloatHandler ()) register(complex , ComplexHandler ()) register(dict , DictHandler ()) register(list , ListHandler ()) register(set , SetHandler ()) register(tuple , TupleHandler ()) register(frozenset , FrozensetHandler()) def dump(obj, file, protocol = 0): """dump(obj, file, protocol = 0) Serializes object OBJ in FILE. PROTOCOL is unused, it exists only for compatibility with Pickle.""" Dumper().dump(obj, file) def load(file): """load(file) -> obj De-serializes an object from FILE.""" return Dumper().undump(file) def dumps(obj, protocol = 0): """dumps(obj, protocol = 0) -> str Serializes object OBJ and returns the serialized string. PROTOCOL is unused, it exists only for compatibility with Pickle.""" s = StringIO() Dumper().dump(obj, s) return s.getvalue() def loads(string): """loads(file) -> obj De-serializes an object from STRING.""" return Dumper().undump(StringIO(string)) def dump_class_of_module(*modules): """dump_class_of_module(*modules) Utility function; for each classes found in the given module, print the needed call to register.""" class D: pass class O(object): pass s = set([c for module in modules for c in module.__dict__.values() if isinstance(c, type(D)) or isinstance(c, type(O))]) l = ['cerealizer.register(%s.%s)' % (c.__module__, c.__name__) for c in s] l.sort() for i in l: print i
Python
#!/usr/bin/python import os, fnmatch for root, dirs, files in os.walk("."): for svg in fnmatch.filter(files, "*.svg"): svg = os.path.join(root, svg) print svg, os.system("inkscape -e '%s' -D '%s' -b black -y 0.0" % (svg.replace(".svg", ".png"), svg))
Python
# -*- coding: ISO-8859-1 -*- # std library from struct import unpack # custom from DataTypeConverters import readBew, readVar, varLen, toBytes # uhh I don't really like this, but there are so many constants to # import otherwise from constants import * class EventDispatcher: def __init__(self, outstream): """ The event dispatcher generates events on the outstream. """ # internal values, don't mess with 'em directly self.outstream = outstream # public flags # A note_on with a velocity of 0x00 is actually the same as a # note_off with a velocity of 0x40. When # "convert_zero_velocity" is set, the zero velocity note_on's # automatically gets converted into note_off's. This is a less # suprising behaviour for those that are not into the intimate # details of the midi spec. self.convert_zero_velocity = 1 # If dispatch_continuos_controllers is true, continuos # controllers gets dispatched to their defined handlers. Else # they just trigger the "continuous_controller" event handler. self.dispatch_continuos_controllers = 1 # NOT IMPLEMENTED YET # If dispatch_meta_events is true, meta events get's dispatched # to their defined events. Else they all they trigger the # "meta_event" handler. self.dispatch_meta_events = 1 def header(self, format, nTracks, division): "Triggers the header event" self.outstream.header(format, nTracks, division) def start_of_track(self, current_track): "Triggers the start of track event" # I do this twice so that users can overwrite the # start_of_track event handler without worrying whether the # track number is updated correctly. self.outstream.set_current_track(current_track) self.outstream.start_of_track(current_track) def sysex_event(self, data): "Dispatcher for sysex events" self.outstream.sysex_event(data) def eof(self): "End of file!" self.outstream.eof() def update_time(self, new_time=0, relative=1): "Updates relative/absolute time." self.outstream.update_time(new_time, relative) def reset_time(self): "Updates relative/absolute time." self.outstream.reset_time() # Event dispatchers for similar types of events def channel_messages(self, hi_nible, channel, data): "Dispatches channel messages" stream = self.outstream data = toBytes(data) if (NOTE_ON & 0xF0) == hi_nible: note, velocity = data # note_on with velocity 0x00 are same as note # off with velocity 0x40 according to spec! if velocity==0 and self.convert_zero_velocity: stream.note_off(channel, note, 0x40) else: stream.note_on(channel, note, velocity) elif (NOTE_OFF & 0xF0) == hi_nible: note, velocity = data stream.note_off(channel, note, velocity) elif (AFTERTOUCH & 0xF0) == hi_nible: note, velocity = data stream.aftertouch(channel, note, velocity) elif (CONTINUOUS_CONTROLLER & 0xF0) == hi_nible: controller, value = data # A lot of the cc's are defined, so we trigger those directly if self.dispatch_continuos_controllers: self.continuous_controllers(channel, controller, value) else: stream.continuous_controller(channel, controller, value) elif (PATCH_CHANGE & 0xF0) == hi_nible: program = data[0] stream.patch_change(channel, program) elif (CHANNEL_PRESSURE & 0xF0) == hi_nible: pressure = data[0] stream.channel_pressure(channel, pressure) elif (PITCH_BEND & 0xF0) == hi_nible: hibyte, lobyte = data value = (hibyte<<7) + lobyte stream.pitch_bend(channel, value) else: raise ValueError, 'Illegal channel message!' def continuous_controllers(self, channel, controller, value): "Dispatches channel messages" stream = self.outstream # I am not really shure if I ought to dispatch continuous controllers # There's so many of them that it can clutter up the OutStream # classes. # So I just trigger the default event handler stream.continuous_controller(channel, controller, value) def system_commons(self, common_type, common_data): "Dispatches system common messages" stream = self.outstream # MTC Midi time code Quarter value if common_type == MTC: data = readBew(common_data) msg_type = (data & 0x07) >> 4 values = (data & 0x0F) stream.midi_time_code(msg_type, values) elif common_type == SONG_POSITION_POINTER: hibyte, lobyte = toBytes(common_data) value = (hibyte<<7) + lobyte stream.song_position_pointer(value) elif common_type == SONG_SELECT: data = readBew(common_data) stream.song_select(data) elif common_type == TUNING_REQUEST: # no data then stream.tuning_request(time=None) def meta_event(self, meta_type, data): "Dispatches meta events" stream = self.outstream # SEQUENCE_NUMBER = 0x00 (00 02 ss ss (seq-number)) if meta_type == SEQUENCE_NUMBER: number = readBew(data) stream.sequence_number(number) # TEXT = 0x01 (01 len text...) elif meta_type == TEXT: stream.text(data) # COPYRIGHT = 0x02 (02 len text...) elif meta_type == COPYRIGHT: stream.copyright(data) # SEQUENCE_NAME = 0x03 (03 len text...) elif meta_type == SEQUENCE_NAME: stream.sequence_name(data) # INSTRUMENT_NAME = 0x04 (04 len text...) elif meta_type == INSTRUMENT_NAME: stream.instrument_name(data) # LYRIC = 0x05 (05 len text...) elif meta_type == LYRIC: stream.lyric(data) # MARKER = 0x06 (06 len text...) elif meta_type == MARKER: stream.marker(data) # CUEPOINT = 0x07 (07 len text...) elif meta_type == CUEPOINT: stream.cuepoint(data) # PROGRAM_NAME = 0x08 (05 len text...) elif meta_type == PROGRAM_NAME: stream.program_name(data) # DEVICE_NAME = 0x09 (09 len text...) elif meta_type == DEVICE_NAME: stream.device_name(data) # MIDI_CH_PREFIX = 0x20 (20 01 channel) elif meta_type == MIDI_CH_PREFIX: channel = readBew(data) stream.midi_ch_prefix(channel) # MIDI_PORT = 0x21 (21 01 port (legacy stuff)) elif meta_type == MIDI_PORT: port = readBew(data) stream.midi_port(port) # END_OFF_TRACK = 0x2F (2F 00) elif meta_type == END_OF_TRACK: stream.end_of_track() # TEMPO = 0x51 (51 03 tt tt tt (tempo in us/quarternote)) elif meta_type == TEMPO: b1, b2, b3 = toBytes(data) # uses 3 bytes to represent time between quarter # notes in microseconds stream.tempo((b1<<16) + (b2<<8) + b3) # SMTP_OFFSET = 0x54 (54 05 hh mm ss ff xx) elif meta_type == SMTP_OFFSET: try: hour, minute, second, frame, framePart = toBytes(data) stream.smtp_offset( hour, minute, second, frame, framePart) except ValueError: pass # TIME_SIGNATURE = 0x58 (58 04 nn dd cc bb) elif meta_type == TIME_SIGNATURE: try: nn, dd, cc, bb = toBytes(data) stream.time_signature(nn, dd, cc, bb) except ValueError, e: pass # KEY_SIGNATURE = 0x59 (59 02 sf mi) elif meta_type == KEY_SIGNATURE: sf, mi = toBytes(data) stream.key_signature(sf, mi) # SPECIFIC = 0x7F (Sequencer specific event) elif meta_type == SPECIFIC: meta_data = toBytes(data) stream.sequencer_specific(meta_data) # Handles any undefined meta events else: # undefined meta type meta_data = toBytes(data) stream.meta_event(meta_type, meta_data) if __name__ == '__main__': from MidiToText import MidiToText outstream = MidiToText() dispatcher = EventDispatcher(outstream) dispatcher.channel_messages(NOTE_ON, 0x00, '\x40\x40')
Python
# -*- coding: ISO-8859-1 -*- from MidiOutStream import MidiOutStream class MidiToText(MidiOutStream): """ This class renders a midi file as text. It is mostly used for debugging """ ############################# # channel events def channel_message(self, message_type, channel, data): """The default event handler for channel messages""" print 'message_type:%X, channel:%X, data size:%X' % (message_type, channel, len(data)) def note_on(self, channel=0, note=0x40, velocity=0x40): print 'note_on - ch:%02X, note:%02X, vel:%02X time:%s' % (channel, note, velocity, self.rel_time()) def note_off(self, channel=0, note=0x40, velocity=0x40): print 'note_off - ch:%02X, note:%02X, vel:%02X time:%s' % (channel, note, velocity, self.rel_time()) def aftertouch(self, channel=0, note=0x40, velocity=0x40): print 'aftertouch', channel, note, velocity def continuous_controller(self, channel, controller, value): print 'controller - ch: %02X, cont: #%02X, value: %02X' % (channel, controller, value) def patch_change(self, channel, patch): print 'patch_change - ch:%02X, patch:%02X' % (channel, patch) def channel_pressure(self, channel, pressure): print 'channel_pressure', channel, pressure def pitch_bend(self, channel, value): print 'pitch_bend ch:%s, value:%s' % (channel, value) ##################### ## Common events def system_exclusive(self, data): print 'system_exclusive - data size: %s' % len(date) def song_position_pointer(self, value): print 'song_position_pointer: %s' % value def song_select(self, songNumber): print 'song_select: %s' % songNumber def tuning_request(self): print 'tuning_request' def midi_time_code(self, msg_type, values): print 'midi_time_code - msg_type: %s, values: %s' % (msg_type, values) ######################### # header does not really belong here. But anyhoo!!! def header(self, format=0, nTracks=1, division=96): print 'format: %s, nTracks: %s, division: %s' % (format, nTracks, division) print '----------------------------------' print '' def eof(self): print 'End of file' def start_of_track(self, n_track=0): print 'Start - track #%s' % n_track def end_of_track(self): print 'End of track' print '' ############### # sysex event def sysex_event(self, data): print 'sysex_event - datasize: %X' % len(data) ##################### ## meta events def meta_event(self, meta_type, data): print 'undefined_meta_event:', meta_type, len(data) def sequence_number(self, value): print 'sequence_number', value def text(self, text): print 'text', text def copyright(self, text): print 'copyright', text def sequence_name(self, text): print 'sequence_name:', text def instrument_name(self, text): print 'instrument_name:', text def lyric(self, text): print 'lyric', text def marker(self, text): print 'marker', text def cuepoint(self, text): print 'cuepoint', text def midi_ch_prefix(self, channel): print 'midi_ch_prefix', channel def midi_port(self, value): print 'midi_port:', value def tempo(self, value): print 'tempo:', value def smtp_offset(self, hour, minute, second, frame, framePart): print 'smtp_offset', hour, minute, second, frame, framePart def time_signature(self, nn, dd, cc, bb): print 'time_signature:', self.abs_time(), nn, dd, cc, bb def key_signature(self, sf, mi): print 'key_signature', sf, mi def sequencer_specific(self, data): print 'sequencer_specific', len(data) if __name__ == '__main__': # get data import sys test_file = sys.argv[1] f = open(test_file, 'rb') # do parsing from MidiInFile import MidiInFile midiIn = MidiInFile(MidiToText(), f) midiIn.read() f.close()
Python
# -*- coding: ISO-8859-1 -*- # standard library imports from types import StringType from struct import unpack # custom import from DataTypeConverters import readBew, readVar, varLen class RawInstreamFile: """ It parses and reads data from an input file. It takes care of big endianess, and keeps track of the cursor position. The midi parser only reads from this object. Never directly from the file. """ def __init__(self, infile=''): """ If 'file' is a string we assume it is a path and read from that file. If it is a file descriptor we read from the file, but we don't close it. Midi files are usually pretty small, so it should be safe to copy them into memory. """ if infile: if type(infile) in [str, unicode]: infile = open(infile, 'rb') self.data = infile.read() infile.close() else: # don't close the f self.data = infile.read() else: self.data = '' # start at beginning ;-) self.cursor = 0 # setting up data manually def setData(self, data=''): "Sets the data from a string." self.data = data # cursor operations def setCursor(self, position=0): "Sets the absolute position if the cursor" self.cursor = position def getCursor(self): "Returns the value of the cursor" return self.cursor def moveCursor(self, relative_position=0): "Moves the cursor to a new relative position" self.cursor += relative_position # native data reading functions def nextSlice(self, length, move_cursor=1): "Reads the next text slice from the raw data, with length" c = self.cursor slc = self.data[c:c+length] if move_cursor: self.moveCursor(length) return slc def readBew(self, n_bytes=1, move_cursor=1): """ Reads n bytes of date from the current cursor position. Moves cursor if move_cursor is true """ return readBew(self.nextSlice(n_bytes, move_cursor)) def readVarLen(self): """ Reads a variable length value from the current cursor position. Moves cursor if move_cursor is true """ MAX_VARLEN = 4 # Max value varlen can be var = readVar(self.nextSlice(MAX_VARLEN, 0)) # only move cursor the actual bytes in varlen self.moveCursor(varLen(var)) return var if __name__ == '__main__': test_file = 'test/midifiles/minimal.mid' fis = RawInstreamFile(test_file) print fis.nextSlice(len(fis.data)) test_file = 'test/midifiles/cubase-minimal.mid' cubase_minimal = open(test_file, 'rb') fis2 = RawInstreamFile(cubase_minimal) print fis2.nextSlice(len(fis2.data)) cubase_minimal.close()
Python
# -*- coding: ISO-8859-1 -*- # std library from struct import unpack # uhh I don't really like this, but there are so many constants to # import otherwise from constants import * from EventDispatcher import EventDispatcher class MidiFileParser: """ The MidiFileParser is the lowest level parser that see the data as midi data. It generates events that gets triggered on the outstream. """ def __init__(self, raw_in, outstream): """ raw_data is the raw content of a midi file as a string. """ # internal values, don't mess with 'em directly self.raw_in = raw_in self.dispatch = EventDispatcher(outstream) # Used to keep track of stuff self._running_status = None def parseMThdChunk(self): "Parses the header chunk" raw_in = self.raw_in header_chunk_type = raw_in.nextSlice(4) header_chunk_zise = raw_in.readBew(4) # check if it is a proper midi file if header_chunk_type != 'MThd': raise TypeError, "It is not a valid midi file!" # Header values are at fixed locations, so no reason to be clever self.format = raw_in.readBew(2) self.nTracks = raw_in.readBew(2) self.division = raw_in.readBew(2) # Theoretically a header larger than 6 bytes can exist # but no one has seen one in the wild # But correctly ignore unknown data if it is though if header_chunk_zise > 6: raw_in.moveCursor(header_chunk_zise-6) # call the header event handler on the stream self.dispatch.header(self.format, self.nTracks, self.division) def parseMTrkChunk(self): "Parses a track chunk. This is the most important part of the parser." # set time to 0 at start of a track self.dispatch.reset_time() dispatch = self.dispatch raw_in = self.raw_in # Trigger event at the start of a track dispatch.start_of_track(self._current_track) # position cursor after track header raw_in.moveCursor(4) # unsigned long is 4 bytes tracklength = raw_in.readBew(4) track_endposition = raw_in.getCursor() + tracklength # absolute position! while raw_in.getCursor() < track_endposition: # find relative time of the event time = raw_in.readVarLen() dispatch.update_time(time) # be aware of running status!!!! peak_ahead = raw_in.readBew(move_cursor=0) if (peak_ahead & 0x80): # the status byte has the high bit set, so it # was not running data but proper status byte status = raw_in.readBew() if not peak_ahead in [META_EVENT, SYSTEM_EXCLUSIVE]: self._running_status = status else: # use that darn running status status = self._running_status # could it be illegal data ?? Do we need to test for that? # I need more example midi files to be shure. # Also, while I am almost certain that no realtime # messages will pop up in a midi file, I might need to # change my mind later. # we need to look at nibbles here hi_nible, lo_nible = status & 0xF0, status & 0x0F # match up with events # Is it a meta_event ?? # these only exists in midi files, not in transmitted midi data # In transmitted data META_EVENT (0xFF) is a system reset if status == META_EVENT: meta_type = raw_in.readBew() meta_length = raw_in.readVarLen() meta_data = raw_in.nextSlice(meta_length) if not meta_length: return dispatch.meta_event(meta_type, meta_data) if meta_type == END_OF_TRACK: return # Is it a sysex_event ?? elif status == SYSTEM_EXCLUSIVE: # ignore sysex events sysex_length = raw_in.readVarLen() # don't read sysex terminator sysex_data = raw_in.nextSlice(sysex_length-1) # only read last data byte if it is a sysex terminator # It should allways be there, but better safe than sorry if raw_in.readBew(move_cursor=0) == END_OFF_EXCLUSIVE: eo_sysex = raw_in.readBew() dispatch.sysex_event(sysex_data) # the sysex code has not been properly tested, and might be fishy! # is it a system common event? elif hi_nible == 0xF0: # Hi bits are set then data_sizes = { MTC:1, SONG_POSITION_POINTER:2, SONG_SELECT:1, } data_size = data_sizes.get(hi_nible, 0) common_data = raw_in.nextSlice(data_size) common_type = lo_nible dispatch.system_common(common_type, common_data) # Oh! Then it must be a midi event (channel voice message) else: data_sizes = { PATCH_CHANGE:1, CHANNEL_PRESSURE:1, NOTE_OFF:2, NOTE_ON:2, AFTERTOUCH:2, CONTINUOUS_CONTROLLER:2, PITCH_BEND:2, } data_size = data_sizes.get(hi_nible, 0) channel_data = raw_in.nextSlice(data_size) event_type, channel = hi_nible, lo_nible dispatch.channel_messages(event_type, channel, channel_data) def parseMTrkChunks(self): "Parses all track chunks." for t in range(self.nTracks): self._current_track = t self.parseMTrkChunk() # this is where it's at! self.dispatch.eof() if __name__ == '__main__': import sys # get data test_file = 'test/midifiles/minimal.mid' test_file = 'test/midifiles/cubase-minimal.mid' test_file = 'test/midifiles/Lola.mid' test_file = sys.argv[1] # f = open(test_file, 'rb') # raw_data = f.read() # f.close() # # # # do parsing from MidiToText import MidiToText from RawInstreamFile import RawInstreamFile midi_in = MidiFileParser(RawInstreamFile(test_file), MidiToText()) midi_in.parseMThdChunk() midi_in.parseMTrkChunks()
Python
# -*- coding: ISO-8859-1 -*- from RawInstreamFile import RawInstreamFile from MidiFileParser import MidiFileParser class MidiInFile: """ Parses a midi file, and triggers the midi events on the outStream object. Get example data from a minimal midi file, generated with cubase. >>> test_file = 'C:/Documents and Settings/maxm/Desktop/temp/midi/src/midi/tests/midifiles/minimal-cubase-type0.mid' Do parsing, and generate events with MidiToText, so we can see what a minimal midi file contains >>> from MidiToText import MidiToText >>> midi_in = MidiInFile(MidiToText(), test_file) >>> midi_in.read() format: 0, nTracks: 1, division: 480 ---------------------------------- <BLANKLINE> Start - track #0 sequence_name: Type 0 tempo: 500000 time_signature: 4 2 24 8 note_on - ch:00, note:48, vel:64 time:0 note_off - ch:00, note:48, vel:40 time:480 End of track <BLANKLINE> End of file """ def __init__(self, outStream, infile): # these could also have been mixins, would that be better? Nah! self.raw_in = RawInstreamFile(infile) self.parser = MidiFileParser(self.raw_in, outStream) def read(self): "Start parsing the file" p = self.parser p.parseMThdChunk() p.parseMTrkChunks() def setData(self, data=''): "Sets the data from a plain string" self.raw_in.setData(data)
Python
# -*- coding: ISO-8859-1 -*- class MidiOutStream: """ MidiOutstream is Basically an eventhandler. It is the most central class in the Midi library. You use it both for writing events to an output stream, and as an event handler for an input stream. This makes it extremely easy to take input from one stream and send it to another. Ie. if you want to read a Midi file, do some processing, and send it to a midiport. All time values are in absolute values from the opening of a stream. To calculate time values, please use the MidiTime and MidiDeltaTime classes. """ def __init__(self): # the time is rather global, so it needs to be stored # here. Otherwise there would be no really simple way to # calculate it. The alternative would be to have each event # handler do it. That sucks even worse! self._absolute_time = 0 self._relative_time = 0 self._current_track = 0 self._running_status = None # time handling event handlers. They should be overwritten with care def update_time(self, new_time=0, relative=1): """ Updates the time, if relative is true, new_time is relative, else it's absolute. """ if relative: self._relative_time = new_time self._absolute_time += new_time else: self._relative_time = new_time - self._absolute_time self._absolute_time = new_time def reset_time(self): """ reset time to 0 """ self._relative_time = 0 self._absolute_time = 0 def rel_time(self): "Returns the relative time" return self._relative_time def abs_time(self): "Returns the absolute time" return self._absolute_time # running status methods def reset_run_stat(self): "Invalidates the running status" self._running_status = None def set_run_stat(self, new_status): "Set the new running status" self._running_status = new_status def get_run_stat(self): "Set the new running status" return self._running_status # track handling event handlers def set_current_track(self, new_track): "Sets the current track number" self._current_track = new_track def get_current_track(self): "Returns the current track number" return self._current_track ##################### ## Midi events def channel_message(self, message_type, channel, data): """The default event handler for channel messages""" pass def note_on(self, channel=0, note=0x40, velocity=0x40): """ channel: 0-15 note, velocity: 0-127 """ pass def note_off(self, channel=0, note=0x40, velocity=0x40): """ channel: 0-15 note, velocity: 0-127 """ pass def aftertouch(self, channel=0, note=0x40, velocity=0x40): """ channel: 0-15 note, velocity: 0-127 """ pass def continuous_controller(self, channel, controller, value): """ channel: 0-15 controller, value: 0-127 """ pass def patch_change(self, channel, patch): """ channel: 0-15 patch: 0-127 """ pass def channel_pressure(self, channel, pressure): """ channel: 0-15 pressure: 0-127 """ pass def pitch_bend(self, channel, value): """ channel: 0-15 value: 0-16383 """ pass ##################### ## System Exclusive def system_exclusive(self, data): """ data: list of values in range(128) """ pass ##################### ## Common events def song_position_pointer(self, value): """ value: 0-16383 """ pass def song_select(self, songNumber): """ songNumber: 0-127 """ pass def tuning_request(self): """ No values passed """ pass def midi_time_code(self, msg_type, values): """ msg_type: 0-7 values: 0-15 """ pass ######################### # header does not really belong here. But anyhoo!!! def header(self, format=0, nTracks=1, division=96): """ format: type of midi file in [1,2] nTracks: number of tracks division: timing division """ pass def eof(self): """ End of file. No more events to be processed. """ pass ##################### ## meta events def meta_event(self, meta_type, data): """ Handles any undefined meta events """ pass def start_of_track(self, n_track=0): """ n_track: number of track """ pass def end_of_track(self): """ n_track: number of track """ pass def sequence_number(self, value): """ value: 0-16383 """ pass def text(self, text): """ Text event text: string """ pass def copyright(self, text): """ Copyright notice text: string """ pass def sequence_name(self, text): """ Sequence/track name text: string """ pass def instrument_name(self, text): """ text: string """ pass def lyric(self, text): """ text: string """ pass def marker(self, text): """ text: string """ pass def cuepoint(self, text): """ text: string """ pass def midi_ch_prefix(self, channel): """ channel: midi channel for subsequent data (deprecated in the spec) """ pass def midi_port(self, value): """ value: Midi port (deprecated in the spec) """ pass def tempo(self, value): """ value: 0-2097151 tempo in us/quarternote (to calculate value from bpm: int(60,000,000.00 / BPM)) """ pass def smtp_offset(self, hour, minute, second, frame, framePart): """ hour, minute, second: 3 bytes specifying the hour (0-23), minutes (0-59) and seconds (0-59), respectively. The hour should be encoded with the SMPTE format, just as it is in MIDI Time Code. frame: A byte specifying the number of frames per second (one of : 24, 25, 29, 30). framePart: A byte specifying the number of fractional frames, in 100ths of a frame (even in SMPTE-based tracks using a different frame subdivision, defined in the MThd chunk). """ pass def time_signature(self, nn, dd, cc, bb): """ nn: Numerator of the signature as notated on sheet music dd: Denominator of the signature as notated on sheet music The denominator is a negative power of 2: 2 = quarter note, 3 = eighth, etc. cc: The number of MIDI clocks in a metronome click bb: The number of notated 32nd notes in a MIDI quarter note (24 MIDI clocks) """ pass def key_signature(self, sf, mi): """ sf: is a byte specifying the number of flats (-ve) or sharps (+ve) that identifies the key signature (-7 = 7 flats, -1 = 1 flat, 0 = key of C, 1 = 1 sharp, etc). mi: is a byte specifying a major (0) or minor (1) key. """ pass def sequencer_specific(self, data): """ data: The data as byte values """ pass ##################### ## realtime events def timing_clock(self): """ No values passed """ pass def song_start(self): """ No values passed """ pass def song_stop(self): """ No values passed """ pass def song_continue(self): """ No values passed """ pass def active_sensing(self): """ No values passed """ pass def system_reset(self): """ No values passed """ pass if __name__ == '__main__': midiOut = MidiOutStream() midiOut.update_time(0,0) midiOut.note_on(0, 63, 127) midiOut.note_off(0, 63, 127)
Python
# -*- coding: ISO-8859-1 -*- # standard library imports import sys from types import StringType from struct import unpack from cStringIO import StringIO # custom import from DataTypeConverters import writeBew, writeVar, fromBytes class RawOutstreamFile: """ Writes a midi file to disk. """ def __init__(self, outfile=''): self.buffer = StringIO() self.outfile = outfile # native data reading functions def writeSlice(self, str_slice): "Writes the next text slice to the raw data" self.buffer.write(str_slice) def writeBew(self, value, length=1): "Writes a value to the file as big endian word" self.writeSlice(writeBew(value, length)) def writeVarLen(self, value): "Writes a variable length word to the file" var = self.writeSlice(writeVar(value)) def write(self): "Writes to disc" if self.outfile: if isinstance(self.outfile, StringType): outfile = open(self.outfile, 'wb') outfile.write(self.getvalue()) outfile.close() else: self.outfile.write(self.getvalue()) else: sys.stdout.write(self.getvalue()) def getvalue(self): return self.buffer.getvalue() if __name__ == '__main__': out_file = 'test/midifiles/midiout.mid' out_file = '' rawOut = RawOutstreamFile(out_file) rawOut.writeSlice('MThd') rawOut.writeBew(6, 4) rawOut.writeBew(1, 2) rawOut.writeBew(2, 2) rawOut.writeBew(15360, 2) rawOut.write()
Python
# -*- coding: ISO-8859-1 -*- from MidiOutStream import MidiOutStream class MidiInStream: """ Takes midi events from the midi input and calls the apropriate method in the eventhandler object """ def __init__(self, midiOutStream, device): """ Sets a default output stream, and sets the device from where the input comes """ if midiOutStream is None: self.midiOutStream = MidiOutStream() else: self.midiOutStream = midiOutStream def close(self): """ Stop the MidiInstream """ def read(self, time=0): """ Start the MidiInstream. "time" sets timer to specific start value. """ def resetTimer(self, time=0): """ Resets the timer, probably a good idea if there is some kind of looping going on """
Python
# -*- coding: ISO-8859-1 -*- ################################################### ## Definitions of the different midi events ################################################### ## Midi channel events (The most usual events) ## also called "Channel Voice Messages" NOTE_OFF = 0x80 # 1000cccc 0nnnnnnn 0vvvvvvv (channel, note, velocity) NOTE_ON = 0x90 # 1001cccc 0nnnnnnn 0vvvvvvv (channel, note, velocity) AFTERTOUCH = 0xA0 # 1010cccc 0nnnnnnn 0vvvvvvv (channel, note, velocity) CONTINUOUS_CONTROLLER = 0xB0 # see Channel Mode Messages!!! # 1011cccc 0ccccccc 0vvvvvvv (channel, controller, value) PATCH_CHANGE = 0xC0 # 1100cccc 0ppppppp (channel, program) CHANNEL_PRESSURE = 0xD0 # 1101cccc 0ppppppp (channel, pressure) PITCH_BEND = 0xE0 # 1110cccc 0vvvvvvv 0wwwwwww (channel, value-lo, value-hi) ################################################### ## Channel Mode Messages (Continuous Controller) ## They share a status byte. ## The controller makes the difference here # High resolution continuous controllers (MSB) BANK_SELECT = 0x00 MODULATION_WHEEL = 0x01 BREATH_CONTROLLER = 0x02 FOOT_CONTROLLER = 0x04 PORTAMENTO_TIME = 0x05 DATA_ENTRY = 0x06 CHANNEL_VOLUME = 0x07 BALANCE = 0x08 PAN = 0x0A EXPRESSION_CONTROLLER = 0x0B EFFECT_CONTROL_1 = 0x0C EFFECT_CONTROL_2 = 0x0D GEN_PURPOSE_CONTROLLER_1 = 0x10 GEN_PURPOSE_CONTROLLER_2 = 0x11 GEN_PURPOSE_CONTROLLER_3 = 0x12 GEN_PURPOSE_CONTROLLER_4 = 0x13 # High resolution continuous controllers (LSB) BANK_SELECT = 0x20 MODULATION_WHEEL = 0x21 BREATH_CONTROLLER = 0x22 FOOT_CONTROLLER = 0x24 PORTAMENTO_TIME = 0x25 DATA_ENTRY = 0x26 CHANNEL_VOLUME = 0x27 BALANCE = 0x28 PAN = 0x2A EXPRESSION_CONTROLLER = 0x2B EFFECT_CONTROL_1 = 0x2C EFFECT_CONTROL_2 = 0x2D GENERAL_PURPOSE_CONTROLLER_1 = 0x30 GENERAL_PURPOSE_CONTROLLER_2 = 0x31 GENERAL_PURPOSE_CONTROLLER_3 = 0x32 GENERAL_PURPOSE_CONTROLLER_4 = 0x33 # Switches SUSTAIN_ONOFF = 0x40 PORTAMENTO_ONOFF = 0x41 SOSTENUTO_ONOFF = 0x42 SOFT_PEDAL_ONOFF = 0x43 LEGATO_ONOFF = 0x44 HOLD_2_ONOFF = 0x45 # Low resolution continuous controllers SOUND_CONTROLLER_1 = 0x46 # (TG: Sound Variation; FX: Exciter On/Off) SOUND_CONTROLLER_2 = 0x47 # (TG: Harmonic Content; FX: Compressor On/Off) SOUND_CONTROLLER_3 = 0x48 # (TG: Release Time; FX: Distortion On/Off) SOUND_CONTROLLER_4 = 0x49 # (TG: Attack Time; FX: EQ On/Off) SOUND_CONTROLLER_5 = 0x4A # (TG: Brightness; FX: Expander On/Off)75 SOUND_CONTROLLER_6 (TG: Undefined; FX: Reverb OnOff) SOUND_CONTROLLER_7 = 0x4C # (TG: Undefined; FX: Delay OnOff) SOUND_CONTROLLER_8 = 0x4D # (TG: Undefined; FX: Pitch Transpose OnOff) SOUND_CONTROLLER_9 = 0x4E # (TG: Undefined; FX: Flange/Chorus OnOff) SOUND_CONTROLLER_10 = 0x4F # (TG: Undefined; FX: Special Effects OnOff) GENERAL_PURPOSE_CONTROLLER_5 = 0x50 GENERAL_PURPOSE_CONTROLLER_6 = 0x51 GENERAL_PURPOSE_CONTROLLER_7 = 0x52 GENERAL_PURPOSE_CONTROLLER_8 = 0x53 PORTAMENTO_CONTROL = 0x54 # (PTC) (0vvvvvvv is the source Note number) (Detail) EFFECTS_1 = 0x5B # (Ext. Effects Depth) EFFECTS_2 = 0x5C # (Tremelo Depth) EFFECTS_3 = 0x5D # (Chorus Depth) EFFECTS_4 = 0x5E # (Celeste Depth) EFFECTS_5 = 0x5F # (Phaser Depth) DATA_INCREMENT = 0x60 # (0vvvvvvv is n/a; use 0) DATA_DECREMENT = 0x61 # (0vvvvvvv is n/a; use 0) NON_REGISTERED_PARAMETER_NUMBER = 0x62 # (LSB) NON_REGISTERED_PARAMETER_NUMBER = 0x63 # (MSB) REGISTERED_PARAMETER_NUMBER = 0x64 # (LSB) REGISTERED_PARAMETER_NUMBER = 0x65 # (MSB) # Channel Mode messages - (Detail) ALL_SOUND_OFF = 0x78 RESET_ALL_CONTROLLERS = 0x79 LOCAL_CONTROL_ONOFF = 0x7A ALL_NOTES_OFF = 0x7B OMNI_MODE_OFF = 0x7C # (also causes ANO) OMNI_MODE_ON = 0x7D # (also causes ANO) MONO_MODE_ON = 0x7E # (Poly Off; also causes ANO) POLY_MODE_ON = 0x7F # (Mono Off; also causes ANO) ################################################### ## System Common Messages, for all channels SYSTEM_EXCLUSIVE = 0xF0 # 11110000 0iiiiiii 0ddddddd ... 11110111 MTC = 0xF1 # MIDI Time Code Quarter Frame # 11110001 SONG_POSITION_POINTER = 0xF2 # 11110010 0vvvvvvv 0wwwwwww (lo-position, hi-position) SONG_SELECT = 0xF3 # 11110011 0sssssss (songnumber) #UNDEFINED = 0xF4 ## 11110100 #UNDEFINED = 0xF5 ## 11110101 TUNING_REQUEST = 0xF6 # 11110110 END_OFF_EXCLUSIVE = 0xF7 # terminator # 11110111 # End of system exclusive ################################################### ## Midifile meta-events SEQUENCE_NUMBER = 0x00 # 00 02 ss ss (seq-number) TEXT = 0x01 # 01 len text... COPYRIGHT = 0x02 # 02 len text... SEQUENCE_NAME = 0x03 # 03 len text... INSTRUMENT_NAME = 0x04 # 04 len text... LYRIC = 0x05 # 05 len text... MARKER = 0x06 # 06 len text... CUEPOINT = 0x07 # 07 len text... PROGRAM_NAME = 0x08 # 08 len text... DEVICE_NAME = 0x09 # 09 len text... MIDI_CH_PREFIX = 0x20 # MIDI channel prefix assignment (unofficial) MIDI_PORT = 0x21 # 21 01 port, legacy stuff but still used END_OF_TRACK = 0x2F # 2f 00 TEMPO = 0x51 # 51 03 tt tt tt (tempo in us/quarternote) SMTP_OFFSET = 0x54 # 54 05 hh mm ss ff xx TIME_SIGNATURE = 0x58 # 58 04 nn dd cc bb KEY_SIGNATURE = 0x59 # ??? len text... SPECIFIC = 0x7F # Sequencer specific event FILE_HEADER = 'MThd' TRACK_HEADER = 'MTrk' ################################################### ## System Realtime messages ## I don't supose these are to be found in midi files?! TIMING_CLOCK = 0xF8 # undefined = 0xF9 SONG_START = 0xFA SONG_CONTINUE = 0xFB SONG_STOP = 0xFC # undefined = 0xFD ACTIVE_SENSING = 0xFE SYSTEM_RESET = 0xFF ################################################### ## META EVENT, it is used only in midi files. ## In transmitted data it means system reset!!! META_EVENT = 0xFF # 11111111 ################################################### ## Helper functions def is_status(byte): return (byte & 0x80) == 0x80 # 1000 0000
Python
# -*- coding: ISO-8859-1 -*- from MidiOutStream import MidiOutStream from MidiOutFile import MidiOutFile from MidiInStream import MidiInStream from MidiInFile import MidiInFile from MidiToText import MidiToText
Python
# -*- coding: ISO-8859-1 -*- from MidiOutStream import MidiOutStream from RawOutstreamFile import RawOutstreamFile from constants import * from DataTypeConverters import fromBytes, writeVar class MidiOutFile(MidiOutStream): """ MidiOutFile is an eventhandler that subclasses MidiOutStream. """ def __init__(self, raw_out=''): self.raw_out = RawOutstreamFile(raw_out) MidiOutStream.__init__(self) def write(self): self.raw_out.write() def event_slice(self, slc): """ Writes the slice of an event to the current track. Correctly inserting a varlen timestamp too. """ trk = self._current_track_buffer trk.writeVarLen(self.rel_time()) trk.writeSlice(slc) ##################### ## Midi events def note_on(self, channel=0, note=0x40, velocity=0x40): """ channel: 0-15 note, velocity: 0-127 """ slc = fromBytes([NOTE_ON + channel, note, velocity]) self.event_slice(slc) def note_off(self, channel=0, note=0x40, velocity=0x40): """ channel: 0-15 note, velocity: 0-127 """ slc = fromBytes([NOTE_OFF + channel, note, velocity]) self.event_slice(slc) def aftertouch(self, channel=0, note=0x40, velocity=0x40): """ channel: 0-15 note, velocity: 0-127 """ slc = fromBytes([AFTERTOUCH + channel, note, velocity]) self.event_slice(slc) def continuous_controller(self, channel, controller, value): """ channel: 0-15 controller, value: 0-127 """ slc = fromBytes([CONTINUOUS_CONTROLLER + channel, controller, value]) self.event_slice(slc) # These should probably be implemented # http://users.argonet.co.uk/users/lenny/midi/tech/spec.html#ctrlnums def patch_change(self, channel, patch): """ channel: 0-15 patch: 0-127 """ slc = fromBytes([PATCH_CHANGE + channel, patch]) self.event_slice(slc) def channel_pressure(self, channel, pressure): """ channel: 0-15 pressure: 0-127 """ slc = fromBytes([CHANNEL_PRESSURE + channel, pressure]) self.event_slice(slc) def pitch_bend(self, channel, value): """ channel: 0-15 value: 0-16383 """ msb = (value>>7) & 0xFF lsb = value & 0xFF slc = fromBytes([PITCH_BEND + channel, msb, lsb]) self.event_slice(slc) ##################### ## System Exclusive # def sysex_slice(sysex_type, data): # "" # sysex_len = writeVar(len(data)+1) # self.event_slice(SYSTEM_EXCLUSIVE + sysex_len + data + END_OFF_EXCLUSIVE) # def system_exclusive(self, data): """ data: list of values in range(128) """ sysex_len = writeVar(len(data)+1) self.event_slice(chr(SYSTEM_EXCLUSIVE) + sysex_len + data + chr(END_OFF_EXCLUSIVE)) ##################### ## Common events def midi_time_code(self, msg_type, values): """ msg_type: 0-7 values: 0-15 """ value = (msg_type<<4) + values self.event_slice(fromBytes([MIDI_TIME_CODE, value])) def song_position_pointer(self, value): """ value: 0-16383 """ lsb = (value & 0x7F) msb = (value >> 7) & 0x7F self.event_slice(fromBytes([SONG_POSITION_POINTER, lsb, msb])) def song_select(self, songNumber): """ songNumber: 0-127 """ self.event_slice(fromBytes([SONG_SELECT, songNumber])) def tuning_request(self): """ No values passed """ self.event_slice(chr(TUNING_REQUEST)) ######################### # header does not really belong here. But anyhoo!!! def header(self, format=0, nTracks=1, division=96): """ format: type of midi file in [0,1,2] nTracks: number of tracks. 1 track for type 0 file division: timing division ie. 96 ppq. """ raw = self.raw_out raw.writeSlice('MThd') bew = raw.writeBew bew(6, 4) # header size bew(format, 2) bew(nTracks, 2) bew(division, 2) def eof(self): """ End of file. No more events to be processed. """ # just write the file then. self.write() ##################### ## meta events def meta_slice(self, meta_type, data_slice): "Writes a meta event" slc = fromBytes([META_EVENT, meta_type]) + \ writeVar(len(data_slice)) + data_slice self.event_slice(slc) def meta_event(self, meta_type, data): """ Handles any undefined meta events """ self.meta_slice(meta_type, fromBytes(data)) def start_of_track(self, n_track=0): """ n_track: number of track """ self._current_track_buffer = RawOutstreamFile() self.reset_time() self._current_track += 1 def end_of_track(self): """ Writes the track to the buffer. """ raw = self.raw_out raw.writeSlice(TRACK_HEADER) track_data = self._current_track_buffer.getvalue() # wee need to know size of track data. eot_slice = writeVar(self.rel_time()) + fromBytes([META_EVENT, END_OF_TRACK, 0]) raw.writeBew(len(track_data)+len(eot_slice), 4) # then write raw.writeSlice(track_data) raw.writeSlice(eot_slice) def sequence_number(self, value): """ value: 0-65535 """ self.meta_slice(meta_type, writeBew(value, 2)) def text(self, text): """ Text event text: string """ self.meta_slice(TEXT, text) def copyright(self, text): """ Copyright notice text: string """ self.meta_slice(COPYRIGHT, text) def sequence_name(self, text): """ Sequence/track name text: string """ self.meta_slice(SEQUENCE_NAME, text) def instrument_name(self, text): """ text: string """ self.meta_slice(INSTRUMENT_NAME, text) def lyric(self, text): """ text: string """ self.meta_slice(LYRIC, text) def marker(self, text): """ text: string """ self.meta_slice(MARKER, text) def cuepoint(self, text): """ text: string """ self.meta_slice(CUEPOINT, text) def midi_ch_prefix(self, channel): """ channel: midi channel for subsequent data (deprecated in the spec) """ self.meta_slice(MIDI_CH_PREFIX, chr(channel)) def midi_port(self, value): """ value: Midi port (deprecated in the spec) """ self.meta_slice(MIDI_CH_PREFIX, chr(value)) def tempo(self, value): """ value: 0-2097151 tempo in us/quarternote (to calculate value from bpm: int(60,000,000.00 / BPM)) """ hb, mb, lb = (value>>16 & 0xff), (value>>8 & 0xff), (value & 0xff) self.meta_slice(TEMPO, fromBytes([hb, mb, lb])) def smtp_offset(self, hour, minute, second, frame, framePart): """ hour, minute, second: 3 bytes specifying the hour (0-23), minutes (0-59) and seconds (0-59), respectively. The hour should be encoded with the SMPTE format, just as it is in MIDI Time Code. frame: A byte specifying the number of frames per second (one of : 24, 25, 29, 30). framePart: A byte specifying the number of fractional frames, in 100ths of a frame (even in SMPTE-based tracks using a different frame subdivision, defined in the MThd chunk). """ self.meta_slice(SMTP_OFFSET, fromBytes([hour, minute, second, frame, framePart])) def time_signature(self, nn, dd, cc, bb): """ nn: Numerator of the signature as notated on sheet music dd: Denominator of the signature as notated on sheet music The denominator is a negative power of 2: 2 = quarter note, 3 = eighth, etc. cc: The number of MIDI clocks in a metronome click bb: The number of notated 32nd notes in a MIDI quarter note (24 MIDI clocks) """ self.meta_slice(TIME_SIGNATURE, fromBytes([nn, dd, cc, bb])) def key_signature(self, sf, mi): """ sf: is a byte specifying the number of flats (-ve) or sharps (+ve) that identifies the key signature (-7 = 7 flats, -1 = 1 flat, 0 = key of C, 1 = 1 sharp, etc). mi: is a byte specifying a major (0) or minor (1) key. """ self.meta_slice(KEY_SIGNATURE, fromBytes([sf, mi])) def sequencer_specific(self, data): """ data: The data as byte values """ self.meta_slice(SEQUENCER_SPECIFIC, data) # ##################### # ## realtime events # These are of no use in a midi file, so they are ignored!!! # def timing_clock(self): # def song_start(self): # def song_stop(self): # def song_continue(self): # def active_sensing(self): # def system_reset(self): if __name__ == '__main__': out_file = 'test/midifiles/midiout.mid' midi = MidiOutFile(out_file) #format: 0, nTracks: 1, division: 480 #---------------------------------- # #Start - track #0 #sequence_name: Type 0 #tempo: 500000 #time_signature: 4 2 24 8 #note_on - ch:00, note:48, vel:64 time:0 #note_off - ch:00, note:48, vel:40 time:480 #End of track # #End of file midi.header(0, 1, 480) midi.start_of_track() midi.sequence_name('Type 0') midi.tempo(750000) midi.time_signature(4, 2, 24, 8) ch = 0 for i in range(127): midi.note_on(ch, i, 0x64) midi.update_time(96) midi.note_off(ch, i, 0x40) midi.update_time(0) midi.update_time(0) midi.end_of_track() midi.eof() # currently optional, should it do the write instead of write?? midi.write()
Python
##################################################################### # -*- coding: iso-8859-1 -*- # # # # Frets on Fire X (FoFiX) # # Copyright (C) 2009 myfingershurt # # 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. # ##################################################################### """Drop-in replacements for socket and asyncore that implement loopback connections, sans the loopback connections. Only the necessary functionality to replace FoFiX's loopback connection is implemented. Limitations: - TCP only - Address connected to/listened to is ignored. - EOF doesn't get passed around correctly, but the rest of the code seems to be able to deal with it. - socket.errors are raised with strings rather than tuples. - All sockets are non-blocking. - No support for select(). - Probably rough around the edges in many other ways. """ __version__ = '$Id: FakeNetworking.py 914 2009-02-05 01:18:15Z john.stumpo $' # Keep track of what ports are being listened to. class FakeTcpStack(object): def __init__(self): self.openPorts = {} def registerOpenPort(self, port, obj): if self.openPorts.has_key(port): raise socket.error, 'Address already in use.' self.openPorts[port] = obj def releaseOpenPort(self, port): del self.openPorts[port] def connectSocket(self, port, sock): if not self.openPorts.has_key(port): raise socket.error, 'Connection refused.' self.openPorts[port].backlog.append(sock) tcpStack = FakeTcpStack() # singleton instance del FakeTcpStack # Reimplementation of socket. class socket(object): AF_INET = None SOCK_STREAM = None class error(Exception): pass def __init__(self, af, socktype, proto): self.bindaddr = None self.pairedSocket = None self.listening = False self.buf = '' def __del__(self): self.close() @staticmethod def socket(af, socktype, proto): return socket(af, socktype, proto) def bind(self, addr): if self.listening or (self.pairedSocket is not None) or (self.bindaddr is not None): raise socket.error, 'Socket already bound.' self.bindaddr = addr def listen(self, backlog): self.backlog = [] self.listening = True tcpStack.registerOpenPort(self.bindaddr[1], self) def accept(self): if not self.listening: raise socket.error, 'Invalid argument.' if not len(self.backlog): raise socket.error, 'The socket operation could not complete without blocking.' s = self.backlog[0] del self.backlog[0] return s, ('127.0.0.1', 1024) def connect(self, addr): self.pairedSocket = socket.socket(None, None, None) self.pairedSocket.pairedSocket = self tcpStack.connectSocket(addr[1], self.pairedSocket) def close(self): if self.pairedSocket is not None: self.pairedSocket = None if self.listening: try: tcpStack.releaseOpenPort(self.bindaddr[1]) except: pass del self.backlog self.listening = False self.bindaddr = None def send(self, buf, length=None): if self.pairedSocket is None: raise socket.error, 'Socket is not connected.' try: self.pairedSocket.buf += buf return len(buf) except: self.close() raise socket.error, 'Connection reset by peer.' sendall = send def recv(self, length=4096): if self.pairedSocket is None: raise socket.error, 'Socket is not connected.' try: if len(self.buf) == 0: raise socket.error, 'The socket operation could not complete without blocking.' if len(self.buf) < length: buf = self.buf self.buf = '' return buf buf = self.buf[:length] self.buf = self.buf[length:] return buf except socket.error: raise except: self.close() raise socket.error, 'Connection reset by peer.' def readable(self): return (len(self.buf) > 0) def writable(self): return (self.pairedSocket is not None) def acceptable(self): return (self.listening and len(self.backlog) > 0) # Reimplementation of asyncore atop the above. class asyncore(object): socket_map = [] class dispatcher(object): def __init__(self, sock=None): self._socket = sock self.connected = False asyncore.socket_map.append(self) def __del__(self): self.close() def create_socket(self, af, socktype): self._socket = socket.socket(af, socktype, 0) def set_reuse_addr(self): pass def bind(self, addr): if self._socket is None: raise socket.error, 'Bad file descriptor' self._socket.bind(addr) def listen(self, backlog): if self._socket is None: raise socket.error, 'Bad file descriptor' self._socket.listen(backlog) def accept(self): if self._socket is None: raise socket.error, 'Bad file descriptor' return self._socket.accept() def close(self): if self._socket is not None: self._socket.close() self._socket = None try: asyncore.socket_map.remove(self) except ValueError: pass def send(self, data): if self._socket is None: raise socket.error, 'Bad file descriptor' return self._socket.send(data) def recv(self, length=4096): if self._socket is None: raise socket.error, 'Bad file descriptor' return self._socket.recv(length) def connect(self, addr): if self._socket is None: raise socket.error, 'Bad file descriptor' self._socket.connect(addr) self.connected = True def readable(self): if self._socket is None: return False return self._socket.readable() def writable(self): if self._socket is None: return False return self._socket.writable() def acceptable(self): if self._socket is None: return False return self._socket.acceptable() @classmethod def poll(self, arg, lst): for d in lst: if d.readable(): if hasattr(d, 'handle_read'): d.handle_read() if d.writable(): if hasattr(d, 'handle_write'): d.handle_write() if d.acceptable(): if hasattr(d, 'handle_accept'): d.handle_accept() @classmethod def close_all(self): pass
Python
import re f = open("/etc/X11/rgb.txt") print "colors = {" for l in f.readlines(): if l.startswith("!"): continue c = re.split("[ \t]+", l.strip()) rgb, names = map(int, c[:3]), c[3:] rgb = [float(c) / 255.0 for c in rgb] for n in names: print ' %-24s: (%.2f, %.2f, %.2f),' % ('"%s"' % n.lower(), rgb[0], rgb[1], rgb[2]) print "}"
Python
##################################################################### # -*- coding: iso-8859-1 -*- # # # # Frets on Fire # # Copyright (C) 2006 Sami Kyostila # # 2008 Alarian # # 2008 myfingershurt # # 2008 Glorandwarf # # 2008 Capo # # 2008 Blazingamer # # 2008 evilynux <evilynux@gmail.com> # # # # 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. # ##################################################################### #altered by myfingershurt to adapt to Alarian mod import Player from Song import Note, Tempo from Mesh import Mesh import Theme import random from copy import deepcopy from Shader import shaders from OpenGL.GL import * import math from numpy import array, float32 #myfingershurt: needed for multi-OS file fetching import os import Log import Song #need the base song defines as well #Normal guitar key color order: Green, Red, Yellow, Blue, Orange #Drum fret color order: Red, Yellow, Blue, Green #actual drum note numbers: #0 = bass drum (stretched Orange fret), normally Green fret #1 = drum Red fret, normally Red fret #2 = drum Yellow fret, normally Yellow fret #3 = drum Blue fret, normally Blue fret #4 = drum Green fret, normally Orange fret # #So, with regard to note number coloring, swap note.number 0's color wih note.number 4. #akedrou - 5-drum support is now available. # to enable it, only here and Player.drums should need changing. class Drum: def __init__(self, engine, playerObj, editorMode = False, player = 0): self.engine = engine self.isDrum = True self.isBassGuitar = False self.isVocal = False #self.starPowerDecreaseDivisor = 200.0*self.engine.audioSpeedFactor self.starPowerDecreaseDivisor = 200.0/self.engine.audioSpeedFactor self.bassDrumPedalDown = False self.lastFretWasBassDrum = False self.lastFretWasT1 = False #Faaa Drum sound self.lastFretWasT2 = False self.lastFretWasT3 = False self.lastFretWasC = False self.useMidiSoloMarkers = False self.canGuitarSolo = False self.guitarSolo = False self.sameNoteHopoString = False self.hopoProblemNoteNum = -1 self.currentGuitarSoloHitNotes = 0 self.matchingNotes = None self.bigRockEndingMarkerSeen = False #MFH - I do not understand fully how the handicap scorecard works at the moment, nor do I have the time to figure it out. #... so for now, I'm just writing some extra code here for the early hitwindow size handicap. self.earlyHitWindowSizeFactor = 0.5 self.starNotesInView = False self.openStarNotesInView = False self.cappedScoreMult = 0 self.isStarPhrase = False self.finalStarSeen = False self.freestyleActive = False # Volshebnyi - BRE scoring variables self.freestyleEnabled = False self.freestyleStart = 0 self.freestyleFirstHit = 0 self.freestyleLength = 0 self.freestyleLastHit = 0 self.freestyleBonusFret = -2 self.freestyleLastFretHitTime = range(5) self.freestyleBaseScore = 750 self.freestylePeriod = 1000 self.freestylePercent = 50 self.drumFillsCount = 0 self.drumFillsTotal = 0 self.drumFillsHits = 0 self.drumFillsActive = False self.drumFillsReady = False self.freestyleReady = False self.freestyleOffset = 5 self.freestyleSP = False self.neckAlpha=[] # necks transparency self.neckAlpha.append( self.engine.config.get("game", "necks_alpha") ) # all necks self.neckAlpha.append( self.neckAlpha[0] * self.engine.config.get("game", "neck_alpha") ) # solo neck self.neckAlpha.append( self.neckAlpha[0] * self.engine.config.get("game", "solo_neck_alpha") ) # solo neck self.neckAlpha.append( self.neckAlpha[0] * self.engine.config.get("game", "overlay_neck_alpha") ) # overlay neck self.neckAlpha.append( self.neckAlpha[0] * self.engine.config.get("game", "fail_neck_alpha") ) # fail neck #self.drumFillOnScreen = False #MFH self.drumFillEvents = [] self.drumFillWasJustActive = False #empty variables for class compatibility self.totalPhrases = 0 self.accThresholdWorstLate = 0 self.accThresholdVeryLate = 0 self.accThresholdLate = 0 self.accThresholdSlightlyLate = 0 self.accThresholdExcellentLate = 0 self.accThresholdPerfect = 0 self.accThresholdExcellentEarly = 0 self.accThresholdSlightlyEarly = 0 self.accThresholdEarly = 0 self.accThresholdVeryEarly = 0 self.tempoBpm = 120 #MFH - default is NEEDED here... self.beatsPerBoard = 5.0 self.strings = 4 self.fretWeight = [0.0] * self.strings self.fretActivity = [0.0] * self.strings self.fretColors = Theme.fretColors self.spColor = self.fretColors[5] self.playedNotes = [] self.missedNotes = [] self.editorMode = editorMode self.selectedString = 0 self.time = 0.0 self.pickStartPos = 0 self.leftyMode = False self.drumFlip = False self.battleSuddenDeath = False self.battleObjectsEnabled = [] self.battleSDObjectsEnabled = [] if self.engine.config.get("game", "battle_Whammy") == 1: self.battleObjectsEnabled.append(4) if self.engine.config.get("game", "battle_Diff_Up") == 1: self.battleObjectsEnabled.append(2) if self.engine.config.get("game", "battle_String_Break") == 1: self.battleObjectsEnabled.append(3) if self.engine.config.get("game", "battle_Double") == 1: self.battleObjectsEnabled.append(7) if self.engine.config.get("game", "battle_Death_Drain") == 1: self.battleObjectsEnabled.append(1) if self.engine.config.get("game", "battle_Amp_Overload") == 1: self.battleObjectsEnabled.append(8) if self.engine.config.get("game", "battle_Switch_Controls") == 1: self.battleObjectsEnabled.append(6) if self.engine.config.get("game", "battle_Steal") == 1: self.battleObjectsEnabled.append(5) #if self.engine.config.get("game", "battle_Tune") == 1: # self.battleObjectsEnabled.append(9) Log.debug(self.battleObjectsEnabled) self.battleNextObject = 0 self.battleObjects = [0] * 3 self.battleBeingUsed = [0] * 2 self.battleStatus = [False] * 9 self.battleStartTimes = [0] * 9 self.battleGetTime = 0 self.battleTarget = 0 self.battleLeftyLength = 8000# self.battleDiffUpLength = 15000 self.battleDiffUpValue = playerObj.getDifficultyInt() self.battleDoubleLength = 8000 self.battleAmpLength = 8000 self.battleWhammyLimit = 6# self.battleWhammyNow = 0 self.battleWhammyDown = False self.battleBreakLimit = 8.0 self.battleBreakNow = 0.0 self.battleBreakString = 0 self.battleObjectGained = 0 self.battleSuddenDeath = False self.battleDrainStart = 0 self.battleDrainLength = 8000 self.freestyleHitFlameCounts = [0 for n in range(self.strings+1)] #MFH self.logClassInits = self.engine.config.get("game", "log_class_inits") if self.logClassInits == 1: Log.debug("Drum class initialization!") self.incomingNeckMode = self.engine.config.get("game", "incoming_neck_mode") self.guitarSoloNeckMode = self.engine.config.get("game", "guitar_solo_neck") self.bigRockEndings = self.engine.config.get("game", "big_rock_endings") #self.actualBpm = 0.0 self.currentBpm = 120.0 #MFH - need a default 120BPM to be set in case a custom song has no tempo events. self.currentPeriod = 60000.0 / self.currentBpm self.targetBpm = self.currentBpm self.targetPeriod = 60000.0 / self.targetBpm self.lastBpmChange = -1.0 self.baseBeat = 0.0 #########For Animations self.Animspeed = 30#Lower value = Faster animations #For Animated Starnotes self.indexCount = 0 #Alarian, For animated hitglow self.HCount = 0 self.HCount2 = 0 self.Hitanim = True self.Hitanim2 = True #myfingershurt: to keep track of pause status here as well self.paused = False self.spEnabled = True self.starPower = 0 self.starPowerActive = False self.starPowerGained = False self.starpowerMode = self.engine.config.get("game", "starpower_mode") #MFH self.killPoints = False if self.starpowerMode == 1: self.starNotesSet = False else: self.starNotesSet = True self.maxStars = [] self.starNotes = [] self.totalNotes = 0 #get difficulty self.difficulty = playerObj.getDifficultyInt() self.controlType = playerObj.controlType self.scoreMultiplier = 1 #myfingershurt: self.hopoStyle = 0 self.LastStrumWasChord = False self.spRefillMode = self.engine.config.get("game","sp_notes_while_active") self.hitglow_color = self.engine.config.get("video", "hitglow_color") #this should be global, not retrieved every fret render. #myfingershurt: this should be retrieved once at init, not repeatedly in-game whenever tails are rendered. self.notedisappear = self.engine.config.get("game", "notedisappear") self.fretsUnderNotes = self.engine.config.get("game", "frets_under_notes") self.staticStrings = self.engine.config.get("performance", "static_strings") self.vbpmLogicType = self.engine.config.get("debug", "use_new_vbpm_beta") self.indexFps = self.engine.config.get("video", "fps") self.twoChord = 0 self.twoChordApply = False self.hopoActive = 0 #myfingershurt: need a separate variable to track whether or not hopos are actually active self.wasLastNoteHopod = False self.hopoLast = -1 self.hopoColor = (0, .5, .5) self.player = player self.scoreMultiplier = 1 self.hit = [False, False, False, False, False] self.freestyleHit = [False, False, False, False, False] playerObj = None #Get theme themename = self.engine.data.themeLabel #now theme determination logic is only in data.py: self.theme = self.engine.data.theme #check if BRE enabled if self.bigRockEndings == 2 or (self.theme == 2 and self.bigRockEndings == 1): self.freestyleEnabled = True if self.theme < 2: #make board same size as guitar board if GH based theme so it rockmeters dont interfere self.boardWidth = 3.0 self.boardLength = 9.0 #blazingamer self.nstype = self.engine.config.get("game", "nstype") self.twoDnote = Theme.twoDnote self.twoDkeys = Theme.twoDkeys self.threeDspin = Theme.threeDspin self.opencolor = Theme.opencolor self.ocount = 0 self.noterotate = self.engine.config.get("coffee", "noterotate") self.rockLevel = 0.0 self.failcount = 0 self.failcount2 = False self.spcount = 0 self.spcount2 = 0 #akedrou self.coOpFailed = False self.coOpRestart = False self.coOpRescueTime = 0.0 #MFH- fixing neck speed if self.nstype < 3: #not constant mode: self.speed = self.engine.config.get("coffee", "neckSpeed")*0.01 else: #constant mode #self.speed = self.engine.config.get("coffee", "neckSpeed") self.speed = 410 - self.engine.config.get("coffee", "neckSpeed") #invert this value self.bigMax = 1 if self.engine.config.get("game", "large_drum_neck"): self.boardWidth = 4.0 self.boardLength = 12.0 #death_au: fixed neck size elif self.twoDnote == False or self.twoDkeys == False: self.boardWidth = Theme.neckWidth + 0.6 self.boardLength = Theme.neckLength else: self.boardWidth = Theme.neckWidth self.boardLength = Theme.neckLength self.muteSustainReleases = self.engine.config.get("game", "sustain_muting") #MFH self.hitw = self.engine.config.get("game", "note_hit_window") #this should be global, not retrieved every BPM change. if self.hitw == 0: self.hitw = 2.3 elif self.hitw == 1: self.hitw = 1.9 elif self.hitw == 2: self.hitw = 1.2 elif self.hitw == 3: self.hitw = 1.0 elif self.hitw == 4: self.hitw = 0.70 else: self.hitw = 1.2 self.keys = [] self.actions = [] self.soloKey = [] self.setBPM(self.currentBpm) engine.loadImgDrawing(self, "glowDrawing", "glow.png") #MFH - making hitflames optional self.hitFlamesPresent = False try: engine.loadImgDrawing(self, "hitflames1Drawing", os.path.join("themes",themename,"hitflames1.png"), textureSize = (128, 128)) engine.loadImgDrawing(self, "hitflames2Drawing", os.path.join("themes",themename,"hitflames2.png"), textureSize = (128, 128)) self.hitFlamesPresent = True except IOError: self.hitFlamesPresent = False self.hitflames1Drawing = None self.hitflames2Drawing = None try: engine.loadImgDrawing(self, "hitflamesAnim", os.path.join("themes",themename,"hitflamesanimation.png"), textureSize = (128, 128)) except IOError: #engine.loadImgDrawing(self, "hitflames1Drawing", os.path.join("themes",themename,"hitflames1.png"), textureSize = (128, 128)) #engine.loadImgDrawing(self, "hitflames2Drawing", os.path.join("themes",themename,"hitflames2.png"), textureSize = (128, 128)) self.Hitanim2 = False try: engine.loadImgDrawing(self, "hitglowAnim", os.path.join("themes",themename,"hitglowanimation.png"), textureSize = (128, 128)) except IOError: try: engine.loadImgDrawing(self, "hitglowDrawing", os.path.join("themes",themename,"hitglow.png"), textureSize = (128, 128)) engine.loadImgDrawing(self, "hitglow2Drawing", os.path.join("themes",themename,"hitglow2.png"), textureSize = (128, 128)) except IOError: self.hitglowDrawing = None self.hitglow2Drawing = None self.hitFlamesPresent = False #MFH - shut down all flames if these are missing. self.Hitanim = False if self.twoDkeys == True: #death_au #myfingershurt: adding drumfretshacked.png for image-corrected drum fret angles in RB: try: engine.loadImgDrawing(self, "fretButtons", os.path.join("themes",themename,"drumfretshacked.png")) except IOError: engine.loadImgDrawing(self, "fretButtons", os.path.join("themes",themename,"fretbuttons.png")) #death_au: adding drumfrets.png (with bass drum frets seperate) try: engine.loadImgDrawing(self, "drumFretButtons", os.path.join("themes",themename,"drumfrets.png")) except IOError: self.drumFretButtons = None else: #death_au #MFH - can't use IOError for fallback logic for a Mesh() call... if self.engine.fileExists(os.path.join("themes", themename, "key.dae")): engine.resource.load(self, "keyMesh", lambda: Mesh(engine.resource.fileName("themes", themename, "key.dae"))) else: engine.resource.load(self, "keyMesh", lambda: Mesh(engine.resource.fileName("key.dae"))) try: for i in range(5): engine.loadImgDrawing(self, "keytex"+chr(97+i), os.path.join("themes", themename, "keytex_"+chr(97+i)+".png")) self.keytex = True except IOError: self.keytex = False #Spinning starnotes or not? self.starspin = False if self.twoDnote == True: try: engine.loadImgDrawing(self, "noteButtons", os.path.join("themes",themename,"drumnotes.png")) self.separateDrumNotes = True except IOError: engine.loadImgDrawing(self, "noteButtons", os.path.join("themes",themename,"notes.png")) self.separateDrumNotes = False else: #MFH - can't use IOError for fallback logic for a Mesh() call... if self.engine.fileExists(os.path.join("themes", themename, "note.dae")): engine.resource.load(self, "noteMesh", lambda: Mesh(engine.resource.fileName("themes", themename, "note.dae"))) else: engine.resource.load(self, "noteMesh", lambda: Mesh(engine.resource.fileName("note.dae"))) try: for i in range(5): engine.loadImgDrawing(self, "notetex"+chr(97+i), os.path.join("themes", themename, "notetex_"+chr(97+i)+".png")) self.notetex = True except IOError: self.notetex = False if self.engine.fileExists(os.path.join("themes", themename, "star.dae")): engine.resource.load(self, "starMesh", lambda: Mesh(engine.resource.fileName("themes", themename, "star.dae"))) else: self.starMesh = None try: for i in range(5): engine.loadImgDrawing(self, "startex"+chr(97+i), os.path.join("themes", themename, "startex_"+chr(97+i)+".png")) self.startex = True except IOError: self.startex = False if self.engine.fileExists(os.path.join("themes", themename, "open.dae")): engine.resource.load(self, "openMesh", lambda: Mesh(engine.resource.fileName("themes", themename, "open.dae"))) else: self.openMesh = None try: engine.loadImgDrawing(self, "opentexture", os.path.join("themes", themename, "opentex.png")) self.opentex = True except IOError: self.opentex = False try: engine.loadImgDrawing(self, "freestyle1", os.path.join("themes", themename, "freestyletail1.png"), textureSize = (128, 128)) engine.loadImgDrawing(self, "freestyle2", os.path.join("themes", themename, "freestyletail2.png"), textureSize = (128, 128)) except IOError: engine.loadImgDrawing(self, "freestyle1", "freestyletail1.png", textureSize = (128, 128)) engine.loadImgDrawing(self, "freestyle2", "freestyletail2.png", textureSize = (128, 128)) if self.theme == 0 or self.theme == 1: engine.loadImgDrawing(self, "hitlightning", os.path.join("themes",themename,"lightning.png"), textureSize = (128, 128)) #MFH: support for optional drum_overdrive_string_flash.png self.overdriveFlashCounts = self.indexFps/4 #how many cycles to display the oFlash: self.indexFps/2 = 1/2 second self.overdriveFlashCount = self.overdriveFlashCounts #t'aint no tails in drums, yo. self.simpleTails = True self.tail1 = None self.tail2 = None self.bigTail1 = None self.bigTail2 = None self.meshColor = Theme.meshColor self.hopoColor = Theme.hopoColor self.spotColor = Theme.spotColor self.keyColor = Theme.keyColor self.key2Color = Theme.key2Color self.tracksColor = Theme.tracksColor self.barsColor = Theme.barsColor self.flameColors = Theme.flameColors self.gh3flameColor = Theme.gh3flameColor self.flameSizes = Theme.flameSizes self.glowColor = Theme.glowColor self.twoChordMax = False self.disableVBPM = self.engine.config.get("game", "disable_vbpm") self.disableNoteSFX = self.engine.config.get("video", "disable_notesfx") self.disableFretSFX = self.engine.config.get("video", "disable_fretsfx") self.disableFlameSFX = self.engine.config.get("video", "disable_flamesfx") self.overdriveFlashCounts = self.indexFps/4 #how many cycles to display the oFlash: self.indexFps/2 = 1/2 second #Blazingamer: These variables are updated through the guitarscene which then pass #through to the neck because it is used in both the neck.py and the guitar.py self.canGuitarSolo = False self.guitarSolo = False self.fretboardHop = 0.00 #stump self.scoreMultiplier = 1 self.coOpFailed = False #akedrou self.coOpRestart = False #akedrou self.starPowerActive = False self.overdriveFlashCount = self.overdriveFlashCounts def selectPreviousString(self): self.selectedString = (self.selectedString - 1) % self.strings def selectString(self, string): self.selectedString = string % self.strings def selectNextString(self): self.selectedString = (self.selectedString + 1) % self.strings def noteBeingHeld(self): noteHeld = False return noteHeld def isKillswitchPossible(self): possible = False return possible def setBPM(self, bpm): if bpm > 200: bpm = 200 #MFH - Filter out unnecessary BPM settings (when currentBPM is already set!) #if self.actualBpm != bpm: # self.actualBpm = bpm self.currentBpm = bpm #update current BPM as well #MFH - Neck speed determination: if self.nstype == 0: #BPM mode self.neckSpeed = (340 - bpm)/self.speed elif self.nstype == 1: #Difficulty mode if self.difficulty == 0: #expert self.neckSpeed = 220/self.speed elif self.difficulty == 1: self.neckSpeed = 250/self.speed elif self.difficulty == 2: self.neckSpeed = 280/self.speed else: #easy self.neckSpeed = 300/self.speed elif self.nstype == 2: #BPM & Diff mode if self.difficulty == 0: #expert self.neckSpeed = (226-(bpm/10))/self.speed elif self.difficulty == 1: self.neckSpeed = (256-(bpm/10))/self.speed elif self.difficulty == 2: self.neckSpeed = (286-(bpm/10))/self.speed else: #easy self.neckSpeed = (306-(bpm/10))/self.speed else: #Percentage mode - pre-calculated self.neckSpeed = self.speed self.earlyMargin = 250 - bpm/5 - 70*self.hitw self.lateMargin = 250 - bpm/5 - 70*self.hitw #self.earlyMargin = self.lateMargin * self.earlyHitWindowSizeFactor #MFH - scale early hit window here #self.noteReleaseMargin = 200 - bpm/5 - 70*self.hitw #if (self.noteReleaseMargin < (200 - bpm/5 - 70*1.2)): #MFH - enforce "tight" hitwindow minimum note release margin # self.noteReleaseMargin = (200 - bpm/5 - 70*1.2) if self.muteSustainReleases == 4: #tight self.noteReleaseMargin = (200 - bpm/5 - 70*1.2) elif self.muteSustainReleases == 3: #standard self.noteReleaseMargin = (200 - bpm/5 - 70*1.0) elif self.muteSustainReleases == 2: #wide self.noteReleaseMargin = (200 - bpm/5 - 70*0.7) else: #ultra-wide self.noteReleaseMargin = (200 - bpm/5 - 70*0.5) #MFH - TODO - only calculate the below values if the realtime hit accuracy feedback display is enabled - otherwise this is a waste! self.accThresholdWorstLate = (0-self.lateMargin) self.accThresholdVeryLate = (0-(3*self.lateMargin/4)) self.accThresholdLate = (0-(2*self.lateMargin/4)) self.accThresholdSlightlyLate = (0-(1*self.lateMargin/4)) self.accThresholdExcellentLate = -1.0 self.accThresholdPerfect = 1.0 self.accThresholdExcellentEarly = (1*self.lateMargin/4) self.accThresholdSlightlyEarly = (2*self.lateMargin/4) self.accThresholdEarly = (3*self.lateMargin/4) self.accThresholdVeryEarly = (4*self.lateMargin/4) def setMultiplier(self, multiplier): self.scoreMultiplier = multiplier #volshebnyi def renderFreestyleLanes(self, visibility, song, pos, controls): if not song: return if not song.readyToGo: return #MFH - check for [section big_rock_ending] to set a flag to determine how to treat the last drum fill marker note: #for time, event in song.eventTracks[Song.TK_SECTIONS].getEvents(pos - self.lateMargin*2, pos): # if event.text.find("big rock ending") > 0: if song.breMarkerTime and pos > song.breMarkerTime: self.bigRockEndingMarkerSeen = True #boardWindowMin = pos - self.currentPeriod * 2 boardWindowMax = pos + self.currentPeriod * self.beatsPerBoard track = song.midiEventTrack[self.player] #self.currentPeriod = self.neckSpeed beatsPerUnit = self.beatsPerBoard / self.boardLength if self.freestyleEnabled: freestyleActive = False self.drumFillsActive = False #drumFillOnScreen = False drumFillEvents = [] #for time, event in track.getEvents(boardWindowMin, boardWindowMax): for time, event in track.getEvents(pos - self.freestyleOffset, boardWindowMax + self.freestyleOffset): if isinstance(event, Song.MarkerNote): if event.number == Song.freestyleMarkingNote and (not event.happened or self.bigRockEndingMarkerSeen): #MFH - don't kill the BRE! #drumFillOnScreen = True drumFillEvents.append(event) length = (event.length - 50) / self.currentPeriod / beatsPerUnit w = self.boardWidth / self.strings self.freestyleLength = event.length #volshebnyi self.freestyleStart = time # volshebnyi z = ((time - pos) / self.currentPeriod) / beatsPerUnit z2 = ((time + event.length - pos) / self.currentPeriod) / beatsPerUnit if z > self.boardLength * .8: f = (self.boardLength - z) / (self.boardLength * .2) elif z < 0: f = min(1, max(0, 1 + z2)) else: f = 1.0 time -= self.freestyleOffset #volshebnyi - allow tail to move under frets if time > pos: self.drumFillsHits = -1 if self.starPower>=50 and not self.starPowerActive: self.drumFillsReady = True else: self.drumFillsReady = False if self.bigRockEndingMarkerSeen: # and ( (self.drumFillsCount == self.drumFillsTotal and time+event.length>pos) or (time > pos and self.drumFillsCount == self.drumFillsTotal-1) ): self.freestyleReady = True self.drumFillsReady = False else: self.freestyleReady = False if time < pos: if self.bigRockEndingMarkerSeen: # and self.drumFillsCount == self.drumFillsTotal: freestyleActive = True else: #if self.drumFillsCount <= self.drumFillsTotal and self.drumFillsReady: if self.drumFillsReady: self.drumFillsActive = True self.drumFillWasJustActive = True if self.drumFillsHits<0: self.drumFillsCount += 1 self.drumFillsHits = 0 if z < -1.5: length += z +1.5 z = -1.5 #if time+event.length>pos and time+event.length-0.5>pos: # if controls.getState(self.keys[4]) or controls.getState(self.keys[8]): # self.starPowerActive = True #volshebnyi - render 4 freestyle tails if self.freestyleReady or self.drumFillsReady: for theFret in range(1,5): x = (self.strings / 2 + .5 - theFret) * w if theFret == 4: c = self.fretColors[0] else: c = self.fretColors[theFret] color = (.1 + .8 * c[0], .1 + .8 * c[1], .1 + .8 * c[2], 1.0 * visibility * f) glPushMatrix() glTranslatef(x, (1.0 - visibility) ** (theFret + 1), z) freestyleTailMode = 1 self.renderTail(length = length, color = color, fret = theFret, freestyleTail = freestyleTailMode, pos = pos) glPopMatrix() if ( self.drumFillsActive and self.drumFillsHits >= 4 and z + length<self.boardLength ): glPushMatrix() color = (.1 + .8 * c[0], .1 + .8 * c[1], .1 + .8 * c[2], 1.0 * visibility * f) glTranslatef(x, 0.0, z + length) self.renderNote(length, sustain = False, color = color, flat = False, tailOnly = False, isTappable = False, fret = 4, spNote = False, isOpen = False) glPopMatrix() self.freestyleActive = freestyleActive #self.drumFillOnScreen = drumFillOnScreen self.drumFillEvents = drumFillEvents def renderTail(self, length, color, flat = False, fret = 0, freestyleTail = 0, pos = 0): #volshebnyi - if freestyleTail == 1, render an freestyle tail # if freestyleTail == 2, render highlighted freestyle tail beatsPerUnit = self.beatsPerBoard / self.boardLength if flat: tailscale = (1, .1, 1) else: tailscale = None size = (.08, length + 0.00001) if size[1] > self.boardLength: s = self.boardLength else: s = (length + 0.00001) # render an inactive freestyle tail (self.freestyle1 & self.freestyle2) zsize = .25 size = (.15, s - zsize) if self.drumFillsActive: if self.drumFillsHits >= 4: size = (.30, s - zsize) if self.drumFillsHits >= 3: size = (.25, s - zsize) elif self.drumFillsHits >= 2: size = (.21, s - zsize) elif self.drumFillsHits >= 1: size = (.17, s - zsize) if self.freestyleActive: size = (.30, s - zsize) tex1 = self.freestyle1 tex2 = self.freestyle2 if freestyleTail == 1: #glColor4f(*color) c1, c2, c3, c4 = color tailGlow = 1 - (pos - self.freestyleLastFretHitTime[fret] ) / self.freestylePeriod if tailGlow < 0: tailGlow = 0 color = (c1 + c1*2.0*tailGlow, c2 + c2*2.0*tailGlow, c3 + c3*2.0*tailGlow, c4*0.6 + c4*0.4*tailGlow) #MFH - this fades inactive tails' color darker tailcol = (color) self.engine.draw3Dtex(tex1, vertex = (-size[0], 0, size[0], size[1]), texcoord = (0.0, 0.0, 1.0, 1.0), scale = tailscale, color = tailcol) self.engine.draw3Dtex(tex2, vertex = (-size[0], size[1] - (.05), size[0], size[1] + (zsize)), scale = tailscale, texcoord = (0.0, 0.05, 1.0, 0.95), color = tailcol) self.engine.draw3Dtex(tex2, vertex = (-size[0], 0-(zsize), size[0], 0 + (.05)), scale = tailscale, texcoord = (0.0, 0.95, 1.0, 0.05), color = tailcol) #myfingershurt: def renderNote(self, length, sustain, color, flat = False, tailOnly = False, isTappable = False, big = False, fret = 0, spNote = False, isOpen = False): if flat: glScalef(1, .1, 1) beatsPerUnit = self.beatsPerBoard / self.boardLength if tailOnly: return #myfingershurt: this should be retrieved once at init, not repeatedly in-game whenever tails are rendered. if self.twoDnote == True: if self.notedisappear == True:#Notes keep on going when missed notecol = (1,1,1,1)#capo else: if flat:#Notes disappear when missed notecol = (.1,.1,.1,1) else: notecol = (1,1,1,1) tailOnly == True #death_au: Adjusted for different image. if self.separateDrumNotes: if isOpen: size = (self.boardWidth/1.9, (self.boardWidth/self.strings)/3.0) texSize = (0,1) if spNote == True: texY = (3.0/6.0,4.0/6.0) elif self.starPowerActive == True: #death_au: drum sp active notes. texY = (5.0/6.0,1.0) else: texY = (1.0/6.0,2.0/6.0) else: size = (self.boardWidth/self.strings/2, self.boardWidth/self.strings/2) fret -= 1 texSize = (fret/4.0,fret/4.0+0.25) if spNote == True: texY = (2.0/6.0,3.0/6.0) elif self.starPowerActive == True: #death_au: drum sp active notes. texY = (4.0/6.0,5.0/6.0) else: texY = (0.0,1.0/6.0) else: #automatically generate drum notes from Notes.png #myfingershurt: swapping notes 0 and 4: if fret == 0: #fret = 4 #fret 4 is angled, get fret 2 :) fret = 2 elif fret == 4: fret = 0 size = (self.boardWidth/self.strings/2, self.boardWidth/self.strings/2) texSize = (fret/5.0,fret/5.0+0.2) if spNote == True: if isTappable: texY = (0.6, 0.8) else: texY = (0.4,0.6) else: if isTappable: texY = (0.2,0.4) else: texY = (0,0.2) if self.starPowerActive: texY = (0.8,1) if isTappable: texSize = (0.2,0.4) else: texSize = (0,0.2) elif self.theme == 2: size = (self.boardWidth/self.strings/2, self.boardWidth/self.strings/2) texSize = (fret/5.0,fret/5.0+0.2) if spNote == True: if isTappable: texY = (3*0.166667, 4*0.166667) else: texY = (2*0.166667, 3*0.166667) else: if isTappable: texY = (1*0.166667, 2*0.166667) else: texY = (0, 1*0.166667) #rock band fret 0 needs to be reversed just like the fret to match angles better if fret == 0: texSize = (fret/5.0+0.2,fret/5.0) #myfingershurt: adding spNote==False conditional so that star notes can appear in overdrive if self.starPowerActive and spNote == False: if isTappable: texY = (5*0.166667, 1) else: texY = (4*0.166667, 5*0.166667) if isOpen: size = (self.boardWidth/2.0, (self.boardWidth/self.strings)/40.0) self.engine.draw3Dtex(self.noteButtons, vertex = (-size[0],size[1],size[0],-size[1]), texcoord = (texSize[0],texY[0],texSize[1],texY[1]), scale = (1,1,1), multiples = True, color = (1,1,1), vertscale = .2) else: #mesh = outer ring (black) #mesh_001 = main note (key color) #mesh_002 = top (spot or hopo if no mesh_003) #mesh_003 = hopo bump (hopo color) if fret == 0: #fret = 4 #fret 4 is angled, get fret 2 :) fret = 2 elif fret == 4: fret = 0 if spNote == True and self.starMesh is not None and isOpen == False: meshObj = self.starMesh elif isOpen == True and self.openMesh is not None: meshObj = self.openMesh else: meshObj = self.noteMesh glPushMatrix() glEnable(GL_DEPTH_TEST) glDepthMask(1) glShadeModel(GL_SMOOTH) if spNote == True and self.threeDspin == True and isOpen == False: glRotate(90 + self.time/3, 0, 1, 0) if isOpen == False and spNote == False and self.noterotate == True: glRotatef(90, 0, 1, 0) glRotatef(-90, 1, 0, 0) if fret == 0: glRotate(Theme.noterotdegrees, 0, 0, Theme.noterot[4]) elif fret == 1: glRotate(Theme.noterotdegrees, 0, 0, Theme.noterot[1]) elif fret == 2: glRotate(Theme.noterotdegrees, 0, 0, Theme.noterot[0]) elif fret == 3: glRotate(Theme.noterotdegrees, 0, 0, Theme.noterot[3]) if self.notetex == True and spNote == False and isOpen==False: glColor3f(1,1,1) glEnable(GL_TEXTURE_2D) getattr(self,"notetex"+chr(97+fret)).texture.bind() glMatrixMode(GL_TEXTURE) glScalef(1, -1, 1) glMatrixMode(GL_MODELVIEW) if isTappable: meshObj.render("Mesh_001") else: meshObj.render("Mesh") glMatrixMode(GL_TEXTURE) glLoadIdentity() glMatrixMode(GL_MODELVIEW) glDisable(GL_TEXTURE_2D) elif self.startex == True and spNote == True and isOpen==False: glColor3f(1,1,1) glEnable(GL_TEXTURE_2D) getattr(self,"startex"+chr(97+fret)).texture.bind() glMatrixMode(GL_TEXTURE) glScalef(1, -1, 1) glMatrixMode(GL_MODELVIEW) if isTappable: meshObj.render("Mesh_001") else: meshObj.render("Mesh") glMatrixMode(GL_TEXTURE) glLoadIdentity() glMatrixMode(GL_MODELVIEW) glDisable(GL_TEXTURE_2D) elif self.opentex == True and isOpen==True: glColor3f(1,1,1) glEnable(GL_TEXTURE_2D) self.opentexture.texture.bind() glMatrixMode(GL_TEXTURE) glScalef(1, -1, 1) glMatrixMode(GL_MODELVIEW) meshObj.render() glMatrixMode(GL_TEXTURE) glLoadIdentity() glMatrixMode(GL_MODELVIEW) glDisable(GL_TEXTURE_2D) else: #death_au: fixed 3D note colours glColor4f(*color) if self.starPowerActive and self.theme != 2 and not color == (0,0,0,1): glColor4f(self.spColor[0],self.spColor[1],self.spColor[2],1) #glColor4f(.3,.7,.9, 1) if isOpen == True and self.starPowerActive == False: glColor4f(self.opencolor[0],self.opencolor[1],self.opencolor[2], 1) meshObj.render("Mesh_001") glColor3f(self.spotColor[0], self.spotColor[1], self.spotColor[2]) meshObj.render("Mesh_002") glColor3f(self.meshColor[0], self.meshColor[1], self.meshColor[2]) meshObj.render("Mesh") glDepthMask(0) glPopMatrix() def renderOpenNotes(self, visibility, song, pos): if not song: return if not song.readyToGo: return self.bigMax = 0 self.currentPeriod = self.neckSpeed self.targetPeriod = self.neckSpeed self.killPoints = False beatsPerUnit = self.beatsPerBoard / self.boardLength w = self.boardWidth / self.strings track = song.track[self.player] num = 0 enable = True self.openStarNotesInView = False #for time, event in track.getEvents(pos - self.currentPeriod * 2, pos + self.currentPeriod * self.beatsPerBoard): for time, event in reversed(track.getEvents(pos - self.currentPeriod * 2, pos + self.currentPeriod * self.beatsPerBoard)): #MFH - reverse order of note rendering if isinstance(event, Tempo): self.tempoBpm = event.bpm if self.lastBpmChange > 0 and self.disableVBPM == True: continue if (pos - time > self.currentPeriod or self.lastBpmChange < 0) and time > self.lastBpmChange: self.baseBeat += (time - self.lastBpmChange) / self.currentPeriod self.targetBpm = event.bpm self.lastBpmChange = time # self.setBPM(self.targetBpm) # glorandwarf: was setDynamicBPM(self.targetBpm) continue if not isinstance(event, Note): continue if (event.noteBpm == 0.0): event.noteBpm = self.tempoBpm if self.coOpFailed: if self.coOpRestart: if time - self.coOpRescueTime < (self.currentPeriod * self.beatsPerBoard * 2): continue elif self.coOpRescueTime + (self.currentPeriod * self.beatsPerBoard * 2) < pos: self.coOpFailed = False self.coOpRestart = False Log.debug("Turning off coOpFailed. Rescue successful.") else: continue #can't break. Tempo. if event.number != 0: #skip all regular notes continue c = self.fretColors[event.number] isOpen = False if event.number == 0: #treat open string note differently x = (self.strings / 2 - .5 - 1.5) * w isOpen = True c = self.fretColors[4] #myfingershurt: need to swap note 0 and note 4 colors for drums: else: #one of the other 4 drum notes x = (self.strings / 2 - .5 - (event.number - 1)) * w if event.number == 4: c = self.fretColors[0] #myfingershurt: need to swap note 0 and note 4 colors for drums: z = ((time - pos) / self.currentPeriod) / beatsPerUnit z2 = ((time + event.length - pos) / self.currentPeriod) / beatsPerUnit if z > self.boardLength * .8: f = (self.boardLength - z) / (self.boardLength * .2) elif z < 0: f = min(1, max(0, 1 + z2)) else: f = 1.0 #volshebnyi - hide open notes in BRE zone if BRE enabled if self.freestyleEnabled and self.freestyleStart > 0: if self.drumFillsReady or self.freestyleReady: if time > self.freestyleStart - self.freestyleOffset and time < self.freestyleStart + self.freestyleOffset + self.freestyleLength: z = -2.0 color = (.1 + .8 * c[0], .1 + .8 * c[1], .1 + .8 * c[2], 1 * visibility * f) length = 0 flat = False tailOnly = False spNote = False #myfingershurt: user setting for starpower refill / replenish notes #if self.starPowerActive and self.theme != 2: #Rock Band theme allows SP notes in overdrive if self.starPowerActive: if self.spRefillMode == 0: #mode 0 = no starpower / overdrive refill notes self.spEnabled = False elif self.spRefillMode == 1 and self.theme != 2: #mode 1 = overdrive refill notes in RB themes only self.spEnabled = False elif self.spRefillMode == 2 and song.midiStyle != 1: #mode 2 = refill based on MIDI type self.spEnabled = False if event.star: #self.isStarPhrase = True self.openStarNotesInView = True if event.finalStar: self.finalStarSeen = True self.openStarNotesInView = True if event.star and self.spEnabled: spNote = True if event.finalStar and self.spEnabled: spNote = True if event.played or event.hopod: if event.flameCount < 1 and not self.starPowerGained: #if self.drumFillOnScreen: #MFH - if there's a drum fill on the screen right now, skip it! if self.starPower < 50: #not enough starpower to activate yet, kill existing drumfills for dfEvent in self.drumFillEvents: dfEvent.happened = True if self.starPower < 100: self.starPower += 25 if self.starPower > 100: self.starPower = 100 self.overdriveFlashCount = 0 #MFH - this triggers the oFlash strings & timer self.starPowerGained = True #if enable: # self.spEnabled = True isTappable = False if self.notedisappear == True:#Notes keep on going when missed ###Capo### if event.played or event.hopod: tailOnly = True length += z z = 0 if length <= 0: continue if z < 0 and not (event.played or event.hopod): color = (.2 + .4, .2 + .4, .2 + .4, .5 * visibility * f) flat = True ###endCapo### else:#Notes disappear when missed if z < 0: if event.played or event.hopod: tailOnly = True length += z z = 0 if length <= 0: continue else: color = (.2 + .4, .2 + .4, .2 + .4, .5 * visibility * f) flat = True sustain = False glPushMatrix() glTranslatef(x, (1.0 - visibility) ** (event.number + 1), z) self.renderNote(length, sustain = sustain, color = color, flat = flat, tailOnly = tailOnly, isTappable = isTappable, fret = event.number, spNote = spNote, isOpen = isOpen) glPopMatrix() #myfingershurt: end FOR loop / note rendering loop if (not self.openStarNotesInView) and (not self.starNotesInView) and self.finalStarSeen: self.spEnabled = True self.finalStarSeen = False self.isStarPhrase = False def renderNotes(self, visibility, song, pos): if not song: return if not song.readyToGo: return self.bigMax = 0 self.currentPeriod = self.neckSpeed self.targetPeriod = self.neckSpeed self.killPoints = False beatsPerUnit = self.beatsPerBoard / self.boardLength w = self.boardWidth / self.strings track = song.track[self.player] num = 0 enable = True self.starNotesInView = False #for time, event in track.getEvents(pos - self.currentPeriod * 2, pos + self.currentPeriod * self.beatsPerBoard): for time, event in reversed(track.getEvents(pos - self.currentPeriod * 2, pos + self.currentPeriod * self.beatsPerBoard)): #MFH - reverse order of note rendering if isinstance(event, Tempo): self.tempoBpm = event.bpm if self.lastBpmChange > 0 and self.disableVBPM == True: continue if (pos - time > self.currentPeriod or self.lastBpmChange < 0) and time > self.lastBpmChange: self.baseBeat += (time - self.lastBpmChange) / self.currentPeriod self.targetBpm = event.bpm self.lastBpmChange = time # self.setBPM(self.targetBpm) # glorandwarf: was setDynamicBPM(self.targetBpm) continue if not isinstance(event, Note): continue if (event.noteBpm == 0.0): event.noteBpm = self.tempoBpm #volshebnyi - removed if event.number == 0: #MFH - skip all open notes continue if self.coOpFailed: if self.coOpRestart: if time - self.coOpRescueTime < (self.currentPeriod * self.beatsPerBoard * 2): continue elif self.coOpRescueTime + (self.currentPeriod * self.beatsPerBoard * 2) < pos: self.coOpFailed = False self.coOpRestart = False Log.debug("Turning off coOpFailed. Rescue successful.") else: continue #can't break. Tempo. c = self.fretColors[event.number] if event.star: #self.isStarPhrase = True self.starNotesInView = True if event.finalStar: self.finalStarSeen = True self.starNotesInView = True isOpen = False if event.number == 0: #treat open string note differently x = (self.strings / 2 - .5 - 1.5) * w isOpen = True c = self.fretColors[4] #myfingershurt: need to swap note 0 and note 4 colors for drums: else: #one of the other 4 drum notes x = (self.strings / 2 - .5 - (event.number - 1)) * w if event.number == 4: c = self.fretColors[0] #myfingershurt: need to swap note 0 and note 4 colors for drums: z = ((time - pos) / self.currentPeriod) / beatsPerUnit z2 = ((time + event.length - pos) / self.currentPeriod) / beatsPerUnit if z > self.boardLength * .8: f = (self.boardLength - z) / (self.boardLength * .2) elif z < 0: f = min(1, max(0, 1 + z2)) else: f = 1.0 #volshebnyi - hide notes in BRE zone if BRE enabled if self.freestyleEnabled: if self.drumFillsReady or self.freestyleReady: if time > self.freestyleStart - self.freestyleOffset and time < self.freestyleStart + self.freestyleOffset + self.freestyleLength: z = -2.0 color = (.1 + .8 * c[0], .1 + .8 * c[1], .1 + .8 * c[2], 1 * visibility * f) length = 0 flat = False tailOnly = False spNote = False #myfingershurt: user setting for starpower refill / replenish notes #if self.starPowerActive and self.theme != 2: #Rock Band theme allows SP notes in overdrive if self.starPowerActive: if self.spRefillMode == 0: #mode 0 = no starpower / overdrive refill notes self.spEnabled = False elif self.spRefillMode == 1 and self.theme != 2: #mode 1 = overdrive refill notes in RB themes only self.spEnabled = False elif self.spRefillMode == 2 and song.midiStyle != 1: #mode 2 = refill based on MIDI type self.spEnabled = False if event.star and self.spEnabled: spNote = True if event.finalStar and self.spEnabled: spNote = True if event.played or event.hopod: if event.flameCount < 1 and not self.starPowerGained: #if self.drumFillOnScreen: #MFH - if there's a drum fill on the screen right now, skip it! if self.starPower < 50: #not enough starpower to activate yet, kill existing drumfills for dfEvent in self.drumFillEvents: dfEvent.happened = True if self.starPower < 100: self.starPower += 25 if self.starPower > 100: self.starPower = 100 self.overdriveFlashCount = 0 #MFH - this triggers the oFlash strings & timer self.starPowerGained = True self.ocount = 0 #if enable: # self.spEnabled = True isTappable = False if self.notedisappear == True:#Notes keep on going when missed ###Capo### if event.played or event.hopod: tailOnly = True length += z z = 0 if length <= 0: continue if z < 0 and not (event.played or event.hopod): color = (.2 + .4, .2 + .4, .2 + .4, .5 * visibility * f) flat = True ###endCapo### else:#Notes disappear when missed if z < 0: if event.played or event.hopod: tailOnly = True length += z z = 0 if length <= 0: continue else: color = (.2 + .4, .2 + .4, .2 + .4, .5 * visibility * f) flat = True sustain = False glPushMatrix() glTranslatef(x, (1.0 - visibility) ** (event.number + 1), z) self.renderNote(length, sustain = sustain, color = color, flat = flat, tailOnly = tailOnly, isTappable = isTappable, fret = event.number, spNote = spNote, isOpen = isOpen) glPopMatrix() #myfingershurt: end FOR loop / note rendering loop if (not self.openStarNotesInView) and (not self.starNotesInView) and self.finalStarSeen: self.spEnabled = True self.isStarPhrase = False self.finalStarSeen = False def renderFrets(self, visibility, song, controls): w = self.boardWidth / self.strings size = (.22, .22) v = 1.0 - visibility glEnable(GL_DEPTH_TEST) #Hitglow color option - myfingershurt sez this should be a Guitar class global, not retrieved ever fret render in-game... #self.hitglow_color = self.engine.config.get("video", "hitglow_color") for n in range(self.strings): f = self.fretWeight[n] if n == 3: c = self.fretColors[0] else: c = self.fretColors[n + 1] if f and (controls.getState(self.keys[0]) or controls.getState(self.keys[5])): f += 0.25 glColor4f(.1 + .8 * c[0] + f, .1 + .8 * c[1] + f, .1 + .8 * c[2] + f, visibility) y = v + f / 6 x = (self.strings / 2 - .5 - n) * w if self.twoDkeys == True: #death_au size = (self.boardWidth/self.strings/2, self.boardWidth/self.strings/2.4) whichFret = n #death_au: only with old-style drum fret images if self.drumFretButtons == None: whichFret = n+1 if whichFret == 4: whichFret = 0 #reversing fret 0 since it's angled in Rock Band texSize = (whichFret/5.0+0.2,whichFret/5.0) else: #texSize = (n/5.0,n/5.0+0.2) texSize = (whichFret/5.0,whichFret/5.0+0.2) texY = (0.0,1.0/3.0) if controls.getState(self.keys[n+1]): texY = (1.0/3.0,2.0/3.0) #myfingershurt: also want to show when alternate drumkeys are pressed! if controls.getState(self.keys[n+6]): texY = (1.0/3.0,2.0/3.0) if self.hit[n]: texY = (2.0/3.0,1.0) #death_au: only with new drum fret images else: texSize = (whichFret/4.0,whichFret/4.0+0.25) texY = (0.0,1.0/6.0) if controls.getState(self.keys[n+1]): texY = (2.0/6.0,3.0/6.0) #myfingershurt: also want to show when alternate drumkeys are pressed! if controls.getState(self.keys[n+6]): texY = (2.0/6.0,3.0/6.0) if self.hit[n]: texY = (4.0/6.0,5.0/6.0) if self.drumFretButtons == None: self.engine.draw3Dtex(self.fretButtons, vertex = (size[0],size[1],-size[0],-size[1]), texcoord = (texSize[0], texY[0], texSize[1], texY[1]), coord = (x,v,0), multiples = True,color = (1,1,1), depth = True) else: self.engine.draw3Dtex(self.drumFretButtons, vertex = (size[0],size[1],-size[0],-size[1]), texcoord = (texSize[0], texY[0], texSize[1], texY[1]), coord = (x,v,0), multiples = True,color = (1,1,1), depth = True) else: #death_au if n == 3: c = self.fretColors[0] else: c = self.fretColors[n + 1] if self.keyMesh: glPushMatrix() #glTranslatef(x, y + v * 6, 0) glDepthMask(1) glEnable(GL_LIGHTING) glEnable(GL_LIGHT0) glShadeModel(GL_SMOOTH) glRotatef(90, 0, 1, 0) glLightfv(GL_LIGHT0, GL_POSITION, (5.0, 10.0, -10.0, 0.0)) glLightfv(GL_LIGHT0, GL_AMBIENT, (.2, .2, .2, 0.0)) glLightfv(GL_LIGHT0, GL_DIFFUSE, (1.0, 1.0, 1.0, 0.0)) glRotatef(-90, 1, 0, 0) glRotatef(-90, 0, 0, 1) #glColor4f(.1 + .8 * c[0] + f, .1 + .8 * c[1] + f, .1 + .8 * c[2] + f, visibility) #Mesh - Main fret #Key_001 - Top of fret (key_color) #Key_002 - Bottom of fret (key2_color) #Glow_001 - Only rendered when a note is hit along with the glow.svg if n == 0: glRotate(Theme.noterotdegrees, 0, 0, Theme.noterot[4]) elif n == 1: glRotate(Theme.noterotdegrees, 0, 0, Theme.noterot[1]) elif n == 2: glRotate(Theme.noterotdegrees, 0, 0, Theme.noterot[0]) elif n == 3: glRotate(Theme.noterotdegrees, 0, 0, Theme.noterot[3]) if self.keytex == True: glColor4f(1,1,1,visibility) glTranslatef(x, v, 0) glEnable(GL_TEXTURE_2D) if n == 0: self.keytexb.texture.bind() elif n == 1: self.keytexc.texture.bind() elif n == 2: self.keytexd.texture.bind() elif n == 3: self.keytexa.texture.bind() glMatrixMode(GL_TEXTURE) glScalef(1, -1, 1) glMatrixMode(GL_MODELVIEW) if f and not self.hit[n]: self.keyMesh.render("Mesh_001") elif self.hit[n]: self.keyMesh.render("Mesh_002") else: self.keyMesh.render("Mesh") glMatrixMode(GL_TEXTURE) glLoadIdentity() glMatrixMode(GL_MODELVIEW) glDisable(GL_TEXTURE_2D) else: glColor4f(.1 + .8 * c[0] + f, .1 + .8 * c[1] + f, .1 + .8 * c[2] + f, visibility) glTranslatef(x, y + v * 6, 0) key = self.keyMesh if(key.find("Glow_001")) == True: key.render("Mesh") if(key.find("Key_001")) == True: glColor3f(self.keyColor[0], self.keyColor[1], self.keyColor[2]) key.render("Key_001") if(key.find("Key_002")) == True: glColor3f(self.key2Color[0], self.key2Color[1], self.key2Color[2]) key.render("Key_002") else: key.render() glDisable(GL_LIGHTING) glDisable(GL_LIGHT0) glDepthMask(0) glPopMatrix() ###################### f = self.fretActivity[n] if f and self.disableFretSFX != True: glBlendFunc(GL_ONE, GL_ONE) if self.glowColor[0] == -1: s = 1.0 else: s = 0.0 while s < 1: ms = s * (math.sin(self.time) * .25 + 1) if self.glowColor[0] == -2: glColor3f(c[0] * (1 - ms), c[1] * (1 - ms), c[2] * (1 - ms)) else: glColor3f(self.glowColor[0] * (1 - ms), self.glowColor[1] * (1 - ms), self.glowColor[2] * (1 - ms)) glPushMatrix() glTranslate(x, y, 0) glScalef(.1 + .02 * ms * f, .1 + .02 * ms * f, .1 + .02 * ms * f) glRotatef( 90, 0, 1, 0) glRotatef(-90, 1, 0, 0) glRotatef(-90, 0, 0, 1) if self.twoDkeys == False and self.keytex == False: if(self.keyMesh.find("Glow_001")) == True: key.render("Glow_001") else: key.render() glPopMatrix() s += 0.2 #Hitglow color if self.hitglow_color == 0: glowcol = (c[0], c[1], c[2])#Same as fret elif self.hitglow_color == 1: glowcol = (1, 1, 1)#Actual color in .svg-file f += 2 self.engine.draw3Dtex(self.glowDrawing, coord = (x, y, 0.01), rot = (f * 90 + self.time, 0, 1, 0), texcoord = (0.0, 0.0, 1.0, 1.0), vertex = (-size[0] * f, -size[1] * f, size[0] * f, size[1] * f), multiples = True, alpha = True, color = glowcol) self.hit[n] = False ############################################### #death_au: #if we leave the depth test enabled, it thinks that the bass drum images #are under the other frets and openGL culls them. So I just leave it disabled glDisable(GL_DEPTH_TEST) if self.twoDkeys == True and self.drumFretButtons != None: #death_au x = 0.0#(self.boardWidth / 2 ) size = (self.boardWidth/2, self.boardWidth/self.strings/2.4) texSize = (0.0,1.0) texY = (1.0/6.0,2.0/6.0) if controls.getState(self.keys[0]) or controls.getState(self.keys[5]): texY = (3.0/6.0,4.0/6.0) if self.hit[0]: texY = (5.0/6.0,1.0) self.engine.draw3Dtex(self.drumFretButtons, vertex = (size[0],size[1],-size[0],-size[1]), texcoord = (texSize[0], texY[0], texSize[1], texY[1]), coord = (x,v,0), multiples = True,color = (1,1,1), depth = True) ############################################### def renderFlames(self, visibility, song, pos, controls): if not song or self.flameColors[0][0][0] == -1: return beatsPerUnit = self.beatsPerBoard / self.boardLength w = self.boardWidth / self.strings track = song.track[self.player] size = (.22, .22) v = 1.0 - visibility #blazingamer- hitglow logic is not required for drums since you can not perform holds with drum pads, uncomment out if you disagree with this ## if self.disableFlameSFX != True: ## for n in range(self.strings): ## f = self.fretWeight[n] ## ## #c = self.fretColors[n] ## c = self.fretColors[n+1] ## if f and (controls.getState(self.keys[0]) or controls.getState(self.keys[5])): ## f += 0.25 ## y = v + f / 6 ## ## x = (self.strings / 2 -.5 - n) * w ## ## ## f = self.fretActivity[n] ## ## if f: ## ms = math.sin(self.time) * .25 + 1 ## ff = f ## ff += 1.2 ## ## glBlendFunc(GL_ONE, GL_ONE) ## ## flameSize = self.flameSizes[self.scoreMultiplier - 1][n] ## if self.theme == 0 or self.theme == 1: #THIS SETS UP GH3 COLOR, ELSE ROCKBAND(which is DEFAULT in Theme.py) ## flameColor = self.gh3flameColor ## else: ## flameColor = self.flameColors[self.scoreMultiplier - 1][n] ## #Below was an if that set the "flame"-color to the same as the fret color if there was no specific flamecolor defined. ## ## flameColorMod0 = 1.1973333333333333333333333333333 ## flameColorMod1 = 1.9710526315789473684210526315789 ## flameColorMod2 = 10.592592592592592592592592592593 ## ## glColor3f(flameColor[0] * flameColorMod0, flameColor[1] * flameColorMod1, flameColor[2] * flameColorMod2) ## if self.starPowerActive: ## if self.theme == 0 or self.theme == 1: #GH3 starcolor ## glColor3f(self.spColor[0],self.spColor[1],self.spColor[2]) ## #glColor3f(.3,.7,.9) ## else: #Default starcolor (Rockband) ## glColor3f(.9,.9,.9) ## ## if not self.Hitanim: ## glEnable(GL_TEXTURE_2D) ## self.hitglowDrawing.texture.bind() ## glPushMatrix() ## glTranslate(x, y + .125, 0) ## glRotate(90, 1, 0, 0) ## glScalef(0.5 + .6 * ms * ff, 1.5 + .6 * ms * ff, 1 + .6 * ms * ff) ## glBegin(GL_TRIANGLE_STRIP) ## glTexCoord2f(0.0, 0.0) ## glVertex3f(-flameSize * ff, 0, -flameSize * ff) ## glTexCoord2f(1.0, 0.0) ## glVertex3f( flameSize * ff, 0, -flameSize * ff) ## glTexCoord2f(0.0, 1.0) ## glVertex3f(-flameSize * ff, 0, flameSize * ff) ## glTexCoord2f(1.0, 1.0) ## glVertex3f( flameSize * ff, 0, flameSize * ff) ## glEnd() ## glPopMatrix() ## glDisable(GL_TEXTURE_2D) ## #Alarian: Animated hitflames ## else: ## self.HCount = self.HCount + 1 ## if self.HCount > self.Animspeed-1: ## self.HCount = 0 ## HIndex = (self.HCount * 16 - (self.HCount * 16) % self.Animspeed) / self.Animspeed ## if HIndex > 15: ## HIndex = 0 ## texX = (HIndex*(1/16.0), HIndex*(1/16.0)+(1/16.0)) ## ## glColor3f(1,1,1) ## glEnable(GL_TEXTURE_2D) ## self.hitglowAnim.texture.bind() ## glPushMatrix() ## glTranslate(x, y + .225, 0) ## glRotate(90, 1, 0, 0) ## ## #glScalef(1.3, 1, 2) ## #glScalef(1.7, 1, 2.6) ## glScalef(2, 1, 2.9) #worldrave correct flame size ## ## ## glBegin(GL_TRIANGLE_STRIP) ## glTexCoord2f(texX[0], 0.0)#upper left corner of frame square in .png ## glVertex3f(-flameSize * ff, 0, -flameSize * ff)#"upper left" corner of surface that texture is rendered on ## glTexCoord2f(texX[1], 0.0)#upper right ## glVertex3f( flameSize * ff, 0, -flameSize * ff) ## glTexCoord2f(texX[0], 1.0)#lower left ## glVertex3f(-flameSize * ff, 0, flameSize * ff) ## glTexCoord2f(texX[1], 1.0)#lower right ## glVertex3f( flameSize * ff, 0, flameSize * ff) ## glEnd() ## glPopMatrix() ## glDisable(GL_TEXTURE_2D) ## ## ff += .3 ## ## #flameSize = self.flameSizes[self.scoreMultiplier - 1][n] ## #flameColor = self.flameColors[self.scoreMultiplier - 1][n] ## ## flameColorMod0 = 1.1973333333333333333333333333333 ## flameColorMod1 = 1.7842105263157894736842105263158 ## flameColorMod2 = 12.222222222222222222222222222222 ## ## glColor3f(flameColor[0] * flameColorMod0, flameColor[1] * flameColorMod1, flameColor[2] * flameColorMod2) ## if self.starPowerActive: ## if self.theme == 0 or self.theme == 1: #GH3 starcolor ## glColor3f(self.spColor[0],self.spColor[1],self.spColor[2]) ## #glColor3f(.3,.7,.9) ## else: #Default starcolor (Rockband) ## glColor3f(.8,.8,.8) ## ## if not self.Hitanim: ## glEnable(GL_TEXTURE_2D) ## self.hitglow2Drawing.texture.bind() ## glPushMatrix() ## glTranslate(x, y + .25, .05) ## glRotate(90, 1, 0, 0) ## glScalef(.40 + .6 * ms * ff, 1.5 + .6 * ms * ff, 1 + .6 * ms * ff) ## glBegin(GL_TRIANGLE_STRIP) ## glTexCoord2f(0.0, 0.0) ## glVertex3f(-flameSize * ff, 0, -flameSize * ff) ## glTexCoord2f(1.0, 0.0) ## glVertex3f( flameSize * ff, 0, -flameSize * ff) ## glTexCoord2f(0.0, 1.0) ## glVertex3f(-flameSize * ff, 0, flameSize * ff) ## glTexCoord2f(1.0, 1.0) ## glVertex3f( flameSize * ff, 0, flameSize * ff) ## glEnd() ## glPopMatrix() ## glDisable(GL_TEXTURE_2D) ## ## glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) ## ## self.hit[n] = True if self.disableFlameSFX != True: flameLimit = 10.0 flameLimitHalf = round(flameLimit/2.0) for time, event in track.getEvents(pos - self.currentPeriod * 2, pos + self.currentPeriod * self.beatsPerBoard): if isinstance(event, Tempo): continue if not isinstance(event, Note): continue if (event.played or event.hopod) and event.flameCount < flameLimit: ms = math.sin(self.time) * .25 + 1 if event.number == 0: x = (self.strings / 2 - 2) * w else: x = (self.strings / 2 +.5 - event.number) * w #x = (self.strings / 2 - event.number) * w xlightning = (self.strings / 2 - event.number)*2.2*w ff = 1 + 0.25 y = v + ff / 6 if self.theme == 2: y -= 0.5 flameSize = self.flameSizes[self.scoreMultiplier - 1][event.number] if self.theme == 0 or self.theme == 1: #THIS SETS UP GH3 COLOR, ELSE ROCKBAND(which is DEFAULT in Theme.py) flameColor = self.gh3flameColor else: flameColor = self.flameColors[self.scoreMultiplier - 1][event.number] if flameColor[0] == -2: flameColor = self.fretColors[event.number] ff += 1.5 #ff first time is 2.75 after this if self.Hitanim2 == True: self.HCount2 = self.HCount2 + 1 self.HCountAni = False if self.HCount2 > 12: if event.length <= 130: self.HCount2 = 0 else: self.HCountAni = True if event.flameCount < flameLimitHalf: HIndex = (self.HCount2 * 13 - (self.HCount2 * 13) % 13) / 13 if HIndex > 12 and self.HCountAni != True: HIndex = 0 texX = (HIndex*(1/13.0), HIndex*(1/13.0)+(1/13.0)) self.engine.draw3Dtex(self.hitflamesAnim, coord = (x, y + .665, 0), rot = (90, 1, 0, 0), scale = (1.6, 1.6, 4.9), vertex = (-flameSize * ff,-flameSize * ff,flameSize * ff,flameSize * ff), texcoord = (texX[0],0.0,texX[1],1.0), multiples = True, alpha = True, color = (1,1,1)) else: flameColorMod0 = 0.1 * (flameLimit - event.flameCount) flameColorMod1 = 0.1 * (flameLimit - event.flameCount) flameColorMod2 = 0.1 * (flameLimit - event.flameCount) flamecol = (flameColor[0] * flameColorMod0, flameColor[1] * flameColorMod1, flameColor[2] * flameColorMod2) spcolmod = (.7,.7,.7) if self.starPowerActive: if self.theme == 0 or self.theme == 1: flamecol = (self.spColor[0]*spcolmod[0], self.spColor[1]*spcolmod[1], self.spColor[2]*spcolmod[2]) #flamecol = (.3,.6,.7)#GH3 starcolor else: flamecol = (.4,.4,.4)#Default starcolor (Rockband) if self.theme != 2 and event.finalStar and self.spEnabled: wid, hei, = self.engine.view.geometry[2:4] self.engine.draw3Dtex(self.hitlightning, coord = (xlightning, y, 3.3), rot = (90, 1, 0, 0), scale = (.15 + .5 * ms * ff, event.flameCount / 3.0 + .6 * ms * ff, 2), vertex = (.4,-2,-.4,2), texcoord = (0.0,0.0,1.0,1.0), multiples = True, alpha = True, color = (1,1,1)) else: self.engine.draw3Dtex(self.hitflames1Drawing, coord = (x, y + .35, 0), rot = (90, 1, 0, 0), scale = (.25 + .6 * ms * ff, event.flameCount / 3.0 + .6 * ms * ff, event.flameCount / 3.0 + .6 * ms * ff), vertex = (-flameSize * ff,-flameSize * ff,flameSize * ff,flameSize * ff), texcoord = (0.0,0.0,1.0,1.0), multiples = True, alpha = True, color = flamecol) flameColorMod0 = 0.1 * (flameLimit - event.flameCount) flameColorMod1 = 0.1 * (flameLimit - event.flameCount) flameColorMod2 = 0.1 * (flameLimit - event.flameCount) flamecol = (flameColor[0] * flameColorMod0, flameColor[1] * flameColorMod1, flameColor[2] * flameColorMod2) spcolmod = (.8,.8,.8) if self.starPowerActive: if self.theme == 0 or self.theme == 1: #GH3 starcolor flamecol = (self.spColor[0]*spcolmod[0], self.spColor[1]*spcolmod[1], self.spColor[2]*spcolmod[2]) #flamecol = (.3,.6,.8) else: #Default starcolor (Rockband) flamecol = (.5,.5,.5) self.engine.draw3Dtex(self.hitflames1Drawing, coord = (x - .005, y + .40 + .005, 0), rot = (90, 1, 0, 0), scale = (.30 + .6 * ms * ff, (event.flameCount + 1)/ 2.5 + .6 * ms * ff, (event.flameCount + 1) / 2.5 + .6 * ms * ff), vertex = (-flameSize * ff,-flameSize * ff,flameSize * ff,flameSize * ff), texcoord = (0.0,0.0,1.0,1.0), multiples = True, alpha = True, color = flamecol) flameColorMod0 = 0.1 * (flameLimit - event.flameCount) flameColorMod1 = 0.1 * (flameLimit - event.flameCount) flameColorMod2 = 0.1 * (flameLimit - event.flameCount) flamecol = (flameColor[0] * flameColorMod0, flameColor[1] * flameColorMod1, flameColor[2] * flameColorMod2) spcolmod = (.9,.9,.9) if self.starPowerActive: if self.theme == 0 or self.theme == 1: #GH3 starcolor flamecol = (self.spColor[0]*spcolmod[0], self.spColor[1]*spcolmod[1], self.spColor[2]*spcolmod[2]) #flamecol = (.3,.7,.8) else: #Default starcolor (Rockband) flamecol = (.6,.6,.6) self.engine.draw3Dtex(self.hitflames1Drawing, coord = (x + .005, y + .35 + .005, 0), rot = (90, 1, 0, 0), scale = (.35 + .6 * ms * ff, (event.flameCount + 1) / 2.0 + .6 * ms * ff, (event.flameCount + 1) / 2.0 + .6 * ms * ff), vertex = (-flameSize * ff,-flameSize * ff,flameSize * ff,flameSize * ff), texcoord = (0.0,0.0,1.0,1.0), multiples = True, alpha = True, color = flamecol) flameColorMod0 = 0.1 * (flameLimit - event.flameCount) flameColorMod1 = 0.1 * (flameLimit - event.flameCount) flameColorMod2 = 0.1 * (flameLimit - event.flameCount) flamecol = (flameColor[0] * flameColorMod0, flameColor[1] * flameColorMod1, flameColor[2] * flameColorMod2) spcolmod = (1,1,1) if self.starPowerActive: if self.theme == 0 or self.theme == 1: #GH3 starcolor flamecol = (self.spColor[0]*spcolmod[0], self.spColor[1]*spcolmod[1], self.spColor[2]*spcolmod[2]) #flamecol = (.3,.7,.9) else: #Default starcolor (Rockband) flamecol = (.7,.7,.7) self.engine.draw3Dtex(self.hitflames1Drawing, coord = (x+.005, y +.35 +.005, 0), rot = (90, 1, 0, 0), scale = (.40 + .6 * ms * ff, (event.flameCount + 1) / 1.7 + .6 * ms * ff, (event.flameCount + 1) / 1.7 + .6 * ms * ff), vertex = (-flameSize * ff,-flameSize * ff,flameSize * ff,flameSize * ff), texcoord = (0.0,0.0,1.0,1.0), multiples = True, alpha = True, color = flamecol) else: self.HCount2 = 13 self.HCountAni = True if event.flameCount < flameLimitHalf: flamecol = (flameColor[0], flameColor[1], flameColor[2]) spcolmod = (.3,.3,.3) if self.starPowerActive: if self.theme == 0 or self.theme == 1: #GH3 starcolor flamecol = (self.spColor[0]*spcolmod[0], self.spColor[1]*spcolmod[1], self.spColor[2]*spcolmod[2]) #flamecol = (.0,.2,.4) else: #Default starcolor (Rockband) flamecol = (.1,.1,.1) self.engine.draw3Dtex(self.hitflames2Drawing, coord = (x, y + .20, 0), rot = (90, 1, 0, 0), scale = (.25 + .6 * ms * ff, event.flameCount/6.0 + .6 * ms * ff, event.flameCount / 6.0 + .6 * ms * ff), vertex = (-flameSize * ff,-flameSize * ff,flameSize * ff,flameSize * ff), texcoord = (0.0,0.0,1.0,1.0), multiples = True, alpha = True, color = flamecol) flamecol = (flameColor[0], flameColor[1], flameColor[2]) spcolmod = (.4,.4,.4) if self.starPowerActive: if self.theme == 0 or self.theme == 1: #GH3 starcolor flamecol = (self.spColor[0]*spcolmod[0], self.spColor[1]*spcolmod[1], self.spColor[2]*spcolmod[2]) #flamecol = (.1,.3,.5) else: #Default starcolor (Rockband) flamecol = (.1,.1,.1) self.engine.draw3Dtex(self.hitflames2Drawing, coord = (x-.005, y + .255, 0), rot = (90, 1, 0, 0), scale = (.30 + .6 * ms * ff, event.flameCount/5.5 + .6 * ms * ff, event.flameCount / 5.5 + .6 * ms * ff), vertex = (-flameSize * ff,-flameSize * ff,flameSize * ff,flameSize * ff), texcoord = (0.0,0.0,1.0,1.0), multiples = True, alpha = True, color = flamecol) flamecol = (flameColor[0], flameColor[1], flameColor[2]) spcolmod = (.5,.5,.5) if self.starPowerActive: if self.theme == 0 or self.theme == 1: #GH3 starcolor flamecol = (self.spColor[0]*spcolmod[0], self.spColor[1]*spcolmod[1], self.spColor[2]*spcolmod[2]) #flamecol = (.2,.4,.7) else: #Default starcolor (Rockband) flamecol = (.2,.2,.2) self.engine.draw3Dtex(self.hitflames2Drawing, coord = (x+.005, y+.255, 0), rot = (90, 1, 0, 0), scale = (.35 + .6 * ms * ff, event.flameCount/5.0 + .6 * ms * ff, event.flameCount / 5.0 + .6 * ms * ff), vertex = (-flameSize * ff,-flameSize * ff,flameSize * ff,flameSize * ff), texcoord = (0.0,0.0,1.0,1.0), multiples = True, alpha = True, color = flamecol) flamecol = (flameColor[0], flameColor[1], flameColor[2]) spcolmod = (.6,.6,.6) if self.starPowerActive: if self.theme == 0 or self.theme == 1: #GH3 starcolor flamecol = (self.spColor[0]*spcolmod[0], self.spColor[1]*spcolmod[1], self.spColor[2]*spcolmod[2]) #flamecol = (.2,.5,.7) else: #Default starcolor (Rockband) flamecol = (.3,.3,.3) self.engine.draw3Dtex(self.hitflames2Drawing, coord = (x, y+.255, 0), rot = (90, 1, 0, 0), scale = (.40 + .6 * ms * ff, event.flameCount/4.7 + .6 * ms * ff, event.flameCount / 4.7 + .6 * ms * ff), vertex = (-flameSize * ff,-flameSize * ff,flameSize * ff,flameSize * ff), texcoord = (0.0,0.0,1.0,1.0), multiples = True, alpha = True, color = flamecol) else: flameColorMod0 = 0.1 * (flameLimit - event.flameCount) flameColorMod1 = 0.1 * (flameLimit - event.flameCount) flameColorMod2 = 0.1 * (flameLimit - event.flameCount) flamecol = (flameColor[0] * flameColorMod0, flameColor[1] * flameColorMod1, flameColor[2] * flameColorMod2) spcolmod = (.7,.7,.7) if self.starPowerActive: if self.theme == 0 or self.theme == 1: flamecol = (self.spColor[0]*spcolmod[0], self.spColor[1]*spcolmod[1], self.spColor[2]*spcolmod[2]) #flamecol = (.3,.6,.7)#GH3 starcolor else: flamecol = (.4,.4,.4)#Default starcolor (Rockband) if self.theme != 2 and event.finalStar and self.spEnabled: wid, hei, = self.engine.view.geometry[2:4] self.engine.draw3Dtex(self.hitlightning, coord = (xlightning, y, 3.3), rot = (90, 1, 0, 0), scale = (.15 + .5 * ms * ff, event.flameCount / 3.0 + .6 * ms * ff, 2), vertex = (.4,-2,-.4,2), texcoord = (0.0,0.0,1.0,1.0), multiples = True, alpha = True, color = (1,1,1)) else: self.engine.draw3Dtex(self.hitflames1Drawing, coord = (x, y + .35, 0), rot = (90, 1, 0, 0), scale = (.25 + .6 * ms * ff, event.flameCount / 3.0 + .6 * ms * ff, event.flameCount / 3.0 + .6 * ms * ff), vertex = (-flameSize * ff,-flameSize * ff,flameSize * ff,flameSize * ff), texcoord = (0.0,0.0,1.0,1.0), multiples = True, alpha = True, color = flamecol) flameColorMod0 = 0.1 * (flameLimit - event.flameCount) flameColorMod1 = 0.1 * (flameLimit - event.flameCount) flameColorMod2 = 0.1 * (flameLimit - event.flameCount) flamecol = (flameColor[0] * flameColorMod0, flameColor[1] * flameColorMod1, flameColor[2] * flameColorMod2) spcolmod = (.8,.8,.8) if self.starPowerActive: if self.theme == 0 or self.theme == 1: #GH3 starcolor flamecol = (self.spColor[0]*spcolmod[0], self.spColor[1]*spcolmod[1], self.spColor[2]*spcolmod[2]) #flamecol = (.3,.6,.8) else: #Default starcolor (Rockband) flamecol = (.5,.5,.5) self.engine.draw3Dtex(self.hitflames1Drawing, coord = (x - .005, y + .40 + .005, 0), rot = (90, 1, 0, 0), scale = (.30 + .6 * ms * ff, (event.flameCount + 1)/ 2.5 + .6 * ms * ff, (event.flameCount + 1) / 2.5 + .6 * ms * ff), vertex = (-flameSize * ff,-flameSize * ff,flameSize * ff,flameSize * ff), texcoord = (0.0,0.0,1.0,1.0), multiples = True, alpha = True, color = flamecol) flameColorMod0 = 0.1 * (flameLimit - event.flameCount) flameColorMod1 = 0.1 * (flameLimit - event.flameCount) flameColorMod2 = 0.1 * (flameLimit - event.flameCount) flamecol = (flameColor[0] * flameColorMod0, flameColor[1] * flameColorMod1, flameColor[2] * flameColorMod2) spcolmod = (.9,.9,.9) if self.starPowerActive: if self.theme == 0 or self.theme == 1: #GH3 starcolor flamecol = (self.spColor[0]*spcolmod[0], self.spColor[1]*spcolmod[1], self.spColor[2]*spcolmod[2]) #flamecol = (.3,.7,.8) else: #Default starcolor (Rockband) flamecol = (.6,.6,.6) self.engine.draw3Dtex(self.hitflames1Drawing, coord = (x + .005, y + .35 + .005, 0), rot = (90, 1, 0, 0), scale = (.35 + .6 * ms * ff, (event.flameCount + 1) / 2.0 + .6 * ms * ff, (event.flameCount + 1) / 2.0 + .6 * ms * ff), vertex = (-flameSize * ff,-flameSize * ff,flameSize * ff,flameSize * ff), texcoord = (0.0,0.0,1.0,1.0), multiples = True, alpha = True, color = flamecol) flameColorMod0 = 0.1 * (flameLimit - event.flameCount) flameColorMod1 = 0.1 * (flameLimit - event.flameCount) flameColorMod2 = 0.1 * (flameLimit - event.flameCount) flamecol = (flameColor[0] * flameColorMod0, flameColor[1] * flameColorMod1, flameColor[2] * flameColorMod2) spcolmod = (1,1,1) if self.starPowerActive: if self.theme == 0 or self.theme == 1: #GH3 starcolor flamecol = (self.spColor[0]*spcolmod[0], self.spColor[1]*spcolmod[1], self.spColor[2]*spcolmod[2]) #flamecol = (.3,.7,.9) else: #Default starcolor (Rockband) flamecol = (.7,.7,.7) self.engine.draw3Dtex(self.hitflames1Drawing, coord = (x+.005, y +.35 +.005, 0), rot = (90, 1, 0, 0), scale = (.40 + .6 * ms * ff, (event.flameCount + 1) / 1.7 + .6 * ms * ff, (event.flameCount + 1) / 1.7 + .6 * ms * ff), vertex = (-flameSize * ff,-flameSize * ff,flameSize * ff,flameSize * ff), texcoord = (0.0,0.0,1.0,1.0), multiples = True, alpha = True, color = flamecol) event.flameCount += 1 def renderFreestyleFlames(self, visibility, controls): if self.flameColors[0][0][0] == -1: return beatsPerUnit = self.beatsPerBoard / self.boardLength w = self.boardWidth / self.strings #track = song.track[self.player] size = (.22, .22) v = 1.0 - visibility ## if self.disableFlameSFX != True: ## for n in range(self.strings): ## f = self.fretWeight[n] ## c = self.fretColors[n+1] #MFH shifted by 1 for most drum colors ## if f and (controls.getState(self.keys[0]) or controls.getState(self.keys[5])): ## f += 0.25 ## y = v + f / 6 ## x = (self.strings / 2 -.5 - n) * w ## f = self.fretActivity[n] ## ## if f: ## ms = math.sin(self.time) * .25 + 1 ## ff = f ## ff += 1.2 ## ## glBlendFunc(GL_ONE, GL_ONE) ## ## flameSize = self.flameSizes[self.scoreMultiplier - 1][n] ## if self.theme == 0 or self.theme == 1: #THIS SETS UP GH3 COLOR, ELSE ROCKBAND(which is DEFAULT in Theme.py) ## flameColor = self.gh3flameColor ## else: ## flameColor = self.flameColors[self.scoreMultiplier - 1][n] ## #Below was an if that set the "flame"-color to the same as the fret color if there was no specific flamecolor defined. ## ## flameColorMod0 = 1.1973333333333333333333333333333 ## flameColorMod1 = 1.9710526315789473684210526315789 ## flameColorMod2 = 10.592592592592592592592592592593 ## ## glColor3f(flameColor[0] * flameColorMod0, flameColor[1] * flameColorMod1, flameColor[2] * flameColorMod2) ## if self.starPowerActive: ## if self.theme == 0 or self.theme == 1: #GH3 starcolor ## glColor3f(self.spColor[0],self.spColor[1],self.spColor[2]) ## #glColor3f(.3,.7,.9) ## else: #Default starcolor (Rockband) ## glColor3f(.9,.9,.9) ## ## if not self.Hitanim: ## glEnable(GL_TEXTURE_2D) ## self.hitglowDrawing.texture.bind() ## glPushMatrix() ## glTranslate(x, y + .125, 0) ## glRotate(90, 1, 0, 0) ## glScalef(0.5 + .6 * ms * ff, 1.5 + .6 * ms * ff, 1 + .6 * ms * ff) ## glBegin(GL_TRIANGLE_STRIP) ## glTexCoord2f(0.0, 0.0) ## glVertex3f(-flameSize * ff, 0, -flameSize * ff) ## glTexCoord2f(1.0, 0.0) ## glVertex3f( flameSize * ff, 0, -flameSize * ff) ## glTexCoord2f(0.0, 1.0) ## glVertex3f(-flameSize * ff, 0, flameSize * ff) ## glTexCoord2f(1.0, 1.0) ## glVertex3f( flameSize * ff, 0, flameSize * ff) ## glEnd() ## glPopMatrix() ## glDisable(GL_TEXTURE_2D) ## #Alarian: Animated hitflames ## else: ## self.HCount = self.HCount + 1 ## if self.HCount > self.Animspeed-1: ## self.HCount = 0 ## HIndex = (self.HCount * 16 - (self.HCount * 16) % self.Animspeed) / self.Animspeed ## if HIndex > 15: ## HIndex = 0 ## texX = (HIndex*(1/16.0), HIndex*(1/16.0)+(1/16.0)) ## ## glColor3f(1,1,1) ## glEnable(GL_TEXTURE_2D) ## self.hitglowAnim.texture.bind() ## glPushMatrix() ## glTranslate(x, y + .225, 0) ## glRotate(90, 1, 0, 0) ## ## #glScalef(1.3, 1, 2) ## #glScalef(1.7, 1, 2.6) ## glScalef(2, 1, 2.9) #worldrave correct flame size ## ## ## glBegin(GL_TRIANGLE_STRIP) ## glTexCoord2f(texX[0], 0.0)#upper left corner of frame square in .png ## glVertex3f(-flameSize * ff, 0, -flameSize * ff)#"upper left" corner of surface that texture is rendered on ## glTexCoord2f(texX[1], 0.0)#upper right ## glVertex3f( flameSize * ff, 0, -flameSize * ff) ## glTexCoord2f(texX[0], 1.0)#lower left ## glVertex3f(-flameSize * ff, 0, flameSize * ff) ## glTexCoord2f(texX[1], 1.0)#lower right ## glVertex3f( flameSize * ff, 0, flameSize * ff) ## glEnd() ## glPopMatrix() ## glDisable(GL_TEXTURE_2D) ## ## ff += .3 ## ## #flameSize = self.flameSizes[self.scoreMultiplier - 1][n] ## #flameColor = self.flameColors[self.scoreMultiplier - 1][n] ## ## flameColorMod0 = 1.1973333333333333333333333333333 ## flameColorMod1 = 1.7842105263157894736842105263158 ## flameColorMod2 = 12.222222222222222222222222222222 ## ## glColor3f(flameColor[0] * flameColorMod0, flameColor[1] * flameColorMod1, flameColor[2] * flameColorMod2) ## if self.starPowerActive: ## if self.theme == 0 or self.theme == 1: #GH3 starcolor ## glColor3f(self.spColor[0],self.spColor[1],self.spColor[2]) ## #glColor3f(.3,.7,.9) ## else: #Default starcolor (Rockband) ## glColor3f(.8,.8,.8) ## ## if not self.Hitanim: ## glEnable(GL_TEXTURE_2D) ## self.hitglow2Drawing.texture.bind() ## glPushMatrix() ## glTranslate(x, y + .25, .05) ## glRotate(90, 1, 0, 0) ## glScalef(.40 + .6 * ms * ff, 1.5 + .6 * ms * ff, 1 + .6 * ms * ff) ## glBegin(GL_TRIANGLE_STRIP) ## glTexCoord2f(0.0, 0.0) ## glVertex3f(-flameSize * ff, 0, -flameSize * ff) ## glTexCoord2f(1.0, 0.0) ## glVertex3f( flameSize * ff, 0, -flameSize * ff) ## glTexCoord2f(0.0, 1.0) ## glVertex3f(-flameSize * ff, 0, flameSize * ff) ## glTexCoord2f(1.0, 1.0) ## glVertex3f( flameSize * ff, 0, flameSize * ff) ## glEnd() ## glPopMatrix() ## glDisable(GL_TEXTURE_2D) ## ## glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) ## ## #self.hit[n] = True if self.disableFlameSFX != True: flameLimit = 10.0 flameLimitHalf = round(flameLimit/2.0) for fretNum in range(self.strings+1): #need to add 1 to string count to check this correctly (bass drum doesnt count as a string) #MFH - must include secondary drum keys here #if controls.getState(self.keys[fretNum]): if controls.getState(self.keys[fretNum]) or controls.getState(self.keys[fretNum+5]): if self.freestyleHitFlameCounts[fretNum] < flameLimit: ms = math.sin(self.time) * .25 + 1 if fretNum == 0: x = (self.strings / 2 - 2) * w else: x = (self.strings / 2 +.5 - fretNum) * w #x = (self.strings / 2 - fretNum) * w xlightning = (self.strings / 2 - fretNum)*2.2*w ff = 1 + 0.25 y = v + ff / 6 glBlendFunc(GL_ONE, GL_ONE) if self.theme == 2: y -= 0.5 #flameSize = self.flameSizes[self.scoreMultiplier - 1][fretNum] flameSize = self.flameSizes[self.cappedScoreMult - 1][fretNum] if self.theme == 0 or self.theme == 1: #THIS SETS UP GH3 COLOR, ELSE ROCKBAND(which is DEFAULT in Theme.py) flameColor = self.gh3flameColor else: #MFH - fixing crash! #try: # flameColor = self.flameColors[self.scoreMultiplier - 1][fretNum] #except IndexError: flameColor = self.fretColors[fretNum] if flameColor[0] == -2: flameColor = self.fretColors[fretNum] ff += 1.5 #ff first time is 2.75 after this if self.freestyleHitFlameCounts[fretNum] < flameLimitHalf: flamecol = (flameColor[0], flameColor[1], flameColor[2]) if self.starPowerActive: if self.theme == 0 or self.theme == 1: #GH3 starcolor flamecol = self.spColor #(.3,.7,.9) else: #Default starcolor (Rockband) flamecol = (.1,.1,.1) self.engine.draw3Dtex(self.hitflames2Drawing, coord = (x, y + .20, 0), rot = (90, 1, 0, 0), scale = (.25 + .6 * ms * ff, self.freestyleHitFlameCounts[fretNum]/6.0 + .6 * ms * ff, self.freestyleHitFlameCounts[fretNum] / 6.0 + .6 * ms * ff), vertex = (-flameSize * ff,-flameSize * ff,flameSize * ff,flameSize * ff), texcoord = (0.0,0.0,1.0,1.0), multiples = True, alpha = True, color = flamecol) flamecol = (flameColor[0], flameColor[1], flameColor[2]) if self.starPowerActive: if self.theme == 0 or self.theme == 1: #GH3 starcolor flamecol = self.spColor #(.3,.7,.9) else: #Default starcolor (Rockband) flamecol = (.1,.1,.1) self.engine.draw3Dtex(self.hitflames2Drawing, coord = (x - .005, y + .25 + .005, 0), rot = (90, 1, 0, 0), scale = (.30 + .6 * ms * ff, (self.freestyleHitFlameCounts[fretNum] + 1) / 5.5 + .6 * ms * ff, (self.freestyleHitFlameCounts[fretNum] + 1) / 5.5 + .6 * ms * ff), vertex = (-flameSize * ff,-flameSize * ff,flameSize * ff,flameSize * ff), texcoord = (0.0,0.0,1.0,1.0), multiples = True, alpha = True, color = flamecol) flamecol = (flameColor[0], flameColor[1], flameColor[2]) if self.starPowerActive: if self.theme == 0 or self.theme == 1: #GH3 starcolor flamecol = self.spColor #(.3,.7,.9) else: #Default starcolor (Rockband) #flamecol = glColor3f(.2,.2,.2) flamecol = (.2,.2,.2) self.engine.draw3Dtex(self.hitflames2Drawing, coord = (x+.005, y +.25 +.005, 0), rot = (90, 1, 0, 0), scale = (.35 + .6 * ms * ff, (self.freestyleHitFlameCounts[fretNum] + 1) / 5.0 + .6 * ms * ff, (self.freestyleHitFlameCounts[fretNum] + 1) / 5.0 + .6 * ms * ff), vertex = (-flameSize * ff,-flameSize * ff,flameSize * ff,flameSize * ff), texcoord = (0.0,0.0,1.0,1.0), multiples = True, alpha = True, color = flamecol) flamecol = (flameColor[0], flameColor[1], flameColor[2]) if self.starPowerActive: if self.theme == 0 or self.theme == 1: #GH3 starcolor flamecol = self.spColor #(.3,.7,.9) else: #Default starcolor (Rockband) flamecol = (.3,.3,.3) self.engine.draw3Dtex(self.hitflames2Drawing, coord = (x, y +.25 +.005, 0), rot = (90, 1, 0, 0), scale = (.40 + .6 * ms * ff, (self.freestyleHitFlameCounts[fretNum] + 1)/ 4.7 + .6 * ms * ff, (self.freestyleHitFlameCounts[fretNum] + 1) / 4.7 + .6 * ms * ff), vertex = (-flameSize * ff,-flameSize * ff,flameSize * ff,flameSize * ff), texcoord = (0.0,0.0,1.0,1.0), multiples = True, alpha = True, color = flamecol) else: flameColorMod0 = 0.1 * (flameLimit - self.freestyleHitFlameCounts[fretNum]) flameColorMod1 = 0.1 * (flameLimit - self.freestyleHitFlameCounts[fretNum]) flameColorMod2 = 0.1 * (flameLimit - self.freestyleHitFlameCounts[fretNum]) flamecol = (flameColor[0] * flameColorMod0, flameColor[1] * flameColorMod1, flameColor[2] * flameColorMod2) #MFH - hit lightning logic is not needed for freestyle flames... self.engine.draw3Dtex(self.hitflames1Drawing, coord = (x, y + .35, 0), rot = (90, 1, 0, 0), scale = (.25 + .6 * ms * ff, self.freestyleHitFlameCounts[fretNum] / 3.0 + .6 * ms * ff, self.freestyleHitFlameCounts[fretNum] / 3.0 + .6 * ms * ff), vertex = (-flameSize * ff,-flameSize * ff,flameSize * ff,flameSize * ff), texcoord = (0.0,0.0,1.0,1.0), multiples = True, alpha = True, color = flamecol) flameColorMod0 = 0.1 * (flameLimit - self.freestyleHitFlameCounts[fretNum]) flameColorMod1 = 0.1 * (flameLimit - self.freestyleHitFlameCounts[fretNum]) flameColorMod2 = 0.1 * (flameLimit - self.freestyleHitFlameCounts[fretNum]) flamecol = (flameColor[0] * flameColorMod0, flameColor[1] * flameColorMod1, flameColor[2] * flameColorMod2) if self.starPowerActive: if self.theme == 0 or self.theme == 1: #GH3 starcolor flamecol = self.spColor #(.3,.7,.9) else: #Default starcolor (Rockband) flamecol = (.5,.5,.5) self.engine.draw3Dtex(self.hitflames1Drawing, coord = (x - .005, y + .40 + .005, 0), rot = (90, 1, 0, 0), scale = (.30 + .6 * ms * ff, (self.freestyleHitFlameCounts[fretNum] + 1)/ 2.5 + .6 * ms * ff, (self.freestyleHitFlameCounts[fretNum] + 1) / 2.5 + .6 * ms * ff), vertex = (-flameSize * ff,-flameSize * ff,flameSize * ff,flameSize * ff), texcoord = (0.0,0.0,1.0,1.0), multiples = True, alpha = True, color = flamecol) flameColorMod0 = 0.1 * (flameLimit - self.freestyleHitFlameCounts[fretNum]) flameColorMod1 = 0.1 * (flameLimit - self.freestyleHitFlameCounts[fretNum]) flameColorMod2 = 0.1 * (flameLimit - self.freestyleHitFlameCounts[fretNum]) flamecol = (flameColor[0] * flameColorMod0, flameColor[1] * flameColorMod1, flameColor[2] * flameColorMod2) if self.starPowerActive: if self.theme == 0 or self.theme == 1: #GH3 starcolor flamecol = self.spColor #(.3,.7,.9) else: #Default starcolor (Rockband) flamecol = (.6,.6,.6) self.engine.draw3Dtex(self.hitflames1Drawing, coord = (x + .005, y + .35 + .005, 0), rot = (90, 1, 0, 0), scale = (.35 + .6 * ms * ff, (self.freestyleHitFlameCounts[fretNum] + 1) / 2.0 + .6 * ms * ff, (self.freestyleHitFlameCounts[fretNum] + 1) / 2.0 + .6 * ms * ff), vertex = (-flameSize * ff,-flameSize * ff,flameSize * ff,flameSize * ff), texcoord = (0.0,0.0,1.0,1.0), multiples = True, alpha = True, color = flamecol) flameColorMod0 = 0.1 * (flameLimit - self.freestyleHitFlameCounts[fretNum]) flameColorMod1 = 0.1 * (flameLimit - self.freestyleHitFlameCounts[fretNum]) flameColorMod2 = 0.1 * (flameLimit - self.freestyleHitFlameCounts[fretNum]) flamecol = (flameColor[0] * flameColorMod0, flameColor[1] * flameColorMod1, flameColor[2] * flameColorMod2) if self.starPowerActive: if self.theme == 0 or self.theme == 1: #GH3 starcolor flamecol = self.spColor #(.3,.7,.9) else: #Default starcolor (Rockband) flamecol = (.7,.7,.7) self.engine.draw3Dtex(self.hitflames1Drawing, coord = (x + .005, y + .35 + .005, 0), rot = (90, 1, 0, 0), scale = (.40 + .6 * ms * ff, (self.freestyleHitFlameCounts[fretNum] + 1) / 1.7 + .6 * ms * ff, (self.freestyleHitFlameCounts[fretNum] + 1) / 1.7 + .6 * ms * ff), vertex = (-flameSize * ff,-flameSize * ff,flameSize * ff,flameSize * ff), texcoord = (0.0,0.0,1.0,1.0), multiples = True, alpha = True, color = flamecol) self.freestyleHitFlameCounts[fretNum] += 1 else: #MFH - flame count is done - reset it! self.freestyleHitFlameCounts[fretNum] = 0 #MFH def render(self, visibility, song, pos, controls, killswitch): if shaders.turnon: shaders.globals["dfActive"] = self.drumFillsActive shaders.globals["breActive"] = self.freestyleActive shaders.globals["rockLevel"] = self.rockLevel if not self.starNotesSet == True: self.totalNotes = 0 for time, event in song.track[self.player].getAllEvents(): if not isinstance(event, Note): continue self.totalNotes += 1 stars = [] maxStars = [] maxPhrase = self.totalNotes/120 for q in range(0,maxPhrase): for n in range(0,10): stars.append(self.totalNotes/maxPhrase*(q)+n+maxPhrase/4) maxStars.append(self.totalNotes/maxPhrase*(q)+10+maxPhrase/4) i = 0 for time, event in song.track[self.player].getAllEvents(): if not isinstance(event, Note): continue for a in stars: if i == a: self.starNotes.append(time) event.star = True for a in maxStars: if i == a: self.maxStars.append(time) event.finalStar = True i += 1 for time, event in song.track[self.player].getAllEvents(): if not isinstance(event, Note): continue for q in self.starNotes: if time == q: event.star = True for q in self.maxStars: if time == q and not event.finalStar: event.star = True self.starNotesSet = True if not (self.coOpFailed and not self.coOpRestart): glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) glEnable(GL_COLOR_MATERIAL) if self.leftyMode: glScalef(-1, 1, 1) if self.freestyleActive or self.drumFillsActive: self.renderOpenNotes(visibility, song, pos) self.renderNotes(visibility, song, pos) self.renderFreestyleLanes(visibility, song, pos, controls) #MFH - render the lanes on top of the notes. self.renderFrets(visibility, song, controls) if self.hitFlamesPresent: #MFH - only when present! self.renderFreestyleFlames(visibility, controls) #MFH - freestyle hit flames else: self.renderFreestyleLanes(visibility, song, pos, controls) #if self.fretsUnderNotes: #MFH if self.fretsUnderNotes and self.twoDnote != False: #MFH self.renderFrets(visibility, song, controls) self.renderOpenNotes(visibility, song, pos) self.renderNotes(visibility, song, pos) else: self.renderOpenNotes(visibility, song, pos) self.renderNotes(visibility, song, pos) self.renderFrets(visibility, song, controls) if self.hitFlamesPresent: #MFH - only when present! self.renderFlames(visibility, song, pos, controls) #MFH - only when freestyle inactive! if self.leftyMode: glScalef(-1, 1, 1) if self.theme == 2 and self.overdriveFlashCount < self.overdriveFlashCounts: self.overdriveFlashCount = self.overdriveFlashCount + 1 def getMissedNotes(self, song, pos, catchup = False): if not song: return if not song.readyToGo: return m1 = self.lateMargin m2 = self.lateMargin * 2 track = song.track[self.player] notes = [(time, event) for time, event in track.getEvents(pos - m1, pos - m2) if isinstance(event, Note)] notes = [(time, event) for time, event in notes if (time >= (pos - m2)) and (time <= (pos - m1))] notes = [(time, event) for time, event in notes if not event.played and not event.hopod and not event.skipped] if catchup == True: for time, event in notes: event.skipped = True return sorted(notes, key=lambda x: x[1].number) def getMissedNotesMFH(self, song, pos, catchup = False): if not song: return if not song.readyToGo: return m1 = self.lateMargin m2 = self.lateMargin * 2 track = song.track[self.player] notes = [(time, event) for time, event in track.getEvents(pos - m2, pos - m1) if isinstance(event, Note)] #was out of order #MFH - this additional filtration step removes sustains whose Note On event time is now outside the hitwindow. notes = [(time, event) for time, event in notes if (time >= (pos - m2)) and (time <= (pos - m1))] notes = [(time, event) for time, event in notes if not event.played and not event.hopod and not event.skipped] if catchup == True: for time, event in notes: event.skipped = True return sorted(notes, key=lambda x: x[0]) #MFH - what the hell, this should be sorted by TIME not note number.... def getRequiredNotes(self, song, pos): return self.getRequiredNotesMFH(song, pos) #- track = song.track[self.player] #- notes = [(time, event) for time, event in track.getEvents(pos - self.lateMargin, pos + self.earlyMargin) if isinstance(event, Note)] #- notes = [(time, event) for time, event in notes if not event.played] #- notes = [(time, event) for time, event in notes if (time >= (pos - self.lateMargin)) and (time <= (pos + self.earlyMargin))] #- if notes: #- t = min([time for time, event in notes]) #- notes = [(time, event) for time, event in notes if time - t < 1e-3] #- return sorted(notes, key=lambda x: x[1].number) def getRequiredNotes2(self, song, pos, hopo = False): return self.getRequiredNotesMFH(song, pos) #- track = song.track[self.player] #- notes = [(time, event) for time, event in track.getEvents(pos - self.lateMargin, pos + self.earlyMargin) if isinstance(event, Note)] #- notes = [(time, event) for time, event in notes if not (event.hopod or event.played)] #- notes = [(time, event) for time, event in notes if (time >= (pos - self.lateMargin)) and (time <= (pos + self.earlyMargin))] #- if notes: #- t = min([time for time, event in notes]) #- notes = [(time, event) for time, event in notes if time - t < 1e-3] #- #- return sorted(notes, key=lambda x: x[1].number) def getRequiredNotes3(self, song, pos, hopo = False): return self.getRequiredNotesMFH(song, pos) #- track = song.track[self.player] #- notes = [(time, event) for time, event in track.getEvents(pos - self.lateMargin, pos + self.earlyMargin) if isinstance(event, Note)] #- notes = [(time, event) for time, event in notes if not (event.hopod or event.played or event.skipped)] #- notes = [(time, event) for time, event in notes if (time >= (pos - self.lateMargin)) and (time <= (pos + self.earlyMargin))] #- #- return sorted(notes, key=lambda x: x[1].number) #MFH - corrected and optimized: def getRequiredNotesMFH(self, song, pos): track = song.track[self.player] notes = [(time, event) for time, event in track.getEvents(pos - self.lateMargin, pos + self.earlyMargin) if isinstance(event, Note)] notes = [(time, event) for time, event in notes if not (event.hopod or event.played or event.skipped)] #MFH - this additional filtration step removes sustains whose Note On event time is now outside the hitwindow. notes = [(time, event) for time, event in notes if (time >= (pos - self.lateMargin)) and (time <= (pos + self.earlyMargin))] return sorted(notes, key=lambda x: x[0]) #MFH - what the hell, this should be sorted by TIME not note number.... #MFH - corrected and optimized: def getRequiredNotesForJurgenOnTime(self, song, pos): track = song.track[self.player] notes = [(time, event) for time, event in track.getEvents(pos - self.lateMargin, pos + 30) if isinstance(event, Note)] notes = [(time, event) for time, event in notes if not (event.hopod or event.played or event.skipped)] return sorted(notes, key=lambda x: x[0]) #MFH - what the hell, this should be sorted by TIME not note number.... def hitNote(self, time, note): self.pickStartPos = max(self.pickStartPos, time) self.playedNotes = [(time, note)] note.played = True return True def areNotesTappable(self, notes): if not notes: return #for time, note in notes: # if note.tappable > 1: # return True return False def playDrumSounds(self, controls, playBassDrumOnly = False): #MFH - handles playing of drum sounds. #Returns list of drums that were just hit (including logic for detecting a held bass pedal) #pass playBassDrumOnly = True (optional paramater) to only play the bass drum sound, but still # return a list of drums just hit (intelligently play the bass drum if it's held down during gameplay) drumsJustHit = [False, False, False, False, False] for i in range (5): if controls.getState(self.keys[i]) or controls.getState(self.keys[5+i]): if i == 0: if not self.bassDrumPedalDown: #MFH - gotta check if bass drum pedal is just held down! if self.engine.data.bassDrumSoundFound: self.engine.data.bassDrumSound.play() self.bassDrumPedalDown = True drumsJustHit[0] = True if self.fretboardHop < 0.04: self.fretboardHop = 0.04 #stump else: self.bassDrumPedalDown = False if i == 1: if self.engine.data.T1DrumSoundFound and not playBassDrumOnly: self.engine.data.T1DrumSound.play() drumsJustHit[i] = True if i == 2: if self.engine.data.T2DrumSoundFound and not playBassDrumOnly: self.engine.data.T2DrumSound.play() drumsJustHit[i] = True if i == 3: if self.engine.data.T3DrumSoundFound and not playBassDrumOnly: self.engine.data.T3DrumSound.play() drumsJustHit[i] = True if i == 4: #MFH - must actually activate starpower! if self.engine.data.CDrumSoundFound and not playBassDrumOnly: self.engine.data.CDrumSound.play() drumsJustHit[i] = True return drumsJustHit #volshebnyi - handle freestyle picks here def freestylePick(self, song, pos, controls): drumsJustHit = self.playDrumSounds(controls) numHits = 0 for i, drumHit in enumerate(drumsJustHit): if drumHit: numHits += 1 if i == 4: if not self.bigRockEndingMarkerSeen and (self.drumFillsActive or self.drumFillWasJustActive) and self.drumFillsHits >= 4 and not self.starPowerActive: drumFillCymbalPos = self.freestyleStart+self.freestyleLength minDrumFillCymbalHitTime = drumFillCymbalPos - self.earlyMargin maxDrumFillCymbalHitTime = drumFillCymbalPos + self.lateMargin if (pos >= minDrumFillCymbalHitTime) and (pos <= maxDrumFillCymbalHitTime): self.freestyleSP = True #- if controls.getState(self.keys[0]): #- if not self.bassDrumPedalDown: #MFH - gotta check if bass drum pedal is just held down! #- numHits = 1 #- if self.engine.data.bassDrumSoundFound: #- self.engine.data.bassDrumSound.play() #- self.bassDrumPedalDown = True #- for i in range (1,5): #- if controls.getState(self.keys[i]) or controls.getState(self.keys[4+i]): #- numHits += 1 #- if i == 1: #- if self.engine.data.T1DrumSoundFound: #- self.engine.data.T1DrumSound.play() #- if i == 2: #- if self.engine.data.T2DrumSoundFound: #- self.engine.data.T2DrumSound.play() #- if i == 3: #- if self.engine.data.T3DrumSoundFound: #- self.engine.data.T3DrumSound.play() #- if i == 4: #MFH - must actually activate starpower! #- if self.engine.data.CDrumSoundFound: #- self.engine.data.CDrumSound.play() #- if self.drumFillsActive and self.drumFillsHits >= 4 and not self.starPowerActive: #- drumFillCymbalPos = self.freestyleStart+self.freestyleLength #- minDrumFillCymbalHitTime = drumFillCymbalPos - self.earlyMargin #- maxDrumFillCymbalHitTime = drumFillCymbalPos + self.lateMargin #- if (pos >= minDrumFillCymbalHitTime) and (pos <= maxDrumFillCymbalHitTime): #- self.freestyleSP = True return numHits def startPick(self, song, pos, controls, hopo = False): if not song: return False if not song.readyToGo: return if self.lastFretWasBassDrum: if controls.getState(self.keys[1]) or controls.getState(self.keys[2]) or controls.getState(self.keys[3]) or controls.getState(self.keys[4]) or controls.getState(self.keys[6]) or controls.getState(self.keys[7]) or controls.getState(self.keys[8]) or controls.getState(self.keys[9]): self.lastFretWasBassDrum = False elif controls.getState(self.keys[0]) or controls.getState(self.keys[5]): self.lastFretWasBassDrum = True else: self.lastFretWasBassDrum = False #Faaa Drum sound if self.lastFretWasT1: if controls.getState(self.keys[0]) or controls.getState(self.keys[2]) or controls.getState(self.keys[3]) or controls.getState(self.keys[4]) or controls.getState(self.keys[5]) or controls.getState(self.keys[7]) or controls.getState(self.keys[8]) or controls.getState(self.keys[9]): self.lastFretWasT1 = False elif controls.getState(self.keys[1]) or controls.getState(self.keys[6]): self.lastFretWasT1 = True else: self.lastFretWasT1 = False if self.lastFretWasT2: if controls.getState(self.keys[0]) or controls.getState(self.keys[1]) or controls.getState(self.keys[3]) or controls.getState(self.keys[4]) or controls.getState(self.keys[5]) or controls.getState(self.keys[6]) or controls.getState(self.keys[8]) or controls.getState(self.keys[9]): self.lastFretWasT2 = False elif controls.getState(self.keys[2]) or controls.getState(self.keys[7]): self.lastFretWasT2 = True else: self.lastFretWasT2 = False if self.lastFretWasT3: if controls.getState(self.keys[0]) or controls.getState(self.keys[1]) or controls.getState(self.keys[2]) or controls.getState(self.keys[4]) or controls.getState(self.keys[5]) or controls.getState(self.keys[6]) or controls.getState(self.keys[7]) or controls.getState(self.keys[9]): self.lastFretWasT3 = False elif controls.getState(self.keys[3]) or controls.getState(self.keys[8]): self.lastFretWasT3 = True else: self.lastFretWasT3 = False if self.lastFretWasC: if controls.getState(self.keys[0]) or controls.getState(self.keys[1]) or controls.getState(self.keys[2]) or controls.getState(self.keys[3]) or controls.getState(self.keys[5]) or controls.getState(self.keys[6]) or controls.getState(self.keys[7]) or controls.getState(self.keys[8]): self.lastFretWasC = False elif controls.getState(self.keys[4]) or controls.getState(self.keys[9]): self.lastFretWasC = True else: self.lastFretWasC = False #self.matchingNotes = self.getRequiredNotes(song, pos) self.matchingNotes = self.getRequiredNotesMFH(song, pos) #MFH - ignore skipped notes please! # no self.matchingNotes? if not self.matchingNotes: return False self.playedNotes = [] self.pickStartPos = pos #adding bass drum hit every bass fret: for time, note in self.matchingNotes: for i in range(5): if note.number == i and (controls.getState(self.keys[i]) or controls.getState(self.keys[i+5])): if self.guitarSolo: self.currentGuitarSoloHitNotes += 1 if i == 0 and self.fretboardHop < 0.07: self.fretboardHop = 0.07 #stump if shaders.turnon: shaders.var["fret"][self.player][note.number]=shaders.time() shaders.var["fretpos"][self.player][note.number]=pos return self.hitNote(time, note) return False def startPick2(self, song, pos, controls, hopo = False): res = self.startPick(song, pos, controls, hopo) return res def startPick3(self, song, pos, controls, hopo = False): res = self.startPick(song, pos, controls, hopo) return res def endPick(self, pos): self.playedNotes = [] #for time, note in self.playedNotes: # if time + note.length > pos + self.noteReleaseMargin: # return False return True def getPickLength(self, pos): #if not self.playedNotes: return 0.0 ## The pick length is limited by the played notes #pickLength = pos - self.pickStartPos #for time, note in self.playedNotes: # pickLength = min(pickLength, note.length) #return pickLength def coOpRescue(self, pos): self.coOpRestart = True #initializes Restart Timer self.coOpRescueTime = pos self.starPower = 0 Log.debug("Rescued at " + str(pos)) def run(self, ticks, pos, controls): if not self.paused: self.time += ticks #myfingershurt: must not decrease SP if paused. if self.starPowerActive == True and self.paused == False: self.starPower -= ticks/self.starPowerDecreaseDivisor if self.starPower <= 0: self.starPower = 0 self.starPowerActive = False activeFrets = [(note.number - 1) for time, note in self.playedNotes] for n in range(self.strings): if n == 0 and (controls.getState(self.keys[1]) or controls.getState(self.keys[6])): self.fretWeight[n] = 0.5 elif n == 1 and (controls.getState(self.keys[2]) or controls.getState(self.keys[7])): self.fretWeight[n] = 0.5 elif n == 2 and (controls.getState(self.keys[3]) or controls.getState(self.keys[8])): self.fretWeight[n] = 0.5 elif n == 3 and (controls.getState(self.keys[4]) or controls.getState(self.keys[9])): self.fretWeight[n] = 0.5 elif controls.getState(self.keys[0]) or controls.getState(self.keys[5]): self.fretWeight[n] = 0.5 else: self.fretWeight[n] = max(self.fretWeight[n] - ticks / 64.0, 0.0) if n in activeFrets: self.fretActivity[n] = min(self.fretActivity[n] + ticks / 32.0, 1.0) else: self.fretActivity[n] = max(self.fretActivity[n] - ticks / 64.0, 0.0) if -1 in activeFrets: self.fretActivity[n] = min(self.fretActivity[n] + ticks / 24.0, 0.6) if self.vbpmLogicType == 0: #MFH - VBPM (old) if self.currentBpm != self.targetBpm: diff = self.targetBpm - self.currentBpm if (round((diff * .03), 4) != 0): self.currentBpm = round(self.currentBpm + (diff * .03), 4) else: self.currentBpm = self.targetBpm self.setBPM(self.currentBpm) # glorandwarf: was setDynamicBPM(self.currentBpm) for time, note in self.playedNotes: if pos > time + note.length: return False return True
Python
# ------------------------------------------------------------------------- # Illusoft Collada 1.4 plugin for Blender version 0.3.89 # -------------------------------------------------------------------------- # ***** BEGIN GPL LICENSE BLOCK ***** # # Copyright (C) 2006: Illusoft - colladablender@illusoft.com # # 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. # # ***** END GPL LICENCE BLOCK ***** # -------------------------------------------------------------------------- from xml.dom.minidom import * from datetime import * # The number of decimals to export floats to ROUND = 5 #---Functions---- angleToRadian = 3.1415926 / 180.0 radianToAngle = 180.0 / 3.1415926 # Convert a string to a float if the value exists def ToFloat(val): if val is None or val == '': return None else: return float(val) # Convert a string to a int if the value exists def ToInt(val): if val is None or val == '': return None else: return int(val) # Convert a string to a list of 3 floats e.g '1.0 2.0 3.0' -> [1.0, 2.0, 3.0] def ToFloat3(stringValue): if stringValue is None: return None split = stringValue.split( ) return [ float( split[ 0 ] ), float( split[ 1 ] ), float( split[ 2 ] ) ] # Convert a string to a list of 2 floats e.g '1.0 2.0' -> [1.0, 2.0] def ToFloat2(stringValue, errorText=''): if stringValue is None: return None split = stringValue.split( ) try: return [ float( split[ 0 ] ), float( split[ 1 ] )] except IndexError: print 'Error: ' + errorText raise def ToList(var): result = [] if var is None: return result split = var.split( ) for i in split: result.append(i) return result # Convert a string or list to a list of floats def ToFloatList(var): result = [] if var is None: return result if type(var) == list: for i in var: result.append(float(i)) else: split = var.split( ) for i in split: result.append(float(i)) return result def ToIntList(lst): result = [] if lst is None: return result if type(lst) == list: for i in lst: result.append(int(i)) else: split = lst.split( ) for i in split: result.append(int(i)) return result def ToBoolList(lst): result = [] if lst is None: return result for i in lst: result.append(bool(i)) return result # Convert a string to a list of 4 floats e.g '1.0 2.0 3.0 4.0' -> [1.0, 2.0, 3.0, 4.0] def ToFloat4(stringValue): split = stringValue.split( ) return [ float( split[ 0 ] ), float( split[ 1 ] ), float( split[ 2 ] ) , float( split[3])] def ToFloat7(stringValue): data = stringValue.split( ) return [ float(data[0]), float(data[1]), float(data[2]), float(data[3]), float(data[4]), float(data[5]), float(data[6])] def AddVec3( vector1, vector2 ): vector1.x += vector2.x vector1.y += vector2.y vector1.z += vector2.z def ToMatrix4( matrixElement ): data = matrixElement.split( ) vec1 = [ float(data[0]), float(data[4]), float(data[8]), float(data[12]) ] vec2 = [ float(data[1]), float(data[5]), float(data[9]), float(data[13]) ] vec3 = [ float(data[2]), float(data[6]), float(data[10]), float(data[14]) ] vec4 = [ float(data[3]), float(data[7]), float(data[11]), float(data[15]) ] return [ vec1, vec2, vec3, vec4 ] def ToMatrix3(matrixElement): data = matrixElement.split( ) vec1 = [ float(data[0]), float(data[3]), float(data[6]) ] vec2 = [ float(data[1]), float(data[4]), float(data[7])] vec3 = [ float(data[2]), float(data[5]), float(data[8])] return [ vec1, vec2, vec3 ] def GetVector3( element ): value = [ float( element[ 0 ] ), float( element[ 1 ] ), float( element[ 2 ] ) ] return value def GetEuler( rotateElement ): euler = [ float( rotateElement[ 0 ] ) * float( rotateElement[ 3 ] ) * angleToRadian, float( rotateElement[ 1 ] ) * float( rotateElement[ 3 ] ) * angleToRadian, float( rotateElement[ 2 ] ) * float( rotateElement[ 3 ] ) * angleToRadian ] return euler def AddEuler(euler1, euler2): euler1.x += euler2.x euler1.y += euler2.y euler1.z += euler2.z def MatrixToString(mat, nDigits): result = '' if mat is None: return result for vec in mat: result += '\n\t' for i in vec: result += str(round(i, nDigits))+' ' return result+'\n' def RoundList(lst, nDigits): result = [] for i in lst: result.append(round(i, nDigits)) return result def ListToString(lst): val = '' if lst is None: return val else: for i in lst: if type(i) == list: val += ListToString(i)+'\n' else: val += str(i)+' ' return val[:-1] #---XML Utils--- # Returns the first child of the specified type in node def FindElementByTagName(parentNode, type): child = parentNode.firstChild while child != None: if child.localName == type: return child child = child.nextSibling ## childs = parentNode.getElementsByTagName(type) ## if len(childs) > 0: ## return childs[0] return None def FindElementsByTagName(parentNode, type): result = [] child = parentNode.firstChild while child != None: if child.localName == type: result.append(child) child = child.nextSibling return result def ReadAttribute(node,attributeName): if node != None and attributeName != None: attribute = node.getAttribute(attributeName) return attribute return None def ReadContents(node): if node != None: child = node.firstChild if child != None and child.nodeType == child.TEXT_NODE: return child.nodeValue return None def ReadDateTime(node): if node == None: return None return GetDateTime(ReadContents(node)) def RemoveWhiteSpace(parent): for child in list(parent.childNodes): if child.nodeType==child.TEXT_NODE and child.data.strip()=='': parent.removeChild(child) else: RemoveWhiteSpace(child) def RemoveWhiteSpaceNode(parent): for child in list(parent.childNodes): if child.nodeType == child.TEXT_NODE and child.data.strip()=='': parent.removeChild(child) return parent ##def RemoveWhiteSpace(node): ## removeList = [] ## for child in node.childNodes: ## if child.nodeType == child.TEXT_NODE and not child.data.strip(): ## removeList.append(child) ## elif child.hasChildNodes(): ## RemoveWhiteSpace(child) ## ## for node in removeList: ## node.parentNode.removeChild(node) def GetDateTime(xmlvalue): return xmlvalue #vals = xmlvalue.split('T') #datestr = vals[0] #timestr = vals[1] #date = datestr.split('-') #time = timestr.split(':') #time[2]=time[2].rstrip('Z') #return datetime(int(date[0]), int(date[1]), int(date[2]),int(time[0]), int(time[1]), int(float(time[2]))) def ToDateTime(val): return val #return '%s-%s-%sT%s:%s:%sZ'%(val.year,str(val.month).zfill(2),str(val.day).zfill(2), str(val.hour).zfill(2), str(val.minute).zfill(2),str(val.second).zfill(2)) def GetStringArrayFromNodes(xmlNodes): vals = [] if xmlNodes == None: return vals for xmlNode in xmlNodes: stringvals = ReadContents(xmlNode).split( ) for string in stringvals: vals.append(string) return vals def GetListFromNodes(xmlNodes, cast=None): result = [] if xmlNodes is None: return result for xmlNode in xmlNodes: val = ReadContents(xmlNode).split( ) if cast == float: val = ToFloatList(val) elif cast == int: val = ToIntList(val) elif cast == bool: val = ToBoolList(val) result.append(val) return result def ToXml(xmlNode, indent='\t', newl='\n'): return '<?xml version="1.0" encoding="utf-8"?>\n%s'%(__ToXml(xmlNode, indent,newl)) def __ToXml(xmlNode, indent='\t',newl='\n',totalIndent=''): childs = xmlNode.childNodes if len(childs) > 0: attrs = '' attributes = xmlNode.attributes if attributes != None: for attr in attributes.keys(): val = attributes[attr].nodeValue attrs += ' %s="%s"'%(attr,val) result = '%s<%s%s>'%(totalIndent,xmlNode.localName,attrs) tempnewl = newl tempTotIndent = totalIndent for child in childs: if child.nodeType == child.TEXT_NODE: tempnewl = '' tempTotIndent = '' result += '%s%s'%(tempnewl,__ToXml(child, indent, newl, totalIndent+indent)) result += '%s%s</%s>'%(tempnewl,tempTotIndent,xmlNode.localName) return result else: if xmlNode.nodeType == xmlNode.TEXT_NODE: return xmlNode.toxml().replace('\n','\n'+totalIndent[:-1]) else: return totalIndent+xmlNode.toxml() def AppendChilds(xmlNode, syntax, lst): if lst is None or syntax is None or xmlNode is None: return for i in lst: el = Element(syntax) text = Text() text.data = ListToString(i) el.appendChild(text) xmlNode.appendChild(el) return xmlNode # TODO: Collada API: finish DaeDocument class DaeDocument(object): def __init__(self, debugM = False): global debugMode debugMode = debugM self.colladaVersion = '1.4.0' self.version = '' self.xmlns = '' self.asset = DaeAsset() self.extras = [] # create all the libraries self.animationsLibrary = DaeLibrary(DaeSyntax.LIBRARY_ANIMATIONS,DaeAnimation,DaeSyntax.ANIMATION) self.animationClipsLibrary = DaeLibrary(DaeSyntax.LIBRARY_ANIMATION_CLIPS,DaeAnimationClip,DaeSyntax.ANIMATION_CLIP) self.camerasLibrary = DaeLibrary(DaeSyntax.LIBRARY_CAMERAS,DaeCamera,DaeSyntax.CAMERA) self.controllersLibrary = DaeLibrary(DaeSyntax.LIBRARY_CONTROLLERS,DaeController,DaeSyntax.CONTROLLER) self.effectsLibrary = DaeLibrary(DaeSyntax.LIBRARY_EFFECTS,DaeFxEffect,DaeFxSyntax.EFFECT) self.geometriesLibrary = DaeLibrary(DaeSyntax.LIBRARY_GEOMETRIES,DaeGeometry,DaeSyntax.GEOMETRY) self.imagesLibrary = DaeLibrary(DaeSyntax.LIBRARY_IMAGES, DaeImage, DaeSyntax.IMAGE) self.lightsLibrary = DaeLibrary(DaeSyntax.LIBRARY_LIGHTS,DaeLight,DaeSyntax.LIGHT) self.materialsLibrary = DaeLibrary(DaeSyntax.LIBRARY_MATERIALS,DaeFxMaterial,DaeFxSyntax.MATERIAL) self.nodesLibrary = DaeLibrary(DaeSyntax.LIBRARY_NODES, DaeNode, DaeSyntax.NODE) self.visualScenesLibrary = DaeLibrary(DaeSyntax.LIBRARY_VISUAL_SCENES,DaeVisualScene,DaeSyntax.VISUAL_SCENE) # Physics Support self.physicsMaterialsLibrary = DaeLibrary(DaeSyntax.LIBRARY_PHYSICS_MATERIALS, DaePhysicsMaterial, DaePhysicsSyntax.PHYSICS_MATERIAL) self.physicsScenesLibrary = DaeLibrary(DaeSyntax.LIBRARY_PHYSICS_SCENES, DaePhysicsScene, DaePhysicsSyntax.PHYSICS_SCENE) self.physicsModelsLibrary = DaeLibrary(DaeSyntax.LIBRARY_PHYSICS_MODELS, DaePhysicsModel, DaePhysicsSyntax.PHYSICS_MODEL) self.scene = None self.physicsScene = None def LoadDocumentFromFile(self, filename): global debugMode # Build DOM tree doc = parse( filename ) # Get COLLADA element colladaNode = doc.documentElement # Get Attributes self.version = colladaNode.getAttribute(DaeSyntax.VERSION) #if not IsVersionOk(self.version, self.colladaVersion): # Debug.Debug('The version of the file (%s) is older then the version supported by this plugin(%s).'%(self.version, self.colladaVersion),'ERROR') # doc.unlink() # return self.xmlns = colladaNode.getAttribute(DaeSyntax.XMLNS) # get the assets element self.asset.LoadFromXml(self,FindElementByTagName(colladaNode,DaeSyntax.ASSET)) # get the extra elements self.extras = CreateObjectsFromXml(self,colladaNode,DaeSyntax.EXTRA,DaeExtra) # parse all the libraries self.imagesLibrary.LoadFromXml(self,FindElementByTagName(colladaNode,DaeSyntax.LIBRARY_IMAGES)) self.animationsLibrary.LoadFromXml(self, FindElementByTagName(colladaNode,DaeSyntax.LIBRARY_ANIMATIONS)) self.animationClipsLibrary.LoadFromXml(self,FindElementByTagName(colladaNode,DaeSyntax.LIBRARY_ANIMATION_CLIPS)) self.camerasLibrary.LoadFromXml(self,FindElementByTagName(colladaNode,DaeSyntax.LIBRARY_CAMERAS)) self.controllersLibrary.LoadFromXml(self,FindElementByTagName(colladaNode,DaeSyntax.LIBRARY_CONTROLLERS)) self.effectsLibrary.LoadFromXml(self,FindElementByTagName(colladaNode,DaeSyntax.LIBRARY_EFFECTS)) self.geometriesLibrary.LoadFromXml(self,FindElementByTagName(colladaNode,DaeSyntax.LIBRARY_GEOMETRIES)) self.lightsLibrary.LoadFromXml(self, FindElementByTagName(colladaNode, DaeSyntax.LIBRARY_LIGHTS)) self.materialsLibrary.LoadFromXml(self,FindElementByTagName(colladaNode,DaeSyntax.LIBRARY_MATERIALS)) self.nodesLibrary.LoadFromXml(self,FindElementByTagName(colladaNode,DaeSyntax.LIBRARY_NODES)) self.visualScenesLibrary.LoadFromXml(self, FindElementByTagName(colladaNode, DaeSyntax.LIBRARY_VISUAL_SCENES)) self.physicsMaterialsLibrary.LoadFromXml(self, FindElementByTagName(colladaNode, DaeSyntax.LIBRARY_PHYSICS_MATERIALS)) self.physicsModelsLibrary.LoadFromXml(self, FindElementByTagName(colladaNode, DaeSyntax.LIBRARY_PHYSICS_MODELS)) self.physicsScenesLibrary.LoadFromXml(self, FindElementByTagName(colladaNode, DaeSyntax.LIBRARY_PHYSICS_SCENES)) # Get the sceneNodes sceneNodes = colladaNode.getElementsByTagName(DaeSyntax.SCENE) # Get the scene sceneNode = FindElementByTagName(colladaNode, DaeSyntax.SCENE) if sceneNode != None: scene = DaeScene() scene.LoadFromXml(self, sceneNode) self.scene = scene doc.unlink() if debugMode: Debug.Debug('Directly exporting this DaeDocument...','DEBUG') self.SaveDocumentToFile(filename+'_out.dae') def SaveDocumentToFile(self, filename): self.version = '1.4.0' self.xmlns = 'http://www.collada.org/2005/11/COLLADASchema' colladaNode = Element(DaeSyntax.COLLADA) colladaNode.setAttribute(DaeSyntax.VERSION, self.version) colladaNode.setAttribute(DaeSyntax.XMLNS, self.xmlns) colladaNode.appendChild(self.asset.SaveToXml(self)) # add the labraries AppendChild(self,colladaNode,self.animationsLibrary) AppendChild(self,colladaNode,self.animationClipsLibrary) AppendChild(self,colladaNode,self.camerasLibrary) AppendChild(self,colladaNode,self.controllersLibrary) AppendChild(self,colladaNode,self.effectsLibrary) AppendChild(self,colladaNode,self.geometriesLibrary) AppendChild(self,colladaNode,self.imagesLibrary) AppendChild(self,colladaNode,self.lightsLibrary) AppendChild(self,colladaNode,self.materialsLibrary) AppendChild(self,colladaNode,self.nodesLibrary) AppendChild(self,colladaNode,self.visualScenesLibrary) AppendChild(self,colladaNode,self.physicsMaterialsLibrary) AppendChild(self,colladaNode,self.physicsModelsLibrary) AppendChild(self,colladaNode,self.physicsScenesLibrary) AppendChild(self,colladaNode,self.scene) # write xml to the file fileref = open(filename, 'w') fileref.write(ToXml(colladaNode)) fileref.flush() fileref.close() colladaNode.unlink() def GetItemCount(self): return (##self.animationClipsLibrary.GetItemCount()+ ##self.animationsLibrary.GetItemCount()+ ##self.camerasLibrary.GetItemCount()+ ##self.controllersLibrary.GetItemCount()+ ##self.effectsLibrary.GetItemCount()+ self.geometriesLibrary.GetItemCount()+ self.lightsLibrary.GetItemCount()+ ##self.materialsLibrary.GetItemCount()+ self.nodesLibrary.GetItemCount()##+ ##self.visualScenesLibrary.GetItemCount() ) def __str__(self): return '%s version: %s, xmlns: %s, asset: %s, extras: %s, scene: %s'%(type(self), self.version, self.xmlns, self.asset, self.extras, self.scene) class DaeEntity(object): def __init__(self): self.syntax = 'UNKNOWN' def LoadFromXml(self, daeDocument, xmlNode): Debug.Debug('DaeEntity: Override this method for %s'%(type(self)),'WARNING') def SaveToXml(self, daeDocument): node = Element(self.syntax) return node def GetType(self): return self.syntax class DaeElement(DaeEntity): def __init__(self): super(DaeElement,self).__init__() self.id = '' self.name = '' def LoadFromXml(self,daeDocument, xmlNode): if xmlNode is None: return self.id = xmlNode.getAttribute(DaeSyntax.ID) self.name = xmlNode.getAttribute(DaeSyntax.NAME) def SaveToXml(self, daeDocument): node = super(DaeElement,self).SaveToXml(daeDocument) SetAttribute(node,DaeSyntax.ID,StripString(self.id)) SetAttribute(node,DaeSyntax.NAME, StripString(self.name)) return node def __str__(self): return super(DaeElement,self).__str__()+'id: %s, name: %s'%(self.id, self.name) # TODO: Collada API: finish DaeLibrary class DaeLibrary(DaeElement): def __init__(self, syntax, objectType, objectSyntax): super(DaeLibrary,self).__init__() self.extras = [] self.asset = None self.items = [] self.__objectSyntax = objectSyntax self.syntax = syntax self.__objectType = objectType def LoadFromXml(self,daeDocument, xmlNode): if xmlNode is None: return super(DaeLibrary,self).LoadFromXml(daeDocument, xmlNode) self.extras = CreateObjectsFromXml(daeDocument, xmlNode, DaeSyntax.EXTRA, DaeExtra) self.asset = CreateObjectFromXml(daeDocument, xmlNode, DaeSyntax.ASSET, DaeAsset) self.items = CreateObjectsFromXml(daeDocument, xmlNode, self.__objectSyntax, self.__objectType) def SaveToXml(self,daeDocument): if len(self.items) > 0: node = super(DaeLibrary,self).SaveToXml(daeDocument) # Add the assets AppendChild(daeDocument,node,self.asset) # Add the library_items AppendChilds(daeDocument,node,self.items) # Add the extra's AppendChilds(self,node,self.extras) return node else: return None def GetItemCount(self): return len(self.items) def FindObject(self,url): for i in self.items: if i.id == url: return i return None def AddItem(self,item): self.items.append(item) def __str__(self): return super(DaeLibrary,self).__str__() + 'extras: %s, asset: %s, items: %s'%(self.extras, self.asset, self.items) class DaeAsset(DaeEntity): def __init__(self): super(DaeAsset,self).__init__() self.contributors = [] self.created = None self.modified = None self.revision = None self.title = None self.subject = None self.keywords = [] self.unit = DaeUnit() self.upAxis = 'Y_UP' self.syntax = DaeSyntax.ASSET def LoadFromXml(self, daeDocument, xmlNode): if xmlNode is None: return # Get the contributor(s) self.contributors = CreateObjectsFromXml(daeDocument, xmlNode,DaeSyntax.CONTRIBUTOR,DaeContributor) # Get created self.created = ReadDateTime(FindElementByTagName(xmlNode,DaeSyntax.CREATED)) # Get modified self.modified = ReadDateTime(FindElementByTagName(xmlNode,DaeSyntax.MODIFIED)) # Get revision self.revision = ReadContents(FindElementByTagName(xmlNode,DaeSyntax.REVISION)) # Get title self.title = ReadContents(FindElementByTagName(xmlNode,DaeSyntax.TITLE)) # Get subject self.subject = ReadContents(FindElementByTagName(xmlNode,DaeSyntax.SUBJECT)) # Get keywords self.keywords = GetStringArrayFromNodes(xmlNode.getElementsByTagName(DaeSyntax.KEYWORDS)) # Get Unit self.unit.LoadFromXml(daeDocument, FindElementByTagName(xmlNode, DaeSyntax.UNIT)) # Get upAxis self.upAxis = ReadContents(FindElementByTagName(xmlNode,DaeSyntax.UP_AXIS)) def SaveToXml(self, daeDocument): node = Element(DaeSyntax.ASSET) AppendChilds(daeDocument,node, self.contributors) AppendTextChild(node, DaeSyntax.CREATED, self.created) AppendTextChild(node, DaeSyntax.MODIFIED, self.modified) AppendTextChild(node, DaeSyntax.REVISION, self.revision) AppendTextChild(node, DaeSyntax.TITLE, self.title) AppendTextChild(node, DaeSyntax.SUBJECT, self.subject) AppendChild(daeDocument, node, self.unit) AppendTextChild(node, DaeSyntax.UP_AXIS, self.upAxis) return node def __str__(self): return super(DaeAsset,self).__str__()+'contributors: %s, created: %s, modified: %s, revision: %s, title: %s, subject: %s, keywords: %s, unit: %s, upAxis: %s'%(self.contributors, self.created, self.modified, self.revision, self.title, self.subject, self.keywords, self.unit, self.upAxis) # TODO: Collada API: finish DaeScene class DaeScene(DaeEntity): def __init__(self): super(DaeScene,self).__init__() self.extras = [] self.iVisualScenes = [] self.iPhysicsScenes = [] self.syntax = DaeSyntax.SCENE def LoadFromXml(self, daeDocument, xmlNode): if xmlNode is None: return self.iVisualScenes = CreateObjectsFromXml(daeDocument, xmlNode, DaeSyntax.INSTANCE_VISUAL_SCENE, DaeVisualSceneInstance) self.iPhysicsScenes = CreateObjectsFromXml(daeDocument, xmlNode, DaeSyntax.INSTANCE_PHYSICS_SCENE, DaePhysicsSceneInstance) def SaveToXml(self, daeDocument): node = super(DaeScene,self).SaveToXml(daeDocument) AppendChilds(daeDocument, node, self.iVisualScenes) AppendChilds(daeDocument, node, self.iPhysicsScenes) return node def GetVisualScenes(self): result = [] for i in self.iVisualScenes: result.append(i.object) return result def GetPhysicsScenes(self): result = [] for i in self.iPhysicsScenes: result.append(i.object) return result def __str__(self): return super(DaeScene,self).__str__()+'extras: %s, visualScenes: %s, physicsScenes: %s'%(self.extras, self.iVisualScenes, self.iPhysicsScenes) class DaeUnit(DaeEntity): def __init__(self): super(DaeUnit,self).__init__() self.name = 'meter' self.meter = 1.0 self.syntax = DaeSyntax.UNIT def LoadFromXml(self, daeDocument, xmlNode): if xmlNode is None: return name = xmlNode.getAttribute(DaeSyntax.NAME) if name != '': self.name = name meter = xmlNode.getAttribute(DaeSyntax.METER) if meter != '': self.meter = float(meter) def SaveToXml(self,daeDocument): node = super(DaeUnit, self).SaveToXml(daeDocument) SetAttribute(node, DaeSyntax.METER, self.meter) SetAttribute(node, DaeSyntax.NAME, self.name) return node def __str__(self): return super(DaeUnit, self).__str__()+' name: %s, meter: %s'%(self.name, self.meter) class DaeContributor(DaeEntity): def __init__(self): super(DaeContributor, self).__init__() self.author = '' self.authoringTool = '' self.comments = '' self.copyright = '' self.sourceData = '' self.syntax = DaeSyntax.CONTRIBUTOR def LoadFromXml(self, daeDocument, xmlNode): self.author = ReadContents(FindElementByTagName(xmlNode,DaeSyntax.AUTHOR)) self.authoringTool = ReadContents(FindElementByTagName(xmlNode,DaeSyntax.AUTHORING_TOOL)) self.comments = ReadContents(FindElementByTagName(xmlNode,DaeSyntax.COMMENTS)) self.copyright = ReadContents(FindElementByTagName(xmlNode,DaeSyntax.COPYRIGHT)) self.sourceData = ReadContents(FindElementByTagName(xmlNode,DaeSyntax.SOURCE_DATA)) def SaveToXml(self, daeDocument): node = super(DaeContributor, self).SaveToXml(daeDocument) AppendTextChild(node, DaeSyntax.AUTHOR, self.author) AppendTextChild(node, DaeSyntax.AUTHORING_TOOL, self.authoringTool) AppendTextChild(node, DaeSyntax.COMMENTS, self.comments) AppendTextChild(node, DaeSyntax.COPYRIGHT, self.copyright) AppendTextChild(node, DaeSyntax.SOURCE_DATA, self.sourceData) return node def __str__(self): return super(DaeContributor,self).__str__() + 'author: %s, authoring_tool: %s, comments: %s, copyright: %s, sourceData: %s'%(self.author, self.authoringTool, self.comments, self.copyright, self.sourceData) class DaeAnimation(DaeElement): def __init__(self): super(DaeAnimation, self).__init__() self.sources = [] self.samplers = [] self.channels = [] self.syntax = DaeSyntax.ANIMATION def LoadFromXml(self, daeDocument, xmlNode): super(DaeAnimation, self).LoadFromXml(daeDocument, xmlNode) self.channels = CreateObjectsFromXml(daeDocument, xmlNode, DaeSyntax.CHANNEL, DaeChannel) self.samplers = CreateObjectsFromXml(daeDocument, xmlNode, DaeSyntax.SAMPLER, DaeSampler) self.sources = CreateObjectsFromXml(daeDocument, xmlNode, DaeSyntax.SOURCE, DaeSource) def SaveToXml(self, daeDocument): node = super(DaeAnimation, self).SaveToXml(daeDocument) AppendChilds(daeDocument, node, self.sources) AppendChilds(daeDocument, node, self.samplers) AppendChilds(daeDocument, node, self.channels) return node def GetSource(self, sourceId): for source in self.sources: if source.id == sourceId: return source return None class DaeSampler(DaeEntity): def __init__(self): self.syntax = DaeSyntax.SAMPLER self.id = None self.inputs = [] def LoadFromXml(self, daeDocument, xmlNode): self.id = ReadAttribute(xmlNode, DaeSyntax.ID) self.inputs = CreateObjectsFromXml(daeDocument, xmlNode, DaeSyntax.INPUT, DaeInput) def SaveToXml(self, daeDocument): node = super(DaeSampler, self).SaveToXml(daeDocument) AppendChilds(daeDocument, node, self.inputs) SetAttribute(node, DaeSyntax.ID, StripString(self.id)) return node def GetInput(self, semantic): for input in self.inputs: if input.semantic == semantic: return input return None class DaeChannel(DaeEntity): def __init__(self): self.syntax = DaeSyntax.CHANNEL self.source = None self.target = None def LoadFromXml(self, daeDocument, xmlNode): self.source = ReadAttribute(xmlNode, DaeSyntax.SOURCE) self.target = ReadAttribute(xmlNode, DaeSyntax.TARGET) def SaveToXml(self, daeDocument): node = super(DaeChannel, self).SaveToXml(daeDocument) SetAttribute(node, DaeSyntax.SOURCE, StripString('#'+self.source.id)) SetAttribute(node, DaeSyntax.TARGET, self.target) return node class DaeAnimationClip(DaeElement): pass class DaeCamera(DaeElement): def __init__(self): super(DaeCamera,self).__init__() self.asset = None self.extras = [] self.optics = DaeOptics() self.imager = None self.syntax = DaeSyntax.CAMERA def LoadFromXml(self, daeDocument, xmlNode): super(DaeCamera, self).LoadFromXml(daeDocument, xmlNode) self.extras = CreateObjectsFromXml(daeDocument, xmlNode, DaeSyntax.EXTRA, DaeExtra) self.asset = CreateObjectFromXml(daeDocument, xmlNode, DaeSyntax.ASSET, DaeAsset) self.optics.LoadFromXml(daeDocument, FindElementByTagName(xmlNode, DaeSyntax.OPTICS)) self.imager = CreateObjectFromXml(daeDocument,xmlNode, DaeSyntax.IMAGER,DaeImager) def SaveToXml(self, daeDocument): node = super(DaeCamera, self).SaveToXml(daeDocument) # Add the assets AppendChild(daeDocument,node,self.asset) # Add the optics node.appendChild(self.optics.SaveToXml(daeDocument)) # Add the imager AppendChild(daeDocument,node,self.imager) # Add the extra's AppendChilds(self,node,self.extras) return node def __str__(self): return super(DaeCamera,self).__str__()+'asset: %s, optics: %s, imager: %s, extras: %s'%(self.asset, self.optics, self.imager, self.extras) class DaeController(DaeElement): pass class DaeImage(DaeElement): def __init__(self): super(DaeImage,self).__init__() self.format = None self.height = None self.width = None self.depth = None self.initFrom = None self.syntax = DaeSyntax.IMAGE def LoadFromXml(self, daeDocument, xmlNode): super(DaeImage, self).LoadFromXml(daeDocument, xmlNode) self.format = ReadAttribute(xmlNode, DaeSyntax.FORMAT) self.height = ReadAttribute(xmlNode, DaeSyntax.HEIGHT) self.width = ReadAttribute(xmlNode, DaeSyntax.WIDTH) self.depth = ReadAttribute(xmlNode, DaeSyntax.DEPTH) self.initFrom = ReadContents(FindElementByTagName(xmlNode, DaeSyntax.INIT_FROM)) def SaveToXml(self, daeDocument): node = super(DaeImage, self).SaveToXml(daeDocument) SetAttribute(node, DaeSyntax.FORMAT, self.format) SetAttribute(node, DaeSyntax.HEIGHT, self.height) SetAttribute(node, DaeSyntax.WIDTH, self.width) SetAttribute(node, DaeSyntax.DEPTH, self.depth) AppendTextChild(node, DaeSyntax.INIT_FROM,self.initFrom, None) return node ##class DaeMaterial(DaeElement): ## def __init__(self): ## super(DaeMaterial,self).__init__() ## self.asset = None ## self.iEffects = [] ## self.extras = None ## self.syntax = DaeSyntax.MATERIAL ## ## def LoadFromXml(self, daeDocument, xmlNode): ## super(DaeMaterial, self).LoadFromXml(daeDocument, xmlNode) ## self.extras = CreateObjectsFromXml(daeDocument, xmlNode, DaeSyntax.EXTRA, DaeExtra) ## self.asset = CreateObjectFromXml(daeDocument, xmlNode, DaeSyntax.ASSET, DaeAsset) ## self.iEffects = CreateObjectsFromXml(daeDocument,xmlNode, DaeSyntax.INSTANCE_EFFECT, DaeEffectInstance) ## ## def SaveToXml(self, daeDocument): ## node = super(DaeMaterial, self).SaveToXml(daeDocument) ## # Add the assets ## AppendChild(daeDocument,node,self.asset) ## # Add the effect instances ## AppendChilds(daeDocument, node, self.iEffects) ## # Add the extra's ## AppendChilds(self,node,self.extras) ## return node ## ## def __str__(self): ## return super(DaeLight,self).__str__()+' assets: %s, data: %s, extras: %s'%(self.asset, self.data, self.extras) class DaeGeometry(DaeElement): def __init__(self): super(DaeGeometry,self).__init__() self.asset = None self.data = None self.extras = None self.syntax = DaeSyntax.GEOMETRY def LoadFromXml(self, daeDocument, xmlNode): super(DaeGeometry, self).LoadFromXml(daeDocument, xmlNode) self.extras = CreateObjectsFromXml(daeDocument, xmlNode, DaeSyntax.EXTRA, DaeExtra) self.asset = CreateObjectFromXml(daeDocument, xmlNode, DaeSyntax.ASSET, DaeAsset) self.data = CreateObjectFromXml(daeDocument, xmlNode, DaeSyntax.MESH, DaeMesh) if self.data is None: self.data = CreateObjectFromXml(daeDocument, xmlNode, DaeSyntax.CONVEX_MESH, DaeConvexMesh) if self.data is None: self.data = CreateObjectFromXml(daeDocument, xmlNode, DaeSyntax.SPLINE, DaeSpline) def SaveToXml(self, daeDocument): node = super(DaeGeometry, self).SaveToXml(daeDocument) # Add the assets AppendChild(daeDocument,node,self.asset) # Add the data AppendChild(daeDocument, node, self.data) # Add the extra's AppendChilds(self,node,self.extras) return node def __str__(self): return super(DaeGeometry,self).__str__()+' assets: %s, data: %s, extras: %s'%(self.asset, self.data, self.extras) class DaeConvexMesh(DaeEntity): def __init__(self): super(DaeConvexMesh, self).__init__() self.syntax = DaeSyntax.CONVEX_MESH self.convexHullOf = None def LoadFromXml(self, daeDocument, xmlNode): self.convexHullOf = ReadAttribute(xmlNode, DaeSyntax.CONVEX_HULL_OF) def SaveToXml(self, daeDocument): node = super(DaeConvexMesh, self).SaveToXml(daeDocument) SetAttribute(node, DaeSyntax.CONVEX_HULL_OF, StripString(self.convexHullOf)) return node class DaeMesh(DaeEntity): def __init__(self): super(DaeMesh, self).__init__() self.sources = [] self.vertices = None self.primitives = [] self.extras = [] self.syntax = DaeSyntax.MESH def LoadFromXml(self, daeDocument, xmlNode): if xmlNode is None: return self.vertices = CreateObjectFromXml(daeDocument, xmlNode, DaeSyntax.VERTICES, DaeVertices) self.sources = CreateObjectsFromXml(daeDocument, xmlNode, DaeSyntax.SOURCE, DaeSource) lines = CreateObjectsFromXml(daeDocument, xmlNode, DaeSyntax.LINES, DaeLines) linestrips = CreateObjectsFromXml(daeDocument, xmlNode, DaeSyntax.LINESTRIPS, DaeLineStrips) polygons = CreateObjectsFromXml(daeDocument, xmlNode, DaeSyntax.POLYGONS, DaePolygons) polylist = CreateObjectsFromXml(daeDocument, xmlNode, DaeSyntax.POLYLIST, DaePolylist) triangles = CreateObjectsFromXml(daeDocument, xmlNode, DaeSyntax.TRIANGLES, DaeTriangles) trifans = CreateObjectsFromXml(daeDocument, xmlNode, DaeSyntax.TRIFANS, DaeTriFans) tristrips = CreateObjectsFromXml(daeDocument, xmlNode, DaeSyntax.TRISTRIPS, DaeTriStrips) if lines != None: self.primitives += lines if linestrips != None: self.primitives += linestrips if polygons != None: self.primitives += polygons if polylist != None: self.primitives += polylist if triangles != None: self.primitives += triangles if trifans != None: self.primitives += trifans if tristrips != None: self.primitives += tristrips self.extras = CreateObjectsFromXml(daeDocument, xmlNode, DaeSyntax.EXTRA, DaeExtra) def FindSource(self,input): for s in self.sources: if s.id == input.source: return s return None def SaveToXml(self, daeDocument): node = super(DaeMesh, self).SaveToXml(daeDocument) AppendChilds(daeDocument, node, self.sources) AppendChild(daeDocument, node, self.vertices) AppendChilds(daeDocument, node, self.primitives) AppendChilds(daeDocument, node, self.extras) return node class DaeVertices(DaeElement): def __init__(self): super(DaeVertices,self).__init__() self.inputs = [] self.extras = [] self.syntax = DaeSyntax.VERTICES def LoadFromXml(self, daeDocument, xmlNode): super(DaeVertices,self).LoadFromXml(daeDocument, xmlNode) self.inputs = CreateObjectsFromXml(daeDocument, xmlNode, DaeSyntax.INPUT, DaeInput) self.extras = CreateObjectsFromXml(daeDocument, xmlNode, DaeSyntax.EXTRA, DaeExtra) def SaveToXml(self, daeDocument): node = super(DaeVertices, self).SaveToXml(daeDocument) AppendChilds(daeDocument, node, self.inputs) AppendChilds(daeDocument, node, self.extras) return node def FindInput(self, semantic): for i in self.inputs: if i.semantic == semantic: return i return None def __str__(self): return super(DaeVertices,self).__str__() + ' inputs: %s, extras: %s'%(self.inputs, self.extras) class DaeInput(DaeEntity): def __init__(self): super(DaeInput, self).__init__() self.offset = None self.semantic = '' self.source = '' self.set = '' self.syntax = DaeSyntax.INPUT def LoadFromXml(self, daeDocument, xmlNode): self.offset = CastAttributeFromXml(xmlNode, DaeSyntax.OFFSET, int) self.semantic = ReadAttribute(xmlNode, DaeSyntax.SEMANTIC) self.source = ReadAttribute(xmlNode, DaeSyntax.SOURCE)[1:] self.set = ReadAttribute(xmlNode, DaeSyntax.SET) def SaveToXml(self, daeDocument): node = super(DaeInput, self).SaveToXml(daeDocument) SetAttribute(node,DaeSyntax.OFFSET, self.offset) SetAttribute(node,DaeSyntax.SEMANTIC, self.semantic) SetAttribute(node,DaeSyntax.SOURCE, StripString('#'+self.source)) SetAttribute(node,DaeSyntax.SET, self.set) return node class DaeSource(DaeElement): def __init__(self): super(DaeSource, self).__init__() self.source = DaeArray() self.vectors = [] self.techniqueCommon = None self.techniques = [] self.syntax = DaeSyntax.SOURCE def LoadFromXml(self, daeDocument, xmlNode): super(DaeSource,self).LoadFromXml(daeDocument, xmlNode) if xmlNode is None: return bools = CreateObjectFromXml(daeDocument, xmlNode, DaeSyntax.BOOL_ARRAY, DaeBoolArray) floats = CreateObjectFromXml(daeDocument, xmlNode, DaeSyntax.FLOAT_ARRAY, DaeFloatArray) ints = CreateObjectFromXml(daeDocument, xmlNode, DaeSyntax.INT_ARRAY, DaeIntArray) names = CreateObjectFromXml(daeDocument, xmlNode, DaeSyntax.NAME_ARRAY, DaeNameArray) if bools != None: self.source = bools elif floats != None: self.source = floats elif ints != None: self.source = ints elif names != None: self.source = names self.techniqueCommon = CreateObjectFromXml(daeDocument, xmlNode, DaeSyntax.TECHNIQUE_COMMON, DaeSource.DaeTechniqueCommon) self.techniques = CreateObjectsFromXml(daeDocument, xmlNode, DaeSyntax.TECHNIQUE,DaeTechnique) if not (self.techniqueCommon is None): for i in range(0,self.techniqueCommon.accessor.count): vec = [] for j in range(0,self.techniqueCommon.accessor.stride): vec.append(self.source.data[i*self.techniqueCommon.accessor.stride+j]) self.vectors.append(vec) def SaveToXml(self, daeDocument): node = super(DaeSource, self).SaveToXml(daeDocument) ## if len(self.vectors) > 0: ## if type(self.vectors[0][0]) == float: ## self.source = DaeFloatArray() ## self.source.id = self.id+'-array' ## ## for i in range(len(self.vectors)): ## for j in range(len(self.vectors[i])): ## self.source.data.append(self.vectors[i][j]) # Add the source AppendChild(daeDocument, node, self.source) # Add the technique common AppendChild(daeDocument,node,self.techniqueCommon) # Add the techniques AppendChilds(daeDocument, node, self.techniques) return node def __str__(self): return super(DaeSource,self).__str__()+' source: %s, techniqueCommon: %s, techniques: %s'%(self.source, self.techniqueCommon, self.techniques) class DaeTechniqueCommon(DaeEntity): def __init__(self): self.accessor = None self.syntax = DaeSyntax.TECHNIQUE_COMMON def LoadFromXml(self, daeDocument, xmlNode): self.accessor = CreateObjectFromXml(daeDocument, xmlNode, DaeSyntax.ACCESSOR, DaeAccessor) def SaveToXml(self, daeDocument): node = super(DaeSource.DaeTechniqueCommon,self).SaveToXml(daeDocument) AppendChild(daeDocument,node, self.accessor) return node def __str__(self): return super(DaeSource.DaeTechniqueCommon,self).__str__()+' accessor: %s'%(self.accessor) class DaeLight(DaeElement): def __init__(self): super(DaeLight,self).__init__() self.asset = None self.techniqueCommon = DaeLight.DaeTechniqueCommon() self.techniques = [] self.extras = None self.syntax = DaeSyntax.LIGHT def LoadFromXml(self, daeDocument, xmlNode): super(DaeLight, self).LoadFromXml(daeDocument, xmlNode) self.extras = CreateObjectsFromXml(daeDocument, xmlNode, DaeSyntax.EXTRA, DaeExtra) self.asset = CreateObjectFromXml(daeDocument, xmlNode, DaeSyntax.ASSET, DaeAsset) ##self.techniqueCommon.LoadFromXml(daeDocument, FindElementByTagName(xmlNode, DaeSyntax.TECHNIQUE_COMMON)) self.techniques = CreateObjectsFromXml(daeDocument, xmlNode, DaeSyntax.TECHNIQUE,DaeTechnique) lightSourceNode = RemoveWhiteSpaceNode(FindElementByTagName(xmlNode, DaeSyntax.TECHNIQUE_COMMON)).firstChild lightSourceName = lightSourceNode.localName if lightSourceName == DaeSyntax.DIRECTIONAL: self.techniqueCommon = DaeLight.DaeDirectional() elif lightSourceName == DaeSyntax.SPOT: self.techniqueCommon = DaeLight.DaeSpot() elif lightSourceName == DaeSyntax.AMBIENT: self.techniqueCommon = DaeLight.DaeAmbient() elif lightSourceName == DaeSyntax.POINT: self.techniqueCommon = DaeLight.DaePoint() self.techniqueCommon.LoadFromXml(daeDocument,lightSourceNode) def SaveToXml(self, daeDocument): node = super(DaeLight, self).SaveToXml(daeDocument) # Add the assets AppendChild(daeDocument,node,self.asset) # Add the technique common AppendChild(daeDocument,node,self.techniqueCommon) # Add the techniques AppendChilds(daeDocument, node, self.techniques) # Add the extra's AppendChilds(self,node,self.extras) return node def __str__(self): return super(DaeLight,self).__str__()+' techniqueCommon: %s, techniques: %s'%(self.techniqueCommon, self.techniques) class DaeTechniqueCommon(DaeEntity): def __init__(self): self.color = [] self.lightSource = None self.syntax = DaeSyntax.TECHNIQUE_COMMON def LoadFromXml(self, daeDocument, xmlNode): self.color = ToFloat3(ReadContents(FindElementByTagName(xmlNode,DaeSyntax.COLOR))) def SaveToXml(self, daeDocument): node = Element(DaeSyntax.TECHNIQUE_COMMON) child = super(DaeLight.DaeTechniqueCommon,self).SaveToXml(daeDocument) AppendTextChild(child,DaeSyntax.COLOR, self.color) node.appendChild(child) return node def __str__(self): return super(DaeLight.DaeTechniqueCommon,self).__str__()+' color: %s'%(self.color) class DaeAmbient(DaeTechniqueCommon): def __init__(self): super(DaeLight.DaeAmbient,self).__init__() self.syntax = DaeSyntax.AMBIENT def LoadFromXml(self, daeDocument, xmlNode): super(DaeLight.DaeAmbient,self).LoadFromXml(daeDocument, xmlNode) def SaveToXml(self, daeDocument): node = super(DaeLight.DaeAmbient,self).SaveToXml(daeDocument) return node def __str__(self): return super(DaeLight.DaeAmbient,self).__str__() class DaeSpot(DaeTechniqueCommon): def __init__(self): super(DaeLight.DaeSpot,self).__init__() self.defConstantAttenuation = 0.0 self.defLinearAttenuation = 0.0 self.defQuadraticAttenuation = 0.0 self.defFalloffAngle = 180.0 self.defFalloffExponent = 0.0 self.constantAttenuation = 0.0 self.linearAttenuation = 0.0 self.quadraticAttenuation = 0.0 self.falloffAngle = 180.0 self.falloffExponent = 0.0 self.syntax = DaeSyntax.SPOT def LoadFromXml(self, daeDocument, xmlNode): super(DaeLight.DaeSpot,self).LoadFromXml(daeDocument, xmlNode) self.constantAttenuation = CastFromXml(daeDocument,xmlNode,DaeSyntax.CONSTANT_ATTENUATION, float, self.defConstantAttenuation, 1.0) self.linearAttenuation = CastFromXml(daeDocument,xmlNode,DaeSyntax.LINEAR_ATTENUATION,float, self.defLinearAttenuation, 0) self.quadraticAttenuation = CastFromXml(daeDocument, xmlNode,DaeSyntax.QUADRATIC_ATTENUATION, float, self.defQuadraticAttenuation, 0) self.falloffAngle = CastFromXml(daeDocument, xmlNode, DaeSyntax.FALLOFF_ANGLE, float, self.defFalloffAngle, 180.0) self.falloffExponent = CastFromXml(daeDocument, xmlNode, DaeSyntax.FALLOFF_EXPONENT, float, self.defFalloffExponent, 0) def SaveToXml(self, daeDocument): node = super(DaeLight.DaeSpot,self).SaveToXml(daeDocument) AppendTextChild(node.firstChild,DaeSyntax.CONSTANT_ATTENUATION, self.constantAttenuation, self.defConstantAttenuation) AppendTextChild(node.firstChild,DaeSyntax.LINEAR_ATTENUATION, self.linearAttenuation, self.defLinearAttenuation) AppendTextChild(node.firstChild,DaeSyntax.QUADRATIC_ATTENUATION, self.quadraticAttenuation, self.defQuadraticAttenuation) AppendTextChild(node.firstChild,DaeSyntax.FALLOFF_ANGLE, self.falloffAngle, self.defFalloffAngle) AppendTextChild(node.firstChild,DaeSyntax.FALLOFF_EXPONENT, self.falloffExponent, self.defFalloffExponent) return node def __str__(self): return super(DaeLight.DaeSpot,self).__str__()+' const.att: %s, lin.att: %s, quad.att: %s, falloffAngle: %s, falloffExponent: %s'%(self.constantAttenuation, self.linearAttenuation, self.quadraticAttenuation, self.falloffAngle, self.falloffExponent) class DaeDirectional(DaeTechniqueCommon): # default direction is [0,0,-1] pointing down the -Z axis. # To change the direction, change the transform of the parent DaeNode def __init__(self): super(DaeLight.DaeDirectional,self).__init__() self.syntax = DaeSyntax.DIRECTIONAL def LoadFromXml(self, daeDocument, xmlNode): super(DaeLight.DaeDirectional,self).LoadFromXml(daeDocument, xmlNode) def SaveToXml(self, daeDocument): node = super(DaeLight.DaeDirectional,self).SaveToXml(daeDocument) return node def __str__(self): return super(DaeLight.DaeDirectional,self).__str__() class DaePoint(DaeTechniqueCommon): def __init__(self): super(DaeLight.DaePoint,self).__init__() self.constantAttenuation = 0.0 self.linearAttenuation = 0.0 self.quadraticAttenuation = 0.0 self.syntax = DaeSyntax.POINT def LoadFromXml(self, daeDocument, xmlNode): super(DaeLight.DaePoint,self).LoadFromXml(daeDocument, xmlNode) self.constantAttenuation = CastFromXml(daeDocument,xmlNode,DaeSyntax.CONSTANT_ATTENUATION, float, 1) self.linearAttenuation = CastFromXml(daeDocument,xmlNode,DaeSyntax.LINEAR_ATTENUATION,float, 0) self.quadraticAttenuation = CastFromXml(daeDocument, xmlNode,DaeSyntax.QUADRATIC_ATTENUATION, float, 0) def SaveToXml(self, daeDocument): node = super(DaeLight.DaePoint,self).SaveToXml(daeDocument) AppendTextChild(node.firstChild,DaeSyntax.CONSTANT_ATTENUATION, self.constantAttenuation) AppendTextChild(node.firstChild,DaeSyntax.LINEAR_ATTENUATION, self.linearAttenuation) AppendTextChild(node.firstChild,DaeSyntax.QUADRATIC_ATTENUATION, self.quadraticAttenuation) return node def __str__(self): return super(DaeLight.DaePoint,self).__str__()+' const.att: %s, lin.att: %s, quad.att: %s'%(self.constantAttenuation, self.linearAttenuation, self.quadraticAttenuation) class DaeVisualScene(DaeElement): def __init__(self): super(DaeVisualScene,self).__init__() self.asset = None self.extras = None self.nodes = [] self.syntax = DaeSyntax.VISUAL_SCENE def LoadFromXml(self, daeDocument, xmlNode): super(DaeVisualScene, self).LoadFromXml(daeDocument, xmlNode) self.extras = CreateObjectsFromXml(daeDocument, xmlNode, DaeSyntax.EXTRA, DaeExtra) self.asset = CreateObjectFromXml(daeDocument, xmlNode, DaeSyntax.ASSET, DaeAsset) self.nodes = CreateObjectsFromXml(daeDocument, xmlNode, DaeSyntax.NODE, DaeNode) def SaveToXml(self, daeDocument): node = super(DaeVisualScene, self).SaveToXml(daeDocument) # Add the assets AppendChild(daeDocument,node,self.asset) # Add the nodes AppendChilds(daeDocument, node, self.nodes) # Add the extra's AppendChilds(self,node,self.extras) return node def FindNode(self, nodeUrl): for n in self.nodes: if n.id == nodeUrl: return n return None def __str__(self): return super(DaeVisualScene,self).__str__()+' asset: %s, nodes: %s, extras: %s'%(self.asset, self.nodes, self.extras) class DaeNode(DaeElement): NODE = 2 JOINT = 1 def __init__(self): super(DaeNode,self).__init__() self.sid = None self.type = DaeNode.NODE self.layer = [] self.transforms = [] self.nodes = [] self.iAnimations = [] self.iCameras = [] self.iControllers = [] self.iGeometries = [] self.iLights = [] self.iNodes = [] self.iVisualScenes = [] self.syntax = DaeSyntax.NODE def LoadFromXml(self, daeDocument, xmlNode): super(DaeNode, self).LoadFromXml(daeDocument, xmlNode) self.sid = ReadAttribute(xmlNode, DaeSyntax.SID) type = ReadAttribute(xmlNode, DaeSyntax.TYPE) if type == DaeSyntax.TYPE_JOINT: self.type = DaeNode.JOINT else: self.type = DaeNode.NODE self.layer = ReadAttribute(xmlNode, DaeSyntax.LAYER).split() # Get transforms RemoveWhiteSpaceNode(xmlNode) child = xmlNode.firstChild while child != None: name = child.localName sid = ReadAttribute(child, DaeSyntax.SID) if name == DaeSyntax.TRANSLATE: self.transforms.append([name,ToFloatList(ReadContents(child)), sid]) elif name == DaeSyntax.ROTATE: self.transforms.append([name,ToFloatList(ReadContents(child)), sid]) elif name == DaeSyntax.SCALE: self.transforms.append([name,ToFloatList(ReadContents(child)), sid]) elif name == DaeSyntax.SKEW: self.transforms.append([name,ToFloatList(ReadContents(child)), sid]) elif name == DaeSyntax.LOOKAT: self.transforms.append([name,ToFloatList(ReadContents(child)), sid]) elif name == DaeSyntax.MATRIX: self.transforms.append([name,ToMatrix4(ReadContents(child)), sid]) child = child.nextSibling # Get the instances self.iAnimations = CreateObjectsFromXml(daeDocument, xmlNode, DaeSyntax.INSTANCE_ANIMATION, DaeAnimationInstance) self.iCameras = CreateObjectsFromXml(daeDocument, xmlNode, DaeSyntax.INSTANCE_CAMERA, DaeCameraInstance) self.iControllers = CreateObjectsFromXml(daeDocument, xmlNode, DaeSyntax.INSTANCE_CONTROLLER, DaeControllerInstance) self.iGeometries = CreateObjectsFromXml(daeDocument, xmlNode, DaeSyntax.INSTANCE_GEOMETRY, DaeGeometryInstance) self.iLights = CreateObjectsFromXml(daeDocument, xmlNode, DaeSyntax.INSTANCE_LIGHT, DaeLightInstance) self.iNodes = CreateObjectsFromXml(daeDocument, xmlNode, DaeSyntax.INSTANCE_NODE, DaeNodeInstance) self.iVisualScenes = CreateObjectsFromXml(daeDocument, xmlNode, DaeSyntax.INSTANCE_VISUAL_SCENE, DaeVisualSceneInstance) # Get childs nodes self.nodes = CreateObjectsFromXml(daeDocument, xmlNode, DaeSyntax.NODE, DaeNode) def SaveToXml(self, daeDocument): node = super(DaeNode, self).SaveToXml(daeDocument) SetAttribute(node, DaeSyntax.SID, self.sid) if self.type == DaeSyntax.TYPE_JOINT: SetAttribute(node, DaeSyntax.TYPE, DaeNode.GetType(self.type)) # Add the layers SetAttribute(node, DaeSyntax.LAYER, ListToString(self.layer)) for i in self.transforms: writeTransform = False el = Element(i[0]) val = i[1] if i[0] == DaeSyntax.MATRIX: val = MatrixToString(val,ROUND) AppendTextChild(node,i[0],val) else: orgval = val val = ListToString(RoundList(val, 5)) if i[0] == DaeSyntax.SCALE: ##AppendTextChild(node,i[0],val,"1.0 1.0 1.0") SetAttribute(AppendTextChild(node,i[0],val,None), DaeSyntax.SID, DaeSyntax.SCALE) elif i[0] == DaeSyntax.TRANSLATE: ##AppendTextChild(node,i[0],val,"0.0 0.0 0.0") SetAttribute(AppendTextChild(node,i[0],val,None), DaeSyntax.SID, DaeSyntax.TRANSLATE) elif i[0] == DaeSyntax.ROTATE: ##AppendTextChild(node,i[0],val,"0.0 0.0 0.0 0.0") axis = None if orgval[0] == 1 and orgval[1] == 0 and orgval[2] == 0: axis = "X" elif orgval[0] == 0 and orgval[1] == 1 and orgval[2] == 0: axis = "Y" elif orgval[0] == 0 and orgval[1] == 0 and orgval[2] == 1: axis = "Z" no = AppendTextChild(node,i[0],val,None) if axis != None: SetAttribute(no, DaeSyntax.SID, DaeSyntax.ROTATE+axis) elif i[0] == DaeSyntax.SKEW: AppendTextChild(node,i[0],val) elif i[0] == DaeSyntax.MATRIX or i[0] == DaeSyntax.LOOKAT: AppendTextChild(node,i[0],val) AppendChilds(daeDocument, node, self.nodes) AppendChilds(daeDocument, node, self.iAnimations) AppendChilds(daeDocument, node, self.iCameras) AppendChilds(daeDocument, node, self.iControllers) AppendChilds(daeDocument, node, self.iGeometries) AppendChilds(daeDocument, node, self.iLights) AppendChilds(daeDocument, node, self.iNodes) AppendChilds(daeDocument, node, self.iVisualScenes) return node def IsJoint(self): return self.type == DaeNode.JOINT def GetType(type): if type == DaeNode.JOINT: return DaeSyntax.TYPE_JOINT else: return DaeSyntax.TYPE_NODE GetType = staticmethod(GetType) def GetInstances(self): return []+self.iAnimations+self.iCameras+self.iControllers+self.iGeometries+self.iLights+self.iNodes # TODO: Collada API: finish DaeTechnique class DaeTechnique(DaeEntity): def __init__(self): super(DaeTechnique,self).__init__() self.profile = '' self.xmlns = '' self.syntax = DaeSyntax.TECHNIQUE def LoadFromXml(self, daeDocument, xmlNode): self.profile = xmlNode.getAttribute(DaeSyntax.PROFILE) self.xmlns = xmlNode.getAttribute(DaeSyntax.XMLNS) def SaveToXml(self, daeDocument): node = super(DaeTechnique,self).SaveToXml(daeDocument) node.setAttribute(DaeSyntax.PROFILE, self.profile) SetAttribute(node, DaeSyntax.XMLNS, self.xmlns) return node class DaeOptics(DaeEntity): def __init__(self): super(DaeOptics,self).__init__() self.techniqueCommon = DaeOptics.DaeTechniqueCommon() self.techniques = [] self.extras = None self.syntax = DaeSyntax.OPTICS def LoadFromXml(self, daeDocument, xmlNode): self.extras = CreateObjectsFromXml(daeDocument, xmlNode, DaeSyntax.EXTRA, DaeExtra) #self.techniqueCommon.LoadFromXml(daeDocument, FindElementByTagName(xmlNode, DaeSyntax.TECHNIQUE_COMMON)) self.techniques = CreateObjectsFromXml(daeDocument, xmlNode, DaeSyntax.TECHNIQUE,DaeTechnique) opticsSourceNode = RemoveWhiteSpaceNode(FindElementByTagName(xmlNode, DaeSyntax.TECHNIQUE_COMMON)).firstChild opticsSourceName = opticsSourceNode.localName if opticsSourceName == DaeSyntax.PERSPECTIVE: self.techniqueCommon = DaeOptics.DaePerspective() elif opticsSourceName == DaeSyntax.ORTHOGRAPHIC: self.techniqueCommon = DaeOptics.DaeOrthoGraphic() self.techniqueCommon.LoadFromXml(daeDocument,opticsSourceNode) def SaveToXml(self, daeDocument): node = super(DaeOptics, self).SaveToXml(daeDocument) # Add the technique common AppendChild(daeDocument,node,self.techniqueCommon) # Add the techniques AppendChilds(daeDocument, node, self.techniques) # Add the extra's AppendChilds(self,node,self.extras) return node def __str__(self): return super(DaeOptics,self).__str__()+' extras: %s, techniqueCommon: %s, techniques: %s'%(self.extras, self.techniqueCommon, self.techniques) class DaeTechniqueCommon(DaeEntity): def __init__(self): self.znear = 0.0 self.zfar = 0.0 self.aspectRatio = None self.syntax = DaeSyntax.TECHNIQUE_COMMON def LoadFromXml(self, daeDocument, xmlNode): self.znear = ToFloat(ReadContents(FindElementByTagName(xmlNode,DaeSyntax.ZNEAR))) self.zfar = ToFloat(ReadContents(FindElementByTagName(xmlNode,DaeSyntax.ZFAR))) self.aspectRatio = ToFloat(ReadContents(FindElementByTagName(xmlNode,DaeSyntax.ASPECT_RATIO))) def SaveToXml(self, daeDocument): node = Element(DaeSyntax.TECHNIQUE_COMMON) child = super(DaeOptics.DaeTechniqueCommon,self).SaveToXml(daeDocument) ## AppendTextChild(child,DaeSyntax.ZNEAR, self.znear) ## AppendTextChild(child,DaeSyntax.ZFAR, self.zfar) ## AppendTextChild(child,DaeSyntax.ASPECT_RATIO, self.aspectRatio) node.appendChild(child) return node def SavePropertiesToXml(self, daeDocument, node): AppendTextChild(node,DaeSyntax.ZNEAR, self.znear) AppendTextChild(node,DaeSyntax.ZFAR, self.zfar) AppendTextChild(node,DaeSyntax.ASPECT_RATIO, self.aspectRatio) def __str__(self): return super(DaeOptics.DaeTechniqueCommon,self).__str__()+' znear: %s, zfar: %s, aspectRatio: %s'%(self.znear, self.zfar, self.aspectRatio) class DaePerspective(DaeTechniqueCommon): def __init__(self): super(DaeOptics.DaePerspective,self).__init__() self.xfov = None self.yfov = None self.syntax = DaeSyntax.PERSPECTIVE def LoadFromXml(self, daeDocument, xmlNode): super(DaeOptics.DaePerspective,self).LoadFromXml(daeDocument, xmlNode) self.xfov = ToFloat(ReadContents(FindElementByTagName(xmlNode,DaeSyntax.XFOV))) self.yfov = ToFloat(ReadContents(FindElementByTagName(xmlNode,DaeSyntax.YFOV))) def SaveToXml(self, daeDocument): node = super(DaeOptics.DaePerspective,self).SaveToXml(daeDocument) AppendTextChild(node.firstChild,DaeSyntax.XFOV, self.xfov) AppendTextChild(node.firstChild,DaeSyntax.YFOV, self.yfov) super(DaeOptics.DaePerspective,self).SavePropertiesToXml(daeDocument, node.firstChild) return node def __str__(self): return super(DaeOptics.DaePerspective,self).__str__()+' xfov: %s, yfov: %s'%(self.xfov, self.yfov) class DaeOrthoGraphic(DaeTechniqueCommon): def __init__(self): super(DaeOptics.DaeOrthoGraphic,self).__init__() self.xmag = None self.ymag = None self.syntax = DaeSyntax.ORTHOGRAPHIC def LoadFromXml(self, daeDocument, xmlNode): super(DaeOptics.DaeOrthoGraphic,self).LoadFromXml(daeDocument, xmlNode) self.xmag = ToFloat(ReadContents(FindElementByTagName(xmlNode,DaeSyntax.XMAG))) self.ymag = ToFloat(ReadContents(FindElementByTagName(xmlNode,DaeSyntax.YMAG))) def SaveToXml(self, daeDocument): node = super(DaeOptics.DaeOrthoGraphic,self).SaveToXml(daeDocument) AppendTextChild(node.firstChild,DaeSyntax.XMAG, self.xmag) AppendTextChild(node.firstChild,DaeSyntax.YMAG, self.ymag) return node def __str__(self): return super(DaeOptics.DaeOrthoGraphic,self).__str__()+ 'xmag: %s, ymag: %s'%(self.xmag, self.ymag) class DaeImager(DaeEntity): def __init__(self): super(DaeImager,self).__init__() self.techniques = [] self.extras = None self.syntax = DaeSyntax.IMAGER def LoadFromXml(self, daeDocument, xmlNode): super(DaeImager, self).LoadFromXml(daeDocument, xmlNode) self.extras = CreateObjectsFromXml(daeDocument, xmlNode, DaeSyntax.EXTRA, DaeExtra) self.techniques = CreateObjectsFromXml(daeDocument, xmlNode, DaeSyntax.TECHNIQUE,DaeTechnique) def SaveToXml(self, daeDocument): node = super(DaeOptics, self).SaveToXml(daeDocument) # Add the techniques AppendChilds(daeDocument, node, self.techniques) # Add the extra's AppendChilds(self,node,self.extras) return node def __str__(self): return super(DaeImager,self).__str__()+' extras: %s, techniques: %s'%(self.techniqueCommon, self.techniques) class DaeExtra(DaeEntity): def __init__(self): super(DaeExtra,self).__init__() self.type = None self.techniques = [] self.syntax = DaeSyntax.EXTRA def LoadFromXml(self, daeDocument, xmlNode): self.type = xmlNode.getAttribute(DaeSyntax.TYPE) self.techniques = CreateObjectsFromXml(daeDocument, xmlNode,DaeSyntax.TECHNIQUE,DaeTechnique) def SaveToXml(self, daeDocument): node = super(DaeExtra,self).SaveToXml(daeDocument) AppendChilds(daeDocument, node, self.techniques) return node def __str__(self): return super(DaeExtra,self).__str__()+'techniques: %s'%(self.techniques) class DaeAccessor(DaeEntity): def __init__(self): super(DaeAccessor,self).__init__() self.count = 0 self.offset = None self.source = '' self.__stride = None ## self.stride = property(self.GetStride) self.params = [] self.syntax = DaeSyntax.ACCESSOR def LoadFromXml(self,daeDocument, xmlNode): self.count = CastAttributeFromXml(xmlNode, DaeSyntax.COUNT,int,0) self.offset = CastAttributeFromXml(xmlNode, DaeSyntax.OFFSET,int) self.source = ReadAttribute(xmlNode, DaeSyntax.SOURCE) self.stride = CastAttributeFromXml(xmlNode, DaeSyntax.STRIDE,int) self.params = CreateObjectsFromXml(daeDocument, xmlNode, DaeSyntax.PARAM, DaeParam) def SaveToXml(self, daeDocument): node = super(DaeAccessor,self).SaveToXml(daeDocument) node.setAttribute(DaeSyntax.COUNT, str(self.count)) SetAttribute(node,DaeSyntax.OFFSET, self.offset) node.setAttribute(DaeSyntax.SOURCE, StripString('#'+self.source)) SetAttribute(node, DaeSyntax.STRIDE, self.stride) AppendChilds(daeDocument, node, self.params) return node def AddParam(self, name, type): param = DaeParam() param.name = name param.type = type self.params.append(param) def GetStride(self): if self.__stride is None: return len(self.params) else: return self.__stride def SetStride(self, val): self.__stride = val def HasParam(self, paramName): return paramName in [param.name for param in self.params] stride = property(GetStride, SetStride) class DaeParam(DaeEntity): def __init__(self): super(DaeParam,self).__init__() self.name = None self.semantic = None self.sid = None self.type = '' self.syntax = DaeSyntax.PARAM def LoadFromXml(self, daeDocument, xmlNode): self.semantic = ReadAttribute(xmlNode, DaeSyntax.SEMANTIC) self.sid = ReadAttribute(xmlNode, DaeSyntax.SID) self.name = ReadAttribute(xmlNode, DaeSyntax.NAME) self.type = xmlNode.getAttribute(DaeSyntax.TYPE) def SaveToXml(self, daeDocument): node = super(DaeParam,self).SaveToXml(daeDocument) SetAttribute(node, DaeSyntax.SEMANTIC, self.semantic) SetAttribute(node, DaeSyntax.SID, self.sid) SetAttribute(node, DaeSyntax.NAME, self.name) node.setAttribute(DaeSyntax.TYPE, self.type) return node class DaeArray(DaeElement): def __init__(self): super(DaeArray, self).__init__() self.count = 0 self.data = [] def LoadFromXml(self, daeDocument, xmlNode): super(DaeArray, self).LoadFromXml(daeDocument, xmlNode) self.count = ToInt(ReadAttribute(xmlNode, DaeSyntax.COUNT)) self.data = ToList(ReadContents(xmlNode)) def SaveToXml(self, daeDocument): node = super(DaeArray,self).SaveToXml(daeDocument) SetAttribute(node, DaeSyntax.COUNT, len(self.data)) AppendTextInChild(node, self.data) return node def __str__(self): return super(DaeArray,self).__str__()+' count: %s'%(self.count) class DaeFloatArray(DaeArray): def __init__(self): super(DaeFloatArray, self).__init__() self.syntax = DaeSyntax.FLOAT_ARRAY def LoadFromXml(self, daeDocument, xmlNode): super(DaeFloatArray, self).LoadFromXml(daeDocument, xmlNode) self.data = ToFloatList(self.data) class DaeIntArray(DaeArray): def __init__(self): super(DaeIntArray, self).__init__() self.syntax = DaeSyntax.INT_ARRAY def LoadFromXml(self, daeDocument, xmlNode): super(DaeIntArray, self).LoadFromXml(daeDocument, xmlNode) self.data = ToIntList(self.data) class DaeBoolArray(DaeArray): def __init__(self): super(DaeBoolArray, self).__init__() self.syntax = DaeSyntax.BOOL_ARRAY def LoadFromXml(self, daeDocument, xmlNode): super(DaeBoolArray, self).LoadFromXml(daeDocument, xmlNode) self.data = ToBoolList(self.data) class DaeNameArray(DaeArray): def __init__(self): super(DaeNameArray, self).__init__() self.syntax = DaeSyntax.NAME_ARRAY def LoadFromXml(self, daeDocument, xmlNode): super(DaeNameArray, self).LoadFromXml(daeDocument, xmlNode) ##self.data = ToFloatList(self.data) class DaeIDREFArray(DaeArray): def __init__(self): super(DaeIDREFArray, self).__init__() self.syntax = DaeSyntax.IDREF_ARRAY def LoadFromXml(self, daeDocument, xmlNode): super(DaeIDREFArray, self).LoadFromXml(daeDocument, xmlNode) ##self.data = ToFloatList(self.data) #---Primitive Classes--- class DaePrimitive(DaeEntity): def __init__(self): super(DaePrimitive, self).__init__() self.name = None self.count = 0 self.material = '' self.inputs = [] def LoadFromXml(self, daeDocument, xmlNode): self.name = ReadAttribute(xmlNode, DaeSyntax.NAME) self.count = int(ReadAttribute(xmlNode, DaeSyntax.COUNT)) self.material = ReadAttribute(xmlNode, DaeSyntax.MATERIAL) def SaveToXml(self, daeDocument): node = super(DaePrimitive, self).SaveToXml(daeDocument) SetAttribute(node, DaeSyntax.NAME, self.name) SetAttribute(node, DaeSyntax.MATERIAL, StripString(self.material)) node.setAttribute(DaeSyntax.COUNT, str(self.count)) return node def GetMaxOffset(self): if self.inputs != []: return max([i.offset for i in self.inputs]) else: return None def FindInput(self, semantic): for i in self.inputs: if i.semantic == semantic: return i return None class DaeLines(DaePrimitive): def __init__(self): super(DaeLines, self).__init__() self.syntax = DaeSyntax.LINES self.lines = [] def LoadFromXml(self, daeDocument, xmlNode): super(DaeLines,self).LoadFromXml(daeDocument, xmlNode) self.syntax = DaeSyntax.LINES self.inputs = CreateObjectsFromXml(daeDocument, xmlNode, DaeSyntax.INPUT, DaeInput) self.lines = ToIntList(ReadContents(FindElementByTagName(xmlNode,DaeSyntax.P))) def SaveToXml(self, daeDocument): node = super(DaeLines,self).SaveToXml(daeDocument) AppendChilds(daeDocument, node, self.inputs) AppendTextChild(node, DaeSyntax.P, self.lines) return node class DaeLineStrips(DaePrimitive): def __init__(self): super(DaeLineStrips, self).__init__() self.syntax = DaeSyntax.LINESTRIPS def LoadFromXml(self, daeDocument, xmlNode): super(DaeLineStrips,self).LoadFromXml(daeDocument, xmlNode) class DaePolygons(DaePrimitive): def __init__(self): super(DaePolygons, self).__init__() self.syntax = DaeSyntax.POLYGONS self.polygons = [] self.holedPolygons = [] def LoadFromXml(self, daeDocument, xmlNode): super(DaePolygons,self).LoadFromXml(daeDocument, xmlNode) self.polygons = GetListFromNodes(xmlNode.getElementsByTagName(DaeSyntax.P), int) self.inputs = CreateObjectsFromXml(daeDocument, xmlNode, DaeSyntax.INPUT, DaeInput) def SaveToXml(self, daeDocument): node = super(DaePolygons,self).SaveToXml(daeDocument) AppendChilds(daeDocument, node, self.inputs) AppendChilds(node, DaeSyntax.P, self.polygons) return node class DaePolylist(DaePrimitive): def __init__(self): super(DaePolylist, self).__init__() self.syntax = DaeSyntax.POLYLIST def LoadFromXml(self, daeDocument, xmlNode): super(DaePolylist,self).LoadFromXml(daeDocument, xmlNode) class DaeTriangles(DaePrimitive): def __init__(self): super(DaeTriangles, self).__init__() self.triangles = [] self.syntax = DaeSyntax.TRIANGLES def LoadFromXml(self, daeDocument, xmlNode): super(DaeTriangles,self).LoadFromXml(daeDocument, xmlNode) self.triangles = ToIntList(ReadContents(FindElementByTagName(xmlNode,DaeSyntax.P))) self.inputs = CreateObjectsFromXml(daeDocument, xmlNode, DaeSyntax.INPUT, DaeInput) def SaveToXml(self, daeDocument): node = super(DaeTriangles,self).SaveToXml(daeDocument) AppendChilds(daeDocument, node, self.inputs) AppendTextChild(node, DaeSyntax.P, self.triangles) return node class DaeTriFans(DaePrimitive): def __init__(self): super(DaeTriFans, self).__init__() self.syntax = DaeSyntax.TRIFANS def LoadFromXml(self, daeDocument, xmlNode): super(DaeTriFans,self).LoadFromXml(daeDocument, xmlNode) class DaeTriStrips(DaePrimitive): def __init__(self): super(DaeTriStrips, self).__init__() self.syntax = DaeSyntax.TRISTRIPS def LoadFromXml(self, daeDocument, xmlNode): super(DaeTriStrips,self).LoadFromXml(daeDocument, xmlNode) #---instance Classes--- class DaeInstance(DaeEntity): def __init__(self): super(DaeInstance, self).__init__() self.url = '' self.extras = [] self.object = None def LoadFromXml(self, daeDocument, xmlNode): self.url = ReadNodeUrl(xmlNode) self.extras = CreateObjectsFromXml(daeDocument, xmlNode, DaeSyntax.EXTRA, DaeExtra) def SaveToXml(self, daeDocument): node = super(DaeInstance,self).SaveToXml(daeDocument) AppendChilds(daeDocument, node, self.extras) WriteNodeUrl(node, self.object.id) return node class DaeAnimationInstance(DaeInstance): def __init__(self): super(DaeAnimationInstance, self).__init__() self.syntax = DaeSyntax.INSTANCE_ANIMATION def LoadFromXml(self, daeDocument, xmlNode): super(DaeAnimationInstance,self).LoadFromXml(daeDocument, xmlNode) self.object = daeDocument.animationsLibrary.FindObject(self.url) def SaveToXml(self, daeDocument): node = super(DaeAnimationInstance,self).SaveToXml(daeDocument) return node class DaeCameraInstance(DaeInstance): def __init__(self): super(DaeCameraInstance, self).__init__() self.syntax = DaeSyntax.INSTANCE_CAMERA def LoadFromXml(self, daeDocument, xmlNode): super(DaeCameraInstance,self).LoadFromXml(daeDocument, xmlNode) self.object = daeDocument.camerasLibrary.FindObject(self.url) def SaveToXml(self, daeDocument): node = super(DaeCameraInstance,self).SaveToXml(daeDocument) return node class DaeControllerInstance(DaeInstance): def __init__(self): super(DaeControllerInstance, self).__init__() self.skeletons = [] self.bindMaterials = [] self.syntax = DaeSyntax.INSTANCE_CONTROLLER def LoadFromXml(self, daeDocument, xmlNode): super(DaeControllerInstance,self).LoadFromXml(daeDocument, xmlNode) self.skeletons = CreateObjectsFromXml(daeDocument, xmlNode, DaeSyntax.SKELETON, DaeSkeleton) self.bindMaterials = CreateObjectsFromXml(daeDocument, xmlNode, DaeFxSyntax.BIND_MATERIAL, DaeFxBindMaterial) self.object = daeDocument.controllersLibrary.FindObject(self.url) def SaveToXml(self, daeDocument): node = super(DaeControllerInstance,self).SaveToXml(daeDocument) AppendChilds(daeDocument, node, self.skeletons) AppendChilds(daeDocument, node, self.bindMaterials) return node # TODO: Collada API: finish DaeEffectInstance class DaeEffectInstance(DaeInstance): def __init__(self): super(DaeEffectInstance, self).__init__() self.syntax = DaeSyntax.INSTANCE_EFFECT def LoadFromXml(self, daeDocument, xmlNode): super(DaeEffectInstance,self).LoadFromXml(daeDocument, xmlNode) self.object = daeDocument.effectsLibrary.FindObject(self.url) def SaveToXml(self, daeDocument): node = super(DaeEffectInstance,self).SaveToXml(daeDocument) return node class DaeGeometryInstance(DaeInstance): def __init__(self): super(DaeGeometryInstance, self).__init__() self.bindMaterials = [] self.syntax = DaeSyntax.INSTANCE_GEOMETRY def LoadFromXml(self, daeDocument, xmlNode): super(DaeGeometryInstance,self).LoadFromXml(daeDocument, xmlNode) self.bindMaterials = CreateObjectsFromXml(daeDocument, xmlNode, DaeFxSyntax.BIND_MATERIAL, DaeFxBindMaterial) self.object = daeDocument.geometriesLibrary.FindObject(self.url) def SaveToXml(self, daeDocument): node = super(DaeGeometryInstance,self).SaveToXml(daeDocument) AppendChilds(daeDocument, node, self.bindMaterials) return node class DaeLightInstance(DaeInstance): def __init__(self): super(DaeLightInstance, self).__init__() self.syntax = DaeSyntax.INSTANCE_LIGHT def LoadFromXml(self, daeDocument, xmlNode): super(DaeLightInstance,self).LoadFromXml(daeDocument, xmlNode) self.object = daeDocument.lightsLibrary.FindObject(self.url) def SaveToXml(self, daeDocument): node = super(DaeLightInstance,self).SaveToXml(daeDocument) return node class DaeNodeInstance(DaeInstance): def __init__(self): super(DaeNodeInstance, self).__init__() self.syntax = DaeSyntax.INSTANCE_NODE def LoadFromXml(self, daeDocument, xmlNode): super(DaeNodeInstance,self).LoadFromXml(daeDocument, xmlNode) self.object = daeDocument.nodesLibrary.FindObject(self.url) def SaveToXml(self, daeDocument): node = super(DaeNodeInstance,self).SaveToXml(daeDocument) return node class DaeVisualSceneInstance(DaeInstance): def __init__(self): super(DaeVisualSceneInstance, self).__init__() self.syntax = DaeSyntax.INSTANCE_VISUAL_SCENE def LoadFromXml(self, daeDocument, xmlNode): super(DaeVisualSceneInstance,self).LoadFromXml(daeDocument, xmlNode) self.object = daeDocument.visualScenesLibrary.FindObject(self.url) def SaveToXml(self, daeDocument): node = super(DaeVisualSceneInstance,self).SaveToXml(daeDocument) return node class DaeSkeleton(DaeEntity): def __init__(self): super(DaeSkeleton,self).__init__() self.iControllers = [] def LoadFromXml(self, daeDocument, xmlNode): self.iControllers = CreateObjectsFromXml(daeDocument, xmlNode, DaeSyntax.INSTANCE_CONTROLLER, DaeControllerInstance) def SaveToXml(self, daeDocument): node = super(DaeSkeleton, self).SaveToXml(daeDocument) AppendChilds(daeDocument, node, self.iControllers) return node class DaeSyntax(object): #---collada--- COLLADA = 'COLLADA' VERSION = 'version' XMLNS = 'xmlns' BODY = 'body' TARGET = 'target' ASSET = 'asset' ID = 'id' NAME = 'name' URL = 'url' COUNT = 'count' OFFSET = 'offset' STRIDE = 'stride' METER = 'meter' SID = 'sid' SEMANTIC = 'semantic' PARAM = 'param' PROFILE = 'profile' TECHNIQUE = 'technique' TECHNIQUE_COMMON = 'technique_common' ##BIND_MATERIAL = 'bind_material' SKELETON = 'skeleton' P = 'p' PH = 'ph' H = 'h' INPUT = 'input' SET = 'set' #---light--- COLOR = 'color' AMBIENT = 'ambient' SPOT = 'spot' DIRECTIONAL = 'directional' POINT = 'point' CONSTANT_ATTENUATION = 'constant_attenuation' LINEAR_ATTENUATION = 'linear_attenuation' QUADRATIC_ATTENUATION = 'quadratic_attenuation' FALLOFF_ANGLE = 'falloff_angle' FALLOFF_EXPONENT = 'falloff_exponent' #---camera-- OPTICS = 'optics' PERSPECTIVE = 'perspective' ORTHOGRAPHIC = 'orthographic' IMAGER = 'imager' ZNEAR = 'znear' ZFAR = 'zfar' XFOV = 'xfov' YFOV = 'yfov' XMAG = 'xmag' YMAG ='ymag' ASPECT_RATIO = 'aspect_ratio' #---geometry--- MESH = 'mesh' CONVEX_MESH ='convex_mesh' SPLINE = 'spline' SOURCE ='source' VERTICES = 'vertices' ACCESSOR = 'accessor' CONVEX_HULL_OF = 'convex_hull_of' #---primitives--- LINES = 'lines' LINESTRIPS = 'linestrips' POLYGONS = 'polygons' POLYLIST = 'polylist' TRIANGLES = 'triangles' TRIFANS = 'trifans' TRISTRIPS = 'tristrips' #---libraries--- LIBRARY_ANIMATIONS = 'library_animations' LIBRARY_ANIMATION_CLIPS = 'library_animation_clips' LIBRARY_CAMERAS = 'library_cameras' LIBRARY_CONTROLLERS = 'library_controllers' LIBRARY_EFFECTS = 'library_effects' LIBRARY_FORCE_FIELDS = 'library_force_fields' LIBRARY_GEOMETRIES = 'library_geometries' LIBRARY_IMAGES = 'library_images' LIBRARY_LIGHTS = 'library_lights' LIBRARY_MATERIALS = 'library_materials' LIBRARY_NODES = 'library_NODES' LIBRARY_PHYSICS_MATERIALS = 'library_physics_materials' LIBRARY_PHYSICS_MODELS = 'library_physics_models' LIBRARY_PHYSICS_SCENES = 'library_physics_scenes' LIBRARY_VISUAL_SCENES = 'library_visual_scenes' SCENE = 'scene' EXTRA = 'extra' TYPE = 'type' LIGHT = 'light' CAMERA = 'camera' ANIMATION = 'animation' ANIMATION_CLIP = 'animation_clip' GEOMETRY = 'geometry' IMAGE = 'image' ##EFFECT = 'effect' VISUAL_SCENE = 'visual_scene' CONTROLLER = 'controller' MATERIAL = 'material' #---asset--- CONTRIBUTOR = 'contributor' CREATED = 'created' MODIFIED = 'modified' REVISION = 'revision' TITLE = 'title' SUBJECT = 'subject' KEYWORDS = 'keywords' UNIT = 'unit' UP_AXIS = 'up_axis' Y_UP = 'Y_UP' Z_UP = 'Z_UP' #---contributor--- AUTHOR = 'author' AUTHORING_TOOL = 'authoring_tool' COMMENTS = 'comments' COPYRIGHT = 'copyright' SOURCE_DATA = 'source_data' #---array--- FLOAT_ARRAY = 'float_array' NAME_ARRAY = 'Name_array' BOOL_ARRAY = 'bool_array' INT_ARRAY = 'int_array' IDREF_ARRAY = 'IDREF_array' #---node--- NODE = 'node' TYPE_JOINT = 'JOINT' TYPE_NODE = 'NODE' LAYER = 'layer' #---transforms--- TRANSLATE = 'translate' ROTATE = 'rotate' SCALE = 'scale' SKEW = 'skew' MATRIX = 'matrix' LOOKAT = 'lookat' #---instances--- INSTANCE_ANIMATION = 'instance_animation' INSTANCE_CAMERA = 'instance_camera' INSTANCE_CONTROLLER = 'instance_controller' ##INSTANCE_EFFECT = 'instance_effect' INSTANCE_GEOMETRY = 'instance_geometry' INSTANCE_LIGHT = 'instance_light' INSTANCE_NODE = 'instance_node' INSTANCE_VISUAL_SCENE = 'instance_visual_scene' INSTANCE_PHYSICS_SCENE = 'instance_physics_scene' #---image--- FORMAT = 'format' DEPTH = 'depth' HEIGHT = 'height' WIDTH = 'width' INIT_FROM = 'init_from' #---animation--- SAMPLER = 'sampler' CHANNEL = 'channel' class DaeFxBindMaterial(DaeEntity): def __init__(self): super(DaeFxBindMaterial, self).__init__() self.syntax = DaeFxSyntax.BIND_MATERIAL self.techniqueCommon = DaeFxBindMaterial.DaeFxTechniqueCommon() def LoadFromXml(self, daeDocument, xmlNode): self.techniqueCommon = CreateObjectFromXml(daeDocument, xmlNode, DaeFxSyntax.TECHNIQUE_COMMON, DaeFxBindMaterial.DaeFxTechniqueCommon) def SaveToXml(self, daeDocument): node = super(DaeFxBindMaterial,self).SaveToXml(daeDocument) AppendChild(daeDocument, node, self.techniqueCommon) return node class DaeFxTechniqueCommon(DaeEntity): def __init__(self): self.syntax = DaeFxSyntax.TECHNIQUE_COMMON self.iMaterials = [] def LoadFromXml(self, daeDocument, xmlNode): self.iMaterials = CreateObjectsFromXml(daeDocument, xmlNode, DaeFxSyntax.INSTANCE_MATERIAL, DaeFxMaterialInstance) def SaveToXml(self, daeDocument): node = super(DaeFxBindMaterial.DaeFxTechniqueCommon,self).SaveToXml(daeDocument) AppendChilds(daeDocument, node, self.iMaterials) return node def __str__(self): return super(DaeFxBindMaterial.DaeFxTechniqueCommon,self).__str__() class DaeFxMaterialInstance(DaeEntity): def __init__(self): super(DaeFxMaterialInstance, self).__init__() self.target = '' self.symbol = '' self.object = None self.syntax = DaeFxSyntax.INSTANCE_MATERIAL def LoadFromXml(self, daeDocument, xmlNode): self.target = ReadAttribute(xmlNode, DaeFxSyntax.TARGET)[1:] self.symbol = ReadAttribute(xmlNode, DaeFxSyntax.SYMBOL) self.object = daeDocument.materialsLibrary.FindObject(self.target) def SaveToXml(self, daeDocument): node = super(DaeFxMaterialInstance,self).SaveToXml(daeDocument) SetAttribute(node, DaeFxSyntax.TARGET, StripString('#'+self.object.id)) SetAttribute(node, DaeFxSyntax.SYMBOL, StripString(self.object.id)) return node def __str__(self): return super(DaeFxMaterialInstance,self).__str__()+' target: %s, symbol: %s'%(self.target, self.symbol) class DaeFxMaterial(DaeElement): def __init__(self): super(DaeFxMaterial, self).__init__() self.asset = None self.iEffects = [] self.extras = None self.syntax = DaeFxSyntax.MATERIAL def LoadFromXml(self, daeDocument, xmlNode): super(DaeFxMaterial, self).LoadFromXml(daeDocument, xmlNode) self.extras = CreateObjectsFromXml(daeDocument, xmlNode, DaeSyntax.EXTRA, DaeExtra) self.asset = CreateObjectFromXml(daeDocument, xmlNode, DaeSyntax.ASSET, DaeAsset) self.iEffects = CreateObjectsFromXml(daeDocument,xmlNode, DaeFxSyntax.INSTANCE_EFFECT, DaeFxEffectInstance) def SaveToXml(self, daeDocument): node = super(DaeFxMaterial,self).SaveToXml(daeDocument) # Add the assets AppendChild(daeDocument,node,self.asset) # Add the effect instances AppendChilds(daeDocument, node, self.iEffects) # Add the extra's AppendChilds(self,node,self.extras) return node def __str__(self): return super(DaeFxMaterial,self).__str__()+' assets: %s, iEffects: %s, extras: %s'%(self.asset, self.iEffects, self.extras) class DaeFxEffectInstance(DaeEntity): def __init__(self): super(DaeFxEffectInstance, self).__init__() self.url = '' self.syntax = DaeFxSyntax.INSTANCE_EFFECT def LoadFromXml(self, daeDocument, xmlNode): self.url = ReadAttribute(xmlNode, DaeFxSyntax.URL)[1:] self.object = daeDocument.effectsLibrary.FindObject(self.url) def SaveToXml(self, daeDocument): node = super(DaeFxEffectInstance,self).SaveToXml(daeDocument) SetAttribute(node, DaeFxSyntax.URL, StripString('#'+self.object.id)) return node class DaeFxEffect(DaeElement): def __init__(self): super(DaeFxEffect, self).__init__() self.profileCommon = DaeFxProfileCommon() self.syntax = DaeFxSyntax.EFFECT def LoadFromXml(self, daeDocument, xmlNode): super(DaeFxEffect, self).LoadFromXml(daeDocument, xmlNode) self.profileCommon = CreateObjectFromXml(daeDocument, xmlNode, DaeFxSyntax.PROFILE_COMMON, DaeFxProfileCommon) def SaveToXml(self, daeDocument): node = super(DaeFxEffect,self).SaveToXml(daeDocument) AppendChild(daeDocument, node, self.profileCommon) return node def __str__(self): return super(DaeFxEffect, self).__str__() + ', profileCommon: %s' % (self.profileCommon) def AddShader(self, daeShader): self.profileCommon.technique.shader = daeShader class DaeFxProfileCommon(DaeEntity): def __init__(self): super(DaeFxProfileCommon, self).__init__() self.technique = DaeFxTechnique() self.images = [] self.newParams = [] self.syntax = DaeFxSyntax.PROFILE_COMMON def LoadFromXml(self, daeDocument, xmlNode): self.images = CreateObjectsFromXml(daeDocument, xmlNode, DaeFxSyntax.IMAGE, DaeFxImage) self.newParams = CreateObjectsFromXml(daeDocument, xmlNode, DaeFxSyntax.NEWPARAM, DaeFxNewParam) self.technique = CreateObjectFromXml(daeDocument, xmlNode, DaeFxSyntax.TECHNIQUE, DaeFxTechnique) def SaveToXml(self, daeDocument): node = super(DaeFxProfileCommon,self).SaveToXml(daeDocument) AppendChilds(daeDocument, node, self.images) AppendChilds(daeDocument, node, self.newParams) AppendChild(daeDocument, node, self.technique) return node def __str__(self): return super(DaeFxProfileCommon, self).__str__() + ', technique: %s, images: %s, newParams: %s' % (self.technique, self.images, self.newParams) class DaeFxImage(DaeEntity): def __init__(self): super(DaeFxImage, self).__init__() self.syntax = DaeFxSyntax.IMAGE def LoadFromXml(self, daeDocument, xmlNode): super(DaeFxImage, self).LoadFromXml(daeDocument, xmlNode) def SaveToXml(self, daeDocument): node = super(DaeFxImage,self).SaveToXml(daeDocument) return node class DaeFxNewParam(DaeEntity): def __init__(self): super(DaeFxNewParam, self).__init__() self.syntax = DaeFxSyntax.NEWPARAM def LoadFromXml(self, daeDocument, xmlNode): super(DaeFxNewParam, self).LoadFromXml(daeDocument, xmlNode) def SaveToXml(self, daeDocument): node = super(DaeFxNewParam,self).SaveToXml(daeDocument) return node class DaeFxTechnique(DaeEntity): def __init__(self): super(DaeFxTechnique, self).__init__() self.syntax = DaeFxSyntax.TECHNIQUE self.shader = DaeFxShadeConstant() self.sid = '' def LoadFromXml(self, daeDocument, xmlNode): # TODO: Collada API: add asset and extra? self.sid = ReadAttribute(xmlNode, DaeFxSyntax.SID) lightSourceNode = FindElementByTagName(xmlNode, DaeFxSyntax.CONSTANT) if lightSourceNode: self.shader = CreateObjectFromXml(daeDocument, xmlNode, DaeFxSyntax.CONSTANT, DaeFxShadeConstant) else: lightSourceNode = FindElementByTagName(xmlNode, DaeFxSyntax.LAMBERT) if lightSourceNode: self.shader = CreateObjectFromXml(daeDocument, xmlNode, DaeFxSyntax.LAMBERT, DaeFxShadeLambert) else: lightSourceNode = FindElementByTagName(xmlNode, DaeFxSyntax.BLINN) if lightSourceNode: self.shader = CreateObjectFromXml(daeDocument, xmlNode, DaeFxSyntax.BLINN, DaeFxShadeBlinn) else: lightSourceNode = FindElementByTagName(xmlNode, DaeFxSyntax.PHONG) self.shader = CreateObjectFromXml(daeDocument, xmlNode, DaeFxSyntax.PHONG, DaeFxShadePhong) def SaveToXml(self, daeDocument): node = super(DaeFxTechnique,self).SaveToXml(daeDocument) node.setAttribute(DaeFxSyntax.SID, self.sid) AppendChild(daeDocument, node, self.shader) return node def __str__(self): return super(DaeFxTechnique,self).__str__()+' shader: %s'%(self.shader) class DaeFxShadeConstant(DaeEntity): def __init__(self): super(DaeFxShadeConstant, self).__init__() self.emission = None self.reflective = None self.reflectivity = None self.transparent = None self.transparency = None self.indexOfRefraction = None self.syntax = DaeFxSyntax.CONSTANT def LoadFromXml(self, daeDocument, xmlNode): self.emission = CreateObjectFromXml(daeDocument, xmlNode, DaeFxSyntax.EMISSION, DaeFxCommonColorAndTextureContainer, True) self.reflective = CreateObjectFromXml(daeDocument, xmlNode, DaeFxSyntax.REFLECTIVE, DaeFxCommonColorAndTextureContainer, True) self.reflectivity = CreateObjectFromXml(daeDocument, xmlNode, DaeFxSyntax.REFLECTIVITY, DaeFxCommonFloatAndParamContainer, True) self.transparent = CreateObjectFromXml(daeDocument, xmlNode, DaeFxSyntax.TRANSPARENT, DaeFxCommonColorAndTextureContainer, True) self.transparency = CreateObjectFromXml(daeDocument, xmlNode, DaeFxSyntax.TRANSPARENCY, DaeFxCommonFloatAndParamContainer, True) self.indexOfRefraction = CreateObjectFromXml(daeDocument, xmlNode, DaeFxSyntax.INDEXOFREFRACTION, DaeFxCommonFloatAndParamContainer, True) def SaveToXml(self, daeDocument): node = super(DaeFxShadeConstant,self).SaveToXml(daeDocument) AppendChild(daeDocument, node, self.emission) if isinstance(self, DaeFxShadeLambert): AppendChild(daeDocument, node, self.ambient) AppendChild(daeDocument, node, self.diffuse) if isinstance(self,DaeFxShadeBlinn): AppendChild(daeDocument, node, self.specular) AppendChild(daeDocument, node, self.shininess) AppendChild(daeDocument, node, self.reflective) AppendChild(daeDocument, node, self.reflectivity) AppendChild(daeDocument, node, self.transparent) AppendChild(daeDocument, node, self.transparency) AppendChild(daeDocument, node, self.indexOfRefraction) return node def AddValue(self, type, val): col = DaeFxColor() col.rgba = val if type == DaeFxSyntax.EMISSION: if not self.emission: self.emission = DaeFxCommonColorAndTextureContainer(type) self.emission.color = col elif type == DaeFxSyntax.REFLECTIVE: if not self.reflective: self.reflective = DaeFxCommonColorAndTextureContainer(type) self.reflective.color = col elif type == DaeFxSyntax.REFLECTIVITY: if not self.reflectivity: self.reflectivity = DaeFxCommonFloatAndParamContainer(type) self.reflectivity.float = val elif type == DaeFxSyntax.TRANSPARENT: if not self.transparent: self.transparent = DaeFxCommonColorAndTextureContainer(type) self.transparent.color = col elif type == DaeFxSyntax.TRANSPARENCY: if not self.transparency: self.transparency = DaeFxCommonFloatAndParamContainer(type) self.transparency.float = val elif type == DaeFxSyntax.INDEXOFREFRACTION: if not self.indexOfRefraction: self.indexOfRefraction = DaeFxCommonFloatAndParamContainer(type) self.indexOfRefraction.float = val else: Debug.Debug('DaeFxShadeConstant: type: %s not recognised'%(type),'ERROR') class DaeFxShadeLambert(DaeFxShadeConstant): def __init__(self): super(DaeFxShadeLambert, self).__init__() self.ambient = None self.diffuse = None self.syntax = DaeFxSyntax.LAMBERT def LoadFromXml(self, daeDocument, xmlNode): super(DaeFxShadeLambert, self).LoadFromXml(daeDocument, xmlNode) self.ambient = CreateObjectFromXml(daeDocument, xmlNode, DaeFxSyntax.AMBIENT, DaeFxCommonColorAndTextureContainer, True) self.diffuse = CreateObjectFromXml(daeDocument, xmlNode, DaeFxSyntax.DIFFUSE, DaeFxCommonColorAndTextureContainer, True) def SaveToXml(self, daeDocument): node = super(DaeFxShadeLambert,self).SaveToXml(daeDocument) #AppendChild(daeDocument, node, self.ambient) #AppendChild(daeDocument, node, self.diffuse) return node def AddValue(self, type, val): col = DaeFxColor() col.rgba = val if type == DaeFxSyntax.DIFFUSE: if not self.diffuse: self.diffuse = DaeFxCommonColorAndTextureContainer(type) if isinstance(val, DaeFxTexture): # its a texture self.diffuse.texture = val else: # it's a color self.diffuse.color = col elif type == DaeFxSyntax.AMBIENT: if not self.ambient: self.ambient = DaeFxCommonColorAndTextureContainer(type) self.ambient.color = col else: super(DaeFxShadeLambert,self).AddValue(type, val) class DaeFxShadeBlinn(DaeFxShadeLambert): def __init__(self): super(DaeFxShadeBlinn, self).__init__() self.specular = None self.shininess = None self.syntax = DaeFxSyntax.BLINN def LoadFromXml(self, daeDocument, xmlNode): super(DaeFxShadeBlinn, self).LoadFromXml(daeDocument, xmlNode) self.specular = CreateObjectFromXml(daeDocument, xmlNode, DaeFxSyntax.SPECULAR, DaeFxCommonColorAndTextureContainer, True) self.shininess = CreateObjectFromXml(daeDocument, xmlNode, DaeFxSyntax.SHININESS, DaeFxCommonFloatAndParamContainer, True) def SaveToXml(self, daeDocument): node = super(DaeFxShadeBlinn,self).SaveToXml(daeDocument) #AppendChild(daeDocument, node, self.specular) #AppendChild(daeDocument, node, self.shininess) return node def AddValue(self, type, val): col = DaeFxColor() col.rgba = val if type == DaeFxSyntax.SPECULAR: if not self.specular: self.specular = DaeFxCommonColorAndTextureContainer(type) self.specular.color = col elif type == DaeFxSyntax.SHININESS: if not self.shininess: self.shininess = DaeFxCommonFloatAndParamContainer(type) self.shininess.float = val else: super(DaeFxShadeBlinn,self).AddValue(type, val) class DaeFxShadePhong(DaeFxShadeBlinn): def __init__(self): super(DaeFxShadePhong, self).__init__() self.syntax = DaeFxSyntax.PHONG class DaeFxCommonColorAndTextureContainer(DaeEntity): def __init__(self, syntax='UNKNOWN'): super(DaeFxCommonColorAndTextureContainer, self).__init__() self.color = None self.texture = None self.syntax = syntax def LoadFromXml(self, daeDocument, xmlNode): self.color = CreateObjectFromXml(daeDocument, xmlNode, DaeFxSyntax.COLOR, DaeFxColor) self.texture = CreateObjectFromXml(daeDocument, xmlNode, DaeFxSyntax.TEXTURE, DaeFxTexture) def SaveToXml(self, daeDocument): node = super(DaeFxCommonColorAndTextureContainer,self).SaveToXml(daeDocument) AppendChild(daeDocument, node, self.color) AppendChild(daeDocument, node, self.texture) return node class DaeFxCommonFloatAndParamContainer(DaeEntity): def __init__(self, syntax = 'UNKNOWN'): super(DaeFxCommonFloatAndParamContainer, self).__init__() self.float = None self.param = None self.syntax = syntax def LoadFromXml(self, daeDocument, xmlNode): self.float = CastFromXml(daeDocument, xmlNode, DaeFxSyntax.FLOAT, float) ##self.param = CreateObjectFromXml(daeDocument, xmlNode, DaeFxSyntax.PARAM, DaeFxParam) def SaveToXml(self, daeDocument): node = super(DaeFxCommonFloatAndParamContainer,self).SaveToXml(daeDocument) AppendTextChild(node, DaeFxSyntax.FLOAT, self.float) AppendChild(daeDocument, node, self.param) return node class DaeFxColor(DaeEntity): def __init__(self): super(DaeFxColor, self).__init__() self.sid = '' self.rgba = [] self.syntax = DaeFxSyntax.COLOR def LoadFromXml(self, daeDocument, xmlNode): self.sid = ReadAttribute(xmlNode, DaeFxSyntax.SID) self.rgba = ToFloatList(ReadContents(xmlNode)) def SaveToXml(self, daeDocument): node = super(DaeFxColor,self).SaveToXml(daeDocument) SetAttribute(node, DaeFxSyntax.SID, self.sid) AppendTextInChild(node, self.rgba) return node class DaeFxTexture(DaeEntity): def __init__(self): super(DaeFxTexture, self).__init__() self.texture = '' self.textCoord = '' self.syntax = DaeFxSyntax.TEXTURE def LoadFromXml(self, daeDocument, xmlNode): self.texture = daeDocument.imagesLibrary.FindObject(ReadAttribute(xmlNode, DaeFxSyntax.TEXTURE)) self.textCoord = ReadAttribute(xmlNode, DaeFxSyntax.TEXCOORD) def SaveToXml(self, daeDocument): node = super(DaeFxTexture,self).SaveToXml(daeDocument) SetAttribute(node, DaeFxSyntax.TEXTURE, StripString(self.texture)) SetAttribute(node, DaeFxSyntax.TEXCOORD, self.textCoord) return node class DaeFxSyntax(object): COLOR = 'color' INSTANCE_MATERIAL = 'instance_material' INSTANCE_EFFECT = 'instance_effect' TECHNIQUE_COMMON = 'technique_common' SID = 'sid' EMISSION = 'emission' REFLECTIVE ='reflective' REFLECTIVITY = 'reflectivity' TRANSPARENT = 'transparent' TRANSPARENCY = 'transparency' INDEXOFREFRACTION = 'index_of_refraction' TEXTURE = 'texture' TEXCOORD = 'texcoord' AMBIENT = 'ambient' DIFFUSE = 'diffuse' BIND_MATERIAL ='bind_material' PROFILE_COMMON = 'profile_COMMON' SYMBOL = 'symbol' MATERIAL = 'material' EFFECT = 'effect' TARGET = 'target' URL = 'url' SYMBOL = 'symbol' BLINN = 'blinn' SHININESS = 'shininess' SPECULAR = 'specular' PHONG = 'phong' IMAGE = 'image' NEWPARAM = 'newparam' TECHNIQUE = 'technique' CONSTANT = 'constant' LAMBERT = 'lambert' FLOAT ='float' #---COLLADA PHYSICS--- class DaePhysicsScene(DaeElement): def __init__(self): super(DaePhysicsScene,self).__init__() self.asset = None self.extras = None self.iPhysicsModels = [] self.syntax = DaePhysicsSyntax.PHYSICS_SCENE def LoadFromXml(self, daeDocument, xmlNode): super(DaePhysicsScene, self).LoadFromXml(daeDocument, xmlNode) self.extras = CreateObjectsFromXml(daeDocument, xmlNode, DaeSyntax.EXTRA, DaeExtra) self.asset = CreateObjectFromXml(daeDocument, xmlNode, DaeSyntax.ASSET, DaeAsset) self.iPhysicsModels = CreateObjectsFromXml(daeDocument, xmlNode, DaePhysicsSyntax.INSTANCE_PHYSICS_MODEL, DaePhysicsModelInstance) def SaveToXml(self, daeDocument): node = super(DaePhysicsScene, self).SaveToXml(daeDocument) # Add the assets AppendChild(daeDocument,node,self.asset) # Add the phyics models AppendChilds(daeDocument, node, self.iPhysicsModels) # Add the extra's AppendChilds(self,node,self.extras) return node def __str__(self): return super(DaePhysicsScene,self).__str__()+' asset: %s, iPhysicsModels: %s, extras: %s'%(self.asset, self.iPhysicsModels, self.extras) class DaePhysicsModelInstance(DaeInstance): def __init__(self): super(DaePhysicsModelInstance, self).__init__() self.syntax = DaePhysicsSyntax.INSTANCE_PHYSICS_MODEL self.iRigidBodies = [] def LoadFromXml(self, daeDocument, xmlNode): super(DaePhysicsModelInstance,self).LoadFromXml(daeDocument, xmlNode) self.object = daeDocument.physicsModelsLibrary.FindObject(self.url) self.iRigidBodies = self.CreateInstanceRigidBodies(daeDocument, xmlNode, self.object) def SaveToXml(self, daeDocument): node = super(DaePhysicsModelInstance,self).SaveToXml(daeDocument) AppendChilds(daeDocument, node, self.iRigidBodies) return node def CreateInstanceRigidBodies(self, daeDocument, xmlNode, physicsModel): objects = [] CreateObjectsFromXml(daeDocument, xmlNode, DaePhysicsSyntax.INSTANCE_RIGID_BODY, DaeRigidBodyInstance) nodes = FindElementsByTagName(xmlNode,DaePhysicsSyntax.INSTANCE_RIGID_BODY) for node in nodes: object = DaeRigidBodyInstance() object.LoadFromXml(daeDocument, node) object.body = physicsModel.FindRigidBody(object.bodyString) n = None for visualScene in daeDocument.visualScenesLibrary.items: n = visualScene.FindNode(object.targetString) if not (n is None): break object.target = n objects.append(object) return objects class DaePhysicsSceneInstance(DaeInstance): def __init__(self): super(DaePhysicsSceneInstance, self).__init__() self.syntax = DaeSyntax.INSTANCE_PHYSICS_SCENE def LoadFromXml(self, daeDocument, xmlNode): super(DaePhysicsSceneInstance,self).LoadFromXml(daeDocument, xmlNode) self.object = daeDocument.physicsScenesLibrary.FindObject(self.url) def SaveToXml(self, daeDocument): node = super(DaePhysicsSceneInstance,self).SaveToXml(daeDocument) return node class DaePhysicsMaterialInstance(DaeInstance): def __init__(self): super(DaePhysicsMaterialInstance, self).__init__() self.syntax = DaePhysicsSyntax.INSTANCE_PHYSICS_MATERIAL def LoadFromXml(self, daeDocument, xmlNode): super(DaePhysicsMaterialInstance,self).LoadFromXml(daeDocument, xmlNode) self.object = daeDocument.physicsMaterialsLibrary.FindObject(self.url) def SaveToXml(self, daeDocument): node = super(DaePhysicsMaterialInstance,self).SaveToXml(daeDocument) return node class DaeRigidBodyInstance(DaeEntity): def __init__(self): super(DaeRigidBodyInstance, self).__init__() self.syntax = DaePhysicsSyntax.INSTANCE_RIGID_BODY self.body = None self.target = None self.bodyString = '' self.targetString = '' def LoadFromXml(self, daeDocument, xmlNode): self.bodyString = ReadAttribute(xmlNode, DaeSyntax.BODY) self.targetString = ReadAttribute(xmlNode, DaeSyntax.TARGET)[1:] def SaveToXml(self, daeDocument): node = super(DaeRigidBodyInstance,self).SaveToXml(daeDocument) SetAttribute(node, DaeSyntax.BODY, self.body.sid) SetAttribute(node, DaeSyntax.TARGET, StripString('#'+self.target.id)) return node class DaePhysicsModel(DaeElement): def __init__(self): super(DaePhysicsModel,self).__init__() self.syntax = DaePhysicsSyntax.PHYSICS_MODEL self.rigidBodies = [] def LoadFromXml(self, daeDocument, xmlNode): super(DaePhysicsModel, self).LoadFromXml(daeDocument, xmlNode) self.rigidBodies = CreateObjectsFromXml(daeDocument, xmlNode, DaePhysicsSyntax.RIGID_BODY, DaeRigidBody) def SaveToXml(self, daeDocument): node = super(DaePhysicsModel, self).SaveToXml(daeDocument) # Add the rigid bodies AppendChilds(daeDocument, node, self.rigidBodies) return node def FindRigidBody(self, url): for rigidBody in self.rigidBodies: if rigidBody.sid == url: return rigidBody return None class DaePhysicsMaterial(DaeElement): def __init__(self): super(DaePhysicsMaterial,self).__init__() self.syntax = DaePhysicsSyntax.PHYSICS_MATERIAL self.techniqueCommon = DaePhysicsMaterial.DaeTechniqueCommon() def LoadFromXml(self, daeDocument, xmlNode): super(DaePhysicsMaterial, self).LoadFromXml(daeDocument, xmlNode) self.techniqueCommon = CreateObjectFromXml(daeDocument, xmlNode, DaeSyntax.TECHNIQUE_COMMON, DaePhysicsMaterial.DaeTechniqueCommon) def SaveToXml(self, daeDocument): node = super(DaePhysicsMaterial, self).SaveToXml(daeDocument) AppendChild(daeDocument,node,self.techniqueCommon) return node class DaeTechniqueCommon(DaeEntity): def __init__(self): super(DaePhysicsMaterial.DaeTechniqueCommon,self).__init__() self.syntax = DaeSyntax.TECHNIQUE_COMMON self.dynamicFriction = 0 self.restitution = 0 self.staticFriction = 0 def LoadFromXml(self, daeDocument, xmlNode): self.dynamicFriction = CastFromXml(daeDocument, xmlNode, DaePhysicsSyntax.DYNAMIC_FRICTION, float, 0) self.restitution = CastFromXml(daeDocument, xmlNode, DaePhysicsSyntax.RESTITUTION, float, 0) self.staticFriction = CastFromXml(daeDocument, xmlNode, DaePhysicsSyntax.STATIC_FRICTION, float, 0) def SaveToXml(self, daeDocument): node = super(DaePhysicsMaterial.DaeTechniqueCommon,self).SaveToXml(daeDocument) AppendTextChild(node, DaePhysicsSyntax.DYNAMIC_FRICTION, self.dynamicFriction, None) AppendTextChild(node, DaePhysicsSyntax.RESTITUTION, self.restitution, None) AppendTextChild(node, DaePhysicsSyntax.STATIC_FRICTION, self.staticFriction, None) return node def __str__(self): return super(DaePhysicsMaterial.DaeTechniqueCommon,self).__str__() class DaeRigidBody(DaeEntity): def __init__(self): super(DaeRigidBody, self).__init__() self.syntax = DaePhysicsSyntax.RIGID_BODY self.name = '' self.sid = '' self.techniqueCommon = DaeRigidBody.DaeTechniqueCommon() def LoadFromXml(self, daeDocument, xmlNode): self.name = xmlNode.getAttribute(DaeSyntax.NAME) self.sid = xmlNode.getAttribute(DaeSyntax.SID) self.techniqueCommon = CreateObjectFromXml(daeDocument, xmlNode, DaeSyntax.TECHNIQUE_COMMON, DaeRigidBody.DaeTechniqueCommon) def SaveToXml(self, daeDocument): node = super(DaeRigidBody, self).SaveToXml(daeDocument) SetAttribute(node,DaeSyntax.NAME, StripString(self.name)) SetAttribute(node,DaeSyntax.SID, StripString(self.sid)) AppendChild(daeDocument,node,self.techniqueCommon) return node class DaeTechniqueCommon(DaeEntity): def __init__(self): super(DaeRigidBody.DaeTechniqueCommon, self).__init__() self.syntax = DaeSyntax.TECHNIQUE_COMMON self.iPhysicsMaterial = None self.physicsMaterial = None self.dynamic = True self.mass = None self.inertia = None self.shapes = [] def LoadFromXml(self, daeDocument, xmlNode): self.iPhysicsMaterial = CreateObjectFromXml(daeDocument, xmlNode, DaePhysicsSyntax.INSTANCE_PHYSICS_MATERIAL, DaePhysicsMaterialInstance) self.physicsMaterial = CreateObjectFromXml(daeDocument, xmlNode, DaePhysicsSyntax.PHYSICS_MATERIAL, DaePhysicsMaterial) self.dynamic = CastFromXml(daeDocument, xmlNode, DaePhysicsSyntax.DYNAMIC,bool,True) self.mass = CastFromXml(daeDocument, xmlNode, DaePhysicsSyntax.MASS, float, 1) self.inertia = ToFloat3(ReadContents(FindElementByTagName(xmlNode,DaePhysicsSyntax.INERTIA))) shapeNodes = FindElementsByTagName(xmlNode, DaePhysicsSyntax.SHAPE) for shapeNode in shapeNodes: s = FindElementByTagName(shapeNode, DaePhysicsSyntax.BOX) b = None if not (s is None): b = DaeBoxShape() else: s = FindElementByTagName(shapeNode, DaePhysicsSyntax.SPHERE) if not (s is None): b = DaeSphereShape() else: s = FindElementByTagName(shapeNode, DaePhysicsSyntax.PLANE) if not (s is None): b = DaePlaneShape() else: s = FindElementByTagName(shapeNode, DaeSyntax.INSTANCE_GEOMETRY) if not (s is None): b = DaeGeometryShape() else: s = FindElementByTagName(shapeNode, DaePhysicsSyntax.CYLINDER) if not (s is None): b = DaeCylinderShape() else: s = FindElementByTagName(shapeNode, DaePhysicsSyntax.TAPERED_CYLINDER) if not (s is None): b = DaeTaperedCylinderShape() else: s = FindElementByTagName(shapeNode, DaePhysicsSyntax.CAPSULE) if not (s is None): b = DaeCapsule() else: # TAPERED_CAPSULE b = DaeTaperedCapsuleShape() b.LoadFromXml(daeDocument, s) self.shapes.append(b) def SaveToXml(self, daeDocument): node = super(DaeRigidBody.DaeTechniqueCommon,self).SaveToXml(daeDocument) AppendChild(daeDocument,node,self.iPhysicsMaterial) AppendChild(daeDocument,node,self.physicsMaterial) shapes = Element(DaePhysicsSyntax.SHAPE) AppendChilds(daeDocument, shapes, self.shapes) node.appendChild(shapes) AppendTextChild(node, DaePhysicsSyntax.DYNAMIC, self.dynamic, None) AppendTextChild(node, DaePhysicsSyntax.MASS, self.mass, None) AppendTextChild(node, DaePhysicsSyntax.INERTIA, self.inertia, None) return node def GetPhysicsMaterial(self): if not (self.physicsMaterial is None): return self.physicsMaterial else: return self.iPhysicsMaterial.object def __str__(self): return super(DaeRigidBody.DaeTechniqueCommon,self).__str__() class DaeShape(DaeEntity): def __init__(self): super(DaeShape, self).__init__() self.mass = None self.density = None self.syntax = DaePhysicsSyntax.SHAPE def LoadFromXml(self, daeDocument, xmlNode): self.iGeometry = CreateObjectFromXml(daeDocument, xmlNode, DaeSyntax.INSTANCE_GEOMETRY,DaeGeometryInstance) self.mass = CastFromXml(daeDocument, xmlNode, DaePhysicsSyntax.MASS, float, None) self.density = CastFromXml(daeDocument, xmlNode, DaePhysicsSyntax.DENSITY, float, None) def SaveToXml(self, daeDocument): node = super(DaeShape, self).SaveToXml(daeDocument) AppendTextChild(node, DaePhysicsSyntax.MASS, self.mass, None) AppendTextChild(node, DaePhysicsSyntax.DENSITY, self.density, None) return node class DaeBoxShape(DaeShape): def __init__(self): super(DaeBoxShape, self).__init__() self.halfExtents = [] self.syntax = DaePhysicsSyntax.BOX def LoadFromXml(self, daeDocument, xmlNode): super(DaeBoxShape, self).LoadFromXml(daeDocument, xmlNode) self.halfExtents = ToFloat3(ReadContents(FindElementByTagName(xmlNode,DaePhysicsSyntax.HALF_EXTENTS))) def SaveToXml(self, daeDocument): node = super(DaeBoxShape, self).SaveToXml(daeDocument) AppendTextChild(node, DaePhysicsSyntax.HALF_EXTENTS, self.halfExtents) return node class DaeSphereShape(DaeShape): def __init__(self): super(DaeSphereShape, self).__init__() self.radius = None self.syntax = DaePhysicsSyntax.SPHERE def LoadFromXml(self, daeDocument, xmlNode): super(DaeSphereShape, self).LoadFromXml(daeDocument, xmlNode) self.radius = CastFromXml(daeDocument, xmlNode, DaePhysicsSyntax.RADIUS, float) def SaveToXml(self, daeDocument): node = super(DaeSphereShape, self).SaveToXml(daeDocument) AppendTextChild(node, DaePhysicsSyntax.RADIUS, self.radius) return node class DaeCylinderShape(DaeShape): def __init__(self): super(DaeCylinderShape, self).__init__() self.radius = [1 , 1] self.height = None self.syntax = DaePhysicsSyntax.CYLINDER def LoadFromXml(self, daeDocument, xmlNode): super(DaeCylinderShape, self).LoadFromXml(daeDocument, xmlNode) self.radius = ToFloat2(ReadContents(FindElementByTagName(xmlNode, DaePhysicsSyntax.RADIUS)),'Not a valid radius found. Must consist of 2 floats') self.height = CastFromXml(daeDocument, xmlNode, DaeSyntax.HEIGHT, float) def SaveToXml(self, daeDocument): node = super(DaeCylinderShape, self).SaveToXml(daeDocument) AppendTextChild(node, DaePhysicsSyntax.RADIUS, self.radius) AppendTextChild(node, DaeSyntax.HEIGHT, self.height) return node class DaeTaperedCylinderShape(DaeShape): def __init__(self): super(DaeTaperedCylinderShape, self).__init__() self.radius1 = [1 , 1] self.radius2 = [1 , 1] self.height = None self.syntax = DaePhysicsSyntax.TAPERED_CYLINDER def LoadFromXml(self, daeDocument, xmlNode): super(DaeTaperedCylinderShape, self).LoadFromXml(daeDocument, xmlNode) self.radius1 = ToFloat2(ReadContents(FindElementByTagName(xmlNode, DaePhysicsSyntax.RADIUS1)),'Not a valid radius found. Must consist of 2 floats') self.radius2 = ToFloat2(ReadContents(FindElementByTagName(xmlNode, DaePhysicsSyntax.RADIUS2)), 'Not a valid radius found. Must consist of 2 floats') self.height = CastFromXml(daeDocument, xmlNode, DaeSyntax.HEIGHT, float) def SaveToXml(self, daeDocument): node = super(DaeTaperedCylinderShape, self).SaveToXml(daeDocument) AppendTextChild(node, DaePhysicsSyntax.RADIUS1, self.radius1) AppendTextChild(node, DaePhysicsSyntax.RADIUS2, self.radius2) AppendTextChild(node, DaeSyntax.HEIGHT, self.height) return node class DaePlaneShape(DaeShape): def __init__(self): super(DaePlaneShape, self).__init__() self.equation = [] self.syntax = DaePhysicsSyntax.PLANE def LoadFromXml(self, daeDocument, xmlNode): super(DaePlaneShape, self).LoadFromXml(daeDocument, xmlNode) self.equation = ToFloat4(ReadContents(FindElementByTagName(xmlNode,DaePhysicsSyntax.EQUATION))) def SaveToXml(self, daeDocument): node = super(DaePlaneShape, self).SaveToXml(daeDocument) AppendTextChild(node, DaePhysicsSyntax.EQUATION, self.equation) return node class DaeCapsuleShape(DaeShape): def __init__(self): super(DaeCapsuleShape, self).__init__() self.radius = None self.height = None self.syntax = DaePhysicsSyntax.CAPSULE def LoadFromXml(self, daeDocument, xmlNode): super(DaeCapsuleShape, self).LoadFromXml(daeDocument, xmlNode) self.radius = CastFromXml(daeDocument, xmlNode, DaePhysicsSyntax.RADIUS, float) self.height = CastFromXml(daeDocument, xmlNode, DaeSyntax.HEIGHT, float) def SaveToXml(self, daeDocument): node = super(DaeCapsuleShape, self).SaveToXml(daeDocument) AppendTextChild(node, DaePhysicsSyntax.RADIUS, self.radius) AppendTextChild(node, DaeSyntax.HEIGHT, self.height) return node class DaeGeometryShape(DaeShape): def __init__(self): super(DaeGeometryShape, self).__init__() self.iGeometry = None def LoadFromXml(self, daeDocument, xmlNode): super(DaeGeometryShape, self).LoadFromXml(daeDocument, xmlNode) self.iGeometry = DaeGeometryInstance() self.iGeometry.LoadFromXml(daeDocument, xmlNode) #self.iGeometry = CreateObjectFromXml(daeDocument, xmlNode, DaeSyntax.INSTANCE_GEOMETRY, DaeGeometryInstance) #print self.iGeometry #print xmlNode.toxml() def SaveToXml(self, daeDocument): #node = super(DaeGeometryShape, self).SaveToXml(daeDocument) #AppendChild(daeDocument, node, self.iGeometry) return self.iGeometry.SaveToXml(daeDocument) class DaePhysicsSyntax(object): PHYSICS_SCENE = 'physics_scene' PHYSICS_MODEL = 'physics_model' PHYSICS_MATERIAL = 'physics_material' RIGID_BODY = 'rigid_body' INSTANCE_PHYSICS_MODEL = 'instance_physics_model' INSTANCE_PHYSICS_MATERIAL = 'instance_physics_material' INSTANCE_RIGID_BODY = 'instance_rigid_body' RESTITUTION = 'restitution' STATIC_FRICTION = 'static_friction' DYNAMIC_FRICTION = 'dynamic_friction' DYNAMIC = 'dynamic' MASS = 'mass' INERTIA = 'inertia' SHAPE = 'shape' DENSITY = 'density' RADIUS = 'radius' RADIUS1 = 'radius1' RADIUS2 = 'radius2' BOX = 'box' PLANE = 'plane' CYLINDER = 'cylinder' SPHERE = 'sphere' CAPSULE = 'capsule' TAPERED_CAPSULE ='tapered_capsule' TAPERED_CYLINDER = 'tapered_cylinder' HALF_EXTENTS = 'half_extents' #---Functions--- def CreateObjectsFromXml(colladaDocument, xmlNode, nodeType, objectType): if xmlNode is None: return None objects = [] nodes = FindElementsByTagName(xmlNode,nodeType) for node in nodes: object = objectType() object.LoadFromXml(colladaDocument, node) objects.append(object) return objects def CreateObjectFromXml(colladaDocument, xmlNode, nodeType, objectType, setSyntax = False): if xmlNode is None: return None node = FindElementByTagName(xmlNode, nodeType) object = None if setSyntax: object = objectType(nodeType) else: object = objectType() if node != None: object.LoadFromXml(colladaDocument, node) return object return None def CastFromXml(colladaDocument, xmlNode, nodeType, cast, default=None): if xmlNode is None: return default node = FindElementByTagName(xmlNode, nodeType) if node != None: textValue = ReadContents(node) if cast == bool: if textValue.lower() == 'false': return False else: return True return cast(textValue) return default def CastAttributeFromXml(xmlNode, nodeType, cast, default=None): if xmlNode is None: return default val = ReadAttribute(xmlNode, nodeType) if val != None and val != '': return cast(val) return default def AppendChild(daeDocument, xmlNode, daeEntity): if daeEntity is None or xmlNode is None: return else: child = daeEntity.SaveToXml(daeDocument) if child is None: return else : xmlNode.appendChild(child) def AppendChilds(daeDocument, xmlNode, daeEntities): if daeEntities is None or xmlNode is None: return else: for daeEntity in daeEntities: AppendChild(daeDocument, xmlNode, daeEntity) def AppendTextChild(xmlNode,syntax, object, default = None): if object is None: return if default != None and object == default: return node = Element(syntax) xmlNode.appendChild(node) return AppendTextInChild(node, object) def AppendTextInChild(xmlNode, object): if object is None: return text = Text() if type(object) == datetime: text.data = object.isoformat()##ToDateTime(object) elif type(object) == list: if len(object) == 0: return if object[0] is not None and type(object[0]) == float: object = RoundList(object, ROUND) text.data = ListToString(object) elif type(object) == float: text.data = round(object, ROUND) elif type(object) == bool: text.data = str(object).lower() else: text.data = str(object) xmlNode.appendChild(text) return xmlNode def SetAttribute(xmlNode,syntax, object): if xmlNode is None or object is None or str(object) == '': return xmlNode.setAttribute(syntax,str(object)) def ReadNodeUrl(node): attribute = ReadAttribute(node,DaeSyntax.URL) if attribute == None: return None else : attribute = str(attribute) if attribute.startswith('#'): return attribute[1:] return None def WriteNodeUrl(node, url): node.setAttribute(DaeSyntax.URL, StripString('#'+url)) def IsVersionOk(version, curVersion): versionAr = version.split('.') curVersionAr = curVersion.split('.') for i in range(len(curVersionAr)): if versionAr[i] != curVersionAr[i]: return False return True def StripString(text): return text.replace(' ','_').replace('.','_')
Python
##################################################################### # -*- coding: iso-8859-1 -*- # # # # Frets on Fire X (FoFiX) # # Copyright (C) 2009 myfingershurt # # 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. # ##################################################################### __version__ = '$Id: CleanHashCache.py 1446 2009-05-06 20:57:12Z john.stumpo $' import os import sys if os.name != 'nt': sys.stderr.write('This script only works on Windows.\n') sys.exit(1) import win32api import win32con import sha try: import sqlite3 except ImportError: import pysqlite2.dbapi2 as sqlite3 from Tkinter import * class CleanHashCacheWindow(object): def __init__(self, master, db): self.master = master self.db = db master.title('CleanHashCache') master.protocol('WM_DELETE_WINDOW', self.close) frame = Frame(master) lbl = Label(master, text='Double-click a version\nto delete its hashes.') lbl.pack(side=TOP, padx=10, pady=10) self.listbox = Listbox(master, exportselection=0) for version in [row[0] for row in self.db.execute('SELECT `version` FROM `verlist`').fetchall()]: self.listbox.insert(END, version) self.listbox.bind('<Double-Button-1>', lambda e: self.delete()) self.listbox.pack(side=TOP, padx=10, pady=0) okbutton = Button(master, text='Done', command=self.close) okbutton.pack(side=TOP, padx=10, pady=10, fill=BOTH, expand=1) master.resizable(0, 0) def run(self): self.master.mainloop() def delete(self): if len(self.listbox.curselection()): if win32api.MessageBox(self.master.winfo_id(), 'Really delete this version\'s hashes?\nThis cannot be undone!', 'CleanHashCache', win32con.MB_YESNO|win32con.MB_ICONQUESTION) == win32con.IDYES: vername = str(self.listbox.get(self.listbox.curselection()[0])) self.db.execute('DELETE FROM `verlist` WHERE `version` = ?', [vername]) self.db.commit() self.db.execute('DROP TABLE `hashes_%s`' % sha.sha(vername).hexdigest()) self.db.commit() self.listbox.delete(self.listbox.curselection()[0]) def close(self): self.db.commit() self.db.execute('VACUUM') self.db.commit() self.db.close() self.master.withdraw() self.master.quit() def main(): hashcache = sqlite3.Connection('HashCache') hashcache.execute('CREATE TABLE IF NOT EXISTS `verlist` (`version` STRING UNIQUE)') hashcache.commit() CleanHashCacheWindow(Tk(), hashcache).run() sys.exit(0) try: main() except (KeyboardInterrupt, SystemExit): raise except: import traceback import win32clipboard if win32api.MessageBox(0, 'A fatal error has occurred. This program will now terminate.\n\n' + traceback.format_exc() + '\n\nCopy traceback to Clipboard?', 'CleanHashCache', win32con.MB_YESNO|win32con.MB_ICONSTOP) == win32con.IDYES: win32clipboard.OpenClipboard() win32clipboard.EmptyClipboard() win32clipboard.SetClipboardText(traceback.format_exc()) win32clipboard.CloseClipboard() raise
Python
##################################################################### # -*- coding: iso-8859-1 -*- # # # # Frets on Fire X (FoFiX) # # Copyright (C) 2009 myfingershurt # # 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 working with WinRAR listfiles and converting them to NSIS script instructions.''' __version__ = '$Id: ListToNSIS.py 1446 2009-05-06 20:57:12Z john.stumpo $' import os import win32api import fnmatch import hashlib class NsisScriptGenerator(object): def __init__(self, baseFolder='.', hashCache=None, oldTblName=None, newTblName=None): self.nodeList = [] self.baseFolder = baseFolder self.hashCache = hashCache self.oldTblName = None self.newTblName = None if oldTblName is not None: self.oldTblName = hashlib.sha1(oldTblName).hexdigest() if newTblName is not None: self.newTblName = hashlib.sha1(newTblName).hexdigest() if self.hashCache is not None: self.hashCache.execute('INSERT OR REPLACE INTO `verlist` (`version`) VALUES (?)', [newTblName]) self.hashCache.execute('DROP TABLE IF EXISTS `hashes_%s`' % self.newTblName) self.hashCache.commit() self.hashCache.execute('VACUUM') self.hashCache.execute('CREATE TABLE `hashes_%s` (`path` STRING UNIQUE, `hash` STRING)' % self.newTblName) self.hashCache.commit() def readList(self, listname): l = open(listname, 'r') for line in l: line = line.partition('//')[0].strip() # remove comments if not len(line): continue if line[0] == '"' and line[-1] == '"': line = line[1:-1] oldpwd = os.getcwd() os.chdir(self.baseFolder) if os.path.dirname(line) == '' or os.path.isdir(os.path.dirname(line)): for f in win32api.FindFiles(line): path = os.path.join(os.path.dirname(line), f[8]) if os.path.isfile(path) and path.find('.svn') == -1: # omit .svn folders if self.hashCache is not None: newhash = hashlib.sha1(open(path, 'rb').read()).hexdigest() self.hashCache.execute('INSERT OR REPLACE INTO `hashes_%s` (`path`, `hash`) VALUES (?, ?)' % self.newTblName, [path, newhash]) if self.oldTblName is not None: oldhash = self.hashCache.execute('SELECT `hash` FROM `hashes_%s` WHERE `path` = ?' % self.oldTblName, [path]).fetchone() if oldhash is not None and oldhash[0] == newhash: continue self.nodeList.append(path) os.chdir(oldpwd) l.close() def readExcludeList(self, listname): patterns = [] l = open(listname, 'r') for line in l: line = line.partition('//')[0].strip() # remove comments if not len(line): continue if line[0] == '"' and line[-1] == '"': line = line[1:-1] patterns.append(line) l.close() for p in patterns: self.nodeList = [n for n in self.nodeList if not fnmatch.fnmatch(n.lower(), p.lower())] def getInstallScript(self): prevFolder = None script = '' for f in self.nodeList: if os.path.dirname(f) != prevFolder: script += 'SetOutPath "$INSTDIR\\%s"\r\n' % os.path.dirname(f).replace('..\\', '') prevFolder = os.path.dirname(f) script += 'File "%s"\r\n' % f script += 'SetOutPath "$INSTDIR"\r\n' return script def getUninstallScript(self): prevFolder = None script = '' for f in reversed(self.nodeList): if os.path.dirname(f) != prevFolder: if prevFolder is not None: p = prevFolder.replace('..\\', '') while len(p): script += 'RmDir "$INSTDIR\\%s"\r\n' % p p = os.path.dirname(p) prevFolder = os.path.dirname(f) script += 'Delete "$INSTDIR\\%s"\r\n' % f.replace('..\\', '') if prevFolder is not None: script += 'RmDir "$INSTDIR\\%s"\r\n' % prevFolder.replace('..\\', '') return script def separate(path, scriptIn): scriptOut = ([], []) for l in scriptIn.splitlines(): if l.lower().find(path.lower()) == -1: scriptOut[0].append(l) else: scriptOut[1].append(l) return ('\r\n'.join(x) for x in scriptOut) class NsisScriptBuilder(object): def __init__(self, header): self.header = header self.sectionScripts = [] def addSection(self, secName, secInstContent, secUninstContent, secDescription, secStart='Section', secEnd='SectionEnd'): self.sectionScripts.append([secName, secInstContent, secUninstContent, secDescription, secStart, secEnd]) def filterSection(self, secName, secFilter, secDescription, secStart='Section', secEnd='SectionEnd', instHeader='', instFooter='', uninstHeader='', uninstFooter=''): self.sectionScripts[0][1], instContent = separate(secFilter, self.sectionScripts[0][1]) self.sectionScripts[0][2], uninstContent = separate(secFilter, self.sectionScripts[0][2]) self.addSection(secName, instHeader+instContent+instFooter, uninstHeader+uninstContent+uninstFooter, secDescription, secStart, secEnd) def getScript(self): script = self.header for name, instContent, uninstContent, desc, start, end in self.sectionScripts: script += ''' %s "%s" SecID_%s %s %s ''' % (start, name, hashlib.sha1(name).hexdigest(), instContent, end) script += '!insertmacro MUI_FUNCTION_DESCRIPTION_BEGIN\r\n' for name, instContent, uninstContent, desc, start, end in self.sectionScripts: script += '!insertmacro MUI_DESCRIPTION_TEXT ${SecID_%s} "%s"\r\n' % (hashlib.sha1(name).hexdigest(), desc) script += '!insertmacro MUI_FUNCTION_DESCRIPTION_END\r\n' for name, instContent, uninstContent, desc, start, end in reversed(self.sectionScripts): script += ''' Section "un.%s" %s SectionEnd ''' % (name, uninstContent) return script
Python
##################################################################### # -*- coding: iso-8859-1 -*- # # # # Frets on Fire X (FoFiX) # # Copyright (C) 2009 myfingershurt # # 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. # ##################################################################### __version__ = '$Id: MakeThemeInstaller.py 1451 2009-05-08 01:55:09Z evilynux $' import os import sys if os.name != 'nt': sys.stderr.write('This script works only on Windows.\n') sys.exit(1) from Tkinter import * try: import sqlite3 except ImportError: import pysqlite2.dbapi2 as sqlite3 import _winreg import win32api import win32con import win32gui import pywintypes class ThemeSelectWindow(object): def __init__(self, master, themelist): self.master = master master.title('Theme Installer Generator') master.protocol('WM_DELETE_WINDOW', lambda: sys.exit(0)) frame = Frame(master) lbl = Label(master, text='Choose theme to package:') lbl.pack(side=TOP, padx=10, pady=10) self.listbox = Listbox(master, exportselection=0) for theme in themelist: self.listbox.insert(END, theme) self.listbox.bind('<Double-Button-1>', lambda e: self.ok()) self.listbox.pack(side=TOP, padx=10, pady=0) okbutton = Button(master, text='OK', command=self.ok) okbutton.pack(side=TOP, padx=10, pady=10, fill=BOTH, expand=1) master.resizable(0, 0) def run(self): self.master.mainloop() return self.listbox.get(self.listbox.curselection()[0]) def ok(self): if len(self.listbox.curselection()): self.master.withdraw() self.master.quit() class VersionSelectWindow(object): def __init__(self, master): self.master = master master.title('Theme Installer Generator') master.protocol('WM_DELETE_WINDOW', lambda: sys.exit(0)) frame = Frame(master) lbl = Label(master, text='Version number:') lbl.pack(side=TOP, padx=10, pady=10) self.entry = Entry(master) self.entry.bind('<Return>', lambda e: self.ok()) self.entry.pack(side=TOP, padx=10, pady=0) okbutton = Button(master, text='OK', command=self.ok) okbutton.pack(side=TOP, padx=10, pady=10, fill=BOTH, expand=1) master.resizable(0, 0) def run(self): self.master.mainloop() return self.entry.get() def ok(self): if self.entry.get() != '': self.master.withdraw() self.master.quit() def main(): # Find NSIS. try: key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, r'Software\NSIS') nsisPath = _winreg.QueryValueEx(key, '')[0] _winreg.CloseKey(key) except WindowsError: win32api.MessageBox(0, '''To create theme installers, you must have NSIS installed on your system. NSIS is needed to create theme installers, but not to use them. NSIS is free software that can be downloaded from http://nsis.sourceforge.net/.''', 'Theme Installer Generator', win32con.MB_OK|win32con.MB_ICONSTOP) sys.exit(1) makensis = os.path.join(nsisPath, 'makensis.exe') # Find possible themes. themes = [] os.chdir(os.path.join('..', 'data', 'themes')) for name in os.listdir('.'): if os.path.isfile(os.path.join(name, 'theme.ini')): themes.append(name) # Get the theme and its version number. themesel = ThemeSelectWindow(Tk(), themes) theme = themesel.run() versel = VersionSelectWindow(Tk()) version = versel.run() # Allow a license agreement to be added. if win32api.MessageBox(0, 'Would you like to display a license agreement in the installer?', 'Theme Installer Generator', win32con.MB_YESNO|win32con.MB_ICONQUESTION) == win32con.IDYES: try: licensefile = win32gui.GetOpenFileNameW( Filter='License Agreements (COPYING,LICENSE,*.txt,*.rtf)\0COPYING;LICENSE;*.txt;*.rtf\0All Files (*.*)\0*.*\0', Title='Theme Installer Generator: Select license agreement', Flags=win32con.OFN_DONTADDTORECENT|win32con.OFN_FILEMUSTEXIST|win32con.OFN_HIDEREADONLY|win32con.OFN_NOCHANGEDIR)[0] except pywintypes.error: sys.exit(0) else: licensefile = None # Where are we putting this? try: destfile = win32gui.GetSaveFileNameW( Filter='Executable files (*.exe)\0*.exe\0All Files (*.*)\0*.*\0', Title='Theme Installer Generator: Save installer', Flags=win32con.OFN_DONTADDTORECENT|win32con.OFN_OVERWRITEPROMPT|win32con.OFN_HIDEREADONLY|win32con.OFN_NOCHANGEDIR)[0] except pywintypes.error: sys.exit(0) # Let's do this. script = r""" !define THEME_NAME "%s" !define THEME_VERSION "%s" !include "MUI2.nsh" # Installer title and filename. Name 'FoFiX Theme "${THEME_NAME}" v${THEME_VERSION}' OutFile '%s' # Installer parameters. SetCompressor /SOLID lzma RequestExecutionLevel user # no UAC on Vista ShowInstDetails show # Where we're going (by default at least) InstallDir '$DOCUMENTS\FoFiX' # Where we stashed the install location. InstallDirRegKey HKCU 'SOFTWARE\myfingershurt\FoFiX' InstallRoot # Function to run FoFiX from the finish page. Function runFoFiX SetOutPath $INSTDIR Exec $INSTDIR\FoFiX.exe FunctionEnd # More installer parameters. !define MUI_ABORTWARNING !define MUI_FINISHPAGE_NOAUTOCLOSE !define MUI_FINISHPAGE_NOREBOOTSUPPORT !define MUI_FINISHPAGE_RUN !define MUI_FINISHPAGE_RUN_TEXT "Run FoFiX" !define MUI_FINISHPAGE_RUN_FUNCTION runFoFiX !define MUI_LICENSEPAGE_RADIOBUTTONS !define MUI_HEADERIMAGE !define MUI_FINISHPAGE_TEXT "FoFiX Theme $\"${THEME_NAME}$\" v${THEME_VERSION} has been installed on your computer.$\r$\n$\r$\nClick Finish to close this wizard.$\r$\n$\r$\nInstaller framework by John Stumpo." !define MUI_FINISHPAGE_TEXT_LARGE # gfx pending #!define MUI_HEADERIMAGE_BITMAP "pkg\installer_gfx\header.bmp" # Function to verify the install path. Function verifyFoFiXInstDir IfFileExists $INSTDIR haveDir Abort haveDir: IfFileExists $INSTDIR\FoFiX.exe allow MessageBox MB_YESNO|MB_ICONEXCLAMATION "This does not look like a valid FoFiX installation folder.$\r$\n$\r$\nIf you would like to merely unpack the theme files into this folder, you may continue anyway.$\r$\n$\r$\nContinue?" IDYES allow Abort allow: FunctionEnd # The pages of the installer... !insertmacro MUI_PAGE_WELCOME %s !define MUI_PAGE_CUSTOMFUNCTION_LEAVE verifyFoFiXInstDir !insertmacro MUI_PAGE_DIRECTORY !insertmacro MUI_PAGE_INSTFILES !insertmacro MUI_PAGE_FINISH # Throw in a cool background image. # gfx pending #!define MUI_CUSTOMFUNCTION_GUIINIT startBackground #Function startBackground # InitPluginsDir # File /oname=$PLUGINSDIR\background.bmp pkg\installer_gfx\background.bmp # BgImage::SetBG /NOUNLOAD /FILLSCREEN $PLUGINSDIR\background.bmp # BgImage::Redraw /NOUNLOAD #FunctionEnd #Function .onGUIEnd # BgImage::Destroy #FunctionEnd !insertmacro MUI_LANGUAGE "English" Section """ % tuple(map(str, (theme, version, destfile, licensefile and ('!insertmacro MUI_PAGE_LICENSE "%s"' % licensefile) or ''))) for root, dirs, files in os.walk(theme): if root.find('.svn') != -1: #stump: skip .svn folders continue script += 'SetOutPath "$INSTDIR\\data\\themes\\%s\\%s"\r\n' % (theme, root[len(theme):]) for f in files: script += 'File "%s"\r\n' % os.path.join(root, f) script += 'SetOutPath $INSTDIR\r\nSectionEnd\r\n' open('Setup.nsi', 'w').write(script) if os.spawnl(os.P_WAIT, makensis, 'makensis.exe', 'Setup.nsi') != 0: raise RuntimeError, 'Installer generation failed.' os.unlink('Setup.nsi') win32api.MessageBox(0, 'Installer generation complete.', 'Theme Installer Generator', win32con.MB_OK|win32con.MB_ICONINFORMATION) try: main() except (KeyboardInterrupt, SystemExit): raise except: import traceback import win32clipboard if win32api.MessageBox(0, 'A fatal error has occurred. This program will now terminate.\n\n' + traceback.format_exc() + '\n\nCopy traceback to Clipboard?', 'Theme Installer Generator', win32con.MB_YESNO|win32con.MB_ICONSTOP) == win32con.IDYES: win32clipboard.OpenClipboard() win32clipboard.EmptyClipboard() win32clipboard.SetClipboardText(traceback.format_exc()) win32clipboard.CloseClipboard() raise
Python
# -*- coding: UTF-8 -*- #分开经文章节 #==================================== za =============================== def convert_za(): f=file('za.txt') buf=f.read() f.close() arr=buf.split('!@#$') for i in range(1362): f=open('za/'+arr[i*2]+'.txt','w') f.write(arr[i*2+1]) f.close() print 'convert za ok!' def convert_za_bai(): f=file('za_bai.txt') buf=f.read() f.close() arr=buf.split('!@#$') for i in range(1362): f=open('za_bai/'+str(i+1)+'.txt','w') f.write(arr[i]) f.close() print 'convert za_bai ok!' #================================= zeng ========================================= def convert_zeng(): f=file('zengok.txt') buf=f.read() f.close() arr=buf.split('!@#$') for i in range(len(arr)): f=open('zeng/'+str(i+1)+'.txt','w') f.write(arr[i]) f.close() #================================= zhong ======================================= def convert_zhong(): pass #================================= chang ======================================= def convert_chang(): pass #================================= zhong_bai ======================================= def convert_zhong_bai(): pass #================================= chang_bai ======================================= def convert_chang_bai(): pass #================================= zeng_bai ======================================= def convert_zeng_bai(): pass #================================= main ======================================= #convert_list=('za','za_bai','zhong','zhong_bai','chang','chang_bai','zeng','zeng_bai','nc_za') convert_list=('zeng',) for item in convert_list: run='convert_'+item+'()' print run eval(run)
Python
# -*- coding: UTF-8 -*- #分开经文章节 # #==================================== za =============================== def convert_za(): f=file('za.txt') buf=f.read() f.close() arr=buf.split('!@#$') for i in range(1362): f=open('za/'+arr[i*2]+'.txt','w') f.write(arr[i*2+1]) f.close() print 'convert za ok!' def convert_za_bai(): f=file('za_bai.txt') buf=f.read() f.close() arr=buf.split('!@#$') for i in range(1362): f=open('za_bai/'+str(i+1)+'.txt','w') f.write(arr[i]) f.close() print 'convert za_bai ok!' #================================= zeng ========================================= def convert_zeng(): f=file('zengok.txt') buf=f.read() f.close() arr=buf.split('!@#$') for i in range(len(arr)): f=open('zeng/'+str(i+1)+'.txt','w') f.write(arr[i]) f.close() #convert_list=('za','za_bai','zhong','zhong_bai','chang','chang_bai','zeng','zeng_bai','nc_za') convert_list=('zeng',) for item in convert_list: run='convert_'+item+'()' print run eval(run)
Python
from vtk import vtkRenderer, vtkActor, vtkPolyDataMapper, vtkSphereSource, vtkPolyDataReader from time import sleep, clock from Sensor import Sensor from numpy import matrix from Recording import Recording ## RecordingState contains the functionality behind the RecordingPanel. class RecordingState: ## The constructor of RecordingState. # @param[in] parent The wx window parent (VisualizationState) of this Panel. # @param[in] main Main wx.App derived instance. def __init__(self, parent, main): ## The wx window parent (VisualizationState) of this Panel. self.parent = parent ## Main wx.App derived instance. self.main = main ## Flag indicating whether the playback is on or off. self.PLAYING = False ## Flag indicating whether this is the first session or not. self.FIRST_TIME = True ## List of recordings, each with its corresping frames. self.recordingSession = None ## Flag that indicates whether the program is recording. self.RECORDING = False # Initiate VTK render window for this state. self.parent.InitiateVTK(self) self.parent.SetRenderActors(self,len(self.main.bonyLandmarks),len(self.main.sensors),len(self.main.GHJoints)) ## Toggles the playing of the visualization on and off. # Is used to stop the visualization when the user is not in this panel. def OnTogglePlayPause(self): if self.PLAYING: self.PLAYING = False else: self.PLAYING = True self.Play() ## Gets the following frame and visualizes it. Checks whether the RECORDING flag of the VisualizationState is on to save the frame. def Play(self): while self.PLAYING: startTime = clock() self.main.driver.SampleSensors() self.parent.update_actor_positions() if self.RECORDING: self.Record() endTime = clock() self.parent.main.Yield() if (endTime - startTime) < (1.0/self.parent.frameRate): sleep((1.0/self.parent.frameRate) - (endTime - startTime)) ## Records the current positions and rotations of the sensors. def Record(self): self.recordingSession.AddFrame(self.main) ## Creates a new recording session. def newRecordingSession(self): self.recordingSession = Recording(self.main)
Python
from time import strftime ## Represents a recording. To allow serialization, the main parameter is not stored. class Recording: ## The constructor of Recording. # @param[in] main Main wx.App derived instance. def __init__(self,main): ## The positions of the sensors. self.sensorPositions = [[] for i in range(0, len(main.sensors))] ## The rotations of the sensors. self.sensorRotations = [[] for i in range(0, len(main.sensors))] ## Array with a timestamp for each frame in the recording. self.timeStamps = [] ## The list containing the bony landmarks. self.bonyLandmarksRecorded = main.bonyLandmarks ## The list containing the GH-Joints. self.GHJointsRecorded = main.GHJoints ## The list containing the sensors. self.sensorsRecorded = main.sensors ## The number of frames in the recording. self.numberOfFrames = 0 ## The current frame in the recording. self.currentFrame = 0 ## The string containing the filename. self.filename = "" ## Adds the current frame with sensorPositions and rotations to the lists. # Adds a timestamp to the frame, and updates the number of frames. # @param[in] main Main wx.App derived instance. def AddFrame(self,main): for i in range(0, len(main.sensors)): self.sensorPositions[i].append(main.sensors[i].position) self.sensorRotations[i].append(main.sensors[i].rotation) self.timeStamps.append(strftime("%Y-%m-%d %H:%M:%S")) self.numberOfFrames += 1 ## Calculates a list with the positions and rotation of the current frame. # @return[array] The list containing the position and rotation of each sensor in the current frame. def GetSensorsCurrentFrame(self): for i in range(0, len(self.sensorsRecorded)): self.sensorsRecorded[i].position = self.sensorPositions[i][self.currentFrame] self.sensorsRecorded[i].rotation = self.sensorRotations[i][self.currentFrame] return self.sensorsRecorded ## Returns the timestamp corresponding to the current frame. # @return[string] A string represantation of the time corresponding to the currentFrame. def GetCurrentTimeStamp(self): return self.timeStamps[self.currentFrame]
Python
from numpy import matrix ## Represents a sensor. Contains data such as ID, name, calibrated and non-calibrated position and rotation matrices. class Sensor: ## The constructor of Sensor. def __init__(self, ID, name="undefined", position=[], rotation=[]): ## The ID of the sensor. self.ID = ID ## The name of the sensor. self.name = name ## The position matrix or matrices for each frame of the sensor. self.position = position ## The rotation matrix or matrices for each frame of the sensor. self.rotation = rotation ## Uncalibrated positions. self.rawPosition = [] ## Uncalibrated rotations. self.rawRotation = []
Python
# ***** BEGIN LICENSE BLOCK ***** # Version: MPL 1.1/GPL 2.0/LGPL 2.1 # # The contents of this file are subject to the Mozilla Public License Version # 1.1 (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # http://www.mozilla.org/MPL/ # # Software distributed under the License is distributed on an "AS IS" basis, # WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License # for the specific language governing rights and limitations under the # License. # # The Original Code is the Python Computer Graphics Kit. # # The Initial Developer of the Original Code is Matthias Baas. # Portions created by the Initial Developer are Copyright (C) 2004 # the Initial Developer. All Rights Reserved. # # Contributor(s): # # Alternatively, the contents of this file may be used under the terms of # either the GNU General Public License Version 2 or later (the "GPL"), or # the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), # in which case the provisions of the GPL or the LGPL are applicable instead # of those above. If you wish to allow use of your version of this file only # under the terms of either the GPL or the LGPL, and not to allow others to # use your version of this file under the terms of the MPL, indicate your # decision by deleting the provisions above and replace them with the notice # and other provisions required by the GPL or the LGPL. If you do not delete # the provisions above, a recipient may use your version of this file under # the terms of any one of the MPL, the GPL or the LGPL. # # ***** END LICENSE BLOCK ***** # $Id: fob.py,v 1.2 2005/04/29 15:10:22 mbaas Exp $ #~ try: import serial serial_installed = True #~ except: #~ print "hoi" #~ serial_installed = False import sys, string, time, struct #from cgtypes import * from math import pi # Commands ANGLES = 'W' ANGLE_ALIGN1 = 'J' ANGLE_ALIGN2 = 'q' BORESIGHT = 'u' BORESIGHT_REMOVE = 'v' BUTTON_MODE = 'M' BUTTON_READ = 'N' CHANGE_VALUE = 'P' EXAMINE_VALUE = 'O' FBB_RESET = '/' HEMISPHERE = 'L' MATRIX = 'X' METAL = 's' METAL_ERROR = 't' NEXT_TRANSMITTER = '0' OFFSET = 'K' POINT = 'B' POSITION = 'V' POSITION_ANGLES = 'Y' POSITION_MATRIX = 'Z' POSITION_QUATERNION = ']' QUATERNION = '\\' REFERENCE_FRAME1 = 'H' REFERENCE_FRAME2 = 'r' REPORT_RATE1 = 'Q' REPORT_RATE2 = 'R' REPORT_RATE8 = 'S' REPORT_RATE32 = 'T' RUN = 'F' SLEEP = 'G' STREAM = '@' STREAM_STOP = '?' SYNC = 'A' XOFF = 0x13 XON = 0x11 # Change value/Examine Value parameters BIRD_STATUS = chr(0x00) SOFTWARE_REVISION_NUMBER = chr(0x01) BIRD_COMPUTER_CRYSTAL_SPEED = chr(0x02) POSITION_SCALING = chr(0x03) BIRD_MEASUREMENT_RATE = chr(0x07) SYSTEM_MODEL_IDENTIFICATION = chr(0x0f) FLOCK_SYSTEM_STATUS = chr(0x24) FBB_AUTO_CONFIGURATION = chr(0x32) # Hemispheres FORWARD = chr(0) + chr(0) AFT = chr(0) + chr(1) UPPER = chr(0xc) + chr(1) LOWER = chr(0xc) + chr(0) LEFT = chr(6) + chr(1) RIGHT = chr(6) + chr(0) class DataError(Exception): """Exception. This exception is thrown when the number of bytes returned from the bird doesn't match what is expected.""" pass def hexdump(data): """data als Hex-Dump ausgeben.""" if len(data)>16: hexdump(data[:16]) hexdump(data[16:]) else: t = "" for c in data: s = hex(ord(c))[2:] if len(s)==1: s="0"+s print s, if c in string.printable and c not in string.whitespace: t+=c else: t+="." print (48-3*len(data))*" ", print t class FOBRecord: def __init__(self): self.pos = (0.0, 0.0, 0.0) self.angles = (0,0,0) self.matrix = (0,0,0,0,0,0,0,0,0) self.quat = (0,0,0,0) self.metal = None # BirdContext class BirdContext: """Context class for one individual bird (sensor). This class stores the output mode in which a particular bird is currently in. This information is used to decode the data record sent by the bird. """ def __init__(self): # 144 for extended range transmitter (see p. 89 of the FOB manual) # 2.54 to convert inches into cm // 25.4 for mms self.pos_scale = 144*25.4 # Mode (ANGLE, POSITION, ...) self.mode = POSITION_ANGLES # Size of data records (default is POSITION/ANGLES) self.record_size = 12 # Number of words in one record (record_size = 2*num_words [+ metal]) self.num_words = 6 self.scales = [self.pos_scale, self.pos_scale, self.pos_scale, 180, 180, 180] self.metal_flag = False def angles(self, addr=None): self.mode = ANGLES self.num_words = 3 self.scales = [180,180,180] self._calc_record_size() def position(self): self.mode = POSITION self.num_words = 3 self.scales = [self.pos_scale, self.pos_scale, self.pos_scale] self._calc_record_size() def position_angles(self, addr=None): """POSITION/ANGLES command.""" self.mode = POSITION_ANGLES self.num_words = 6 self.scales = [self.pos_scale, self.pos_scale, self.pos_scale,180,180,180] self._calc_record_size() def matrix(self, addr=None): self.mode = MATRIX self.num_words = 9 self.scales = [1,1,1,1,1,1,1,1,1] self._calc_record_size() def position_matrix(self, addr=None): """POSITION/MATRIX command.""" self.mode = POSITION_MATRIX self.num_words = 12 self.scales = [self.pos_scale, self.pos_scale, self.pos_scale,1,1,1,1,1,1,1,1,1] self._calc_record_size() def quaternion(self, addr=None): """QUATERNION command.""" self.mode = QUATERNION self.num_words = 4 self.scales = [1,1,1,1] self._calc_record_size() def position_quaternion(self, addr=None): """POSITION/QUATERNION command.""" self.mode = POSITION_QUATERNION self.num_words = 7 self.scales = [self.pos_scale, self.pos_scale, self.pos_scale,1,1,1,1] self._calc_record_size() def metal(self, flag): self.metal_flag = flag self._calc_record_size() def decode(self, s): values = [] for i in range(self.num_words): v = self.decodeWord(s[2*i:2*i+2]) v*=self.scales[i] v=v/32768.0 values.append(v) # if self.metal_flag: # print "Metal:",ord(s[-1]) return values def decodeWord(self, s): """Decode the word in string s. s must contain exactly 2 bytes. """ ls = ord(s[0]) & 0x7f ms = ord(s[1]) if ms&0x80==0x80: print "MSB bit7 nicht 0!" v = (ms<<9) | (ls<<2) if v<0x8000: return v else: return v-0x10000 def _calc_record_size(self): self.record_size = 2*self.num_words # if self.metal_flag: # self.record_size+=1 # FOB class FOB: """Interface to the Ascension Flock Of Birds. This class can be used to communicate with the Ascension Flock of Birds motion tracker (http://www.ascension-tech.com/). The class directly accesses the serial port and has methods that correspond to the commands described in the \em Flock \em of \em Birds \em Installation \em and \em Operation \em Guide. Example usage: \code fob = FOB() # Open a connection on the serial port fob.open() # Initialize fob.fbbAutoConfig(numbirds=4) fob.fbbReset() ... # Set output mode for bird 1 to "position" fob.position(1) # Obtain a sensor value from bird 1 pos = fob.point(1) ... fob.close() \endcode """ def __init__(self): """Constructor.""" # Serial() instance self.ser = None # Default-Context (Master) self.defaultctx = BirdContext() # A list of bird context classes (one per sensor) self.birds = [] def __str__(self): if self.ser==None: serstr = "not connected" else: serstr = "port:%s, baudrate:%d"%(self.ser.portstr, self.ser.baudrate) s = "Flock of Birds (%s):\n"%serstr s += ' Device Description: "%s"\n'%self.examineValue(SYSTEM_MODEL_IDENTIFICATION) status = self.examineValue(FLOCK_SYSTEM_STATUS) for i in range(14): s += " Bird %2d: "%i b = status[i] if b&0x01: s += "ERT#0, " if b&0x02: s += "ERT#1, " if b&0x04: s += "ERT#2, " if b&0x08: s += "ERT#3, " if b&0x10: s += "Extended Range Controller, " if b&0x80==0: s += "not " s += "accessible, " if b&0x40==0: s += "not " s += "running, " if b&0x20: s += "has a sensor" else: s += "has no sensor" if i<14: s += "\n" # c,dev,deps = self.examineValue(FBB_AUTO_CONFIGURATION) # for i in range(14): # s += " Bird %2d: "%i # if dev&(1<<i): # s += "running, " # else: # s += "not running, " # if deps&(1<<i): # s += "dependent\n" # else: # s += "not dependent\n" return s # open def open(self, port=0, baudrate=115200, timeout=3): """Open a connection to the flock. \param port (\c int) Port number (0,1,...) \param baudrate (\c int) Baud rate \param timeout (\c float) Time out value for RS232 operations """ if not serial_installed: raise RuntimeError, 'Cannot import the serial module (http://pyserial.sourceforge.net).' self.ser = serial.Serial(port=port, baudrate=baudrate, bytesize=serial.EIGHTBITS, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, xonxoff=0, rtscts=0, timeout=timeout) self.ser.setRTS(0) ser = self.ser # print "Port:",ser.portstr # print "Baudrates:",ser.BAUDRATES # print "Bytesizes:",ser.BYTESIZES # print "Parities:",ser.PARITIES # print "Stopbits:",ser.STOPBITS # print "CTS:",ser.getCTS() # print "DSR:",ser.getDSR() # print "RI:",ser.getRI() # print "CD:",ser.getCD() # self.ser.setRTS(1) # time.sleep(1.0) # self.ser.setRTS(0) # close def close(self): if self.ser!=None: self.ser.close() self.ser = None def examineValue(self, param, addr=None): """EXAMINE VALUE command. Here are the possible parameters and their return values - BIRD_STATUS: Integer (actually a word) - SOFTWARE_REVISION_NUMBER: Tuple (int,fra). The version number is int.fra - BIRD_COMPUTER_CRYSTAL_SPEED: Frequeny in MHz as an integer - BIRD_MEASUREMENT_RATE: Measurement rate in cycles/sec (as float) - SYSTEM_MODEL_IDENTIFICATION: Device description string - FLOCK_SYSTEM_STATUS: 14-tuple with the status byte for each bird - FBB_AUTO_CONFIGURATION: Tuple (configmode, devices, dependents) \param param Parameter number (there are symbolic constants) \return Value """ if addr!=None: self.rs232ToFbb(addr) self._write(EXAMINE_VALUE+param) # BIRD_STATUS if param==BIRD_STATUS: v = self._read(2, exc=True) res = struct.unpack("<H", v)[0] # SOFTWARE_REVISION_NUMBER elif param==SOFTWARE_REVISION_NUMBER: v = self._read(2, exc=True) int = struct.unpack("B", v[1])[0] fra = struct.unpack("B", v[0])[0] res = (int, fra) # BIRD_COMPUTER_CRYSTAL_SPEED elif param==BIRD_COMPUTER_CRYSTAL_SPEED: v = self._read(2, exc=True) res = struct.unpack("B", v[0])[0] # BIRD_MEASUREMENT_RATE elif param==BIRD_MEASUREMENT_RATE: v = self._read(2, exc=True) rate = struct.unpack("<H", v)[0] res = float(rate)/256.0 # SYSTEM_MODEL_IDENTIFICATION elif param==SYSTEM_MODEL_IDENTIFICATION: v = self._read(10, exc=True) res = v.strip() # FLOCK_SYSTEM_STATUS elif param==FLOCK_SYSTEM_STATUS: v = self._read(14, exc=True) res = struct.unpack("BBBBBBBBBBBBBB", v) # FBB AUTO-CONFIGURATION elif param==FBB_AUTO_CONFIGURATION: v = self._read(5, exc=True) configmode = struct.unpack("B", v[0])[0] dev = struct.unpack("<H", v[1:3])[0] deps = struct.unpack("<H", v[3:])[0] res = (configmode, dev, deps) else: raise ValueError, 'Unknown parameter: %s'%param return res def fbbReset(self): """FBB RESET command. \see Flock of Birds Installation and Operation Guide, chapter 7: \em RS232 \em Commands """ self._write(FBB_RESET) def angles(self, addr=None): """ANGLES command. \param addr Bird address (0,1,2...). \see Flock of Birds Installation and Operation Guide, chapter 7: \em RS232 \em Commands """ ctx = self._switch_mode(ANGLES, addr) ctx.angles() def position(self, addr=None): """POSITION command. \param addr Bird address (0,1,2...). \see Flock of Birds Installation and Operation Guide, chapter 7: \em RS232 \em Commands """ ctx = self._switch_mode(POSITION, addr) ctx.position() def position_angles(self, addr=None): """POSITION/ANGLES command. \param addr Bird address (0,1,2...). \see Flock of Birds Installation and Operation Guide, chapter 7: \em RS232 \em Commands """ ctx = self._switch_mode(POSITION_ANGLES, addr) ctx.position_angles() def matrix(self, addr=None): """MATRIX command. \param addr Bird address (0,1,2...). \see Flock of Birds Installation and Operation Guide, chapter 7: \em RS232 \em Commands """ ctx = self._switch_mode(MATRIX, addr) ctx.matrix() def position_matrix(self, addr=None): """POSITION/MATRIX command. \param addr Bird address (0,1,2...). \see Flock of Birds Installation and Operation Guide, chapter 7: \em RS232 \em Commands """ ctx = self._switch_mode(POSITION_MATRIX, addr) ctx.position_matrix() def quaternion(self, addr=None): """QUATERNION command. \param addr Bird address (0,1,2...). \see Flock of Birds Installation and Operation Guide, chapter 7: \em RS232 \em Commands """ ctx = self._switch_mode(QUATERNION, addr) ctx.quaternion() def position_quaternion(self, addr=None): """POSITION/QUATERNION command. \param addr Bird address (0,1,2...). \see Flock of Birds Installation and Operation Guide, chapter 7: \em RS232 \em Commands """ ctx = self._switch_mode(POSITION_QUATERNION, addr) ctx.position_quaternion() def point(self, addr=None): """POINT command. \param addr Bird address (0,1,2...). \return A list of sensor values (the number of values depends on the output mode). \see Flock of Birds Installation and Operation Guide, chapter 7: \em RS232 \em Commands """ if addr==None: ctx = self.defaultctx else: self.rs232ToFbb(addr) ctx = self.birds[addr] self._write(POINT) while 1: record = self._read() if record=="": print "FOB: No feedback from the ERC" return if ord(record[0])&0x80: break print "FOB: Bit 7 not set" record += self._read(ctx.record_size-1) if len(record)!=ctx.record_size: print "Wrong number of bytes read (%d instead of %d)"%(len(record), ctx.record_size) return None # hexdump(res) res = ctx.decode(record) # print res return res def hemisphere(self, hemisphere, addr=None): """HEMISPHERE command. \param hemisphere The hemisphere to use (one of FORWARD, AFT, UPPER, LOWER, LEFT, RIGHT) \param addr Bird address (0,1,2...). \see Flock of Birds Installation and Operation Guide, chapter 7: \em RS232 \em Commands """ if addr!=None: self.rs232ToFbb(addr) self._write(HEMISPHERE+hemisphere) def run(self): """RUN command. \see Flock of Birds Installation and Operation Guide, chapter 7: \em RS232 \em Commands """ self._write(RUN) def sleep(self): """SLEEP command. \see Flock of Birds Installation and Operation Guide, chapter 7: \em RS232 \em Commands """ self._write(SLEEP) def metal(self, flag, data, addr=None): """METAL command. \param flag (\c int) Flag (see Flock of Birds manual) \param data (\c int) Data (see Flock of Birds manual) \param addr Bird address (0,1,2...). \see Flock of Birds Installation and Operation Guide, chapter 7: \em RS232 \em Commands """ if addr==None: ctx = self.defaultctx else: self.rs232ToFbb(addr) ctx = self.birds[addr] self._write(METAL+chr(flag)+chr(data)) if flag==0 and data==0: ctx.metal(False) else: ctx.metal(True) def metal_error(self, addr=None): """METAL ERROR command. \param addr Bird address (0,1,2...). \see Flock of Birds Installation and Operation Guide, chapter 7: \em RS232 \em Commands """ if addr==None: ctx = self.defaultctx else: self.rs232ToFbb(addr) ctx = self.birds[addr] self._write(METAL_ERROR) met = self._read(1) if len(met)!=1: print "Metal error byte nicht erhalten" return print "Metal error:",ord(met[0]) def fbbAutoConfig(self, numbirds): """FBB AUTO-CONFIGURATION command. Send the FBB AUTO-CONFIGURATION command (via CHANGE VALUE). \param numbirds (\c int) The number of birds to use (this is the parameter byte that the FBB AUTO-CONFIGURATION command expects) \see Flock of Birds Installation and Operation Guide, chapter 7: \em RS232 \em Commands \see Flock of Birds Installation and Operation Guide, chapter 8: \em Change \em Value / \em Examine \em Value """ time.sleep(1.0) self._write(CHANGE_VALUE+FBB_AUTO_CONFIGURATION+chr(numbirds)) time.sleep(1.0) # First element is not used (addr 0 does not exist) self.birds = [None] for i in range(numbirds): self.birds.append(BirdContext()) # res = self._read(2) # print len(res) def rs232ToFbb(self, addr): """Address a particular bird. Only for normal addressing mode! This method has to be called before the actual command is issued. \param addr (\c int) Bird address (1-14) """ self._write(chr(0xf0+addr)) def _switch_mode(self, mode, addr=None): """Generic mode switch command. mode is one of ANGLES, POSITION, MATRIX, QUATERNION, POSITION_ANGLES, POSITION_MATRIX, POSITION_QUATERNION. addr is the bird addr or None. The return value is the corresponding bird context. The calling function must still call the appropriate mode switch method on the context. \param mode Output mode \param addr Bird address (0,1,2...) \return A bird context class (BirdContext). """ if addr==None: ctx = self.defaultctx else: self.rs232ToFbb(addr) ctx = self.birds[addr] self._write(mode) return ctx def _write(self, s): """Send string s to the Bird.""" # print 70*"-" # print "Host->Bird:" # hexdump(s) self.ser.write(s) def _read(self, size=1, exc=False): """Receive size bytes of data from the bird. If the timeout value is exceeded an empty string is returned. \param size (\c int) Number of bytes to read. \param exc (\c bool) If True an exception is thrown when the number of read bytes does not match \return String containing the received bytes (or empty string). """ v = self.ser.read(size) if exc and len(v)!=size: raise DataError, 'Expected %d bytes from the bird, but got %d'%(size, len(v)) return v # def _decode(self, s): # values = [] # for i in range(self.num_words): # v = self._decodeWord(s[2*i:2*i+2]) # v*=self.scales[i] # v=v/32768.0 # values.append(v) # return values # def _decodeWord(self, s): # """Decode the word in string s. # s must contain exactly 2 bytes. # """ # ls = ord(s[0]) & 0x7f # ms = ord(s[1]) # if ms&0x80==0x80: # print "MSB bit7 nicht 0!" # v = (ms<<9) | (ls<<2) # if v<0x8000: # return v # else: # return v-0x10000 # def _readAll(self): # buf = "" # while 1: # s = self._read() # if s=="": # break # buf+=s # print 70*"-" # print "Bird->Host:" # hexdump(buf)
Python
import wx from ConfigfileReader import ConfigfileReader import time import fob ## ComportCheck helps determining the correct COM port for each connected sensor. class ComportCheck(wx.Frame): ## The constructor of the COM port check menu. # @param[in] parent The parent needed to create the Frame. # @param[in] id The ID needed to create the Frame. # @param[in] title The title of the menu window. # @param[in] configMain The configuration file instance. # @param[in] flockDict A (key,value) mapping with comport numbers as key and corresponding FoB objects as value. def __init__(self, parent, id, title, configMain, flockDict): wx.Frame.__init__(self, parent, id, title, wx.DefaultPosition, wx.Size(400, 300)) self.SetIcon(wx.Icon("Images/icon.ico", wx.BITMAP_TYPE_ICO, 32, 32)) ## ConfigFileReader instance. self.config = configMain ## A (key,value) mapping with sensor ID's as key and corresponding COM ports as value. self.flockCOM = self.CreateComportDict() ## A (key,value) mapping with comport numbers as key and corresponding FoB objects as value. self.flock = flockDict # Setup the GUI elements. panel = wx.Panel(self, -1) box = wx.BoxSizer(wx.HORIZONTAL) # Now continue with the normal construction of the dialog. sizer = wx.FlexGridSizer(len(self.flock),2,10,10) ## List of labels for the COM ports. self.comPortLabels = [] ## List of labels for the data read from the corresponding COM ports. self.comPortDataLabels = [] # Create labels, and add them to the FlexGridSizer sizer. for i in range(1, len(self.flock)+1): ## Boolean value indicating whether the XRC is connected. self.connected = True # The XRC. if i == 1: textLabel = wx.StaticText(panel,-1,"XRC COM Port %s"%self.flockCOM[i]) ## Indicates whether the XRC is running. self.xrcrunning = 0 # Are we connected? If so, can we get the XRC running? try: status = self.flock[i].examineValue(chr(0x24)) b = status[i] self.xrcrunning = b&0x40 except: self.connected = False # If the XRC is connected: if self.connected: # If the XRC is not running: if self.xrcrunning == 0: dataLabel = wx.StaticText(panel,-1,"XRC connected, but mapped on the wrong COM port.") # If the XRC is running: else: dataLabel = wx.StaticText(panel,-1,"XRC is running.") # if the XRC is not connected: else: dataLabel = wx.StaticText(panel,-1,"Not connected to any FoB hardware.") # One of the sensors. else: textLabel = wx.StaticText(panel,-1,"COM Port %s"%self.flockCOM[i]) dataLabel = wx.StaticText(panel,-1,"No Data") self.comPortLabels.append(textLabel) sizer.Add(textLabel, 0, wx.EXPAND, 10) self.comPortDataLabels.append(dataLabel) sizer.Add(dataLabel, 0, wx.EXPAND, 10) # Add the FlexGridSizer sizer to the BoxSizer box. box.Add(sizer, 1, wx.ALL | wx.EXPAND, 15) panel.SetSizer(box) self.Centre() self.Show(True) ## Boolean to break the timer loop on closing. self.interruptTimer = False # Set the Timer and its event handler. ## The timer responsible for refreshing the data labels. self.timer = wx.Timer(self) self.Bind(wx.EVT_TIMER, self.OnTimer, self.timer) self.Bind(wx.EVT_CLOSE, self.OnClose) self.timer.Start(50) ## Event handler triggered by timer. Sets the data labels of each comports. def OnTimer(self, event): if not self.interruptTimer and self.xrcrunning != 0: for i in range(2, len(self.flock)+1): pm = self.flock[i].point()[0:3] positionString = "(%s, %s, %s)" % (round(pm[0],0), round(pm[1],0), round(pm[2],0)) self.comPortDataLabels[i-1].SetLabel(positionString) ## Reads the sensor:comport mapping from the config file. # @return[dictionary] A (key,value) mapping with sensor ID's as key and corresponding COM ports as value. def CreateComportDict(self): comports = self.config.ReadComports() com_dict = {} for gsi, comport in comports.items(): comport = int(comport) gsi = int(gsi) if gsi != 1: com_dict[gsi] = comport com_dict[1] = int(comports['1']) return com_dict ## Stop the timer and destroy the window. def OnClose(self,event): self.interruptTimer = True self.Destroy()
Python
import wx import sys from vtk.wx.wxVTKRenderWindowInteractor import wxVTKRenderWindowInteractor from vtk import vtkInteractorStyleTrackballCamera import wx.lib.mixins.listctrl as listmix ## Subpanel of VisualizationPanel in which the playback of previously recorded movements can be played. # Functions such as pausing and stopping and importing a recording are possible as well. class PlaybackPanel(wx.Panel): ## The constructor of PlaybackPanel. GUI elements of the panel are setup here. # @param[in] parent The wx window parent (VisualizationState) of this panel. # @param[in] state PlaybackState instance attached to this panel. def __init__(self, parent, state): wx.Panel.__init__(self, parent) ## The wx window parent (VisualizationState) of this panel. self.parent = parent ## The name of this notebook panel. self.name = "Playback" ## PlaybackState instance attached to this panel. self.__state = state self.__state.panel = self ## Split window between the 3D model and the list. self.splitterWindow = wx.SplitterWindow(self, -1, style=wx.SP_3D|wx.SP_BORDER) recordingListWindow = wx.Panel(self.splitterWindow, -1) visWindow = wx.Panel(self.splitterWindow, -1) ## wxVTKRenderWindowInteractor used to show the 3D model. self.widget = wxVTKRenderWindowInteractor(visWindow, -1) self.widget.SetInteractorStyle(vtkInteractorStyleTrackballCamera()) self.widget.GetRenderWindow().AddRenderer(self.__state.ren) if self.__state.main.Smooth3DModel: self.widget.GetRenderWindow().SetAAFrames(3) recordingListStaticBox = wx.StaticBox(recordingListWindow, -1, "Recordings") ## Rewind by one frame. self.backwardButton = wx.BitmapButton(visWindow, -1, wx.Bitmap("Images/Backward.png", wx.BITMAP_TYPE_PNG)) ## The time slider indicating progress of the playback. self.slider = wx.Slider(visWindow, -1, 0, 0, 0) ## Forward by one frame. self.forwardButton = wx.BitmapButton(visWindow, -1, wx.Bitmap("Images/Forward.png", wx.BITMAP_TYPE_PNG)) ## Start playback. self.playPauseButton = wx.BitmapButton(visWindow, -1, wx.Bitmap("Images/Play.png", wx.BITMAP_TYPE_PNG)) spacing = wx.Panel(visWindow, -1) ## Stop playback. self.stopButton = wx.BitmapButton(visWindow, -1, wx.Bitmap("Images/Stop.png", wx.BITMAP_TYPE_PNG)) ## Reset Camera button. self.resetCamButton = wx.Button(visWindow, -1, "Reset Camera") ## The list containing all imported/newly created recording. self.recordingList = wx.ListBox(recordingListWindow, style=wx.LB_HSCROLL) ## Delete a recording from the list. self.deleteButton = wx.Button(recordingListWindow, -1, "Delete") ## Rename a recording in the list. self.renameButton = wx.Button(recordingListWindow, -1, "Rename") ## Import a recording to the list. self.importButton = wx.Button(recordingListWindow, -1, "Import") # Set properties. self.widget.SetSize(self.widget.GetBestSize()) self.backwardButton.SetMinSize((75, 25)) self.forwardButton.SetMinSize((75, 25)) self.playPauseButton.SetMinSize((75, 23)) self.stopButton.SetMinSize((75, 25)) # Set sizers. recordingSizer = wx.BoxSizer(wx.HORIZONTAL) recordingListSizer = wx.BoxSizer(wx.VERTICAL) recordingListStaticBoxSizer = wx.StaticBoxSizer(recordingListStaticBox, wx.HORIZONTAL) listButtonSizer = wx.FlexGridSizer(4,1,10,0) visGrid = wx.FlexGridSizer(3, 1, 10, 0) player_grid_sizer = wx.FlexGridSizer(2, 4, 10, 20) visGrid.Add(self.widget, 0, wx.ALL|wx.EXPAND, 10) player_grid_sizer.Add(self.backwardButton, 0, wx.LEFT, 10) player_grid_sizer.Add(self.slider, 0, wx.EXPAND, 0) player_grid_sizer.Add(self.forwardButton, 0, wx.RIGHT|wx.ALIGN_RIGHT, 10) player_grid_sizer.Add(self.playPauseButton, 0, wx.LEFT|wx.BOTTOM, 10) player_grid_sizer.Add(spacing, 0, wx.EXPAND, 0) player_grid_sizer.Add(self.stopButton, 0, wx.RIGHT|wx.ALIGN_RIGHT, 10) player_grid_sizer.Add(self.resetCamButton, 0, wx.LEFT|wx.BOTTOM, 10) player_grid_sizer.AddGrowableCol(1) visGrid.Add(player_grid_sizer, 1, wx.EXPAND, 0) visWindow.SetSizer(visGrid) visGrid.AddGrowableRow(0) visGrid.AddGrowableCol(0) listButtonSizer.Add(self.recordingList, 1, wx.EXPAND, 0) listButtonSizer.Add(self.renameButton, 1, wx.EXPAND) listButtonSizer.Add(self.deleteButton, 1, wx.EXPAND) listButtonSizer.Add(self.importButton, 1, wx.EXPAND) listButtonSizer.AddGrowableRow(0) listButtonSizer.AddGrowableCol(0) recordingListStaticBoxSizer.Add(listButtonSizer, 1, wx.ALL|wx.EXPAND, 10) recordingListSizer.Add(recordingListStaticBoxSizer, 1, wx.ALL|wx.EXPAND, 10) recordingListWindow.SetSizer(recordingListSizer) self.splitterWindow.SplitVertically(visWindow, recordingListWindow, 624) self.splitterWindow.SetMinimumPaneSize(5) recordingSizer.Add(self.splitterWindow, 1, wx.EXPAND, 0) self.SetSizer(recordingSizer) self.Layout() # Bind events. self.Bind(wx.EVT_BUTTON, self.OnTogglePlayPause, self.playPauseButton) self.Bind(wx.EVT_BUTTON, self.__state.OnStop, self.stopButton) self.Bind(wx.EVT_BUTTON, self.__state.OnBackward, self.backwardButton) self.Bind(wx.EVT_BUTTON, self.__state.OnForward, self.forwardButton) self.Bind(wx.EVT_BUTTON, self.__state.OnDelete, self.deleteButton) self.Bind(wx.EVT_BUTTON, self.__state.OnRename, self.renameButton) self.Bind(wx.EVT_BUTTON, self.__state.OnImport, self.importButton) self.Bind(wx.EVT_BUTTON, self.OnResetCam, self.resetCamButton) self.Bind(wx.EVT_SLIDER, self.__state.OnSlide, self.slider) self.Bind(wx.EVT_LISTBOX, self.__state.OnItemSelected, self.recordingList) self.Bind(wx.EVT_SIZE, self.OnSize) self.DisableFunctions() ## Sets the new tracking bar position so visual feedback during dragging will represent that change that will actually take place. def OnSize(self, event): self.splitterWindow.SetSashPosition(event.GetSize()[0]-250) self.Layout() ## Event Handler for clicking the play/pause button. def OnTogglePlayPause(self, event): if self.__state.selectedRecording != None: if self.__state.PLAYING: self.playPauseButton.SetBitmapLabel(wx.Bitmap(self.__state.main.config.root+"\\Images\\Play.png", wx.BITMAP_TYPE_PNG)) else: self.playPauseButton.SetBitmapLabel(wx.Bitmap(self.__state.main.config.root+"\\Images\\Pause.png", wx.BITMAP_TYPE_PNG)) self.__state.OnTogglePlayPause() ## Disables all buttons. def DisableFunctions(self): self.playPauseButton.Disable() self.stopButton.Disable() self.backwardButton.Disable() self.forwardButton.Disable() self.deleteButton.Disable() self.renameButton.Disable() self.slider.Disable() self.resetCamButton.Disable() ## Enables all buttons. def EnableFunctions(self): self.playPauseButton.Enable() self.stopButton.Enable() self.backwardButton.Enable() self.forwardButton.Enable() self.deleteButton.Enable() self.renameButton.Enable() self.slider.Enable() self.resetCamButton.Enable() ## Resets the camera. def OnResetCam(self, event): self.__state.parent.ResetCamera(self.__state) self.widget.Render()
Python
import wx ## The GH-Joints are estimated in this panel. There are two methods available to calculate the GH-Joints, regression or movement. class GHJPanel(wx.Panel): ## The contructor of GHJPanel. GUI elements of the panel are setup here. # @param[in] parent The wx window parent (notebook) of this panel. # @param[in] state GHJState instance attached to this panel. def __init__(self, parent, state): wx.Panel.__init__(self, parent) ## The wx window parent (notebook) of this panel. self.parent = parent ## GHJState instance attached to this panel. self.state = state ## The name of this notebook panel. self.name = "GH-Joint" helptxt = "Select the method to be used for calculating the " \ "location of the glenohumeral joint.\n\n" \ "The regression method uses the location of the bony landmarks " \ "of the scapula, therefore no further action is needed.\n\n" \ "The movement method requires the patient to move his/her arm in a " \ "circular movement to calculate the centre of rotation." self.helpSizer_staticbox = wx.StaticBox(self, -1, "Help") self.methodSizer_staticbox = wx.StaticBox(self, -1, "Select Method") self.radio_button_regression = wx.RadioButton(self, -1, "Regression") self.radio_button_movement = wx.RadioButton(self, -1, "Movement") self.static_line_select_method = wx.StaticLine(self, -1) ## "Start/Stop Define Left". self.defineButtonL = wx.Button(self, -1, "Start/Stop Define Left") ## "Start/Stop Define Right". self.defineButtonR = wx.Button(self, -1, "Start/Stop Define Right") ## "Reset Left". self.defineButtonLReset = wx.Button(self, -1, "Reset Left") ## "Reset Right". self.defineButtonRReset = wx.Button(self, -1, "Reset Right") ## Upper gauge. self.gauge_left = wx.Gauge(self, -1, 50) ## Lower gauge. self.gauge_right = wx.Gauge(self, -1, 50) self.label_help = wx.StaticText(self, -1, helptxt) self.panel_1 = wx.Panel(self, -1) self.panel_2 = wx.Panel(self, -1) self.panel_3 = wx.Panel(self, -1) self.panel_4 = wx.Panel(self, -1) self.panel_5 = wx.Panel(self, -1) self.panel_6 = wx.Panel(self, -1) self.static_line_1 = wx.StaticLine(self, -1) self.static_line_2 = wx.StaticLine(self, -1) self.static_line_3 = wx.StaticLine(self, -1) ## Goes to the previous panel. self.ghBackButton = wx.Button(self, -1, "< Back") ## Goes to the next panel. self.ghFinishButton = wx.Button(self, -1, "Finish") ## Timer associated with gauge_left. self.timerLeft = wx.Timer(self, 1) ## Timer associated with gauge_right. self.timerRight = wx.Timer(self, 2) ## Boolean indicating whether the left GH-Joint has been calculated. self.leftCalculated = False ## Boolean indicating whether the right GH-Joint has been calculated. self.rightCalculated = False ## Makes sure gauge_left stops running when defineButtonL is pressed for the second time. self.leftCalled = 0 ## Makes sure gauge_right stops running when defineButtonR is pressed for the second time. self.rightCalled = 0 ## Process indicator for the gauges. self.count = 0 self.__BindEvents() self.__SetProperties() self.__DoLayout() self.OnRadioButton(None) ## Sets several properties for the panel. def __SetProperties(self): self.defineButtonL.Disable() self.defineButtonR.Disable() self.defineButtonL.Enable() self.defineButtonR.Enable() self.gauge_left.SetMinSize((300, 20)) self.gauge_right.SetMinSize((300, 20)) self.label_help.SetMinSize((150, 254)) self.radio_button_regression.SetValue(1) ## Sets layout for the panel elements. def __DoLayout(self): grid_sizer_menu_top = wx.FlexGridSizer(4, 3, 0, 0) grid_sizer_menu_bottom = wx.FlexGridSizer(1, 2, 0, 10) ghHelp = wx.StaticBoxSizer(self.helpSizer_staticbox, wx.HORIZONTAL) ghSizer = wx.StaticBoxSizer(self.methodSizer_staticbox, wx.HORIZONTAL) grid_sizer_select_method = wx.FlexGridSizer(4, 1, 0, 0) grid_sizer_select_method.Add(self.radio_button_regression, 0, wx.BOTTOM, 10) grid_sizer_select_method.Add(self.radio_button_movement, 0, wx.BOTTOM, 5) grid_sizer_select_method.Add(self.static_line_select_method, 0, wx.BOTTOM|wx.EXPAND, 10) grid_sizer_select_method_sub = wx.FlexGridSizer(2, 3, 0, 0) grid_sizer_select_method_sub.Add(self.defineButtonL, 0, wx.RIGHT, 10) grid_sizer_select_method_sub.Add(self.defineButtonLReset, 0, wx.RIGHT, 10) grid_sizer_select_method_sub.Add(self.gauge_left, 0, wx.LEFT, 0) grid_sizer_select_method_sub.Add(self.defineButtonR, 0, wx.RIGHT, 10) grid_sizer_select_method_sub.Add(self.defineButtonRReset, 0, wx.RIGHT, 10) grid_sizer_select_method_sub.Add(self.gauge_right, 0, wx.LEFT, 0) grid_sizer_select_method_sub.AddGrowableCol(1) grid_sizer_select_method.Add(grid_sizer_select_method_sub, 1, wx.EXPAND, 0) ghSizer.Add(grid_sizer_select_method, 1, wx.ALL|wx.EXPAND, 10) ghHelp.Add(self.label_help, 0, wx.ALL, 10) grid_sizer_menu_top.Add(ghSizer, 1, wx.ALL, 10) grid_sizer_menu_top.Add(self.panel_1, 1, wx.EXPAND, 0) grid_sizer_menu_top.Add(ghHelp, 1, wx.ALL|wx.ALIGN_RIGHT, 10) grid_sizer_menu_top.Add(self.panel_4, 1, wx.EXPAND, 0) grid_sizer_menu_top.Add(self.panel_6, 1, wx.EXPAND, 0) grid_sizer_menu_top.Add(self.panel_2, 1, wx.EXPAND, 0) grid_sizer_menu_top.Add(self.static_line_1, 0, wx.EXPAND, 0) grid_sizer_menu_top.Add(self.static_line_2, 0, wx.EXPAND, 0) grid_sizer_menu_top.Add(self.static_line_3, 0, wx.EXPAND, 0) grid_sizer_menu_top.Add(self.panel_3, 1, wx.EXPAND, 0) grid_sizer_menu_top.Add(self.panel_5, 1, wx.EXPAND, 0) grid_sizer_menu_top.Add(grid_sizer_menu_bottom, 1, wx.TOP|wx.BOTTOM|wx.ALIGN_RIGHT|wx.ALIGN_BOTTOM, 5) grid_sizer_menu_top.AddGrowableRow(1) grid_sizer_menu_top.AddGrowableCol(2) grid_sizer_menu_bottom.Add(self.ghBackButton, 0, wx.ALIGN_RIGHT, 0) grid_sizer_menu_bottom.Add(self.ghFinishButton, 0, wx.RIGHT|wx.ALIGN_RIGHT, 10) self.SetSizer(grid_sizer_menu_top) grid_sizer_menu_top.Fit(self) self.Layout() ## Binds the panel elements to event handlers. def __BindEvents(self): self.Bind(wx.EVT_RADIOBUTTON, self.OnRadioButton, id=self.radio_button_movement.GetId()) self.Bind(wx.EVT_RADIOBUTTON, self.OnRadioButton, id=self.radio_button_regression.GetId()) self.Bind(wx.EVT_BUTTON, self.OnDefineLeft, id=self.defineButtonL.GetId()) self.Bind(wx.EVT_BUTTON, self.OnDefineRight, id=self.defineButtonR.GetId()) self.Bind(wx.EVT_BUTTON, self.OnDefineLeftReset, id=self.defineButtonLReset.GetId()) self.Bind(wx.EVT_BUTTON, self.OnDefineRightReset, id=self.defineButtonRReset.GetId()) self.Bind(wx.EVT_TIMER, self.OnTimerLeft, self.timerLeft) self.Bind(wx.EVT_TIMER, self.OnTimerRight, self.timerRight) self.Bind(wx.EVT_BUTTON, self.OnBack, self.ghBackButton) self.Bind(wx.EVT_BUTTON, self.OnNext, self.ghFinishButton) ## Disables or enables the define buttons depending on which radiobutton is enabled. def OnRadioButton(self, event): self.EventWhileMeasuring() if self.radio_button_movement.GetValue(): msg = "The movement method can not be used in this program version, no GH-Joints will be calculated." dlg = wx.MessageDialog(self.state.main.gui, msg, 'Warning', wx.OK | wx.NO_DEFAULT | wx.ICON_EXCLAMATION) dlg.ShowModal() if not self.leftCalculated: self.defineButtonL.Enable() self.defineButtonLReset.Disable() else: self.defineButtonL.Disable() self.defineButtonLReset.Enable() if not self.rightCalculated: self.defineButtonR.Enable() self.defineButtonRReset.Disable() else: self.defineButtonR.Disable() self.defineButtonRReset.Enable() else: self.defineButtonL.Disable() self.defineButtonR.Disable() self.defineButtonLReset.Disable() self.defineButtonRReset.Disable() ## Event handler for the left GH-Joint Define button. def OnDefineLeft(self, event): self.leftCalled += 1 # Disable the define and reset button of the right GH-Joint. self.defineButtonR.Disable() self.defineButtonRReset.Disable() # If the define button has been pressed for the second time, the user indicates the measurement is complete. if self.leftCalled == 2: self.timerLeft.Stop() self.gauge_left.SetValue(50) self.leftCalculated = True # Disable the define button, and enable the reset button. self.defineButtonL.Disable() self.defineButtonLReset.Enable() # Reset the value. self.leftCalled = 0 self.count = 0 # Check whether the right Joint has been measurement is completed, and set the dialog message and the buttons according to the situation. if self.rightCalculated: msg = "Left GH-Joint calculation is complete. All Joints have now been calculated. You can now proceed to visualization." self.defineButtonRReset.Enable() else: msg = "Left GH-Joint calculation is completed. You may now calculate the right GH-Joint or proceed to visualization." self.defineButtonR.Enable() dlg = wx.MessageDialog(self, msg, 'Measurement completed', wx.OK | wx.ICON_INFORMATION) dlg.ShowModal() return self.timerLeft.Start(100) ## Event handler for the right GH-Joint Define button. def OnDefineRight(self, event): self.rightCalled += 1 # Disable the define and reset button of the left GH-Joint self.defineButtonL.Disable() self.defineButtonLReset.Disable() # If the define button has been pressed for the second time, the user indicates the measurement is complete. if self.rightCalled == 2: self.timerRight.Stop() self.gauge_right.SetValue(50) self.rightCalculated = True # Disable the define button, and enable the reset button. self.defineButtonR.Disable() self.defineButtonRReset.Enable() # Reset the value. self.rightCalled = 0 self.count = 0 # Check whether the right GH-Joint has been measurement, and set the dialog message and the buttons according to the situation. if self.leftCalculated: msg = "Right GH-Joint calculation is complete. All Joints have now been calculated. You can now proceed to the visualization." self.defineButtonLReset.Enable() else: msg = "Right GH-Joint calculation is complete. You may now calculate the left GH-Joint or proceed to visualization." self.defineButtonL.Enable() dlg = wx.MessageDialog(self, msg, 'Measurement completed', wx.OK | wx.ICON_INFORMATION) dlg.ShowModal() return self.timerRight.Start(100) ## Event handler for the Define Left Reset Button, resets the measurements. def OnDefineLeftReset(self, event): msg = "Are you sure you want to reset the left GH-Joint calculation?" dlg = wx.MessageDialog(self, msg, 'Confirm deletion', wx.YES_NO | wx.ICON_EXCLAMATION) if(dlg.ShowModal() == wx.ID_YES): self.leftCalculated = False self.defineButtonL.Enable() self.defineButtonLReset.Disable() self.gauge_left.SetValue(0) dlg.Destroy() ## Event handler for the Define Right Reset Button, resets the measurements. def OnDefineRightReset(self, event): msg = "Are you sure you want to reset the right GH-Joint calculation?" dlg = wx.MessageDialog(self, msg, 'Confirm deletion', wx.YES_NO | wx.ICON_EXCLAMATION) if(dlg.ShowModal() == wx.ID_YES): self.rightCalculated = False self.defineButtonR.Enable() self.defineButtonRReset.Disable() self.gauge_right.SetValue(0) dlg.Destroy() ## Event handler for the Timer belonging to the left GH-Joint gauge. def OnTimerLeft(self, event): self.count = self.count +1 self.gauge_left.SetValue(self.count) if self.count == 50: self.count = 0 ## Event handler for the Timer belonging to the right GH-Joint gauge. def OnTimerRight(self, event): self.count = self.count +1 self.gauge_right.SetValue(self.count) if self.count == 50: self.count = 0 ## Panel navigation, goes back in the panel navigation to the previous state. # @param[in] new The tab index to go to. def OnBack(self, event, new = 1): self.parent.ChangeSelection(new) self.EventWhileMeasuring() ## Handles events when the finished button is pressed. # @param[in] new The tab index to go to. # @return[boolean] False when navigation to following panel is somehow cancelled, else True. def OnNext(self, event, new = 3): if self.radio_button_movement.GetValue(): self.state.CalcMovementMethod() else: self.state.CalcRegressionMethod() NAVIGATED_TO_NEXT = False self.parent.ChangeSelection(new) self.EventWhileMeasuring() self.state.main.states.visualization.OnTogglePlayPause() NAVIGATED_TO_NEXT = True return NAVIGATED_TO_NEXT ## If an event is triggered while measuring, this method will provide a dialogue on whether or not the event should proceed. def EventWhileMeasuring(self): if( self.leftCalled or self.rightCalled): msg = "You were in the process of calculating a GH-Joint. This process has now been cancelled." dlg = wx.MessageDialog(self, msg, 'Confirm action', wx.OK | wx.ICON_EXCLAMATION) if(dlg.ShowModal() == wx.ID_OK): if self.leftCalled == 1: self.gauge_left.SetValue(0) self.timerLeft.Stop() self.leftCalled = 0 if self.rightCalculated: self.defineButtonRReset.Enable() else: self.defineButtonR.Enable() if self.rightCalled == 1: self.gauge_right.SetValue(0) self.timerRight.Stop() self.rightCalled = 0 if self.leftCalculated: self.defineButtonLReset.Enable() else: self.defineButtonL.Enable() dlg.Destroy()
Python
from numpy import mean, std, hstack, size, matrix, transpose from Sensor import Sensor import wx import os, sys ## BLState contains the functionality behind the BLPanel. class BLState: ## The constructor of BLState. # @param[in] main Main wx.App derived instance. def __init__(self, main): ## Main wx.App derived instance. self.main = main ## A matrix with boolean values, used to save the results of the checks, so they can be used for the color representation of the measurements. self.colours = [[] for i in range(0, len(self.main.bonyLandmarks) - len(self.main.GHJoints))] ## Boolean value indicating whether a bony landmark has been checked or not. self.BL_CHECKED = False ## Rulebase used to validate bony landmark measurements. self.ruleBase = self.main.config.ReadBLRulebase() ## Descriptions belonging to the bony landmarks. self.descriptions = self.main.config.ReadDescriptions() ## Returns the names of the bony landmarks as a list. # @return[array] The list of bony landmarks. def GetBonyLandmarkList(self): blList = [] for i in range(0, len(self.main.bonyLandmarks)-len(self.main.GHJoints)): blList.append(self.main.bonyLandmarks[i].name) return blList ## Calculates a matrix of relative bl vecs. # @param[in] index The number ID of the bony landmark. # @return[matrix] The matrix containing the bl vecs. def __GetMeasurements(self, index): measurements = matrix("") if self.main.driver.imSensors[index] != []: for j in range(0, len(self.main.driver.imSensors[index])): blvec = self.main.driver.GetBLRelativePosition(self.main.driver.stylus[index][j],self.main.driver.imSensors[index][j]) if j==0: measurements = blvec else: measurements = hstack((measurements, blvec)) return measurements ## Checks the five measurements of the bony landmark with index as ID. # Checks if the latest measurements are not substantially different compared to the # earlier measurements of the bony landmark. The average of measurements is compared to # the new meausurement. # @param[in] index The number ID of the bony landmark being checked. def CheckSelf(self, index): measurements = self.__GetMeasurements(index) if size(measurements,1) > 1: checkList = [[],[],[]] for axis in range(0, 3): average = measurements[axis, :].mean() error = 1.5 for i in range(0, size(measurements,1)): check = abs(measurements[axis,i] - average) < error checkList[axis].append(check) result = [] for i in range(0, size(measurements,1)): result.append(checkList[0][i] and checkList[1][i] and checkList[2][i]) self.colours[index] = result else: self.colours[index] = [True]*size(measurements,1) ## Checks all global positions on the bony landmarks using the rulebase. # @return[boolean] True if all 24 bony landmarks are true, else False. def CheckBonyLandmarks(self): # If the bony landmarks are not correct, there is no need to calculate the BLVecs, etc. and there will be no relativepositions calculated. for bools in self.colours: if len(bools) == 0: return False for bool in bools: if bool == False: return False # Then calculate the global positions using these relative positions. globalPositions_dict = {} # For every bony landmark except the GH-Joints. for bl in range(0,len(self.main.bonyLandmarks)- len(self.main.GHJoints)): relativeSensor = None bl = self.main.bonyLandmarks[bl] # Find the sensor that is connected to the bony landmark. for sensor in self.main.sensors: if sensor.ID == bl.sensorID: relativeSensor = sensor if bl.relativePosition.all() == 0: globalPositions_dict[bl.ID] = bl.relativePosition else: globalPositions_dict[bl.ID] = self.main.driver.RelativeToGlobal(bl.relativePosition, relativeSensor.position, relativeSensor.rotation) # Check all rules in the rulebase using these global positions. result_dict = {} for resultKey in globalPositions_dict.keys(): result_dict[resultKey] = True for rule in self.ruleBase: result_dict[rule.ID1] = result_dict[rule.ID1] and rule.IsTrue(globalPositions_dict) result_dict[rule.ID2] = result_dict[rule.ID2] and rule.IsTrue(globalPositions_dict) # Acquire a dictionary list in which the keys are the bony landmark ID's and the items are their corresponding index in a lists. # This is essentially mapping to make the code more generic. blDict = self.main.GetBonyLandmarkDict(False) # If the rule base returned a false value, make all five measurements orange by setting colours to false accordingly. for blKey in result_dict.keys(): if result_dict[blKey] == False: # colours is a list, and works with the index instead of a key, so the index of the blKey is acquired through blDict. self.colours[blDict[blKey]] = [False for foo in range(0, len(self.colours[blDict[blKey]]))] # Finally returns True if ALL bony landmarks are True, otherwise False. for itemBool in result_dict.items(): if itemBool == False: return False return True def StoreRawBLVecs(self): rawoutputlist = [] for k in range(0, len(self.main.driver.imSensors)): imSensorItem = self.main.driver.imSensors[k] imStylusItem = self.main.driver.stylus[k] for i in range(0, len(imSensorItem)): # 5 stuks, als het goed is imStylus = imStylusItem[i] sensorstring = imStylus.ID.split('_') sample = [] for j in imStylus.rawPosition: sample.append(j) for j in imStylus.rawRotation: sample.append(j) rawoutputlist.append(sensorstring[1] + ' %.2f %.2f %.2f \r\n %.2f %.2f %.2f \r\n %.2f %.2f %.2f \r\n %.2f %.2f %.2f \r\n\r\n' % (sample[0], sample[1], sample[2], sample[3], sample[4],sample[5], sample[6], sample[7], sample[8], sample[9],sample[10],sample[11])) imSensor = imSensorItem[i] sensorstring = imSensor.ID.split('_') sample = [] for j in imSensor.rawPosition: sample.append(j) for j in imSensor.rawRotation: sample.append(j) rawoutputlist.append(sensorstring[1] + ' %.2f %.2f %.2f \r\n %.2f %.2f %.2f \r\n %.2f %.2f %.2f \r\n %.2f %.2f %.2f \r\n\r\n' % (sample[0], sample[1], sample[2], sample[3], sample[4],sample[5], sample[6], sample[7], sample[8], sample[9],sample[10],sample[11])) dlg = wx.FileDialog(self.main.gui, message="Save RAW bonylandmark vectors", defaultDir=os.getcwd(), defaultFile="", wildcard="FoB file (*.txt)|*.txt", style=wx.SAVE | wx.CHANGE_DIR | wx.OVERWRITE_PROMPT) if dlg.ShowModal() == wx.ID_OK: filename = dlg.GetPath() fileWriter = open(filename, 'w') for i in rawoutputlist: fileWriter.write(i) fileWriter.close() self.main.driver.rawoutputlist = [] ## Resets the measurements for a bony landmark. # @param[in] index The number ID of the bony landmark that has to be reset. def ResetBL(self, index): self.BL_CHECKED = False self.main.bonyLandmarks[index].relativePosition = matrix("[0.0; 0.0; 0.0]") self.colours[index] = [] self.main.driver.imSensors[index] = [] ## Calculates and averages vector of the relative bony landmark measurement and sets it in the main bony landmark. # @param[in] index The number ID of the bony landmark. def setRelativeBL(self, index): self.main.bonyLandmarks[index].relativePosition = self.__GetMeasurements(index).mean(1)
Python
import wx from AddBLFrame import AddBLFrame from vtk.wx.wxVTKRenderWindowInteractor import wxVTKRenderWindowInteractor from vtk import vtkInteractorStyleTrackballCamera, vtkRenderer, vtkCellPicker ## AddBonyLandmark contains the functionality behind the AddBLFrame. class AddBonyLandmark: ## The constructor of AddBonyLandmark. Here, the 3D model and Cellpicker are loaded. # @param[in] parent The wx window parent (notebook) of this panel. # @param[in] gui GUI instance. def __init__(self,parent,gui): ## GUI instance. self.gui = gui ## Instance of the AddBlFrame class. self._addblframe = AddBLFrame(gui,parent) self._addblframe.Show() self._addblframe.rwi.SetInteractorStyle(vtkInteractorStyleTrackballCamera()) ## Flag that indicates whether the program is recording. self.RECORDING = False # Initialize VTK. self.gui.main.states.visualization.InitiateVTK(self) # Initialize 3D model, disables the sensor and bony landmark spheres by passing 0 values. self.gui.main.states.visualization.SetRenderActors(self,0,0,0) # Set the 3D model parts to visible. for j in range(0, len(self.actorList)): self.actorList[j].VisibilityOn() # Position the 3D model correctly. self.ren.ResetCamera() self.ren.GetActiveCamera().Azimuth(90) self.ren.GetActiveCamera().Roll(180) self._addblframe.rwi.GetRenderWindow().AddRenderer(self.ren) self._addblframe.rwi.GetRenderWindow().SetAAFrames(3) ## The vtkCellPicker used to get 3D coordinates. self.cellpicker = vtkCellPicker() self.cellpicker.SetTolerance(0.005) self.cellpicker.InitializePickList() # Add props to the PickList. for j in range(0, len(self.actorList)): self.cellpicker.AddPickList(self.actorList[j]) self.cellpicker.PickFromListOn() ## The event listening for right mouseclicks. self.rbpe = self._addblframe.rwi.AddObserver("RightButtonPressEvent", self.PointPicked, 1.0) self.__BindEvents() ## Binds items of the panel to event handlers. def __BindEvents(self): self._addblframe.Bind(wx.EVT_BUTTON, self.OnHelp, self._addblframe.help_button) self._addblframe.Bind(wx.EVT_BUTTON, self.OnFinish, self._addblframe.finish_button) self._addblframe.Bind(wx.EVT_CLOSE, self.OnClose) ## Picks a point on the 3D model and adds it to the list when the right mouse button is pressed. # @param[in] object_binding Automatically passed parameter. # @param[in] event_name Automatically passed parameter. def PointPicked(self, object_binding, event_name): x,y = object_binding.GetEventPosition() self.cellpicker.Pick(x,y,0.0,self.ren) ## The point clicked on by the mouse. self.pickPos = self.cellpicker.GetPickPosition() result = "".join(['%.1f ' % round(self.pickPos[i], 1) for i in range (0,3)]) self._addblframe.bony_landmarks_listctrl.InsertStringItem(0, result) ## Displays a help dialog for the user. def OnHelp(self,event): msg = "To pick a coordinate, right click on the model at the desired position. The coordinate will then be added to the list.\nYou can rotate the model by clicking and holding the left mouse button. Zooming in and out of the model is possible using the scroll wheel.\nWhen all the desired positions have been picked, click on the Finish button." dlg = wx.MessageDialog(self._addblframe, msg, 'Picking a position', wx.OK | wx.ICON_INFORMATION) dlg.ShowModal() ## Copies the 3D coordinates to the clipboard and closes the AddBonyLandmark frame. def OnFinish(self,event): result = "".join([self._addblframe.bony_landmarks_listctrl.GetItemText(i)+"\r\n" for i in range(self._addblframe.bony_landmarks_listctrl.GetItemCount())]) string = wx.TextDataObject(result) wx.TheClipboard.Open() wx.TheClipboard.SetData(string) wx.TheClipboard.Close() msg = "The new coordinates have been copied to the clipboard.\nYou may now add the name, description, rule and picture using the configuration file." dlg = wx.MessageDialog(self._addblframe, msg, 'Measurement completed', wx.OK | wx.ICON_INFORMATION) dlg.ShowModal() self._addblframe.rwi.RemoveObserver(self.rbpe) self._addblframe.Close() ## Overwrites the standard OnClose method, this is needed to prevent the vtkRenderer from getting destroyed. def OnClose(self,event): try: if self.gui.notebook.GetCurrentPage().name == "Visualization": if self.gui.notebook.GetCurrentPage().visNotebook.GetCurrentPage().name == "Playback": self._addblframe.rwi.Destroy() self.gui.main.states.visualization.InitiateVTK(self) event.Skip() else: self.gui.main.states.visualization.InitiateVTK(self) event.Skip() else: event.Skip() # Sometimes a wglMakeCurrent error occurs, preventing the frame from being closed. except: self._addblframe.Destroy()
Python
## Used to check the truth of the rules from the rulebase. # These rules are used to check coordinates of the bony landmarks and sensors relative to eachother. class Rule: ## The constructor of Rule. def __init__(self, axis, ID1, ID2, ruleType): ## The x, y or z axis. self.axis = axis ## The first ID (bony landmark or sensor) to compare with ID2. self.ID1 = ID1 ## The second ID (bony landmark or sensor) to compare with ID1. self.ID2 = ID2 ## Bony landmark or sensor. self.ruleType = ruleType ## Compares two objects and determines whether the positions of the measured objects are correct. # @param[in] positions Either sensor instances or the globalPositions from the bony landmarks. # @return[boolean] True if the measurement is correct, else False. def IsTrue(self, positions): ## Either sensor instances or the globalPositions from the bony landmarks. self.positions = positions # Order z x y! if self.axis=="z": return self.__GetPosition(self.ID1, 0) > self.__GetPosition(self.ID2, 0) elif self.axis=="x": return self.__GetPosition(self.ID1, 1) > self.__GetPosition(self.ID2, 1) elif self.axis=="y": return self.__GetPosition(self.ID1, 2) > self.__GetPosition(self.ID2, 2) else: print "error in Rule: invalid axis" return False ## Returns the position of either a sensor or bony landmark depending on the ruletype. # @param[in] ID A bony landmark or sensor ID. # @param[in] axis The x, y or z axis. # @return[array] The position belonging to this axis. def __GetPosition(self, ID, axis): return self.positions[ID][axis][0,0]
Python
from DriverInterface import DriverInterface from math import * from numpy import * from numpy.linalg import * from BonyLandmark import BonyLandmark from Sensor import Sensor import time import fob import time import wx import threading ## Handles communication with the Flock of Birds system through the serial port. class FoBDriver(DriverInterface): ## The constructor of FoBDriver. You may only call this method if you inherit from DriverInterface. # @param[in] main Main wx.App derived instance. # @param[in] numbirds The number of birds connected to the XRC including the XRC itself. def __init__(self, main, numbirds = 10, fobrunning = True): if not isinstance(self, DriverInterface): raise TypeError("FoBDriver.__init__ requires DriverInterface.") ## Opens a workfile to write the raw data to. #self.fileWriter = open('workfile.txt', 'w') ## Main wx.App derived instance. self.main = main self.rawoutputlist = [] ## Indicates whether the FoB system has started successfully. self.fobrunning = fobrunning ## Make the COM ports when fobrunning is set to true. if self.fobrunning: ## A (key,value) mapping with comport numbers as key and corresponding FoB objects as value. self.flock = self.SetComports() ## The list with five position measurements of each sensor connected to the corresponding bony landmarks. self.imSensors = [[] for i in range(len(self.main.bonyLandmarks) - len(self.main.GHJoints))] ## The list with five position measurements of each bony landmark as measured with the stylus. # Each entry in the list represents a bony landmark. self.stylus = [[] for i in range(len(self.main.bonyLandmarks) - len(self.main.GHJoints))] stylfile = main.prefReader.stylusFile try: stylusData = open(stylfile,'r').read() except: msg = "An error ocurred while opening %s." % stylfile dlg = wx.MessageDialog(self.main.gui, msg, 'Warning', wx.OK | wx.NO_DEFAULT | wx.ICON_EXCLAMATION) dlg.ShowModal() ## The length of the stylus. self.__stylusLength = transpose(matrix("["+stylusData+"]"))/10 ## Reads the sensor:comport mapping from the config file and creates FoB objects. # @return[dictionary] A (key,value) mapping with sensor ID's numbers as key and corresponding FoB objects as value. def SetComports(self): comports = self.main.config.ReadComports() ## A (key,value) mapping with sensor ID's numbers as key and corresponding FoB objects as value. self.fob_dict = {} for gsi, comport in comports.items(): comport = int(comport) gsi = int(gsi) if gsi != 1: #self.fob_dict[gsi] = self.init_FOB_parallel(comport) thread = threading.Thread(group = None, target = self.ThreadedFOBsetup, args = ([comport, gsi])) thread.start() while (len(threading.enumerate())>1): time.sleep(0.003) self.fob_dict[1] = self.init_XRC(10,int(comports['1'])) return self.fob_dict ## Creates an object for and starts the XRC. # @param[in] nr_of_birds The number of sensors connected to the XRC including the XRC itself. # @param[in] port The comport where the XRC is plugged into. def init_XRC(self, nr_of_birds, port): f = fob.FOB() time.sleep(0.01) comport = port-1 baudrate = 19200#19200 # Default timeout in seconds. timeout = 5 try: f.open(comport, baudrate, timeout) except: msg = "Could not open FoB connections: COM port %d does not exist on this computer.\nPlease reconfigure the FobDevice of the config.ini file." %comport dlg = wx.MessageDialog(self.main.gui, msg, 'Error', wx.OK | wx.NO_DEFAULT | wx.ICON_ERROR | wx.STAY_ON_TOP) dlg.ShowModal() raise RuntimeError f.fbbAutoConfig(nr_of_birds) time.sleep(0.01) f.fbbReset() time.sleep(0.01) f.position_matrix() time.sleep(0.01) f.run() return f def ThreadedFOBsetup(self, *args): comport = args[0] gsi = args[1] self.fob_dict[gsi] = self.init_FOB_parallel(comport) ## Creates an object for and starts a sensor. # @param[in] port The comport where the sensor is plugged into. def init_FOB_parallel(self,port): f = fob.FOB() time.sleep(0.01) comport = port-1 baudrate = 19200#19200 # Default timeout in seconds. timeout = 5 try: f.open(comport, baudrate, timeout) time.sleep(0.01) f.fbbAutoConfig(1) f.position_matrix() time.sleep(0.01) f.run() return f except: msg = "Could not open FoB connections: COM port %d does not exist on this computer.\nPlease reconfigure the FobDevice section of the config.ini file." %comport print msg return -1 #~ dlg = wx.MessageDialog(self.main.gui, msg, 'Error', wx.OK | wx.NO_DEFAULT | wx.ICON_ERROR | wx.STAY_ON_TOP) #~ dlg.ShowModal() #~ raise RuntimeError ## Puts FoB to sleep. You may only call this method if you inherit from DriverInterface. def sleep(self): if not isinstance(self, DriverInterface): raise TypeError("FoBDriver.sleep requires DriverInterface.") for gsi,object in self.flock.items(): object.sleep() ## Runs XRC. You may only call this method if you inherit from DriverInterface. def run(self): if not isinstance(self, DriverInterface): raise TypeError("FoBDriver.run requires DriverInterface.") self.flock[1].run() ## Closes communication. You may only call this method if you inherit from DriverInterface. def close(self): if not isinstance(self, DriverInterface): raise TypeError("FoBDriver.close requires DriverInterface.") if self.fobrunning: for gsi,object in self.flock.items(): object.sleep() object.close() self.fileWriter.close() def closeBLFile(self): self.fileWriter.close() ## Returns raw FoB data of the sensor with the corresponding ID. You may only call this method if you inherit from DriverInterface. # @param[in] id The sensor ID from which we are requesting data. def get_sample(self, id): if not isinstance(self, DriverInterface): raise TypeError("FoBDriver.get_sample requires DriverInterface.") sample = [] sensorstring = id.split('_') # flock is a dict with key gsi, value fob object. sample = self.flock[int(sensorstring[1])].point() # Write the rawData to a file #~ print (sensorstring[1] + ' %.2f %.2f %.2f \r\n %.2f %.2f %.2f \r\n %.2f %.2f %.2f \r\n %.2f %.2f %.2f \r\n\r\n' % (sample[0], sample[1], sample[2], sample[3], sample[4],sample[5], sample[6], sample[7], sample[8], sample[9],sample[10],sample[11])) #~ print ('\n') try: if (self.main.DATA_WRITE or self.main.FAST_ACQUISITION) and self.main.states.visualization.recordingState.RECORDING: self.rawoutputlist.append(sensorstring[1] + ' %.2f %.2f %.2f \r\n %.2f %.2f %.2f \r\n %.2f %.2f %.2f \r\n %.2f %.2f %.2f \r\n\r\n' % (sample[0], sample[1], sample[2], sample[3], sample[4],sample[5], sample[6], sample[7], sample[8], sample[9],sample[10],sample[11])) except (AttributeError, ValueError): pass return sample ## Calculates the rotations x, y, and z resp. around the x-, y-, and z-axis from matrix R. # You may only call this method if you inherit from DriverInterface. def __RotXYZ(self, R): if not isinstance(self, DriverInterface): raise TypeError("FoBDriver.__init__ requires DriverInterface.") y1 = asin(R[0,2]) sz = -R[0,1] / cos(y1) cz = R[0,0] / cos(y1) z1 = atan2(sz,cz) sx = -R[1,2] / cos(y1) cx = R[2,2] / cos(y1) x1 = atan2(sx,cx) if y1 >= 0: y2 = pi - y1 else: y2 = -pi -y1 sz = -R[0,1] / cos(y2) cz = R[0,0] / cos(y2) z2 = atan2(sz,cz) sx = -R[1,2] / cos(y2) cx = R[2,2] / cos(y2) x2 = atan2(sx,cx) if (-pi/2 <= y1) and (y1 <= pi/2): return (x1, y1, z1) else: return (x2, y2, z2) ## Calculates the endpoint of the stylus. # The position and rotation data was not in the correct format and this resulted in a matrix return, this is now fixed. # You may only call this method if you inherit from DriverInterface. def __StylusCompensation(self, sensorPosition, sensorRotation): if not isinstance(self, DriverInterface): raise TypeError("FoBDriver.__init__ requires DriverInterface.") return sensorPosition + transpose(sensorRotation) * self.__stylusLength ## Calculates the relative vector of the bony landmark w.r.t. the sensor. # You may only call this method if you inherit from DriverInterface. def __CalcBLVec(self, bonyLandmarkPosition, sensorPosition, sensorRotation): if not isinstance(self, DriverInterface): raise TypeError("FoBDriver.__init__ requires DriverInterface.") return sensorRotation * (bonyLandmarkPosition - sensorPosition) ## Calculate position vector of bony landmark relative to its sensors. # You may only call this method if you inherit from DriverInterface. def GetBLRelativePosition(self, stylusSensor, sampleSensor): if not isinstance(self, DriverInterface): raise TypeError("FoBDriver.__init__ requires DriverInterface.") relativeSensor = None globalBLpos = self.__StylusCompensation(stylusSensor.position,stylusSensor.rotation) blvec = self.__CalcBLVec(globalBLpos, sampleSensor.position, sampleSensor.rotation) return blvec.mean(axis=1) ## Calculates the global vector of the bony landmark w.r.t. the transmitter coordinate system, # using the local vector of the bony landmark and global vector of the sensor. # You may only call this method if you inherit from DriverInterface. def RelativeToGlobal(self, relativePosition, sensorPosition, sensorRotation): if not isinstance(self, DriverInterface): raise TypeError("FoBDriver.__init__ requires DriverInterface.") return sensorPosition + transpose(sensorRotation) * relativePosition ## Gets position and rotation data for all sensors. # You may only call this method if you inherit from DriverInterface. def SampleSensors(self): if not isinstance(self, DriverInterface): raise TypeError("FoBDriver.__init__ requires DriverInterface.") #~ start = time.clock() for sensor in self.main.sensors: thread = threading.Thread(group = None, target = self.ThreadedSampler, args = ([sensor])) thread.start() while (len(threading.enumerate())>1): time.sleep(0.003) #~ eind = time.clock() #~ print eind-start #~ for sensor in self.main.sensors: #~ ##~ start = time.clock() #~ m = self.main.driver.get_sample(sensor.ID) #~ ##~ eind = time.clock() #~ ##~ print eind-start #~ if not self.main.FAST_ACQUISITION: #~ sensor.rawPosition = m[0:3] #~ sensor.rawRotation = m[3:13] #~ sensor = self.CalibrateSingleSensor(sensor) def ThreadedSampler(self, *args): sensor = args[0] m = self.main.driver.get_sample(sensor.ID) sensor.rawPosition = m[0:3] sensor.rawRotation = m[3:13] sensor = self.CalibrateSingleSensor(sensor) ## Append a new 'OnPedal transform' to the "bony landmark - sensor mapping": imSensor. # You may only call this method if you inherit from DriverInterface. # @param[in] blIndex The bony landmark number. # @param[in] sensorID The sensor number. def FetchBL_SensorPositionRotation(self, blIndex, sensorID): if not isinstance(self, DriverInterface): raise TypeError("FoBDriver.__init__ requires DriverInterface.") # Get the stylus, now from the self.main.sensors, not form the hardcoded "fob0_2" ID. stylusSample = self.get_sample(self.main.sensors[0].ID) outputStylusSensor = Sensor(self.main.sensors[0].ID) outputStylusSensor.rawPosition = stylusSample[0:3] outputStylusSensor.rawRotation = stylusSample[3:13] outputStylusSensor = self.CalibrateSingleSensor(outputStylusSensor) # Get the measurements for the bony landmark with sensorID id. sensorTransform = self.get_sample(sensorID) outputSensor = Sensor(sensorID) outputSensor.rawPosition = sensorTransform[0:3] outputSensor.rawRotation = sensorTransform[3:13] outputSensor = self.CalibrateSingleSensor(outputSensor) # Outputsensor now has a calibrated position and rotation. Add to imSensors. if len(self.imSensors[blIndex]) == 0: self.imSensors[blIndex] = [outputSensor] self.stylus[blIndex] = [outputStylusSensor] else: self.imSensors[blIndex].append(outputSensor) self.stylus[blIndex].append(outputStylusSensor) ## This is the new version of CalibrateSensorSSS, because we are only going to calibrate one sensor now. # You may only call this method if you inherit from DriverInterface. # @param[in] singleSensor The sensor we are calibrating. def CalibrateSingleSensor(self, singleSensor): if not isinstance(self, DriverInterface): raise TypeError("FoBDriver.__init__ requires DriverInterface.") sensorstring = singleSensor.ID.split('_') sensornr = int(sensorstring[1]) # Insert the rawpositions in a matrix. rawData = matrix("[%f %f %f]" % (singleSensor.rawPosition[0],singleSensor.rawPosition[1],singleSensor.rawPosition[2])) # Include the rawrotations in the same matrix. rawData = vstack((rawData, matrix("[%f %f %f;%f %f %f;%f %f %f]" % (singleSensor.rawRotation[0], singleSensor.rawRotation[1], singleSensor.rawRotation[2], singleSensor.rawRotation[3], singleSensor.rawRotation[4], singleSensor.rawRotation[5], singleSensor.rawRotation[6], singleSensor.rawRotation[7], singleSensor.rawRotation[8])))) # Calibrate the data. newData = self.__CalibrateRawData(rawData) # Set the newly caclulated positions and rotation in the sensor. pos = transpose(newData[0]) rot = transpose(newData[1:4]) singleSensor.position = pos singleSensor.rotation = rot return singleSensor ## Applies the calibration procedure on the raw FoB data using the given calibration file path. # # This is called by CalibrateSensors after having built up the rawData structure. # You may only call this method if you inherit from DriverInterface. # # @param[in] rawData Matrix with 4 columns of 'raw' fob data (sensor_id, pos, pos, pos) or (sensor_id, rot, rot, rot). # # For each sensor id, there is one line with position, and three with the complete rotation matrix. # After a complete sequence of all sensor IDs, the next frame is added. def __CalibrateRawData(self, rawData): if not isinstance(self, DriverInterface): raise TypeError("FoBDriver.__init__ requires DriverInterface.") # First iterate through all the POSITION lines. # (the skip=4) in the range skips all the rotation matrices. for i in range(0,size(rawData,0),4): # Transpose rotation matrix, determine rotations x,y,z around x-, y- and z- axes. (x,y,z) = self.__RotXYZ(transpose(rawData[i:i+3,0:3])) # Create matrix c [posx, posy, posz, rotx, roty rotz]. a = matrix("[%f %f %f]" % (x,y,z)) b = rawData[i,0:3] c = concatenate((b,a),1) # Append matrix c to reg. if i > 0: reg = concatenate((reg,c)) else: reg = c # For EACH row (of 6 elements) do: # aa ab ac bb bc cc (done here for 3; just determine all combinations). # Store result vector / matrix in T_cross. We could do this per sample. for i in range(0,6): for j in range(i,6): if (i==0) and (j==0): T_cross = multiply(reg[:,i],reg[:,j]) else: T_cross = concatenate((T_cross, multiply(reg[:,i],reg[:,j])),1) # Determine magnitude of position vector. # sqrt(x^2 + y^2 + z^2) af = sqrt(multiply(reg[:,0],reg[:,0]) + multiply(reg[:,1],reg[:,1]) + multiply(reg[:,2],reg[:,2])) # T has 29 columns. # # 1 x y z magpos rotx roty rotz aa bb cc bb bc cc # 1 x y z magpos rotx roty rotz ... # 1 x y z magpos rotx roty rotz ... T = hstack((ones((size(reg,0),1)), reg[:,0:3], af, reg[:,3:6], T_cross)) # th_nonline has 29 rows and 3 columns. th_nonlin = self.main.calibrationMatrix # error has size(reg,0) rows and 3 columns. error = T * th_nonlin # Copy complete rawData (only positions have been converted to millimetres). newData = rawData.copy() # For each position (note the skip=4), add x, y and z error to the position, divide the whole thing by 10 to get centimetres. for i in range(0, size(rawData,0), 4): newData[i,0:3] = (rawData[i,0:3] +error[(i)/4,:])/10 return newData
Python
from numpy import matrix ## Represents the bony landmark with its ID, name, relative position and relative sensor ID. class BonyLandmark: ## The constructor of BonyLandmark. def __init__(self, ID=-1, name="undefined", relativePosition=None, sensorID=-1): ## The number ID belonging to this bony landmark. self.ID = ID ## The name belonging to this bony landmark. self.name = name ## The sensor ID belonging to this bony landmark, formatted as fob0_x. self.sensorID = sensorID if relativePosition == None: ## The relative position matrix of this bony landmark. self.relativePosition = matrix("[0.0; 0.0; 0.0]") else: self.relativePosition = relativePosition
Python
from ConfigParser import ConfigParser from numpy import matrix import wx import os ## Reads the prefences from the preference file in which the location of the stylus, calibration and bony landmark position files are stored. class PreferencesFileReader: ## The constructor of PreferencesFileReader. # @param[in] gui GUI instance. def __init__(self,gui): ## GUI instance. self.gui = gui ## The location of the preferences file. self.preferencesFile = os.path.join('Preferences', 'preferences.ini') config = ConfigParser() try: config.read(self.preferencesFile) ## Location of the stylusFile, contains data for the pointer sensor. # Default location: Data\Stylus.dat. self.stylusFile = config.get("Preferences", "stylusFile") ## Location of the calibration file, containing data concerning calibration data for the elektromagnetic field of the Flock of Birds system. # Default location: Data\Calibration.dat. self.calibrationFile = config.get("Preferences", "calibrationFile") ## Location of the bony landmark position file, containing coordinates for the bony landmarks in the bone models. # Default location: \BLPositions.ini. self.blPositionsFile = config.get("Preferences", "blPositionsFile") ## Location of the cofiguration file, containing sensor and bony landmark configurations. # Default location: \config.ini. self.configFile = config.get("Preferences", "configFile") except: msg = "Could not read the preferences file. Please check the settings in %s for inconsistencies." % self.preferencesFile self.DisplayErrorDialog(msg) ## Parses the calibration file. # @param[in] fileName The location of the calibration file. # @return[matrix] The calibration file in matrix representation. def ReadCalibration(self, fileName): try: datFile = open(fileName,'r') fullString = "[" + datFile.read().replace('\n', ';') + "]" except: msg = "Could not read the calibration file. Please check the settings in %s for inconsistencies." % fileName self.DisplayErrorDialog(msg) return matrix(fullString) ## Saves the system preferences files. # @return[bool] Returns a boolean value representing a system reset. def SavePreferences(self, dlg): try: file = open(self.preferencesFile, 'w') file.write("[Preferences]\n") file.write("stylusFile: %s\n" % dlg.stylusFile.GetValue()) file.write("calibrationFile: %s\n" % dlg.calibrationFile.GetValue()) file.write("blPositionsFile: %s\n"% dlg.blPositionsFile.GetValue()) file.write("configFile: %s\n"% dlg.configFile.GetValue()) file.close() except: msg = "An error occured while writing to the preferences file %" % self.preferencesFile self.DisplayErrorDiload(msg) ## Displays an error dialog. # @param[in] msg The message to be displayed. def DisplayErrorDialog(self, msg): dlg = wx.MessageDialog(self.gui, msg, 'Warning', wx.OK | wx.ICON_EXCLAMATION) dlg.ShowModal()
Python
import wx from RecordingPanel import RecordingPanel from PlaybackPanel import PlaybackPanel VISNOTEBOOK = 8938 ## Notebook tab containing the visualization for the recording and playing of measurements of movements. class VisualizationPanel(wx.Panel): ## The contructor of VisualizationPanel. GUI elements of the panel are setup here. # @param[in] parent The wx window parent (notebook) of this panel. # @param[in] state VisualizationState instance attached to this panel. def __init__(self, parent, state): wx.Panel.__init__(self, parent) ## VisualizationState instance attached to this panel. self.__state = state self.__state.panel = self ## The name of this notebook panel. self.name = "Visualization" ## The wx window parent (notebook) of this panel. self.parent = parent ## The wx.Notebook(). self.visNotebook = wx.Notebook(self, id=VISNOTEBOOK, style=0) ## Only load the recording page when the fob is running if self.__state.main.FOB_RUNNING: self.LoadRecordingPage() self.LoadPlaybackPage() self.SetSize((915, 760)) sizer_1 = wx.BoxSizer(wx.VERTICAL) sizer_1.Add(self.visNotebook, 1, wx.EXPAND, 0) self.SetSizer(sizer_1) self.Bind(wx.EVT_NOTEBOOK_PAGE_CHANGED, self.OnPageChanged, id=VISNOTEBOOK) self.Layout() self.Centre() ## Loads the subpanel (referred to with "page") for recording and realtime visualization. def LoadRecordingPage(self): self.visNotebook.AddPage(RecordingPanel(self.visNotebook, self.__state.recordingState), "Recording") ## Loads the subpanel for replaying and importing recordings. def LoadPlaybackPage(self): self.visNotebook.AddPage(PlaybackPanel(self.visNotebook, self.__state.playbackState), "Playback") ## Panel navigation, goes back in the panel navigation to the previous state. # @param[in] new The tab index to go to. def OnBack(self, event, new = 2): self.__state.Stop() self.parent.ChangeSelection(new) ## Sets the properties when the selection of the subpanels is switched. def OnPageChanged(self, event): if self.__state.playbackState.PLAYING: self.__state.playbackState.panel.OnTogglePlayPause(event) try: self.__state.recordingState.OnTogglePlayPause() except: msg = "Cannot switch panels when a recording is being played, please press pause first." dlg = wx.MessageDialog(self.__state.main.gui, msg, 'Warning', wx.OK | wx.NO_DEFAULT | wx.ICON_EXCLAMATION) dlg.ShowModal() self.parent.ChangeSelection(3) if self.__state.recordingState.FIRST_TIME or self.__state.playbackState.FIRST_TIME: self.__state.update_actor_positions()
Python
import wx import wx.lib.mixins.listctrl from vtk.wx.wxVTKRenderWindowInteractor import wxVTKRenderWindowInteractor ## New bony landmark 3D coordinates can be chosen using this menu. class AddBLFrame(wx.Frame): ## The constructor of AddBLFrame. GUI elements of the panel are setup here. # @param[in] gui GUI instance. # @param[in] *args Automatically passed parameter. # @param[in] **kwds Automatically passed parameter. def __init__(self, gui, *args, **kwds): kwds["style"] = wx.DEFAULT_FRAME_STYLE wx.Frame.__init__(self, *args, **kwds) ## The Panel on which we are attaching our GUI. self.panel_1 = wx.Panel(self, -1) ## Gui instance. self.gui = gui ## The list for the 3D coordinates. self.bony_landmarks_listctrl = CoordinatesListCtrl(self, -1, style=wx.LC_REPORT|wx.LC_NO_HEADER|wx.LC_SINGLE_SEL|wx.SUNKEN_BORDER) ## Displays a help dialog. self.help_button = wx.Button(self.panel_1, -1, "Help") ## Finishes picking points and closes the panel. self.finish_button = wx.Button(self.panel_1, -1, "Finish") ## wxVTKRenderWindowInteractor used to show the 3D model. self.rwi = wxVTKRenderWindowInteractor(self.panel_1, -1) self.__set_properties() self.__do_layout() ## Sets properties for the panel. def __set_properties(self): self.SetTitle("Bony Landmarks Editor") self.SetIcon(wx.Icon(self.gui.main.config.root+"\\Images\\icon.ico", wx.BITMAP_TYPE_ICO, 32, 32)) ## Sets layout for the panel. def __do_layout(self): sizer_1 = wx.BoxSizer(wx.VERTICAL) sizer_3 = wx.BoxSizer(wx.VERTICAL) sizer_4 = wx.BoxSizer(wx.VERTICAL) sizer_5 = wx.BoxSizer(wx.HORIZONTAL) sizer_7 = wx.BoxSizer(wx.VERTICAL) sizer_6 = wx.BoxSizer(wx.VERTICAL) sizer_8 = wx.BoxSizer(wx.HORIZONTAL) sizer_6.Add(self.bony_landmarks_listctrl, 1, wx.EXPAND, 0) sizer_8.Add(self.help_button, 0, wx.RIGHT|wx.ALIGN_CENTER_HORIZONTAL, 4) sizer_8.Add(self.finish_button, 0, wx.ALIGN_CENTER_HORIZONTAL, 0) sizer_6.Add(sizer_8, 0, wx.TOP|wx.EXPAND, 7) sizer_5.Add(sizer_6, 0, wx.RIGHT|wx.EXPAND, 7) sizer_7.Add(self.rwi, 1, wx.EXPAND, 0) sizer_7.Add((450, 0), 0, 0, 0) sizer_5.Add(sizer_7, 1, wx.EXPAND, 0) sizer_5.Add((0, 480), 0, 0, 0) sizer_4.Add(sizer_5, 1, wx.EXPAND, 0) sizer_3.Add(sizer_4, 1, wx.ALL|wx.EXPAND, 7) self.panel_1.SetSizer(sizer_3) sizer_1.Add(self.panel_1, 1, wx.EXPAND, 0) self.SetSizer(sizer_1) sizer_1.Fit(self) self.Layout() ## List for the 3D coordinates. # Here, wx.ListCtrl is used with ListCtrlAutoWidthMixin to create fitting columns. class CoordinatesListCtrl(wx.ListCtrl, wx.lib.mixins.listctrl.ListCtrlAutoWidthMixin): ## The constructor of CoordinatesListCtrl. def __init__(self, parent, ID, pos=wx.DefaultPosition, size=wx.DefaultSize, style=0): wx.ListCtrl.__init__(self, parent, ID, pos, size, style) wx.lib.mixins.listctrl.ListCtrlAutoWidthMixin.__init__(self) self.InsertColumn(0, "Column 1")
Python
import vtk import math import time def create(parent): return ColorScales(parent) class ColorScales(): def __init__(self, parent): self.parent = parent self.differencetable = vtk.vtkLookupTable() self.dynamic_blue = vtk.vtkLookupTable() self.dynamic_yellow = vtk.vtkLookupTable() self.dynamic_green = vtk.vtkLookupTable() self.dynamic_red = vtk.vtkLookupTable() self.LUT_Statistics = vtk.vtkLookupTable() self.counter = 0.0 self.colornumber = 10000 self.dynamic_generic = vtk.vtkLookupTable() self.dynamic_generic.SetNumberOfColors(4) self.dynamic_generic.SetRange(0, 4) self.LUT_GenericDynamic() self.dynamic_generic2 = vtk.vtkLookupTable() self.dynamic_generic2.SetNumberOfColors(4) self.dynamic_generic2.SetRange(0, 4) self.LUT_GenericDynamic2() self.dynamic_generic3 = vtk.vtkLookupTable() self.dynamic_generic3.SetNumberOfColors(4) self.dynamic_generic3.SetRange(0, 4) self.LUT_GenericDynamic3() self.LUT_Woosh = vtk.vtkLookupTable() self.LUT_Woosh.SetNumberOfColors(20) self.LUT_Woosh.SetRange(0, 20) self.LUT_WooshCreate() self.LUT_WooshBlue = vtk.vtkLookupTable() self.LUT_WooshBlue.SetNumberOfColors(20) self.LUT_WooshBlue.SetRange(0, 20) self.LUT_WooshBlueCreate() self.LUT_WooshYellow = vtk.vtkLookupTable() self.LUT_WooshYellow.SetNumberOfColors(20) self.LUT_WooshYellow.SetRange(0, 20) self.LUT_WooshYellowCreate() self.dynamic_blue.SetNumberOfColors(self.colornumber) self.dynamic_blue.SetRange(0, self.colornumber) self.LUT_Statistics.SetNumberOfColors(60) self.LUT_Statistics.SetRange(0, 60) self.LUT_StatisticsCreate() [self.dynamic_blue.SetTableValue(i, (0.0, 0.0, 0.7, 0.0)) for i in range(0, self.colornumber)] self.dynamic_yellow.SetNumberOfColors(self.colornumber) self.dynamic_yellow.SetRange(0, self.colornumber) [self.dynamic_yellow.SetTableValue(i, (0.7, 0.7, 0.0, 0.0)) for i in range(0, self.colornumber)] self.dynamic_green.SetNumberOfColors(self.colornumber) self.dynamic_green.SetRange(0, self.colornumber) [self.dynamic_green.SetTableValue(i, (0.0, 0.7, 0.0, 0.0)) for i in range(0, self.colornumber)] self.dynamic_yellow.Build() self.dynamic_green.Build() print 'ColorScales loaded.' def LUT_GenericDynamic(self): #~ self.dynamic_generic.SetTableValue( 0, (0.0, 0.0, 0.7 ,1.0)) #Blauw #~ self.dynamic_generic.SetTableValue( 1, (0.7, 0.7, 0.0 ,1.0)) #Geel #~ self.dynamic_generic.SetTableValue( 2, (0.0, 0.7, 0.0 ,1.0)) #Groen #~ self.dynamic_generic.SetTableValue( 3, (0.7, 0.0, 0.0 ,1.0)) #Rood whitening = 0.5 self.dynamic_generic.SetTableValue( 0, (whitening, whitening, 1.0 ,1.0)) #Blauw self.dynamic_generic.SetTableValue( 1, (whitening, whitening, 1.0 ,1.0)) #Blauw self.dynamic_generic.SetTableValue( 2, (whitening, whitening, 1.0 ,1.0)) #Blauw self.dynamic_generic.SetTableValue( 3, (whitening, whitening, 1.0 ,1.0)) #Blauw self.dynamic_generic.Build() return self.dynamic_generic def LUT_GenericDynamic2(self): self.dynamic_generic2.SetTableValue( 0, (1.0, 1.0, 0.0 ,1.0)) #Geel self.dynamic_generic2.SetTableValue( 1, (1.0, 1.0, 0.0 ,1.0)) #Geel self.dynamic_generic2.SetTableValue( 2, (1.0, 1.0, 0.0 ,1.0)) #Geel self.dynamic_generic2.SetTableValue( 3, (1.0, 1.0, 0.0 ,1.0)) #Geel #~ self.dynamic_generic2.SetTableValue( 0, (0.7, 0.0, 0.7 ,1.0)) #Paars #~ self.dynamic_generic2.SetTableValue( 1, (0.0, 0.7, 0.7 ,1.0)) #Turqoise #~ self.dynamic_generic2.SetTableValue( 2, (0.0, 0.3, 0.0 ,1.0)) #Donkergroen #~ self.dynamic_generic2.SetTableValue( 3, (0.7, 0.3, 0.3 ,1.0)) #Iets anders self.dynamic_generic2.Build() return self.dynamic_generic2 def LUT_GenericDynamic3(self): self.dynamic_generic3.SetTableValue( 0, (0.0, 0.0, 0.0 ,1.0)) self.dynamic_generic3.SetTableValue( 1, (0.0, 0.0, 0.0 ,1.0)) self.dynamic_generic3.SetTableValue( 2, (0.0, 0.0, 0.0 ,1.0)) self.dynamic_generic3.SetTableValue( 3, (0.0, 0.0, 0.0 ,1.0)) self.dynamic_generic3.Build() return self.dynamic_generic3 def LUT_StatisticsCreate(self): for i in range(0,60): self.LUT_Statistics.SetTableValue( i, (1.0, 1.0 - i/60.0, 0.0 ,1.0 - i/60.0)) #Geel #~ self.LUT_Statistics.SetTableValue( i, (0.4, 0.0, 0.0 ,0.0)) #Donkerrood self.LUT_Statistics.Build() return self.LUT_Statistics def LUT_WooshCreate(self): for i in range(0,20): self.LUT_Woosh.SetTableValue( i, (1.0, 1.0, 1.0, 1.0 - pow((float(i)/20.0), 0.5))) self.LUT_Woosh.Build() return self.LUT_Woosh def LUT_WooshBlueCreate(self): for i in range(0,20): self.LUT_WooshBlue.SetTableValue( i, (0.2, 0.2, 1.0, 1.0 - pow((float(i)/20.0), 0.5))) self.LUT_WooshBlue.Build() return self.LUT_WooshBlue def LUT_WooshYellowCreate(self): for i in range(0,20): self.LUT_WooshYellow.SetTableValue( i, (1.0, 1.0, 0.0, 1.0 - pow((float(i)/20.0), 0.5))) self.LUT_WooshYellow.Build() return self.LUT_WooshYellow def LUT_BlueDynamic(self, filterranges): starttijd = time.clock() #~ self.dynamic_blue.SetNumberOfColors(self.colornumber) #~ self.dynamic_blue.SetRange(0, self.colornumber) tb = self.dynamic_blue.GetTable() #~ def ev_fun(i): #~ value1 = i % 10 #~ value10 = i / 10 % 10 #~ value100 = i / 100 % 10 #~ value1000 = i / 1000 % 10 #~ value10000 = i / 10000 % 10 #~ visible = True #~ if filterranges[3][0] > value1 or filterranges[3][1] < value1: #axial abduct #~ visible = False #~ elif filterranges[2][0] > value10 or filterranges[2][1] < value10: #elbow flexion #~ visible = False #~ elif filterranges[1][0] > value100 or filterranges[1][1] < value100: #abduct #~ visible = False #~ elif filterranges[0][0] > value1000 or filterranges[0][1] < value1000: #plane of abd #~ visible = False #~ elif filterranges[4][0] > value10000 or filterranges[4][1] < value10000: #plane of abd #~ visible = False #~ map(ev_fun, #~ [ty.SetValue(i*4+3, tb.GetValue(i*4+3)) for i in range(0, self.colornumber)] i=0 #maxvalue = 18000.0 while i<self.colornumber: value1 = i % 10 value10 = i / 10 % 10 value100 = i / 100 % 10 value1000 = i / 1000 % 10 #~ value10000 = i / 10000 % 10 visible = True if filterranges[3][0] > value1 or filterranges[3][1] < value1: #axial abduct visible = False elif filterranges[2][0] > value10 or filterranges[2][1] < value10: #elbow flexion visible = False elif filterranges[1][0] > value100 or filterranges[1][1] < value100: #abduct visible = False elif filterranges[0][0] > value1000 or filterranges[0][1] < value1000: #plane of abd visible = False #~ elif filterranges[4][0] > value10000 or filterranges[4][1] < value10000: #plane of abd #~ visible = False if visible: self.dynamic_blue.SetTableValue( i, (0, 0, 0.7 ,0.1)) #~ tb.SetValue(i*4+3, 0.1) else: self.dynamic_blue.SetTableValue( i, (0, 0, 0.7 ,0.0)) #~ tb.SetValue(i*4+3, 0.0) i=i+1 tussentijd = time.clock() self.dynamic_blue.Build() eindtijd = time.clock() #~ print (tussentijd - starttijd)," - building: ", (eindtijd - tussentijd) return self.dynamic_blue #~ def LUT_BlueDynamic(self, filterranges): #~ starttijd = time.clock() #~ self.dynamic_blue.SetNumberOfColors(self.colornumber) #~ self.dynamic_blue.SetRange(0, self.colornumber) #~ i=0 #~ changingFilter = [-1, -1] # filter_index, scenario #~ # scenario's: #~ # 1 (A0): ondergrens verhoogt, filter wordt smaller #~ # 2 (A1): bovengrens verlaagt, filter wordt smaller #~ # 3 (B0): ondergrens verlaagt, filter wordt groter #~ # 4 (B1): bovengrens verhoogt, filter wordt groter #~ # 5 (C): beide grenzen verhogen #~ # 6 (D): beide grenzen verlagen #~ for i in range (0, len(filterranges)): #~ if filterranges[i][0] < self.last_filterranges [i][0]: #~ #ondergrens verlaagt #~ if filterranges[i][1] < self.last_filterranges [i][1]: #~ #bovengrens verlaagt ook => D #~ changingFilter = [i, 6] #~ else: #~ #bovengrens constant => B0 #~ changingFilter = [i, 3] #~ elif filterranges[i][1] < self.last_filterranges [i][1]: #~ #bovengrens verlaagt => A1 #~ changingFilter = [i, 2] #~ elif filterranges[i][0] > self.last_filterranges [i][0]: #~ #ondergrens verhoogt #~ if filterranges[i][1] > self.last_filterranges [i][1]: #~ #bovengrens verhoogt ook => C #~ changingFilter = [i, 5] #~ else: #~ #ondergrens verhoogt => A0 #~ changingFilter = [i, 1] #~ elif filterranges[i][1] > self.last_filterranges [i][1]: #~ #bovengrens verhoogt alleen #~ #ondergrens constant => B1 #~ changingFilter = [i, 4] #~ i=0 #~ if changingFilter != [-1, -1]: #~ if changingFilter[1] == 1: #~ # 1 (A0): ondergrens verhoogt, filter wordt smaller #~ checkvalue = i / (math.pow(10, changingFilter[0])) % 10 #~ added_i = math.pow(10, changingFilter[0]) #~ while i < self.colornumber: #~ if self.dynamic_blue.GetTableValue(i) -> visible: #~ if filterranges[i][0] > checkvalue: #~ self.dynamic_blue.SetTableValue( i, ( 0.0, 0.0, 0.7 , 0.1)) #~ else: #~ self.dynamic_blue.SetTableValue( i, ( 0.0, 0.0, 0.7 , 0.0)) #~ i = i + added_i def CopyBlueToYellow(self): starttijd = time.clock() tb = self.dynamic_blue.GetTable() ty = self.dynamic_yellow.GetTable() [ty.SetValue(i*4+3, tb.GetValue(i*4+3)) for i in range(0, self.colornumber)] self.dynamic_yellow.Build() eindtijd = time.clock() #~ print "building: ", (eindtijd - starttijd) return self.dynamic_yellow def CopyBlueToGreen(self): starttijd = time.clock() tb = self.dynamic_blue.GetTable() ty = self.dynamic_green.GetTable() [ty.SetValue(i*4+3, tb.GetValue(i*4+3)) for i in range(0, self.colornumber)] self.dynamic_green.Build() eindtijd = time.clock() #~ print "building: ", (eindtijd - starttijd) return self.dynamic_green def CopyBlueToRed(self): self.dynamic_red.SetNumberOfColors(self.colornumber) self.dynamic_red.SetRange(0, self.colornumber) i = 0 while i<self.colornumber: tablevalue = self.dynamic_blue.GetTableValue (i) self.dynamic_red.SetTableValue(i, (0.7, 0.0, 0.0, tablevalue[3])) i = i +1 self.dynamic_red.Build() return self.dynamic_red def LUT_BlueToYellowAnimated(self, LUrange): while self.counter < 50.0: self.differencetable.SetNumberOfColors(50) self.differencetable.SetRange(LUrange[0], LUrange[1]) i=0.0 while i<50: self.differencetable.SetTableValue( int(i), (i/50.0, i/50.0, ((50-i+self.counter)/100.0) ,1.0)) i=i+1 self.differencetable.Build() self.counter = self.counter + 1.0 self.parent.renwini3.Render() self.counter = 0.0 def LUT_BlueToYellow(self, LUrange): try: return self.BlueToYellow except AttributeError: differencetable = vtk.vtkLookupTable() differencetable.SetNumberOfColors(50) differencetable.SetRange(LUrange[0], LUrange[1]) i=0.0 while i<50: differencetable.SetTableValue( int(i), (i/50.0, i/50.0, 1-(i/50.0) ,1.0)) i=i+1 differencetable.Build() self.BlueToYellow = differencetable return self.BlueToYellow def LUT_Linear_Heat(self, LUrange): try: return self.Linear_Heat except AttributeError: L1table = vtk.vtkLookupTable() L1table.SetRange(LUrange[0], LUrange[1]) L1table.SetNumberOfColors(256) L1table.SetTableValue( 0 , ( 0.000 , 0.000 , 0.000 ,1.0)) L1table.SetTableValue( 1 , ( 0.000 , 0.000 , 0.000 ,1.0)) L1table.SetTableValue( 2 , ( 0.000 , 0.000 , 0.000 ,1.0)) L1table.SetTableValue( 3 , ( 0.004 , 0.000 , 0.000 ,1.0)) L1table.SetTableValue( 4 , ( 0.008 , 0.000 , 0.000 ,1.0)) L1table.SetTableValue( 5 , ( 0.008 , 0.000 , 0.000 ,1.0)) L1table.SetTableValue( 6 , ( 0.012 , 0.000 , 0.000 ,1.0)) L1table.SetTableValue( 7 , ( 0.012 , 0.000 , 0.000 ,1.0)) L1table.SetTableValue( 8 , ( 0.016 , 0.000 , 0.000 ,1.0)) L1table.SetTableValue( 9 , ( 0.020 , 0.000 , 0.000 ,1.0)) L1table.SetTableValue( 10 , ( 0.020 , 0.000 , 0.000 ,1.0)) L1table.SetTableValue( 11 , ( 0.024 , 0.000 , 0.000 ,1.0)) L1table.SetTableValue( 12 , ( 0.027 , 0.000 , 0.000 ,1.0)) L1table.SetTableValue( 13 , ( 0.027 , 0.000 , 0.000 ,1.0)) L1table.SetTableValue( 14 , ( 0.031 , 0.000 , 0.000 ,1.0)) L1table.SetTableValue( 15 , ( 0.035 , 0.000 , 0.000 ,1.0)) L1table.SetTableValue( 16 , ( 0.035 , 0.000 , 0.000 ,1.0)) L1table.SetTableValue( 17 , ( 0.039 , 0.000 , 0.000 ,1.0)) L1table.SetTableValue( 18 , ( 0.043 , 0.000 , 0.000 ,1.0)) L1table.SetTableValue( 19 , ( 0.047 , 0.000 , 0.000 ,1.0)) L1table.SetTableValue( 20 , ( 0.051 , 0.000 , 0.000 ,1.0)) L1table.SetTableValue( 21 , ( 0.055 , 0.000 , 0.000 ,1.0)) L1table.SetTableValue( 22 , ( 0.059 , 0.000 , 0.000 ,1.0)) L1table.SetTableValue( 23 , ( 0.063 , 0.000 , 0.000 ,1.0)) L1table.SetTableValue( 24 , ( 0.067 , 0.000 , 0.000 ,1.0)) L1table.SetTableValue( 25 , ( 0.071 , 0.000 , 0.000 ,1.0)) L1table.SetTableValue( 26 , ( 0.075 , 0.000 , 0.000 ,1.0)) L1table.SetTableValue( 27 , ( 0.078 , 0.000 , 0.000 ,1.0)) L1table.SetTableValue( 28 , ( 0.082 , 0.000 , 0.000 ,1.0)) L1table.SetTableValue( 29 , ( 0.086 , 0.000 , 0.000 ,1.0)) L1table.SetTableValue( 30 , ( 0.090 , 0.000 , 0.000 ,1.0)) L1table.SetTableValue( 31 , ( 0.098 , 0.000 , 0.000 ,1.0)) L1table.SetTableValue( 32 , ( 0.102 , 0.000 , 0.000 ,1.0)) L1table.SetTableValue( 33 , ( 0.106 , 0.000 , 0.000 ,1.0)) L1table.SetTableValue( 34 , ( 0.110 , 0.000 , 0.000 ,1.0)) L1table.SetTableValue( 35 , ( 0.118 , 0.000 , 0.000 ,1.0)) L1table.SetTableValue( 36 , ( 0.122 , 0.000 , 0.000 ,1.0)) L1table.SetTableValue( 37 , ( 0.129 , 0.000 , 0.000 ,1.0)) L1table.SetTableValue( 38 , ( 0.133 , 0.000 , 0.000 ,1.0)) L1table.SetTableValue( 39 , ( 0.137 , 0.000 , 0.000 ,1.0)) L1table.SetTableValue( 40 , ( 0.145 , 0.000 , 0.000 ,1.0)) L1table.SetTableValue( 41 , ( 0.153 , 0.000 , 0.000 ,1.0)) L1table.SetTableValue( 42 , ( 0.157 , 0.000 , 0.000 ,1.0)) L1table.SetTableValue( 43 , ( 0.169 , 0.000 , 0.000 ,1.0)) L1table.SetTableValue( 44 , ( 0.176 , 0.000 , 0.000 ,1.0)) L1table.SetTableValue( 45 , ( 0.180 , 0.000 , 0.000 ,1.0)) L1table.SetTableValue( 46 , ( 0.192 , 0.000 , 0.000 ,1.0)) L1table.SetTableValue( 47 , ( 0.200 , 0.000 , 0.000 ,1.0)) L1table.SetTableValue( 48 , ( 0.208 , 0.000 , 0.000 ,1.0)) L1table.SetTableValue( 49 , ( 0.212 , 0.000 , 0.000 ,1.0)) L1table.SetTableValue( 50 , ( 0.220 , 0.000 , 0.000 ,1.0)) L1table.SetTableValue( 51 , ( 0.227 , 0.000 , 0.000 ,1.0)) L1table.SetTableValue( 52 , ( 0.235 , 0.000 , 0.000 ,1.0)) L1table.SetTableValue( 53 , ( 0.243 , 0.000 , 0.000 ,1.0)) L1table.SetTableValue( 54 , ( 0.251 , 0.000 , 0.000 ,1.0)) L1table.SetTableValue( 55 , ( 0.263 , 0.000 , 0.000 ,1.0)) L1table.SetTableValue( 56 , ( 0.271 , 0.000 , 0.000 ,1.0)) L1table.SetTableValue( 57 , ( 0.278 , 0.000 , 0.000 ,1.0)) L1table.SetTableValue( 58 , ( 0.290 , 0.000 , 0.000 ,1.0)) L1table.SetTableValue( 59 , ( 0.298 , 0.000 , 0.000 ,1.0)) L1table.SetTableValue( 60 , ( 0.314 , 0.000 , 0.000 ,1.0)) L1table.SetTableValue( 61 , ( 0.318 , 0.000 , 0.000 ,1.0)) L1table.SetTableValue( 62 , ( 0.329 , 0.000 , 0.000 ,1.0)) L1table.SetTableValue( 63 , ( 0.337 , 0.000 , 0.000 ,1.0)) L1table.SetTableValue( 64 , ( 0.349 , 0.000 , 0.000 ,1.0)) L1table.SetTableValue( 65 , ( 0.361 , 0.000 , 0.000 ,1.0)) L1table.SetTableValue( 66 , ( 0.369 , 0.000 , 0.000 ,1.0)) L1table.SetTableValue( 67 , ( 0.380 , 0.000 , 0.000 ,1.0)) L1table.SetTableValue( 68 , ( 0.392 , 0.000 , 0.000 ,1.0)) L1table.SetTableValue( 69 , ( 0.404 , 0.000 , 0.000 ,1.0)) L1table.SetTableValue( 70 , ( 0.416 , 0.000 , 0.000 ,1.0)) L1table.SetTableValue( 71 , ( 0.427 , 0.000 , 0.000 ,1.0)) L1table.SetTableValue( 72 , ( 0.439 , 0.000 , 0.000 ,1.0)) L1table.SetTableValue( 73 , ( 0.451 , 0.000 , 0.000 ,1.0)) L1table.SetTableValue( 74 , ( 0.459 , 0.000 , 0.000 ,1.0)) L1table.SetTableValue( 75 , ( 0.478 , 0.000 , 0.000 ,1.0)) L1table.SetTableValue( 76 , ( 0.494 , 0.000 , 0.000 ,1.0)) L1table.SetTableValue( 77 , ( 0.502 , 0.000 , 0.000 ,1.0)) L1table.SetTableValue( 78 , ( 0.514 , 0.000 , 0.000 ,1.0)) L1table.SetTableValue( 79 , ( 0.529 , 0.000 , 0.000 ,1.0)) L1table.SetTableValue( 80 , ( 0.529 , 0.000 , 0.000 ,1.0)) L1table.SetTableValue( 81 , ( 0.529 , 0.004 , 0.000 ,1.0)) L1table.SetTableValue( 82 , ( 0.529 , 0.008 , 0.000 ,1.0)) L1table.SetTableValue( 83 , ( 0.529 , 0.012 , 0.000 ,1.0)) L1table.SetTableValue( 84 , ( 0.529 , 0.016 , 0.000 ,1.0)) L1table.SetTableValue( 85 , ( 0.529 , 0.024 , 0.000 ,1.0)) L1table.SetTableValue( 86 , ( 0.529 , 0.024 , 0.000 ,1.0)) L1table.SetTableValue( 87 , ( 0.529 , 0.031 , 0.000 ,1.0)) L1table.SetTableValue( 88 , ( 0.529 , 0.035 , 0.000 ,1.0)) L1table.SetTableValue( 89 , ( 0.529 , 0.039 , 0.000 ,1.0)) L1table.SetTableValue( 90 , ( 0.529 , 0.043 , 0.000 ,1.0)) L1table.SetTableValue( 91 , ( 0.529 , 0.051 , 0.000 ,1.0)) L1table.SetTableValue( 92 , ( 0.529 , 0.051 , 0.000 ,1.0)) L1table.SetTableValue( 93 , ( 0.529 , 0.059 , 0.000 ,1.0)) L1table.SetTableValue( 94 , ( 0.529 , 0.067 , 0.000 ,1.0)) L1table.SetTableValue( 95 , ( 0.529 , 0.067 , 0.000 ,1.0)) L1table.SetTableValue( 96 , ( 0.529 , 0.075 , 0.000 ,1.0)) L1table.SetTableValue( 97 , ( 0.529 , 0.082 , 0.000 ,1.0)) L1table.SetTableValue( 98 , ( 0.529 , 0.086 , 0.000 ,1.0)) L1table.SetTableValue( 99 , ( 0.529 , 0.090 , 0.000 ,1.0)) L1table.SetTableValue( 100 , ( 0.529 , 0.098 , 0.000 ,1.0)) L1table.SetTableValue( 101 , ( 0.529 , 0.102 , 0.000 ,1.0)) L1table.SetTableValue( 102 , ( 0.529 , 0.106 , 0.000 ,1.0)) L1table.SetTableValue( 103 , ( 0.529 , 0.114 , 0.000 ,1.0)) L1table.SetTableValue( 104 , ( 0.529 , 0.122 , 0.000 ,1.0)) L1table.SetTableValue( 105 , ( 0.529 , 0.125 , 0.000 ,1.0)) L1table.SetTableValue( 106 , ( 0.529 , 0.129 , 0.000 ,1.0)) L1table.SetTableValue( 107 , ( 0.529 , 0.137 , 0.000 ,1.0)) L1table.SetTableValue( 108 , ( 0.529 , 0.141 , 0.000 ,1.0)) L1table.SetTableValue( 109 , ( 0.529 , 0.149 , 0.000 ,1.0)) L1table.SetTableValue( 110 , ( 0.529 , 0.157 , 0.000 ,1.0)) L1table.SetTableValue( 111 , ( 0.529 , 0.165 , 0.000 ,1.0)) L1table.SetTableValue( 112 , ( 0.529 , 0.173 , 0.000 ,1.0)) L1table.SetTableValue( 113 , ( 0.529 , 0.180 , 0.000 ,1.0)) L1table.SetTableValue( 114 , ( 0.529 , 0.184 , 0.000 ,1.0)) L1table.SetTableValue( 115 , ( 0.529 , 0.192 , 0.000 ,1.0)) L1table.SetTableValue( 116 , ( 0.529 , 0.200 , 0.000 ,1.0)) L1table.SetTableValue( 117 , ( 0.529 , 0.204 , 0.000 ,1.0)) L1table.SetTableValue( 118 , ( 0.529 , 0.212 , 0.000 ,1.0)) L1table.SetTableValue( 119 , ( 0.529 , 0.220 , 0.000 ,1.0)) L1table.SetTableValue( 120 , ( 0.529 , 0.224 , 0.000 ,1.0)) L1table.SetTableValue( 121 , ( 0.529 , 0.231 , 0.000 ,1.0)) L1table.SetTableValue( 122 , ( 0.529 , 0.243 , 0.000 ,1.0)) L1table.SetTableValue( 123 , ( 0.529 , 0.247 , 0.000 ,1.0)) L1table.SetTableValue( 124 , ( 0.529 , 0.255 , 0.000 ,1.0)) L1table.SetTableValue( 125 , ( 0.529 , 0.263 , 0.000 ,1.0)) L1table.SetTableValue( 126 , ( 0.529 , 0.271 , 0.000 ,1.0)) L1table.SetTableValue( 127 , ( 0.529 , 0.282 , 0.000 ,1.0)) L1table.SetTableValue( 128 , ( 0.529 , 0.286 , 0.000 ,1.0)) L1table.SetTableValue( 129 , ( 0.529 , 0.298 , 0.000 ,1.0)) L1table.SetTableValue( 130 , ( 0.529 , 0.306 , 0.000 ,1.0)) L1table.SetTableValue( 131 , ( 0.529 , 0.314 , 0.000 ,1.0)) L1table.SetTableValue( 132 , ( 0.529 , 0.322 , 0.000 ,1.0)) L1table.SetTableValue( 133 , ( 0.529 , 0.329 , 0.000 ,1.0)) L1table.SetTableValue( 134 , ( 0.529 , 0.341 , 0.000 ,1.0)) L1table.SetTableValue( 135 , ( 0.529 , 0.345 , 0.000 ,1.0)) L1table.SetTableValue( 136 , ( 0.529 , 0.353 , 0.000 ,1.0)) L1table.SetTableValue( 137 , ( 0.529 , 0.365 , 0.000 ,1.0)) L1table.SetTableValue( 138 , ( 0.529 , 0.373 , 0.000 ,1.0)) L1table.SetTableValue( 139 , ( 0.529 , 0.384 , 0.000 ,1.0)) L1table.SetTableValue( 140 , ( 0.529 , 0.396 , 0.000 ,1.0)) L1table.SetTableValue( 141 , ( 0.529 , 0.404 , 0.000 ,1.0)) L1table.SetTableValue( 142 , ( 0.529 , 0.416 , 0.000 ,1.0)) L1table.SetTableValue( 143 , ( 0.529 , 0.420 , 0.000 ,1.0)) L1table.SetTableValue( 144 , ( 0.529 , 0.431 , 0.000 ,1.0)) L1table.SetTableValue( 145 , ( 0.529 , 0.443 , 0.000 ,1.0)) L1table.SetTableValue( 146 , ( 0.529 , 0.451 , 0.000 ,1.0)) L1table.SetTableValue( 147 , ( 0.529 , 0.463 , 0.000 ,1.0)) L1table.SetTableValue( 148 , ( 0.529 , 0.475 , 0.000 ,1.0)) L1table.SetTableValue( 149 , ( 0.529 , 0.486 , 0.000 ,1.0)) L1table.SetTableValue( 150 , ( 0.529 , 0.498 , 0.000 ,1.0)) L1table.SetTableValue( 151 , ( 0.529 , 0.506 , 0.000 ,1.0)) L1table.SetTableValue( 152 , ( 0.529 , 0.522 , 0.000 ,1.0)) L1table.SetTableValue( 153 , ( 0.529 , 0.529 , 0.000 ,1.0)) L1table.SetTableValue( 154 , ( 0.529 , 0.541 , 0.000 ,1.0)) L1table.SetTableValue( 155 , ( 0.529 , 0.553 , 0.000 ,1.0)) L1table.SetTableValue( 156 , ( 0.529 , 0.565 , 0.000 ,1.0)) L1table.SetTableValue( 157 , ( 0.529 , 0.580 , 0.000 ,1.0)) L1table.SetTableValue( 158 , ( 0.529 , 0.588 , 0.000 ,1.0)) L1table.SetTableValue( 159 , ( 0.529 , 0.608 , 0.000 ,1.0)) L1table.SetTableValue( 160 , ( 0.529 , 0.616 , 0.000 ,1.0)) L1table.SetTableValue( 161 , ( 0.529 , 0.627 , 0.000 ,1.0)) L1table.SetTableValue( 162 , ( 0.529 , 0.639 , 0.000 ,1.0)) L1table.SetTableValue( 163 , ( 0.529 , 0.651 , 0.000 ,1.0)) L1table.SetTableValue( 164 , ( 0.529 , 0.667 , 0.000 ,1.0)) L1table.SetTableValue( 165 , ( 0.529 , 0.682 , 0.000 ,1.0)) L1table.SetTableValue( 166 , ( 0.529 , 0.694 , 0.000 ,1.0)) L1table.SetTableValue( 167 , ( 0.529 , 0.706 , 0.000 ,1.0)) L1table.SetTableValue( 168 , ( 0.529 , 0.722 , 0.000 ,1.0)) L1table.SetTableValue( 169 , ( 0.529 , 0.737 , 0.000 ,1.0)) L1table.SetTableValue( 170 , ( 0.529 , 0.753 , 0.000 ,1.0)) L1table.SetTableValue( 171 , ( 0.529 , 0.765 , 0.000 ,1.0)) L1table.SetTableValue( 172 , ( 0.529 , 0.784 , 0.000 ,1.0)) L1table.SetTableValue( 173 , ( 0.529 , 0.796 , 0.000 ,1.0)) L1table.SetTableValue( 174 , ( 0.529 , 0.804 , 0.000 ,1.0)) L1table.SetTableValue( 175 , ( 0.529 , 0.824 , 0.000 ,1.0)) L1table.SetTableValue( 176 , ( 0.529 , 0.839 , 0.000 ,1.0)) L1table.SetTableValue( 177 , ( 0.529 , 0.855 , 0.000 ,1.0)) L1table.SetTableValue( 178 , ( 0.529 , 0.871 , 0.000 ,1.0)) L1table.SetTableValue( 179 , ( 0.529 , 0.886 , 0.000 ,1.0)) L1table.SetTableValue( 180 , ( 0.529 , 0.906 , 0.000 ,1.0)) L1table.SetTableValue( 181 , ( 0.529 , 0.925 , 0.000 ,1.0)) L1table.SetTableValue( 182 , ( 0.529 , 0.937 , 0.000 ,1.0)) L1table.SetTableValue( 183 , ( 0.529 , 0.957 , 0.000 ,1.0)) L1table.SetTableValue( 184 , ( 0.529 , 0.976 , 0.000 ,1.0)) L1table.SetTableValue( 185 , ( 0.529 , 0.996 , 0.000 ,1.0)) L1table.SetTableValue( 186 , ( 0.529 , 1.000 , 0.004 ,1.0)) L1table.SetTableValue( 187 , ( 0.529 , 1.000 , 0.020 ,1.0)) L1table.SetTableValue( 188 , ( 0.529 , 1.000 , 0.039 ,1.0)) L1table.SetTableValue( 189 , ( 0.529 , 1.000 , 0.059 ,1.0)) L1table.SetTableValue( 190 , ( 0.529 , 1.000 , 0.078 ,1.0)) L1table.SetTableValue( 191 , ( 0.529 , 1.000 , 0.090 ,1.0)) L1table.SetTableValue( 192 , ( 0.529 , 1.000 , 0.110 ,1.0)) L1table.SetTableValue( 193 , ( 0.529 , 1.000 , 0.129 ,1.0)) L1table.SetTableValue( 194 , ( 0.529 , 1.000 , 0.149 ,1.0)) L1table.SetTableValue( 195 , ( 0.529 , 1.000 , 0.169 ,1.0)) L1table.SetTableValue( 196 , ( 0.529 , 1.000 , 0.176 ,1.0)) L1table.SetTableValue( 197 , ( 0.529 , 1.000 , 0.192 ,1.0)) L1table.SetTableValue( 198 , ( 0.529 , 1.000 , 0.212 ,1.0)) L1table.SetTableValue( 199 , ( 0.529 , 1.000 , 0.231 ,1.0)) L1table.SetTableValue( 200 , ( 0.529 , 1.000 , 0.255 ,1.0)) L1table.SetTableValue( 201 , ( 0.529 , 1.000 , 0.275 ,1.0)) L1table.SetTableValue( 202 , ( 0.529 , 1.000 , 0.290 ,1.0)) L1table.SetTableValue( 203 , ( 0.529 , 1.000 , 0.314 ,1.0)) L1table.SetTableValue( 204 , ( 0.529 , 1.000 , 0.329 ,1.0)) L1table.SetTableValue( 205 , ( 0.529 , 1.000 , 0.353 ,1.0)) L1table.SetTableValue( 206 , ( 0.529 , 1.000 , 0.373 ,1.0)) L1table.SetTableValue( 207 , ( 0.529 , 1.000 , 0.384 ,1.0)) L1table.SetTableValue( 208 , ( 0.529 , 1.000 , 0.408 ,1.0)) L1table.SetTableValue( 209 , ( 0.529 , 1.000 , 0.431 ,1.0)) L1table.SetTableValue( 210 , ( 0.529 , 1.000 , 0.455 ,1.0)) L1table.SetTableValue( 211 , ( 0.529 , 1.000 , 0.471 ,1.0)) L1table.SetTableValue( 212 , ( 0.529 , 1.000 , 0.490 ,1.0)) L1table.SetTableValue( 213 , ( 0.529 , 1.000 , 0.514 ,1.0)) L1table.SetTableValue( 214 , ( 0.529 , 1.000 , 0.537 ,1.0)) L1table.SetTableValue( 215 , ( 0.529 , 1.000 , 0.565 ,1.0)) L1table.SetTableValue( 216 , ( 0.529 , 1.000 , 0.584 ,1.0)) L1table.SetTableValue( 217 , ( 0.529 , 1.000 , 0.604 ,1.0)) L1table.SetTableValue( 218 , ( 0.529 , 1.000 , 0.620 ,1.0)) L1table.SetTableValue( 219 , ( 0.529 , 1.000 , 0.647 ,1.0)) L1table.SetTableValue( 220 , ( 0.529 , 1.000 , 0.675 ,1.0)) L1table.SetTableValue( 221 , ( 0.529 , 1.000 , 0.702 ,1.0)) L1table.SetTableValue( 222 , ( 0.529 , 1.000 , 0.729 ,1.0)) L1table.SetTableValue( 223 , ( 0.529 , 1.000 , 0.749 ,1.0)) L1table.SetTableValue( 224 , ( 0.529 , 1.000 , 0.776 ,1.0)) L1table.SetTableValue( 225 , ( 0.529 , 1.000 , 0.796 ,1.0)) L1table.SetTableValue( 226 , ( 0.529 , 1.000 , 0.827 ,1.0)) L1table.SetTableValue( 227 , ( 0.529 , 1.000 , 0.847 ,1.0)) L1table.SetTableValue( 228 , ( 0.529 , 1.000 , 0.878 ,1.0)) L1table.SetTableValue( 229 , ( 0.529 , 1.000 , 0.910 ,1.0)) L1table.SetTableValue( 230 , ( 0.529 , 1.000 , 0.941 ,1.0)) L1table.SetTableValue( 231 , ( 0.529 , 1.000 , 0.973 ,1.0)) L1table.SetTableValue( 232 , ( 0.529 , 1.000 , 0.996 ,1.0)) L1table.SetTableValue( 233 , ( 0.529 , 1.000 , 1.000 ,1.0)) L1table.SetTableValue( 234 , ( 0.549 , 1.000 , 1.000 ,1.0)) L1table.SetTableValue( 235 , ( 0.573 , 1.000 , 1.000 ,1.0)) L1table.SetTableValue( 236 , ( 0.600 , 1.000 , 1.000 ,1.0)) L1table.SetTableValue( 237 , ( 0.612 , 1.000 , 1.000 ,1.0)) L1table.SetTableValue( 238 , ( 0.631 , 1.000 , 1.000 ,1.0)) L1table.SetTableValue( 239 , ( 0.659 , 1.000 , 1.000 ,1.0)) L1table.SetTableValue( 240 , ( 0.675 , 1.000 , 1.000 ,1.0)) L1table.SetTableValue( 241 , ( 0.694 , 1.000 , 1.000 ,1.0)) L1table.SetTableValue( 242 , ( 0.714 , 1.000 , 1.000 ,1.0)) L1table.SetTableValue( 243 , ( 0.741 , 1.000 , 1.000 ,1.0)) L1table.SetTableValue( 244 , ( 0.753 , 1.000 , 1.000 ,1.0)) L1table.SetTableValue( 245 , ( 0.780 , 1.000 , 1.000 ,1.0)) L1table.SetTableValue( 246 , ( 0.800 , 1.000 , 1.000 ,1.0)) L1table.SetTableValue( 247 , ( 0.824 , 1.000 , 1.000 ,1.0)) L1table.SetTableValue( 248 , ( 0.843 , 1.000 , 1.000 ,1.0)) L1table.SetTableValue( 249 , ( 0.863 , 1.000 , 1.000 ,1.0)) L1table.SetTableValue( 250 , ( 0.882 , 1.000 , 1.000 ,1.0)) L1table.SetTableValue( 251 , ( 0.910 , 1.000 , 1.000 ,1.0)) L1table.SetTableValue( 252 , ( 0.925 , 1.000 , 1.000 ,1.0)) L1table.SetTableValue( 253 , ( 0.941 , 1.000 , 1.000 ,1.0)) L1table.SetTableValue( 254 , ( 0.973 , 1.000 , 1.000 ,1.0)) L1table.SetTableValue( 255 , ( 1.000 , 1.000 , 1.000 ,1.0)) L1table.Build() self.Linear_Heat = L1table return self.Linear_Heat def LUT_Linear_BlackToWhite(self, LUrange): try: return self.Linear_BlackToWhite except AttributeError: L1table = vtk.vtkLookupTable() L1table.SetRange(LUrange[0], LUrange[1]) L1table.SetNumberOfColors(256) L1table.SetTableValue( 0 , ( 0.000 , 0.000 , 0.000 ,1.0)) L1table.SetTableValue( 1 , ( 0.000 , 0.000 , 0.000 ,1.0)) L1table.SetTableValue( 2 , ( 0.000 , 0.000 , 0.000 ,1.0)) L1table.SetTableValue( 3 , ( 0.000 , 0.000 , 0.000 ,1.0)) L1table.SetTableValue( 4 , ( 0.000 , 0.000 , 0.000 ,1.0)) L1table.SetTableValue( 5 , ( 0.000 , 0.000 , 0.000 ,1.0)) L1table.SetTableValue( 6 , ( 0.000 , 0.000 , 0.000 ,1.0)) L1table.SetTableValue( 7 , ( 0.004 , 0.004 , 0.004 ,1.0)) L1table.SetTableValue( 8 , ( 0.004 , 0.004 , 0.004 ,1.0)) L1table.SetTableValue( 9 , ( 0.004 , 0.004 , 0.004 ,1.0)) L1table.SetTableValue( 10 , ( 0.004 , 0.004 , 0.004 ,1.0)) L1table.SetTableValue( 11 , ( 0.004 , 0.004 , 0.004 ,1.0)) L1table.SetTableValue( 12 , ( 0.004 , 0.004 , 0.004 ,1.0)) L1table.SetTableValue( 13 , ( 0.004 , 0.004 , 0.004 ,1.0)) L1table.SetTableValue( 14 , ( 0.004 , 0.004 , 0.004 ,1.0)) L1table.SetTableValue( 15 , ( 0.004 , 0.004 , 0.004 ,1.0)) L1table.SetTableValue( 16 , ( 0.008 , 0.008 , 0.008 ,1.0)) L1table.SetTableValue( 17 , ( 0.008 , 0.008 , 0.008 ,1.0)) L1table.SetTableValue( 18 , ( 0.008 , 0.008 , 0.008 ,1.0)) L1table.SetTableValue( 19 , ( 0.008 , 0.008 , 0.008 ,1.0)) L1table.SetTableValue( 20 , ( 0.008 , 0.008 , 0.008 ,1.0)) L1table.SetTableValue( 21 , ( 0.008 , 0.008 , 0.008 ,1.0)) L1table.SetTableValue( 22 , ( 0.008 , 0.008 , 0.008 ,1.0)) L1table.SetTableValue( 23 , ( 0.012 , 0.012 , 0.012 ,1.0)) L1table.SetTableValue( 24 , ( 0.012 , 0.012 , 0.012 ,1.0)) L1table.SetTableValue( 25 , ( 0.012 , 0.012 , 0.012 ,1.0)) L1table.SetTableValue( 26 , ( 0.012 , 0.012 , 0.012 ,1.0)) L1table.SetTableValue( 27 , ( 0.012 , 0.012 , 0.012 ,1.0)) L1table.SetTableValue( 28 , ( 0.012 , 0.012 , 0.012 ,1.0)) L1table.SetTableValue( 29 , ( 0.012 , 0.012 , 0.012 ,1.0)) L1table.SetTableValue( 30 , ( 0.016 , 0.016 , 0.016 ,1.0)) L1table.SetTableValue( 31 , ( 0.016 , 0.016 , 0.016 ,1.0)) L1table.SetTableValue( 32 , ( 0.016 , 0.016 , 0.016 ,1.0)) L1table.SetTableValue( 33 , ( 0.016 , 0.016 , 0.016 ,1.0)) L1table.SetTableValue( 34 , ( 0.016 , 0.016 , 0.016 ,1.0)) L1table.SetTableValue( 35 , ( 0.020 , 0.020 , 0.020 ,1.0)) L1table.SetTableValue( 36 , ( 0.020 , 0.020 , 0.020 ,1.0)) L1table.SetTableValue( 37 , ( 0.020 , 0.020 , 0.020 ,1.0)) L1table.SetTableValue( 38 , ( 0.020 , 0.020 , 0.020 ,1.0)) L1table.SetTableValue( 39 , ( 0.020 , 0.020 , 0.020 ,1.0)) L1table.SetTableValue( 40 , ( 0.024 , 0.024 , 0.024 ,1.0)) L1table.SetTableValue( 41 , ( 0.024 , 0.024 , 0.024 ,1.0)) L1table.SetTableValue( 42 , ( 0.024 , 0.024 , 0.024 ,1.0)) L1table.SetTableValue( 43 , ( 0.024 , 0.024 , 0.024 ,1.0)) L1table.SetTableValue( 44 , ( 0.024 , 0.024 , 0.024 ,1.0)) L1table.SetTableValue( 45 , ( 0.027 , 0.027 , 0.027 ,1.0)) L1table.SetTableValue( 46 , ( 0.027 , 0.027 , 0.027 ,1.0)) L1table.SetTableValue( 47 , ( 0.027 , 0.027 , 0.027 ,1.0)) L1table.SetTableValue( 48 , ( 0.027 , 0.027 , 0.027 ,1.0)) L1table.SetTableValue( 49 , ( 0.027 , 0.027 , 0.027 ,1.0)) L1table.SetTableValue( 50 , ( 0.031 , 0.031 , 0.031 ,1.0)) L1table.SetTableValue( 51 , ( 0.031 , 0.031 , 0.031 ,1.0)) L1table.SetTableValue( 52 , ( 0.035 , 0.035 , 0.035 ,1.0)) L1table.SetTableValue( 53 , ( 0.035 , 0.035 , 0.035 ,1.0)) L1table.SetTableValue( 54 , ( 0.035 , 0.035 , 0.035 ,1.0)) L1table.SetTableValue( 55 , ( 0.035 , 0.035 , 0.035 ,1.0)) L1table.SetTableValue( 56 , ( 0.039 , 0.039 , 0.039 ,1.0)) L1table.SetTableValue( 57 , ( 0.039 , 0.039 , 0.039 ,1.0)) L1table.SetTableValue( 58 , ( 0.039 , 0.039 , 0.039 ,1.0)) L1table.SetTableValue( 59 , ( 0.039 , 0.039 , 0.039 ,1.0)) L1table.SetTableValue( 60 , ( 0.039 , 0.039 , 0.039 ,1.0)) L1table.SetTableValue( 61 , ( 0.043 , 0.043 , 0.043 ,1.0)) L1table.SetTableValue( 62 , ( 0.043 , 0.043 , 0.043 ,1.0)) L1table.SetTableValue( 63 , ( 0.047 , 0.047 , 0.047 ,1.0)) L1table.SetTableValue( 64 , ( 0.047 , 0.047 , 0.047 ,1.0)) L1table.SetTableValue( 65 , ( 0.047 , 0.047 , 0.047 ,1.0)) L1table.SetTableValue( 66 , ( 0.051 , 0.051 , 0.051 ,1.0)) L1table.SetTableValue( 67 , ( 0.051 , 0.051 , 0.051 ,1.0)) L1table.SetTableValue( 68 , ( 0.055 , 0.055 , 0.055 ,1.0)) L1table.SetTableValue( 69 , ( 0.055 , 0.055 , 0.055 ,1.0)) L1table.SetTableValue( 70 , ( 0.059 , 0.059 , 0.059 ,1.0)) L1table.SetTableValue( 71 , ( 0.059 , 0.059 , 0.059 ,1.0)) L1table.SetTableValue( 72 , ( 0.059 , 0.059 , 0.059 ,1.0)) L1table.SetTableValue( 73 , ( 0.063 , 0.063 , 0.063 ,1.0)) L1table.SetTableValue( 74 , ( 0.063 , 0.063 , 0.063 ,1.0)) L1table.SetTableValue( 75 , ( 0.067 , 0.067 , 0.067 ,1.0)) L1table.SetTableValue( 76 , ( 0.067 , 0.067 , 0.067 ,1.0)) L1table.SetTableValue( 77 , ( 0.071 , 0.071 , 0.071 ,1.0)) L1table.SetTableValue( 78 , ( 0.071 , 0.071 , 0.071 ,1.0)) L1table.SetTableValue( 79 , ( 0.075 , 0.075 , 0.075 ,1.0)) L1table.SetTableValue( 80 , ( 0.075 , 0.075 , 0.075 ,1.0)) L1table.SetTableValue( 81 , ( 0.075 , 0.075 , 0.075 ,1.0)) L1table.SetTableValue( 82 , ( 0.075 , 0.075 , 0.075 ,1.0)) L1table.SetTableValue( 83 , ( 0.075 , 0.075 , 0.075 ,1.0)) L1table.SetTableValue( 84 , ( 0.078 , 0.078 , 0.078 ,1.0)) L1table.SetTableValue( 85 , ( 0.078 , 0.078 , 0.078 ,1.0)) L1table.SetTableValue( 86 , ( 0.086 , 0.086 , 0.086 ,1.0)) L1table.SetTableValue( 87 , ( 0.086 , 0.086 , 0.086 ,1.0)) L1table.SetTableValue( 88 , ( 0.086 , 0.086 , 0.086 ,1.0)) L1table.SetTableValue( 89 , ( 0.090 , 0.090 , 0.090 ,1.0)) L1table.SetTableValue( 90 , ( 0.090 , 0.090 , 0.090 ,1.0)) L1table.SetTableValue( 91 , ( 0.094 , 0.094 , 0.094 ,1.0)) L1table.SetTableValue( 92 , ( 0.094 , 0.094 , 0.094 ,1.0)) L1table.SetTableValue( 93 , ( 0.102 , 0.102 , 0.102 ,1.0)) L1table.SetTableValue( 94 , ( 0.102 , 0.102 , 0.102 ,1.0)) L1table.SetTableValue( 95 , ( 0.102 , 0.102 , 0.102 ,1.0)) L1table.SetTableValue( 96 , ( 0.106 , 0.106 , 0.106 ,1.0)) L1table.SetTableValue( 97 , ( 0.106 , 0.106 , 0.106 ,1.0)) L1table.SetTableValue( 98 , ( 0.114 , 0.114 , 0.114 ,1.0)) L1table.SetTableValue( 99 , ( 0.114 , 0.114 , 0.114 ,1.0)) L1table.SetTableValue( 100 , ( 0.118 , 0.118 , 0.118 ,1.0)) L1table.SetTableValue( 101 , ( 0.118 , 0.118 , 0.118 ,1.0)) L1table.SetTableValue( 102 , ( 0.125 , 0.125 , 0.125 ,1.0)) L1table.SetTableValue( 103 , ( 0.125 , 0.125 , 0.125 ,1.0)) L1table.SetTableValue( 104 , ( 0.125 , 0.125 , 0.125 ,1.0)) L1table.SetTableValue( 105 , ( 0.125 , 0.125 , 0.125 ,1.0)) L1table.SetTableValue( 106 , ( 0.125 , 0.125 , 0.125 ,1.0)) L1table.SetTableValue( 107 , ( 0.133 , 0.133 , 0.133 ,1.0)) L1table.SetTableValue( 108 , ( 0.133 , 0.133 , 0.133 ,1.0)) L1table.SetTableValue( 109 , ( 0.137 , 0.137 , 0.137 ,1.0)) L1table.SetTableValue( 110 , ( 0.137 , 0.137 , 0.137 ,1.0)) L1table.SetTableValue( 111 , ( 0.137 , 0.137 , 0.137 ,1.0)) L1table.SetTableValue( 112 , ( 0.145 , 0.145 , 0.145 ,1.0)) L1table.SetTableValue( 113 , ( 0.145 , 0.145 , 0.145 ,1.0)) L1table.SetTableValue( 114 , ( 0.153 , 0.153 , 0.153 ,1.0)) L1table.SetTableValue( 115 , ( 0.153 , 0.153 , 0.153 ,1.0)) L1table.SetTableValue( 116 , ( 0.161 , 0.161 , 0.161 ,1.0)) L1table.SetTableValue( 117 , ( 0.161 , 0.161 , 0.161 ,1.0)) L1table.SetTableValue( 118 , ( 0.161 , 0.161 , 0.161 ,1.0)) L1table.SetTableValue( 119 , ( 0.169 , 0.169 , 0.169 ,1.0)) L1table.SetTableValue( 120 , ( 0.169 , 0.169 , 0.169 ,1.0)) L1table.SetTableValue( 121 , ( 0.176 , 0.176 , 0.176 ,1.0)) L1table.SetTableValue( 122 , ( 0.176 , 0.176 , 0.176 ,1.0)) L1table.SetTableValue( 123 , ( 0.180 , 0.180 , 0.180 ,1.0)) L1table.SetTableValue( 124 , ( 0.180 , 0.180 , 0.180 ,1.0)) L1table.SetTableValue( 125 , ( 0.180 , 0.180 , 0.180 ,1.0)) L1table.SetTableValue( 126 , ( 0.184 , 0.184 , 0.184 ,1.0)) L1table.SetTableValue( 127 , ( 0.184 , 0.184 , 0.184 ,1.0)) L1table.SetTableValue( 128 , ( 0.192 , 0.192 , 0.192 ,1.0)) L1table.SetTableValue( 129 , ( 0.192 , 0.192 , 0.192 ,1.0)) L1table.SetTableValue( 130 , ( 0.200 , 0.200 , 0.200 ,1.0)) L1table.SetTableValue( 131 , ( 0.200 , 0.200 , 0.200 ,1.0)) L1table.SetTableValue( 132 , ( 0.204 , 0.204 , 0.204 ,1.0)) L1table.SetTableValue( 133 , ( 0.204 , 0.204 , 0.204 ,1.0)) L1table.SetTableValue( 134 , ( 0.204 , 0.204 , 0.204 ,1.0)) L1table.SetTableValue( 135 , ( 0.212 , 0.212 , 0.212 ,1.0)) L1table.SetTableValue( 136 , ( 0.212 , 0.212 , 0.212 ,1.0)) L1table.SetTableValue( 137 , ( 0.220 , 0.220 , 0.220 ,1.0)) L1table.SetTableValue( 138 , ( 0.220 , 0.220 , 0.220 ,1.0)) L1table.SetTableValue( 139 , ( 0.231 , 0.231 , 0.231 ,1.0)) L1table.SetTableValue( 140 , ( 0.231 , 0.231 , 0.231 ,1.0)) L1table.SetTableValue( 141 , ( 0.231 , 0.231 , 0.231 ,1.0)) L1table.SetTableValue( 142 , ( 0.239 , 0.239 , 0.239 ,1.0)) L1table.SetTableValue( 143 , ( 0.239 , 0.239 , 0.239 ,1.0)) L1table.SetTableValue( 144 , ( 0.251 , 0.251 , 0.251 ,1.0)) L1table.SetTableValue( 145 , ( 0.251 , 0.251 , 0.251 ,1.0)) L1table.SetTableValue( 146 , ( 0.263 , 0.263 , 0.263 ,1.0)) L1table.SetTableValue( 147 , ( 0.263 , 0.263 , 0.263 ,1.0)) L1table.SetTableValue( 148 , ( 0.263 , 0.263 , 0.263 ,1.0)) L1table.SetTableValue( 149 , ( 0.271 , 0.271 , 0.271 ,1.0)) L1table.SetTableValue( 150 , ( 0.271 , 0.271 , 0.271 ,1.0)) L1table.SetTableValue( 151 , ( 0.282 , 0.282 , 0.282 ,1.0)) L1table.SetTableValue( 152 , ( 0.282 , 0.282 , 0.282 ,1.0)) L1table.SetTableValue( 153 , ( 0.294 , 0.294 , 0.294 ,1.0)) L1table.SetTableValue( 154 , ( 0.294 , 0.294 , 0.294 ,1.0)) L1table.SetTableValue( 155 , ( 0.298 , 0.298 , 0.298 ,1.0)) L1table.SetTableValue( 156 , ( 0.298 , 0.298 , 0.298 ,1.0)) L1table.SetTableValue( 157 , ( 0.298 , 0.298 , 0.298 ,1.0)) L1table.SetTableValue( 158 , ( 0.306 , 0.306 , 0.306 ,1.0)) L1table.SetTableValue( 159 , ( 0.306 , 0.306 , 0.306 ,1.0)) L1table.SetTableValue( 160 , ( 0.318 , 0.318 , 0.318 ,1.0)) L1table.SetTableValue( 161 , ( 0.318 , 0.318 , 0.318 ,1.0)) L1table.SetTableValue( 162 , ( 0.329 , 0.329 , 0.329 ,1.0)) L1table.SetTableValue( 163 , ( 0.329 , 0.329 , 0.329 ,1.0)) L1table.SetTableValue( 164 , ( 0.329 , 0.329 , 0.329 ,1.0)) L1table.SetTableValue( 165 , ( 0.341 , 0.341 , 0.341 ,1.0)) L1table.SetTableValue( 166 , ( 0.341 , 0.341 , 0.341 ,1.0)) L1table.SetTableValue( 167 , ( 0.357 , 0.357 , 0.357 ,1.0)) L1table.SetTableValue( 168 , ( 0.357 , 0.357 , 0.357 ,1.0)) L1table.SetTableValue( 169 , ( 0.369 , 0.369 , 0.369 ,1.0)) L1table.SetTableValue( 170 , ( 0.369 , 0.369 , 0.369 ,1.0)) L1table.SetTableValue( 171 , ( 0.369 , 0.369 , 0.369 ,1.0)) L1table.SetTableValue( 172 , ( 0.380 , 0.380 , 0.380 ,1.0)) L1table.SetTableValue( 173 , ( 0.380 , 0.380 , 0.380 ,1.0)) L1table.SetTableValue( 174 , ( 0.396 , 0.396 , 0.396 ,1.0)) L1table.SetTableValue( 175 , ( 0.396 , 0.396 , 0.396 ,1.0)) L1table.SetTableValue( 176 , ( 0.408 , 0.408 , 0.408 ,1.0)) L1table.SetTableValue( 177 , ( 0.408 , 0.408 , 0.408 ,1.0)) L1table.SetTableValue( 178 , ( 0.420 , 0.420 , 0.420 ,1.0)) L1table.SetTableValue( 179 , ( 0.420 , 0.420 , 0.420 ,1.0)) L1table.SetTableValue( 180 , ( 0.420 , 0.420 , 0.420 ,1.0)) L1table.SetTableValue( 181 , ( 0.424 , 0.424 , 0.424 ,1.0)) L1table.SetTableValue( 182 , ( 0.424 , 0.424 , 0.424 ,1.0)) L1table.SetTableValue( 183 , ( 0.439 , 0.439 , 0.439 ,1.0)) L1table.SetTableValue( 184 , ( 0.439 , 0.439 , 0.439 ,1.0)) L1table.SetTableValue( 185 , ( 0.455 , 0.455 , 0.455 ,1.0)) L1table.SetTableValue( 186 , ( 0.455 , 0.455 , 0.455 ,1.0)) L1table.SetTableValue( 187 , ( 0.455 , 0.455 , 0.455 ,1.0)) L1table.SetTableValue( 188 , ( 0.471 , 0.471 , 0.471 ,1.0)) L1table.SetTableValue( 189 , ( 0.471 , 0.471 , 0.471 ,1.0)) L1table.SetTableValue( 190 , ( 0.486 , 0.486 , 0.486 ,1.0)) L1table.SetTableValue( 191 , ( 0.486 , 0.486 , 0.486 ,1.0)) L1table.SetTableValue( 192 , ( 0.502 , 0.502 , 0.502 ,1.0)) L1table.SetTableValue( 193 , ( 0.502 , 0.502 , 0.502 ,1.0)) L1table.SetTableValue( 194 , ( 0.502 , 0.502 , 0.502 ,1.0)) L1table.SetTableValue( 195 , ( 0.518 , 0.518 , 0.518 ,1.0)) L1table.SetTableValue( 196 , ( 0.518 , 0.518 , 0.518 ,1.0)) L1table.SetTableValue( 197 , ( 0.533 , 0.533 , 0.533 ,1.0)) L1table.SetTableValue( 198 , ( 0.533 , 0.533 , 0.533 ,1.0)) L1table.SetTableValue( 199 , ( 0.553 , 0.553 , 0.553 ,1.0)) L1table.SetTableValue( 200 , ( 0.553 , 0.553 , 0.553 ,1.0)) L1table.SetTableValue( 201 , ( 0.569 , 0.569 , 0.569 ,1.0)) L1table.SetTableValue( 202 , ( 0.569 , 0.569 , 0.569 ,1.0)) L1table.SetTableValue( 203 , ( 0.569 , 0.569 , 0.569 ,1.0)) L1table.SetTableValue( 204 , ( 0.576 , 0.576 , 0.576 ,1.0)) L1table.SetTableValue( 205 , ( 0.576 , 0.576 , 0.576 ,1.0)) L1table.SetTableValue( 206 , ( 0.588 , 0.588 , 0.588 ,1.0)) L1table.SetTableValue( 207 , ( 0.588 , 0.588 , 0.588 ,1.0)) L1table.SetTableValue( 208 , ( 0.604 , 0.604 , 0.604 ,1.0)) L1table.SetTableValue( 209 , ( 0.604 , 0.604 , 0.604 ,1.0)) L1table.SetTableValue( 210 , ( 0.604 , 0.604 , 0.604 ,1.0)) L1table.SetTableValue( 211 , ( 0.624 , 0.624 , 0.624 ,1.0)) L1table.SetTableValue( 212 , ( 0.624 , 0.624 , 0.624 ,1.0)) L1table.SetTableValue( 213 , ( 0.643 , 0.643 , 0.643 ,1.0)) L1table.SetTableValue( 214 , ( 0.643 , 0.643 , 0.643 ,1.0)) L1table.SetTableValue( 215 , ( 0.663 , 0.663 , 0.663 ,1.0)) L1table.SetTableValue( 216 , ( 0.663 , 0.663 , 0.663 ,1.0)) L1table.SetTableValue( 217 , ( 0.663 , 0.663 , 0.663 ,1.0)) L1table.SetTableValue( 218 , ( 0.682 , 0.682 , 0.682 ,1.0)) L1table.SetTableValue( 219 , ( 0.682 , 0.682 , 0.682 ,1.0)) L1table.SetTableValue( 220 , ( 0.702 , 0.702 , 0.702 ,1.0)) L1table.SetTableValue( 221 , ( 0.702 , 0.702 , 0.702 ,1.0)) L1table.SetTableValue( 222 , ( 0.725 , 0.725 , 0.725 ,1.0)) L1table.SetTableValue( 223 , ( 0.725 , 0.725 , 0.725 ,1.0)) L1table.SetTableValue( 224 , ( 0.745 , 0.745 , 0.745 ,1.0)) L1table.SetTableValue( 225 , ( 0.745 , 0.745 , 0.745 ,1.0)) L1table.SetTableValue( 226 , ( 0.745 , 0.745 , 0.745 ,1.0)) L1table.SetTableValue( 227 , ( 0.765 , 0.765 , 0.765 ,1.0)) L1table.SetTableValue( 228 , ( 0.765 , 0.765 , 0.765 ,1.0)) L1table.SetTableValue( 229 , ( 0.765 , 0.765 , 0.765 ,1.0)) L1table.SetTableValue( 230 , ( 0.765 , 0.765 , 0.765 ,1.0)) L1table.SetTableValue( 231 , ( 0.788 , 0.788 , 0.788 ,1.0)) L1table.SetTableValue( 232 , ( 0.788 , 0.788 , 0.788 ,1.0)) L1table.SetTableValue( 233 , ( 0.788 , 0.788 , 0.788 ,1.0)) L1table.SetTableValue( 234 , ( 0.812 , 0.812 , 0.812 ,1.0)) L1table.SetTableValue( 235 , ( 0.812 , 0.812 , 0.812 ,1.0)) L1table.SetTableValue( 236 , ( 0.831 , 0.831 , 0.831 ,1.0)) L1table.SetTableValue( 237 , ( 0.831 , 0.831 , 0.831 ,1.0)) L1table.SetTableValue( 238 , ( 0.855 , 0.855 , 0.855 ,1.0)) L1table.SetTableValue( 239 , ( 0.855 , 0.855 , 0.855 ,1.0)) L1table.SetTableValue( 240 , ( 0.855 , 0.855 , 0.855 ,1.0)) L1table.SetTableValue( 241 , ( 0.878 , 0.878 , 0.878 ,1.0)) L1table.SetTableValue( 242 , ( 0.878 , 0.878 , 0.878 ,1.0)) L1table.SetTableValue( 243 , ( 0.902 , 0.902 , 0.902 ,1.0)) L1table.SetTableValue( 244 , ( 0.902 , 0.902 , 0.902 ,1.0)) L1table.SetTableValue( 245 , ( 0.929 , 0.929 , 0.929 ,1.0)) L1table.SetTableValue( 246 , ( 0.929 , 0.929 , 0.929 ,1.0)) L1table.SetTableValue( 247 , ( 0.953 , 0.953 , 0.953 ,1.0)) L1table.SetTableValue( 248 , ( 0.953 , 0.953 , 0.953 ,1.0)) L1table.SetTableValue( 249 , ( 0.953 , 0.953 , 0.953 ,1.0)) L1table.SetTableValue( 250 , ( 0.976 , 0.976 , 0.976 ,1.0)) L1table.SetTableValue( 251 , ( 0.976 , 0.976 , 0.976 ,1.0)) L1table.SetTableValue( 252 , ( 0.988 , 0.988 , 0.988 ,1.0)) L1table.SetTableValue( 253 , ( 0.988 , 0.988 , 0.988 ,1.0)) L1table.SetTableValue( 254 , ( 0.988 , 0.988 , 0.988 ,1.0)) L1table.SetTableValue( 255 , ( 1.000 , 1.000 , 1.000 ,1.0)) L1table.Build() self.Linear_BlackToWhite = L1table return self.Linear_BlackToWhite def LUT_Linear_BlueToYellow(self, LUrange): try: return self.Linear_BlueToYellow except AttributeError: L1table = vtk.vtkLookupTable() L1table.SetRange(LUrange[0], LUrange[1]) L1table.SetNumberOfColors(256) L1table.SetTableValue( 0 , ( 0.027 , 0.027 , 0.996 ,1.0)) L1table.SetTableValue( 1 , ( 0.090 , 0.090 , 0.988 ,1.0)) L1table.SetTableValue( 2 , ( 0.118 , 0.118 , 0.980 ,1.0)) L1table.SetTableValue( 3 , ( 0.141 , 0.141 , 0.973 ,1.0)) L1table.SetTableValue( 4 , ( 0.157 , 0.157 , 0.969 ,1.0)) L1table.SetTableValue( 5 , ( 0.173 , 0.173 , 0.961 ,1.0)) L1table.SetTableValue( 6 , ( 0.184 , 0.184 , 0.953 ,1.0)) L1table.SetTableValue( 7 , ( 0.196 , 0.196 , 0.949 ,1.0)) L1table.SetTableValue( 8 , ( 0.204 , 0.204 , 0.941 ,1.0)) L1table.SetTableValue( 9 , ( 0.216 , 0.216 , 0.937 ,1.0)) L1table.SetTableValue( 10 , ( 0.224 , 0.224 , 0.933 ,1.0)) L1table.SetTableValue( 11 , ( 0.231 , 0.231 , 0.925 ,1.0)) L1table.SetTableValue( 12 , ( 0.239 , 0.239 , 0.922 ,1.0)) L1table.SetTableValue( 13 , ( 0.247 , 0.247 , 0.918 ,1.0)) L1table.SetTableValue( 14 , ( 0.255 , 0.255 , 0.914 ,1.0)) L1table.SetTableValue( 15 , ( 0.259 , 0.259 , 0.906 ,1.0)) L1table.SetTableValue( 16 , ( 0.267 , 0.267 , 0.902 ,1.0)) L1table.SetTableValue( 17 , ( 0.271 , 0.271 , 0.898 ,1.0)) L1table.SetTableValue( 18 , ( 0.278 , 0.278 , 0.894 ,1.0)) L1table.SetTableValue( 19 , ( 0.282 , 0.282 , 0.890 ,1.0)) L1table.SetTableValue( 20 , ( 0.290 , 0.290 , 0.886 ,1.0)) L1table.SetTableValue( 21 , ( 0.294 , 0.294 , 0.882 ,1.0)) L1table.SetTableValue( 22 , ( 0.298 , 0.298 , 0.882 ,1.0)) L1table.SetTableValue( 23 , ( 0.306 , 0.306 , 0.878 ,1.0)) L1table.SetTableValue( 24 , ( 0.310 , 0.310 , 0.875 ,1.0)) L1table.SetTableValue( 25 , ( 0.314 , 0.314 , 0.871 ,1.0)) L1table.SetTableValue( 26 , ( 0.318 , 0.318 , 0.867 ,1.0)) L1table.SetTableValue( 27 , ( 0.322 , 0.322 , 0.867 ,1.0)) L1table.SetTableValue( 28 , ( 0.329 , 0.329 , 0.863 ,1.0)) L1table.SetTableValue( 29 , ( 0.333 , 0.333 , 0.859 ,1.0)) L1table.SetTableValue( 30 , ( 0.337 , 0.337 , 0.855 ,1.0)) L1table.SetTableValue( 31 , ( 0.341 , 0.341 , 0.855 ,1.0)) L1table.SetTableValue( 32 , ( 0.345 , 0.345 , 0.851 ,1.0)) L1table.SetTableValue( 33 , ( 0.349 , 0.349 , 0.847 ,1.0)) L1table.SetTableValue( 34 , ( 0.353 , 0.353 , 0.847 ,1.0)) L1table.SetTableValue( 35 , ( 0.357 , 0.357 , 0.843 ,1.0)) L1table.SetTableValue( 36 , ( 0.361 , 0.361 , 0.839 ,1.0)) L1table.SetTableValue( 37 , ( 0.365 , 0.365 , 0.839 ,1.0)) L1table.SetTableValue( 38 , ( 0.369 , 0.369 , 0.835 ,1.0)) L1table.SetTableValue( 39 , ( 0.373 , 0.373 , 0.835 ,1.0)) L1table.SetTableValue( 40 , ( 0.376 , 0.376 , 0.831 ,1.0)) L1table.SetTableValue( 41 , ( 0.380 , 0.380 , 0.831 ,1.0)) L1table.SetTableValue( 42 , ( 0.384 , 0.384 , 0.827 ,1.0)) L1table.SetTableValue( 43 , ( 0.384 , 0.384 , 0.824 ,1.0)) L1table.SetTableValue( 44 , ( 0.388 , 0.388 , 0.824 ,1.0)) L1table.SetTableValue( 45 , ( 0.392 , 0.392 , 0.820 ,1.0)) L1table.SetTableValue( 46 , ( 0.396 , 0.396 , 0.820 ,1.0)) L1table.SetTableValue( 47 , ( 0.400 , 0.400 , 0.816 ,1.0)) L1table.SetTableValue( 48 , ( 0.404 , 0.404 , 0.816 ,1.0)) L1table.SetTableValue( 49 , ( 0.408 , 0.408 , 0.816 ,1.0)) L1table.SetTableValue( 50 , ( 0.412 , 0.412 , 0.812 ,1.0)) L1table.SetTableValue( 51 , ( 0.412 , 0.412 , 0.812 ,1.0)) L1table.SetTableValue( 52 , ( 0.416 , 0.416 , 0.808 ,1.0)) L1table.SetTableValue( 53 , ( 0.420 , 0.420 , 0.808 ,1.0)) L1table.SetTableValue( 54 , ( 0.424 , 0.424 , 0.804 ,1.0)) L1table.SetTableValue( 55 , ( 0.427 , 0.427 , 0.804 ,1.0)) L1table.SetTableValue( 56 , ( 0.431 , 0.431 , 0.800 ,1.0)) L1table.SetTableValue( 57 , ( 0.431 , 0.431 , 0.800 ,1.0)) L1table.SetTableValue( 58 , ( 0.435 , 0.435 , 0.800 ,1.0)) L1table.SetTableValue( 59 , ( 0.439 , 0.439 , 0.796 ,1.0)) L1table.SetTableValue( 60 , ( 0.443 , 0.443 , 0.796 ,1.0)) L1table.SetTableValue( 61 , ( 0.447 , 0.447 , 0.792 ,1.0)) L1table.SetTableValue( 62 , ( 0.447 , 0.447 , 0.792 ,1.0)) L1table.SetTableValue( 63 , ( 0.451 , 0.451 , 0.792 ,1.0)) L1table.SetTableValue( 64 , ( 0.455 , 0.455 , 0.788 ,1.0)) L1table.SetTableValue( 65 , ( 0.459 , 0.459 , 0.788 ,1.0)) L1table.SetTableValue( 66 , ( 0.463 , 0.463 , 0.784 ,1.0)) L1table.SetTableValue( 67 , ( 0.463 , 0.463 , 0.784 ,1.0)) L1table.SetTableValue( 68 , ( 0.467 , 0.467 , 0.784 ,1.0)) L1table.SetTableValue( 69 , ( 0.471 , 0.471 , 0.780 ,1.0)) L1table.SetTableValue( 70 , ( 0.475 , 0.475 , 0.780 ,1.0)) L1table.SetTableValue( 71 , ( 0.475 , 0.475 , 0.780 ,1.0)) L1table.SetTableValue( 72 , ( 0.478 , 0.478 , 0.776 ,1.0)) L1table.SetTableValue( 73 , ( 0.482 , 0.482 , 0.776 ,1.0)) L1table.SetTableValue( 74 , ( 0.486 , 0.486 , 0.776 ,1.0)) L1table.SetTableValue( 75 , ( 0.486 , 0.486 , 0.773 ,1.0)) L1table.SetTableValue( 76 , ( 0.490 , 0.490 , 0.773 ,1.0)) L1table.SetTableValue( 77 , ( 0.494 , 0.494 , 0.773 ,1.0)) L1table.SetTableValue( 78 , ( 0.498 , 0.498 , 0.769 ,1.0)) L1table.SetTableValue( 79 , ( 0.502 , 0.502 , 0.769 ,1.0)) L1table.SetTableValue( 80 , ( 0.502 , 0.502 , 0.765 ,1.0)) L1table.SetTableValue( 81 , ( 0.506 , 0.506 , 0.765 ,1.0)) L1table.SetTableValue( 82 , ( 0.510 , 0.510 , 0.765 ,1.0)) L1table.SetTableValue( 83 , ( 0.510 , 0.510 , 0.761 ,1.0)) L1table.SetTableValue( 84 , ( 0.514 , 0.514 , 0.761 ,1.0)) L1table.SetTableValue( 85 , ( 0.518 , 0.518 , 0.761 ,1.0)) L1table.SetTableValue( 86 , ( 0.522 , 0.522 , 0.757 ,1.0)) L1table.SetTableValue( 87 , ( 0.522 , 0.522 , 0.757 ,1.0)) L1table.SetTableValue( 88 , ( 0.525 , 0.525 , 0.757 ,1.0)) L1table.SetTableValue( 89 , ( 0.529 , 0.529 , 0.753 ,1.0)) L1table.SetTableValue( 90 , ( 0.533 , 0.533 , 0.753 ,1.0)) L1table.SetTableValue( 91 , ( 0.533 , 0.533 , 0.753 ,1.0)) L1table.SetTableValue( 92 , ( 0.537 , 0.537 , 0.749 ,1.0)) L1table.SetTableValue( 93 , ( 0.541 , 0.541 , 0.749 ,1.0)) L1table.SetTableValue( 94 , ( 0.545 , 0.545 , 0.749 ,1.0)) L1table.SetTableValue( 95 , ( 0.545 , 0.545 , 0.745 ,1.0)) L1table.SetTableValue( 96 , ( 0.549 , 0.549 , 0.745 ,1.0)) L1table.SetTableValue( 97 , ( 0.553 , 0.553 , 0.745 ,1.0)) L1table.SetTableValue( 98 , ( 0.557 , 0.557 , 0.741 ,1.0)) L1table.SetTableValue( 99 , ( 0.557 , 0.557 , 0.741 ,1.0)) L1table.SetTableValue( 100 , ( 0.561 , 0.561 , 0.741 ,1.0)) L1table.SetTableValue( 101 , ( 0.565 , 0.565 , 0.737 ,1.0)) L1table.SetTableValue( 102 , ( 0.565 , 0.565 , 0.737 ,1.0)) L1table.SetTableValue( 103 , ( 0.569 , 0.569 , 0.737 ,1.0)) L1table.SetTableValue( 104 , ( 0.573 , 0.573 , 0.733 ,1.0)) L1table.SetTableValue( 105 , ( 0.576 , 0.576 , 0.733 ,1.0)) L1table.SetTableValue( 106 , ( 0.576 , 0.576 , 0.733 ,1.0)) L1table.SetTableValue( 107 , ( 0.580 , 0.580 , 0.729 ,1.0)) L1table.SetTableValue( 108 , ( 0.584 , 0.584 , 0.729 ,1.0)) L1table.SetTableValue( 109 , ( 0.584 , 0.584 , 0.729 ,1.0)) L1table.SetTableValue( 110 , ( 0.588 , 0.588 , 0.725 ,1.0)) L1table.SetTableValue( 111 , ( 0.592 , 0.592 , 0.725 ,1.0)) L1table.SetTableValue( 112 , ( 0.596 , 0.596 , 0.725 ,1.0)) L1table.SetTableValue( 113 , ( 0.596 , 0.596 , 0.722 ,1.0)) L1table.SetTableValue( 114 , ( 0.600 , 0.600 , 0.722 ,1.0)) L1table.SetTableValue( 115 , ( 0.604 , 0.604 , 0.722 ,1.0)) L1table.SetTableValue( 116 , ( 0.604 , 0.604 , 0.718 ,1.0)) L1table.SetTableValue( 117 , ( 0.608 , 0.608 , 0.718 ,1.0)) L1table.SetTableValue( 118 , ( 0.612 , 0.612 , 0.714 ,1.0)) L1table.SetTableValue( 119 , ( 0.616 , 0.616 , 0.714 ,1.0)) L1table.SetTableValue( 120 , ( 0.616 , 0.616 , 0.714 ,1.0)) L1table.SetTableValue( 121 , ( 0.620 , 0.620 , 0.710 ,1.0)) L1table.SetTableValue( 122 , ( 0.624 , 0.624 , 0.710 ,1.0)) L1table.SetTableValue( 123 , ( 0.624 , 0.624 , 0.710 ,1.0)) L1table.SetTableValue( 124 , ( 0.627 , 0.627 , 0.706 ,1.0)) L1table.SetTableValue( 125 , ( 0.631 , 0.631 , 0.706 ,1.0)) L1table.SetTableValue( 126 , ( 0.635 , 0.635 , 0.706 ,1.0)) L1table.SetTableValue( 127 , ( 0.635 , 0.635 , 0.702 ,1.0)) L1table.SetTableValue( 128 , ( 0.639 , 0.639 , 0.702 ,1.0)) L1table.SetTableValue( 129 , ( 0.643 , 0.643 , 0.698 ,1.0)) L1table.SetTableValue( 130 , ( 0.643 , 0.643 , 0.698 ,1.0)) L1table.SetTableValue( 131 , ( 0.647 , 0.647 , 0.698 ,1.0)) L1table.SetTableValue( 132 , ( 0.651 , 0.651 , 0.694 ,1.0)) L1table.SetTableValue( 133 , ( 0.655 , 0.655 , 0.694 ,1.0)) L1table.SetTableValue( 134 , ( 0.655 , 0.655 , 0.690 ,1.0)) L1table.SetTableValue( 135 , ( 0.659 , 0.659 , 0.690 ,1.0)) L1table.SetTableValue( 136 , ( 0.663 , 0.663 , 0.690 ,1.0)) L1table.SetTableValue( 137 , ( 0.663 , 0.663 , 0.686 ,1.0)) L1table.SetTableValue( 138 , ( 0.667 , 0.667 , 0.686 ,1.0)) L1table.SetTableValue( 139 , ( 0.671 , 0.671 , 0.682 ,1.0)) L1table.SetTableValue( 140 , ( 0.675 , 0.675 , 0.682 ,1.0)) L1table.SetTableValue( 141 , ( 0.675 , 0.675 , 0.678 ,1.0)) L1table.SetTableValue( 142 , ( 0.678 , 0.678 , 0.678 ,1.0)) L1table.SetTableValue( 143 , ( 0.682 , 0.682 , 0.678 ,1.0)) L1table.SetTableValue( 144 , ( 0.682 , 0.682 , 0.675 ,1.0)) L1table.SetTableValue( 145 , ( 0.686 , 0.686 , 0.675 ,1.0)) L1table.SetTableValue( 146 , ( 0.690 , 0.690 , 0.671 ,1.0)) L1table.SetTableValue( 147 , ( 0.694 , 0.694 , 0.671 ,1.0)) L1table.SetTableValue( 148 , ( 0.694 , 0.694 , 0.667 ,1.0)) L1table.SetTableValue( 149 , ( 0.698 , 0.698 , 0.667 ,1.0)) L1table.SetTableValue( 150 , ( 0.702 , 0.702 , 0.663 ,1.0)) L1table.SetTableValue( 151 , ( 0.702 , 0.702 , 0.663 ,1.0)) L1table.SetTableValue( 152 , ( 0.706 , 0.706 , 0.659 ,1.0)) L1table.SetTableValue( 153 , ( 0.710 , 0.710 , 0.659 ,1.0)) L1table.SetTableValue( 154 , ( 0.710 , 0.710 , 0.655 ,1.0)) L1table.SetTableValue( 155 , ( 0.714 , 0.714 , 0.655 ,1.0)) L1table.SetTableValue( 156 , ( 0.718 , 0.718 , 0.651 ,1.0)) L1table.SetTableValue( 157 , ( 0.722 , 0.722 , 0.651 ,1.0)) L1table.SetTableValue( 158 , ( 0.722 , 0.722 , 0.647 ,1.0)) L1table.SetTableValue( 159 , ( 0.725 , 0.725 , 0.647 ,1.0)) L1table.SetTableValue( 160 , ( 0.729 , 0.729 , 0.643 ,1.0)) L1table.SetTableValue( 161 , ( 0.729 , 0.729 , 0.643 ,1.0)) L1table.SetTableValue( 162 , ( 0.733 , 0.733 , 0.639 ,1.0)) L1table.SetTableValue( 163 , ( 0.737 , 0.737 , 0.639 ,1.0)) L1table.SetTableValue( 164 , ( 0.741 , 0.741 , 0.635 ,1.0)) L1table.SetTableValue( 165 , ( 0.741 , 0.741 , 0.635 ,1.0)) L1table.SetTableValue( 166 , ( 0.745 , 0.745 , 0.631 ,1.0)) L1table.SetTableValue( 167 , ( 0.749 , 0.749 , 0.631 ,1.0)) L1table.SetTableValue( 168 , ( 0.749 , 0.749 , 0.627 ,1.0)) L1table.SetTableValue( 169 , ( 0.753 , 0.753 , 0.624 ,1.0)) L1table.SetTableValue( 170 , ( 0.757 , 0.757 , 0.624 ,1.0)) L1table.SetTableValue( 171 , ( 0.761 , 0.761 , 0.620 ,1.0)) L1table.SetTableValue( 172 , ( 0.761 , 0.761 , 0.620 ,1.0)) L1table.SetTableValue( 173 , ( 0.765 , 0.765 , 0.616 ,1.0)) L1table.SetTableValue( 174 , ( 0.769 , 0.769 , 0.616 ,1.0)) L1table.SetTableValue( 175 , ( 0.769 , 0.769 , 0.612 ,1.0)) L1table.SetTableValue( 176 , ( 0.773 , 0.773 , 0.608 ,1.0)) L1table.SetTableValue( 177 , ( 0.776 , 0.776 , 0.608 ,1.0)) L1table.SetTableValue( 178 , ( 0.780 , 0.780 , 0.604 ,1.0)) L1table.SetTableValue( 179 , ( 0.780 , 0.780 , 0.600 ,1.0)) L1table.SetTableValue( 180 , ( 0.784 , 0.784 , 0.600 ,1.0)) L1table.SetTableValue( 181 , ( 0.788 , 0.788 , 0.596 ,1.0)) L1table.SetTableValue( 182 , ( 0.788 , 0.788 , 0.592 ,1.0)) L1table.SetTableValue( 183 , ( 0.792 , 0.792 , 0.592 ,1.0)) L1table.SetTableValue( 184 , ( 0.796 , 0.796 , 0.588 ,1.0)) L1table.SetTableValue( 185 , ( 0.800 , 0.800 , 0.584 ,1.0)) L1table.SetTableValue( 186 , ( 0.800 , 0.800 , 0.584 ,1.0)) L1table.SetTableValue( 187 , ( 0.804 , 0.804 , 0.580 ,1.0)) L1table.SetTableValue( 188 , ( 0.808 , 0.808 , 0.576 ,1.0)) L1table.SetTableValue( 189 , ( 0.808 , 0.808 , 0.573 ,1.0)) L1table.SetTableValue( 190 , ( 0.812 , 0.812 , 0.573 ,1.0)) L1table.SetTableValue( 191 , ( 0.816 , 0.816 , 0.569 ,1.0)) L1table.SetTableValue( 192 , ( 0.820 , 0.820 , 0.565 ,1.0)) L1table.SetTableValue( 193 , ( 0.820 , 0.820 , 0.561 ,1.0)) L1table.SetTableValue( 194 , ( 0.824 , 0.824 , 0.561 ,1.0)) L1table.SetTableValue( 195 , ( 0.827 , 0.827 , 0.557 ,1.0)) L1table.SetTableValue( 196 , ( 0.827 , 0.827 , 0.553 ,1.0)) L1table.SetTableValue( 197 , ( 0.831 , 0.831 , 0.549 ,1.0)) L1table.SetTableValue( 198 , ( 0.835 , 0.835 , 0.545 ,1.0)) L1table.SetTableValue( 199 , ( 0.839 , 0.839 , 0.541 ,1.0)) L1table.SetTableValue( 200 , ( 0.839 , 0.839 , 0.541 ,1.0)) L1table.SetTableValue( 201 , ( 0.843 , 0.843 , 0.537 ,1.0)) L1table.SetTableValue( 202 , ( 0.847 , 0.847 , 0.533 ,1.0)) L1table.SetTableValue( 203 , ( 0.847 , 0.847 , 0.529 ,1.0)) L1table.SetTableValue( 204 , ( 0.851 , 0.851 , 0.525 ,1.0)) L1table.SetTableValue( 205 , ( 0.855 , 0.855 , 0.522 ,1.0)) L1table.SetTableValue( 206 , ( 0.859 , 0.859 , 0.518 ,1.0)) L1table.SetTableValue( 207 , ( 0.859 , 0.859 , 0.514 ,1.0)) L1table.SetTableValue( 208 , ( 0.863 , 0.863 , 0.510 ,1.0)) L1table.SetTableValue( 209 , ( 0.867 , 0.867 , 0.506 ,1.0)) L1table.SetTableValue( 210 , ( 0.867 , 0.867 , 0.502 ,1.0)) L1table.SetTableValue( 211 , ( 0.871 , 0.871 , 0.498 ,1.0)) L1table.SetTableValue( 212 , ( 0.875 , 0.875 , 0.494 ,1.0)) L1table.SetTableValue( 213 , ( 0.878 , 0.878 , 0.490 ,1.0)) L1table.SetTableValue( 214 , ( 0.878 , 0.878 , 0.486 ,1.0)) L1table.SetTableValue( 215 , ( 0.882 , 0.882 , 0.482 ,1.0)) L1table.SetTableValue( 216 , ( 0.886 , 0.886 , 0.478 ,1.0)) L1table.SetTableValue( 217 , ( 0.886 , 0.886 , 0.475 ,1.0)) L1table.SetTableValue( 218 , ( 0.890 , 0.890 , 0.467 ,1.0)) L1table.SetTableValue( 219 , ( 0.894 , 0.894 , 0.463 ,1.0)) L1table.SetTableValue( 220 , ( 0.898 , 0.898 , 0.459 ,1.0)) L1table.SetTableValue( 221 , ( 0.898 , 0.898 , 0.455 ,1.0)) L1table.SetTableValue( 222 , ( 0.902 , 0.902 , 0.447 ,1.0)) L1table.SetTableValue( 223 , ( 0.906 , 0.906 , 0.443 ,1.0)) L1table.SetTableValue( 224 , ( 0.910 , 0.910 , 0.439 ,1.0)) L1table.SetTableValue( 225 , ( 0.910 , 0.910 , 0.431 ,1.0)) L1table.SetTableValue( 226 , ( 0.914 , 0.914 , 0.427 ,1.0)) L1table.SetTableValue( 227 , ( 0.918 , 0.918 , 0.420 ,1.0)) L1table.SetTableValue( 228 , ( 0.918 , 0.918 , 0.416 ,1.0)) L1table.SetTableValue( 229 , ( 0.922 , 0.922 , 0.408 ,1.0)) L1table.SetTableValue( 230 , ( 0.925 , 0.925 , 0.404 ,1.0)) L1table.SetTableValue( 231 , ( 0.929 , 0.929 , 0.396 ,1.0)) L1table.SetTableValue( 232 , ( 0.929 , 0.929 , 0.392 ,1.0)) L1table.SetTableValue( 233 , ( 0.933 , 0.933 , 0.384 ,1.0)) L1table.SetTableValue( 234 , ( 0.937 , 0.937 , 0.376 ,1.0)) L1table.SetTableValue( 235 , ( 0.937 , 0.937 , 0.369 ,1.0)) L1table.SetTableValue( 236 , ( 0.941 , 0.941 , 0.361 ,1.0)) L1table.SetTableValue( 237 , ( 0.945 , 0.945 , 0.357 ,1.0)) L1table.SetTableValue( 238 , ( 0.949 , 0.949 , 0.349 ,1.0)) L1table.SetTableValue( 239 , ( 0.949 , 0.949 , 0.337 ,1.0)) L1table.SetTableValue( 240 , ( 0.953 , 0.953 , 0.329 ,1.0)) L1table.SetTableValue( 241 , ( 0.957 , 0.957 , 0.322 ,1.0)) L1table.SetTableValue( 242 , ( 0.961 , 0.961 , 0.314 ,1.0)) L1table.SetTableValue( 243 , ( 0.961 , 0.961 , 0.302 ,1.0)) L1table.SetTableValue( 244 , ( 0.965 , 0.965 , 0.290 ,1.0)) L1table.SetTableValue( 245 , ( 0.969 , 0.969 , 0.282 ,1.0)) L1table.SetTableValue( 246 , ( 0.969 , 0.969 , 0.271 ,1.0)) L1table.SetTableValue( 247 , ( 0.973 , 0.973 , 0.255 ,1.0)) L1table.SetTableValue( 248 , ( 0.976 , 0.976 , 0.243 ,1.0)) L1table.SetTableValue( 249 , ( 0.980 , 0.980 , 0.227 ,1.0)) L1table.SetTableValue( 250 , ( 0.980 , 0.980 , 0.212 ,1.0)) L1table.SetTableValue( 251 , ( 0.984 , 0.984 , 0.192 ,1.0)) L1table.SetTableValue( 252 , ( 0.988 , 0.988 , 0.173 ,1.0)) L1table.SetTableValue( 253 , ( 0.992 , 0.992 , 0.145 ,1.0)) L1table.SetTableValue( 254 , ( 0.992 , 0.992 , 0.110 ,1.0)) L1table.SetTableValue( 255 , ( 0.996 , 0.996 , 0.051 ,1.0)) L1table.Build() self.Linear_BlueToYellow = L1table return self.Linear_BlueToYellow
Python
import time import wx import vtk import math import numpy import vtktudoss try: import extended.BaseCalc as BaseCalc except ImportError: import BaseCalc def create(parent, renderwindow, primaryrenderer): return PlotOverlay(parent, renderwindow, primaryrenderer) class PlotOverlay: def __init__(self, parent, renderwindow, primaryrenderer): print "PCP overlay module loaded." self.parent = parent self.renderwindow = renderwindow.GetRenderWindow() self.interactorstyle = renderwindow.GetInteractorStyle() self.renX = primaryrenderer self.baseCalc = BaseCalc.create(self, self) self.windowsize = renderwindow.GetSize() self.labellist = [] self.guidelineCollection = [] self.parent.renwini3.Unbind(wx.EVT_RIGHT_DOWN) self.parent.renwini3.Bind(wx.EVT_RIGHT_DOWN, self.PCP_rightclick) def PCP_rightclick(self, event): x,y = event.GetX(), event.GetY() vtk_y = self.parent.flip_y(y) coords = self.Get3DCoords([x, vtk_y, 0.0]) for i in range(1, len(self.parent.parent.Filters.plottedAngles)): if coords[0]<(i+1) and coords[0]>(i): self.parent.AddScatter(i-1, i) def RefreshOverlay(self): labellistlength = len(self.labellist) for i in range(0, labellistlength): self.renX.RemoveActor2D(self.labellist.pop(0)) for i in range(0, len(self.guidelineCollection)): self.renX.RemoveActor(self.guidelineCollection.pop(0)) self.PutLabels() self.CreateGuidelines() def Get2DCoords(self, pos): outputpoint = [0.0,0.0,0.0] self.interactorstyle.ComputeWorldToDisplay(self.renX, pos[0], pos[1], pos[2], outputpoint) return outputpoint def Get3DCoords(self, pos): outputpoint = [0.0,0.0,0.0, 0.0] self.interactorstyle.ComputeDisplayToWorld(self.renX, pos[0], pos[1], pos[2], outputpoint) return outputpoint def PutLabels(self): Filters = self.parent.parent.Filters windowsize = self.renderwindow.GetSize() positionYa = windowsize[1]-30.0 positionYb = 35.0 minX = 70.0 maxX = windowsize[0] - 100.0 #~ for i in range(0, len(self.parent.parent.Filters.jointAngleCollection)): i=0 for stanceID in Filters.plottedAngles: for filter in Filters.jointAngleCollection: if filter['stanceID'] == stanceID: positionX = self.Get2DCoords((i + 1, 0.0, 0.0))[0] if positionX < minX: if positionX < 0.0: positionX = 0.0 opacity = positionX / minX elif positionX > maxX: if positionX > windowsize[0]: positionX = windowsize[0] opacity = (positionX - maxX) / (windowsize[0] - maxX) else: opacity = 1.0 #~ print opacity #~ if 0.0 < positionX < windowsize[0]: if 70.0 < positionX < windowsize[0]-100: description = filter['description'] textActor = vtk.vtkTextActor3D() textprop = vtk.vtkTextProperty() textprop.SetFontFamilyToArial() textprop.SetFontSize(288) textprop.ShadowOn() textprop.SetOpacity(opacity) #~ textprop.ShadowOn() #~ textprop.BoldOn() textprop.SetJustificationToCentered() #~ textprop.SetVerticalJustificationToBottom() textActor.SetTextProperty(textprop) #~ if i%2 == 0: coords = self.Get3DCoords([positionX, positionYa, 0.0]) #~ else: #~ coords = self.Get3DCoords([positionX, positionYb, 0.0]) coords[2] = 0.0 ##~ textActor.RotateZ(22) textActor.SetScale(0.0005) textActor.SetInput(description) self.labellist.append(textActor) self.renX.AddActor(textActor) bbox = [0,0,0,0] textActor.GetBoundingBox (bbox) textActor.SetPosition(coords[0] - bbox[1]/(2000.0), coords[1] + bbox[2]/(1000.0), coords[2]) self.PutValues(i, opacity) i=i+1 def PutValues(self, i, opacity): yInd = [[0.0, 180.0], [-0.5, 90.0], [-1.0, 0.0], [-1.5, -90.0], [-2.0, -180.0]] windowsize = self.renderwindow.GetSize() for yPair in yInd: coord2D = self.Get2DCoords((i+1, yPair[0], 0.0)) coord2Dx = coord2D[0] coord2Dy = coord2D[1] if 25.0 < coord2Dy < (windowsize[1]-40.0): textActor = vtk.vtkTextActor3D() textprop = vtk.vtkTextProperty() textprop.SetFontFamilyToArial() textprop.SetFontSize(144) textprop.ShadowOn() textprop.SetOpacity(opacity) textprop.SetJustificationToCentered() textprop.SetColor(0.8, 0.8 ,0.8) textActor.SetTextProperty(textprop) coords = self.Get3DCoords([coord2Dx + 4, coord2Dy + 4, 0.0]) coords[2] = 0.0 textActor.SetPosition(coords[0], coords[1], coords[2]) ##~ textActor.RotateZ(22) textActor.SetScale(0.0007) textActor.SetInput(str(yPair[1])) self.labellist.append(textActor) self.renX.AddActor(textActor) def CreateGuidelines(self): nrParameters = len(self.parent.parent.Filters.plottedAngles) #~ linelength = max(1.0, float(nrParameters-1.0)) #14.0 #~ if linelength>0.0: #~ dashes = int(linelength * 10) #~ dashlenght = linelength/(dashes*2.0) #~ dashedPoints = vtk.vtkPoints() #~ dashedPoints.SetNumberOfPoints(dashes*2) #~ for i in range(0, dashes): #~ dashedPoints.InsertPoint(i, 1.0 + dashlenght * 2*i, 0.0, 0.01) #~ dashedPoints.InsertPoint(i, 1.0 + dashlenght * 2*i+ dashlenght, 0.0, 0.01) #~ dashedLines = vtk.vtkCellArray() #~ for j in range(0, dashes): #~ dashedLines.InsertNextCell(2) #~ dashedLines.InsertCellPoint(2*j) #~ dashedLines.InsertCellPoint(2*j+1) #~ dashedGuideline = vtk.vtkPolyData() #~ dashedGuideline.SetLines(dashedLines) #~ dashedGuideline.SetPoints(dashedPoints) #~ dashedGuideline.Update() #~ for i in range(1, 4): #3 lines on top of each other #~ dashedCopy = vtk.vtkPolyData() #~ dashedCopy.DeepCopy(dashedGuideline) #~ dashedMapper1 = vtktud.vtktudExtendedOpenGLPolyDataMapper() #~ dashedMapper1.SetInput(dashedCopy) #~ dashedActor1 = vtk.vtkActor() #~ dashedActor1.SetMapper(dashedMapper1) #~ dashedActor1.GetProperty().SetOpacity(0.5) #~ dashedActor1.GetProperty().SetDiffuseColor(0.75, 0.75, 0.0) #~ dashedActor1.SetPosition(0.0, -i * 0.5, 0.0) #~ self.renX.AddActor(dashedActor1) #~ self.guidelineCollection.append(dashedActor1) windowsize = self.renderwindow.GetSize() positionYa = windowsize[1]-70.0 positionYb = 70.0 highpt = self.Get3DCoords((0, positionYa, 0)) lowpt = self.Get3DCoords((0, positionYb, 0)) linelength = 2.0 verticalPoints = vtk.vtkPoints() verticalPoints.SetNumberOfPoints(2) verticalPoints.InsertPoint(0, 0.0, highpt[1], 0.01) verticalPoints.InsertPoint(1, 0.0, lowpt[1], 0.01) verticalLines = vtk.vtkCellArray() verticalLines.InsertNextCell(2) verticalLines.InsertCellPoint(0) verticalLines.InsertCellPoint(1) verticalGuideline = vtk.vtkPolyData() verticalGuideline.SetLines(verticalLines) verticalGuideline.SetPoints(verticalPoints) verticalGuideline.Update() for i in range(0,nrParameters): verticalMapper1 = vtktudoss.vtktudExtendedOpenGLPolyDataMapper() verticalMapper1.SetInput(verticalGuideline) verticalActor1 = vtk.vtkActor() verticalActor1.SetMapper(verticalMapper1) verticalActor1.GetProperty().SetOpacity(0.5) verticalActor1.GetProperty().SetDiffuseColor(0.75, 0.75, 0.0) verticalActor1.SetPosition(1.0 + i, 0.0, 0.0) self.renX.AddActor(verticalActor1) self.guidelineCollection.append(verticalActor1) def PutSelectionOutline(self): pass
Python
#!/usr/bin/env python # This example demonstrates the use of vtkCardinalSpline. # It creates random points and connects them with a spline import os, sys import vtk import vtktudoss import cPickle from wx import * import wx.aui from vtk.wx.wxVTKRenderWindow import * from vtk.wx.wxVTKRenderWindowInteractor import * from vtk.util.colors import tomato, banana, blue_light import numpy import statistics import time import superthread import AngleCalculations try: import extended.Annotation as Annotation import extended.ColorScales as ColorScales import extended.BaseCalc as BaseCalc import extended.CoordinateSystems as CoordinateSystems import extended.GUI as GUI import extended.InverseKinematics as IK import extended.Filters as Filters except ImportError: import Annotation import ColorScales import BaseCalc import CoordinateSystems import GUI import InverseKinematics as IK import Filters [wxID_FRAME ] = [wx.NewId() for _init_ctrls in range(1)] def create(parent, root, appdir): return PatternViewer(parent, root, appdir) class PatternViewer(): pointwidgetinitialized = False BLmeshList = [ 246.6 , 198.2 , -1087.9 ] ,\ [ 238.8 , 222.9 , -932.1 ] ,\ [ 244.4 , 321.6 , -877 ] ,\ [ 244.5 , 371.7 , -1071.1 ] ,\ [ 235.1 , 224 , -928.9 ] ,\ [ 94.4 , 256.8 , -924.4 ] ,\ [ 80.4 , 297.2 , -897.3 ] ,\ [ 50.1 , 314.2 , -914.2 ] ,\ [ 158.5 , 359.6 , -942.8 ] ,\ [ 139.8 , 363.4 , -1058.6 ] ,\ [ 54.4 , 270 , -1215.2 ] ,\ [ 76.6 , 331.6 , -1215.7 ] ,\ [ 122.8 , 206.9 , -1454.8 ] ,\ [ 76.7 , 234.4 , -1458 ] ,\ [ 250.9 , 224 , -928.9 ] ,\ [ 389.1 , 260 , -914.8 ] ,\ [ 405.8 , 301.4 , -885.2 ] ,\ [ 431.3 , 323.5 , -911.4 ] ,\ [ 321.9 , 365.2 , -942.8 ] ,\ [ 355.2 , 363.4 , -1056 ] ,\ [ 441.8 , 286.1 , -1211.9 ] ,\ [ 396.4 , 328.2 , -1211.5 ] ,\ [ 362.1 , 200.8 , -1442.4 ] ,\ [ 407.5 , 237.8 , -1444.8 ] ,\ [ 65.4 , 277.8 , -932.9 ] ,\ [ 421.6 , 280.3 , -923.8 ] imagenumber = 0 def __init__(self, parent, root, appdir): self.parent = parent self._root = root self.appdir = appdir self.kdpoints = vtk.vtkPoints() self.kdvertices = vtk.vtkCellArray() self.kdpolydata = vtk.vtkPolyData() self.kdpoints2 = vtk.vtkPoints() self.kdvertices2 = vtk.vtkCellArray() self.kdpolydata2 = vtk.vtkPolyData() self.kdtree_modified = True self.gui = GUI.create(self, self._root) self.baseCalc = BaseCalc.create(self, self) self.colorscales = ColorScales.create(self) self.coordinatesystems = CoordinateSystems.create(self) self.IK = IK.create(self) self.InitializePointWidget() self.shaderrate = 1.0 self.pulserate = 0.0 self.CreateArmObject() self.AddSkeleton() self.angleCalculations = AngleCalculations.create(self, self._root) self.Filters = Filters.create(self) self.rollover_activated = False self.cellpickercreated = False self.baseSkeleton = -1 self.ActivateAngleRollOver(None) self.lbpe = self.gui.renwini3.AddObserver("LeftButtonPressEvent", \ self.AngleRollOver, 1.0) #SPLINES self.splineCollection = [] self.splineReferences = [] self.splineCollection_seqfilter = [] self.splineReferences_seqfilter = [] self.Filters.UpdateShaderOpacity self.glyphlist = [] self.statisticsActor = vtk.vtkActor() self.customPose = vtk.vtkActor() self.PoseActor9 = vtk.vtkActor() self.stablejointindex = 0 #0 = spine only, 1 = spine and clavicle etc. self.displayfrom = 0 def CreateArmObject(self): arcparts = 100 a1= [0.0, 0.0, 0.0] a2= [0.0, 0.0, 0.0] staticArcPoints = vtk.vtkPoints() staticArcPoints.SetNumberOfPoints(arcparts*4) height = 0.0 for i in range(0, arcparts): staticArcPoints.InsertPoint(i, 0, 0, height) height += 0.1 cells2 = vtk.vtkCellArray() for j in range(0, arcparts-1): cells2.InsertNextCell(2) cells2.InsertCellPoint(j) cells2.InsertCellPoint(j+1) self.armObject = vtk.vtkPolyData() self.armObject.SetLines(cells2) self.armObject.SetPoints(staticArcPoints) self.armObject.Update() path = os.path.join(self.appdir, "Shaders") self.xray_shader = vtk.vtkProperty() self.xray_shader.SetAmbient(1.0) self.xray_shader.LoadMaterial(os.path.join(path, "GLSLxray.xml")) self.xray_shader.ShadingOn() a = self.gui.ren2.GetActiveCamera().GetViewTransformMatrix() campos = self.gui.ren2.GetActiveCamera().GetPosition() self.xray_shader.AddShaderVariableFloat ("camPos", campos[0], campos[1], campos[2]) self.xray_shader.AddShaderVariableFloat ("camproj1", a.GetElement(0,0), a.GetElement(1,0), a.GetElement(2,0), a.GetElement(3,0)) self.xray_shader.AddShaderVariableFloat ("camproj2", a.GetElement(0,1), a.GetElement(1,1), a.GetElement(2,1), a.GetElement(3,1)) self.xray_shader.AddShaderVariableFloat ("camproj3", a.GetElement(0,2), a.GetElement(1,2), a.GetElement(2,2), a.GetElement(3,2)) self.xray_shader.AddShaderVariableFloat ("camproj4", a.GetElement(0,3), a.GetElement(1,3), a.GetElement(2,3), a.GetElement(3,3)) self.exoblue_shader = vtk.vtkProperty() self.exoblue_shader.SetAmbient(1.0) self.exoblue_shader.SetColor(0.3,0.3,1.0) self.exoblue_shader.LoadMaterial(os.path.join(path, "GLSLTwistThis.xml")) self.exoblue_shader.AddShaderVariableFloat("Rate", 1.0) self.exoblue_shader.AddShaderVariableFloat("Amplitude", 0.0) self.exoblue_shader.AddShaderVariableFloat("alphamultiplier", 1.0) self.exoyellow_shader = vtk.vtkProperty() self.exoyellow_shader.SetAmbient(1.0) self.exoyellow_shader.SetColor(0.7,0.7,0.3) self.exoyellow_shader.LoadMaterial(os.path.join(path, "GLSLTwistThis.xml")) self.exoyellow_shader.AddShaderVariableFloat("Rate", 1.0) self.exoyellow_shader.AddShaderVariableFloat("Amplitude", 0.0) self.exoyellow_shader.AddShaderVariableFloat("alphamultiplier", 1.0) self.blue_shader = vtk.vtkProperty() self.blue_shader.SetAmbient(1.0) self.blue_shader.SetColor(0.3,0.3,1.0)#1.0,1.0,0.3)#0.3,0.3,1.0) self.blue_shader.LoadMaterial(os.path.join(path, "GLSLBlueMe.xml")) self.blue_shader.AddShaderVariableFloat("alphamultiplier", 1.0) self.blue_shader.AddShaderVariableFloat ("camPos", campos[0], campos[1], campos[2]) self.blue_shader.AddShaderVariableFloat ("camproj1", a.GetElement(0,0), a.GetElement(1,0), a.GetElement(2,0), a.GetElement(3,0)) self.blue_shader.AddShaderVariableFloat ("camproj2", a.GetElement(0,1), a.GetElement(1,1), a.GetElement(2,1), a.GetElement(3,1)) self.blue_shader.AddShaderVariableFloat ("camproj3", a.GetElement(0,2), a.GetElement(1,2), a.GetElement(2,2), a.GetElement(3,2)) self.blue_shader.AddShaderVariableFloat ("camproj4", a.GetElement(0,3), a.GetElement(1,3), a.GetElement(2,3), a.GetElement(3,3)) self.yellow_shader = vtk.vtkProperty() self.yellow_shader.SetAmbient(1.0) self.yellow_shader.SetColor(0.7,0.7,0.3) self.yellow_shader.LoadMaterial(os.path.join(path, "GLSLBlueMe.xml")) self.yellow_shader.AddShaderVariableFloat("alphamultiplier", 1.0) self.yellow_shader.AddShaderVariableFloat ("camPos", campos[0], campos[1], campos[2]) self.yellow_shader.AddShaderVariableFloat ("camproj1", a.GetElement(0,0), a.GetElement(1,0), a.GetElement(2,0), a.GetElement(3,0)) self.yellow_shader.AddShaderVariableFloat ("camproj2", a.GetElement(0,1), a.GetElement(1,1), a.GetElement(2,1), a.GetElement(3,1)) self.yellow_shader.AddShaderVariableFloat ("camproj3", a.GetElement(0,2), a.GetElement(1,2), a.GetElement(2,2), a.GetElement(3,2)) self.yellow_shader.AddShaderVariableFloat ("camproj4", a.GetElement(0,3), a.GetElement(1,3), a.GetElement(2,3), a.GetElement(3,3)) #SPLINES: self.bluespline_shader = vtk.vtkProperty() self.bluespline_shader.SetAmbient(1.0) self.bluespline_shader.SetColor(0.3,0.3,1.0) self.bluespline_shader.LoadMaterial(os.path.join(path, "GLSLJustColor.xml")) self.bluespline_shader.AddShaderVariableFloat("alphamultiplier", 1.0) self.yellowspline_shader = vtk.vtkProperty() self.yellowspline_shader.SetAmbient(1.0) self.yellowspline_shader.SetColor(1.0,1.0,0.3) self.yellowspline_shader.LoadMaterial(os.path.join(path, "GLSLJustColor.xml")) self.yellowspline_shader.AddShaderVariableFloat("alphamultiplier", 1.0) def Render(self): self.gui.renwini1.Render() self.gui.renwini2.Render() self.gui.renwini3.Render() def SmoothObject(self, obj): Smooth = vtk.vtkSmoothPolyDataFilter() Smooth.SetInput(obj) Smooth.SetNumberOfIterations(50) Smooth.SetRelaxationFactor(0.01) return Smooth.GetOutput() def RecalcNormals(self, obj): Normals = vtk.vtkPolyDataNormals() Normals.SetInput(obj) Normals.SetFeatureAngle(60.0) return Normals.GetOutput() def ClearGlyphs(self): for i in self.glyphlist: self.gui.ren3.RemoveActor(i) self.glyphlist[:] = [] def ClearData(self, whichone=2): if whichone==0 or whichone==2: for i in self.splineCollection: self.Filters.HideSpline(i) if whichone==1 or whichone==2: for i in self.splineReferences: self.Filters.HideSpline(i) #~ self.ClearGlyphs() for i in self.Filters.jointAngleCollection: if whichone==0 or whichone==2: i['min1'] =None i['max1'] =None if i['widget'] != None: i['widget'].SetWidgetRange1(90.0, 90.0) if whichone==1 or whichone==2: if i['widget'] != None: i['widget'].SetWidgetRange2(90.0, 90.0) i['min2'] =None i['max2'] =None if whichone==2: i['filter_min'] = None i['filter_max'] = None if i['widget'] != None: i['widget'].SetfilterRangeMin(90.0) i['widget'].SetfilterRangeMax(90.0) self.gui.widgets.UpdateWidgets() if whichone==0 or whichone==2: self.splineCollection[:] = [] self.kdpoints = vtk.vtkPoints() self.kdvertices = vtk.vtkCellArray() self.kdpolydata = vtk.vtkPolyData() if whichone==1 or whichone==2: self.splineReferences[:] = [] self.kdpoints2 = vtk.vtkPoints() self.kdvertices2 = vtk.vtkCellArray() self.kdpolydata2 = vtk.vtkPolyData() self.kdtree_modified = True self.cellpicker.InitializePickList() self.gui.Render() def RegenerateSplineObjects(self): self.ClearGlyphs() for spline in self.splineCollection: profileActor = self.CreateSplineObject(spline['stance'],\ updatewidget = False, referenceSpline=False) spline['splineActor'].SetMapper(profileActor.GetMapper()) for spline in self.splineReferences: profileActor = self.CreateSplineObject(spline['stance'],\ updatewidget = False, referenceSpline=True) spline['splineActor'].SetMapper(profileActor.GetMapper()) def CorrectBLsForStaticElements(self, blPos, useStableJointIndex = True): self.angleCalculations.SetupCoordinateSystems(blPos) if self.stablejointindex >= 0 or not useStableJointIndex: transfThorax = self.CorrectSpine() else: transfThorax = vtk.vtkTransform() if self.stablejointindex >= 1 or not useStableJointIndex: transfClavicle = self.CorrectOXYZ(self.angleCalculations.OXYZThorax, self.angleCalculations.Right_OXYZClavicle) else: transfClavicle = vtk.vtkTransform() claviclevector = (numpy.array(blPos[6])-numpy.array(blPos[4])) p1 = claviclevector.tolist() vtk.vtkMath().Normalize(p1) norm = lambda x: numpy.sqrt(numpy.square(claviclevector).sum()) current_clavicle_length = norm(claviclevector) length_difference = self.clavicle_length - current_clavicle_length transfClavicle.Translate((numpy.array(p1) * length_difference).tolist()) if self.stablejointindex >= 2 or not useStableJointIndex: transfScapula = self.CorrectOXYZ(self.angleCalculations.Right_OXYZClavicle, self.angleCalculations.Right_OXYZScapula) else: transfScapula = vtk.vtkTransform() if self.stablejointindex >= 3 or not useStableJointIndex: transfHumerus = self.CorrectOXYZ(self.angleCalculations.Right_OXYZScapula, self.angleCalculations.Right_OXYZHumerus) else: transfHumerus = vtk.vtkTransform() humerusvector = (((numpy.array(blPos[10])+numpy.array(blPos[11]))/2)-numpy.array(blPos[24])) p2 = humerusvector.tolist() vtk.vtkMath().Normalize(p2) norm = lambda x: numpy.sqrt(numpy.square(humerusvector).sum()) current_humerus_length = norm(humerusvector) length_difference2 = self.humerus_length - current_humerus_length transfHumerus.Translate((numpy.array(p2) * length_difference2).tolist()) if self.stablejointindex >= 4 or not useStableJointIndex: transfForearm = self.CorrectOXYZ(self.angleCalculations.Right_OXYZHumerus, self.angleCalculations.Right_OXYZForearm) else: transfForearm = vtk.vtkTransform() new_blPos = blPos[:] #SPINE spine = [0, 1, 2, 3, 4] for pt in spine: new_blPos[pt] = transfThorax.TransformFloatPoint(blPos[pt]) #CLAVICLE clavicle = [6] tmp = self.ApplyCorrectionTransform(transfClavicle, blPos[4], blPos[6]) new_blPos[6] = transfThorax.TransformFloatPoint(tmp) #SCAPULA scapula = [5, 7, 8, 9, 24] for pt in scapula: tmp1 = self.ApplyCorrectionTransform(transfScapula, blPos[6], blPos[pt]) tmp2 = self.ApplyCorrectionTransform(transfClavicle, blPos[4], tmp1) tmp3 = transfThorax.TransformFloatPoint(tmp2) new_blPos[pt] = tmp3 # HUMERUS humerus = [10, 11] for pt in humerus: tmp1 = self.ApplyCorrectionTransform(transfHumerus, blPos[24], blPos[pt]) tmp2 = self.ApplyCorrectionTransform(transfScapula, blPos[6], tmp1) tmp3 = self.ApplyCorrectionTransform(transfClavicle, blPos[4], tmp2) tmp4 = transfThorax.TransformFloatPoint(tmp3) new_blPos[pt] = tmp4 # FOREARM forearm = [12, 13] for pt in forearm: tmp1 = self.ApplyCorrectionTransform(transfForearm, self.angleCalculations.Right_midELEM, blPos[pt]) tmp2 = self.ApplyCorrectionTransform(transfHumerus, blPos[24], tmp1) tmp3 = self.ApplyCorrectionTransform(transfScapula, blPos[6], tmp2) tmp4 = self.ApplyCorrectionTransform(transfClavicle, blPos[4], tmp3) tmp5 = transfThorax.TransformFloatPoint(tmp4) new_blPos[pt] = tmp5 return new_blPos def GenerateArmObject(self, em, el, gh, exoindex, color): newarm = vtk.vtkPolyData() newarm.DeepCopy(self.armObject) #~ map = vtk.vtkPolyDataMapper() map = vtktudoss.vtktudExtendedOpenGLPolyDataMapper() map.SetInput(newarm) shaderactor = vtk.vtkActor() shaderactor.SetMapper(map) if color==1: shaderactor.SetProperty(self.exoblue_shader) else: shaderactor.SetProperty(self.exoyellow_shader) #~ shaderactor.GetProperty().SetColor(color[0], color[1], color[2]) #~ shaderactor.GetProperty().SetDiffuseColor( shaderactor.GetProperty().ShadingOn() vfl = vtk.vtkFloatArray() vfl.SetNumberOfComponents(3) rated_exo = float(exoindex)/180 for i in range(0,100): vfl.InsertTuple3(i, rated_exo, color,0) newarm.GetPointData().SetNormals(vfl) newarm.Update() mPoints = vtk.vtkPoints() rPoints = vtk.vtkPoints() mPoints.InsertPoint(0, [-0.5,0.0,10.0]) rPoints.InsertPoint(0, em) mPoints.InsertPoint(1, [0.5,0.0,10.0]) rPoints.InsertPoint(1, el) mPoints.InsertPoint(2, [0.0, 0.0, 0.0]) rPoints.InsertPoint(2, gh) transformer = vtk.vtkLandmarkTransform() transformer.SetSourceLandmarks(mPoints) transformer.SetTargetLandmarks(rPoints) transformer.Update() shaderactor.SetUserTransform(transformer) return shaderactor def ShowPose(self, blPos_spline, type, stance = None, showbones = True, shadedArm = False): #type -> 0 Collection 1 Reference 2 mean poseAppend = vtk.vtkAppendPolyData() #~ new_blPos = self.CorrectBLsForStaticElements(blPos_spline) #~ blPos = self.angleCalculations.SetupCoordinateSystems(new_blPos) blPos = self.CorrectBLsForStaticElements(blPos_spline) midPXT8 = self._root.baseCalc.Average2Points(blPos[0], blPos[3]) midIJC7 = self._root.baseCalc.Average2Points(blPos[1], blPos[2]) Right_midELEM = self._root.baseCalc.Average2Points(blPos[10], blPos[11]) if showbones: self.SetBones(blPos) poseAppend = vtk.vtkAppendPolyData() #~ poseAppend.AddInput(self.PoseVis_add(self.angleCalculations.midPXT8, self.angleCalculations.midIJC7, "spine")) poseAppend.AddInput(self.PoseVis_add(midPXT8, midIJC7, "spine")) poseAppend.AddInput(self.PoseVis_add(blPos[4], blPos[6], "clavicle")) poseAppend.AddInput(self.PoseVis_add(blPos[7], blPos[8], "scapula")) poseAppend.AddInput(self.PoseVis_add(blPos[8], blPos[9], "scapula")) poseAppend.AddInput(self.PoseVis_add(blPos[9], blPos[7], "scapula")) #~ poseAppend.AddInput(self.PoseVis_add(self.angleCalculations.Right_midELEM, blPos[13], "arm")) poseAppend.AddInput(self.PoseVis_add(Right_midELEM, blPos[13], "arm")) if shadedArm: if type == 0: ShadedArmActor = self.GenerateArmObject(blPos[10], blPos[11], blPos[24], stance[11], color=1) #[0.3, 0.3, 1.0] else: ShadedArmActor = self.GenerateArmObject(blPos[10], blPos[11], blPos[24], stance[11], color=0) # [1.0, 1.0, 0.3] poseMapper = vtktudoss.vtktudExtendedOpenGLPolyDataMapper() poseActor = vtk.vtkActor() poseActor.SetMapper(poseMapper) #~ poseMapper = vtk.vtkPolyDataMapper() poseMapper.SetInput(poseAppend.GetOutput()) #~ poseMapper.ScalarVisibilityOn() #~ poseMapper.SetUseLookupTableScalarRange(1) #~ poseMapper.SetScalarModeToUsePointData() #~ tmppoly = vtk.vtkPolyData() #~ tmppoly.DeepCopy(poseAppend.GetOutput()) #~ tmppoly.Update() #~ poseMapper.SetInput(tmppoly) #tmppoly)# #~ vfl = vtk.vtkFloatArray() #~ vfl.SetNumberOfComponents(3) #~ alpha = 0.5 #~ for i in range(0,14): #~ vfl.InsertTuple3(i, alpha, alpha, alpha) #~ tmppoly.GetPointData().SetNormals(vfl) #~ tmppoly.Update() #~ tmppoly.GetPointData().SetNormals(vfl) #~ tmppoly.Update() poseMapper.Update() if type == 0: #~ poseMapper.SetLookupTable(self.colorscales.dynamic_generic) #poseActor.GetProperty().SetOpacity(0.05) poseActor.SetProperty(self.blue_shader) poseActor.GetProperty().ShadingOn() elif type ==1: #~ poseMapper.SetLookupTable(self.colorscales.dynamic_generic2) #~ poseActor.GetProperty().SetOpacity(0.05) poseActor.SetProperty(self.yellow_shader) poseActor.GetProperty().ShadingOn() else: #~ poseMapper.SetLookupTable(self.colorscales.dynamic_generic3) poseActor.GetProperty().SetOpacity(1.0) if shadedArm: return [poseActor, ShadedArmActor] else: return poseActor def ApplyCorrectionTransform(self, transform, origin, point): point2 = self.baseCalc.SubtractPoints(point, origin) point2 = transform.TransformPoint(point2) point2 = self.baseCalc.AddPoints(origin, point2) return point2 def CorrectOXYZ(self, parentOXYZ, childOXYZ): old_OXYQ = [[0,0,0],\ childOXYZ[1],\ childOXYZ[2],\ childOXYZ[3]] target_OXYQ = [[0,0,0],\ parentOXYZ[1],\ parentOXYZ[2],\ parentOXYZ[3]] return self.angleCalculations.MatchCoordinateSystemAtoB(old_OXYQ, target_OXYQ) def CorrectSpine(self): currentOXYZThorax_GLOBAL = [self.angleCalculations.OXYZThorax[0],\ self.baseCalc.AddPoints(self.angleCalculations.OXYZThorax[0], self.angleCalculations.OXYZThorax[1]),\ self.baseCalc.AddPoints(self.angleCalculations.OXYZThorax[0], self.angleCalculations.OXYZThorax[2]),\ self.baseCalc.AddPoints(self.angleCalculations.OXYZThorax[0], self.angleCalculations.OXYZThorax[3])] O = [0,0,0] X = self.baseCalc.AddPoints(O, [1,0,0]) Y = self.baseCalc.AddPoints(O, [0,1,0]) Z = self.baseCalc.AddPoints(O, [0,0,1]) goalOXYZThorax_GLOBAL = [O, X, Y, Z] return self.angleCalculations.MatchCoordinateSystemAtoB(currentOXYZThorax_GLOBAL, goalOXYZThorax_GLOBAL) def RegeneratePoses(self): self.kdpoints = vtk.vtkPoints() self.kdvertices = vtk.vtkCellArray() for i in range(0, len(self.splineCollection)): actorcollection = self.ShowPose(self.splineCollection[i]['blPos'], 0,\ self.splineCollection[i]['stance'], showbones = False, shadedArm=True) self.splineCollection[i]['poseActor'].SetMapper(actorcollection[0].GetMapper()) self.splineCollection[i]['poseActor'].GetMapper().Update() self.splineCollection[i]['shadedArm'].SetMapper(actorcollection[1].GetMapper()) self.splineCollection[i]['shadedArm'].SetUserTransform(actorcollection[1].GetUserTransform()) self.splineCollection[i]['shadedArm'].GetMapper().Update() self.kdpoints.InsertNextPoint(self.splineCollection[i]['poseActor'].GetMapper()\ .GetInput().GetPoints().GetPoint(11)) self.kdvertices.InsertNextCell(1) self.kdvertices.InsertCellPoint(self.kdpoints.GetNumberOfPoints()-1) self.kdpolydata = vtk.vtkPolyData() self.kdpolydata.SetPoints(self.kdpoints) self.kdpolydata.SetVerts(self.kdvertices) self.kdpoints2 = vtk.vtkPoints() self.kdvertices2 = vtk.vtkCellArray() for i in range(0, len(self.splineReferences)): actorcollection = self.ShowPose(self.splineReferences[i]['blPos'], 1,\ self.splineReferences[i]['stance'], showbones = False, shadedArm=True) self.splineReferences[i]['poseActor'].SetMapper(actorcollection[0].GetMapper()) self.splineReferences[i]['poseActor'].GetMapper().Update() self.splineReferences[i]['shadedArm'].SetMapper(actorcollection[1].GetMapper()) self.splineReferences[i]['shadedArm'].SetUserTransform(actorcollection[1].GetUserTransform()) self.splineReferences[i]['shadedArm'].GetMapper().Update() self.kdpoints2.InsertNextPoint(self.splineReferences[i]['poseActor'].GetMapper()\ .GetInput().GetPoints().GetPoint(11)) self.kdvertices2.InsertNextCell(1) self.kdvertices2.InsertCellPoint(self.kdpoints2.GetNumberOfPoints()-1) self.kdpolydata2 = vtk.vtkPolyData() self.kdpolydata2.SetPoints(self.kdpoints2) self.kdpolydata2.SetVerts(self.kdvertices2) self.Filters.RestartFiltering() self.Filters.RestartFilteringReferences() def PoseVis_add(self, point1, point2, part): polys = vtk.vtkCellArray() points = vtk.vtkPoints() lijntje = vtk.vtkPolyData() points.InsertPoint(0, point1) points.InsertPoint(1, point2) polys.InsertNextCell(2) polys.InsertCellPoint(0) polys.InsertCellPoint(1) lijntje.SetPoints(points) lijntje.SetLines(polys) if part == "arm": vfl = vtk.vtkFloatArray() vfl.SetNumberOfComponents(3) alpha = 0.2 vfl.InsertTuple3(0, alpha, alpha, alpha) vfl.InsertTuple3(1, alpha, alpha, alpha) lijntje.GetPointData().SetNormals(vfl) lijntje.Update() return lijntje elif part == "scapula": vfl = vtk.vtkFloatArray() vfl.SetNumberOfComponents(3) alpha = 0.04 vfl.InsertTuple3(0, alpha, alpha, alpha) vfl.InsertTuple3(1, alpha, alpha, alpha) lijntje.GetPointData().SetNormals(vfl) lijntje.Update() return lijntje elif part == "spine": vfl = vtk.vtkFloatArray() vfl.SetNumberOfComponents(3) alpha = 1.0 vfl.InsertTuple3(0, alpha, alpha, alpha) vfl.InsertTuple3(1, alpha, alpha, alpha) lijntje.GetPointData().SetNormals(vfl) lijntje.Update() return lijntje elif part == "clavicle": vfl = vtk.vtkFloatArray() vfl.SetNumberOfComponents(3) alpha = 0.04 vfl.InsertTuple3(0, alpha, alpha, alpha) vfl.InsertTuple3(1, alpha, alpha, alpha) lijntje.GetPointData().SetNormals(vfl) lijntje.Update() return lijntje def OldPoseVis_add(self, point1, point2, part): polys = vtk.vtkCellArray() points = vtk.vtkPoints() lijntje = vtk.vtkPolyData() points.InsertPoint(0, point1) points.InsertPoint(1, point2) polys.InsertNextCell(2) polys.InsertCellPoint(0) polys.InsertCellPoint(1) lijntje.SetPoints(points) lijntje.SetLines(polys) if part == "arm": poseColors = vtk.vtkFloatArray() poseColors.SetName("poseColors") lijntje.GetPointData().AddArray(poseColors) lijntje.GetPointData().SetActiveScalars("poseColors") poseColors.InsertTuple1(0, 0) poseColors.InsertTuple1(1, 0) return lijntje elif part == "scapula": poseColors = vtk.vtkFloatArray() poseColors.SetName("poseColors") lijntje.GetPointData().AddArray(poseColors) lijntje.GetPointData().SetActiveScalars("poseColors") poseColors.InsertTuple1(0, 1) poseColors.InsertTuple1(1, 1) return lijntje elif part == "spine": poseColors = vtk.vtkFloatArray() poseColors.SetName("poseColors") lijntje.GetPointData().AddArray(poseColors) lijntje.GetPointData().SetActiveScalars("poseColors") poseColors.InsertTuple1(0, 3) poseColors.InsertTuple1(1, 3) return lijntje elif part == "clavicle": poseColors = vtk.vtkFloatArray() poseColors.SetName("poseColors") lijntje.GetPointData().AddArray(poseColors) lijntje.GetPointData().SetActiveScalars("poseColors") poseColors.InsertTuple1(0, 2) poseColors.InsertTuple1(1, 2) return lijntje def StanceRated(self, stance): stance_rated = [] for i in stance: stance_rated = stance_rated + [-1 + float(i)/180] return stance_rated def CreateSplineObject(self, stance, updatewidget = False, referenceSpline=False): # Generate SplineObject aSplineX = vtk.vtkCardinalSpline() aSplineY = vtk.vtkCardinalSpline() aSplineZ = vtk.vtkCardinalSpline() # Generate random (pivot) points and add the corresponding # coordinates to the splines. # aSplineX will interpolate the x values of the points # aSplineY will interpolate the y values of the points # aSplineZ will interpolate the z values of the points inputPoints = vtk.vtkPoints() x_count = 0 numberOfInputPoints = len(self.Filters.plottedAngles) stance_usedonly = [] for i in self.Filters.plottedAngles: stance_usedonly.append(stance[i]) stance_rated = self.StanceRated(stance_usedonly) #conversion to range [0, 2] for i in range(0, numberOfInputPoints): y = stance_rated[i] x_count = x_count + 1 x = x_count z = 0 aSplineX.AddPoint(i, x) aSplineY.AddPoint(i, y) aSplineZ.AddPoint(i, z) inputPoints.InsertPoint(i, x, y, z) profileData = vtk.vtkPolyData() if len(self.Filters.plottedAngles)>1: # Generate the polyline for the spline. points = vtk.vtkPoints() # Number of points on the spline if self.gui.editorpanel.radio_btn_6.GetValue(): numberOfOutputPoints = len(self.Filters.plottedAngles) #linear else: numberOfOutputPoints = len(self.Filters.plottedAngles) * 14 # Interpolate x, y and z by using the three spline filters and # create new points for i in range(0, numberOfOutputPoints): t = (numberOfInputPoints-1.0)/(numberOfOutputPoints-1.0)*i points.InsertPoint(i, aSplineX.Evaluate(t), aSplineY.Evaluate(t), aSplineZ.Evaluate(t)) # Create the polyline. lines = vtk.vtkCellArray() lines.InsertNextCell(numberOfOutputPoints) for i in range(0, numberOfOutputPoints): lines.InsertCellPoint(i) profileData.SetPoints(points) profileData.SetLines(lines) #~ profileMapper = vtk.vtkPolyDataMapper() profileMapper = vtktudoss.vtktudExtendedOpenGLPolyDataMapper() profileMapper.SetInput(profileData) profileActor = vtk.vtkActor() profileActor.SetMapper(profileMapper) #~ profileActor.GetProperty().SetOpacity(0.05) if referenceSpline == True: #set yellow profileActor.SetProperty(self.yellowspline_shader) profileActor.GetProperty().ShadingOn() else: #set blue profileActor.SetProperty(self.bluespline_shader) profileActor.GetProperty().ShadingOn() self.CreateGlyphs(inputPoints, referenceSpline) profileMapper.Update() return profileActor def CreateGlyphs(self, inputPoints, referenceSpline): # Create a polydata to be glyphed. inputData = vtk.vtkPolyData() inputData.SetPoints(inputPoints) # Use sphere as glyph source. balls = vtk.vtkSphereSource() balls.SetRadius(.01) balls.SetPhiResolution(4) balls.SetThetaResolution(4) glyphPoints = vtk.vtkGlyph3D() glyphPoints.SetInput(inputData) glyphPoints.SetSource(balls.GetOutput()) glyphMapper = vtk.vtkPolyDataMapper() glyphMapper.SetInputConnection(glyphPoints.GetOutputPort()) glyph = vtk.vtkActor() glyph.SetMapper(glyphMapper) if referenceSpline: glyph.GetProperty().SetDiffuseColor(banana) glyph.SetPosition(0.02, 0.0, 0.0) else: glyph.GetProperty().SetDiffuseColor(blue_light ) glyph.SetPosition(-0.02, 0.0, 0.0) glyph.GetProperty().SetSpecular(.3) glyph.GetProperty().SetSpecularPower(30) self.gui.ren3.AddActor(glyph) self.glyphlist.append(glyph) def AddSpline(self, stance, blpositions, updatewidget = False, referenceSpline = False): #Update Range Indicators (Not visually) if referenceSpline: range_min = 'min2' range_max = 'max2' else: range_min = 'min1' range_max = 'max1' for i in range(0, len(self.Filters.jointAngleCollection)): if self.Filters.jointAngleCollection[i]['max1'] == None: self.Filters.jointAngleCollection[i]['filter_min'] = stance[i]-1 self.Filters.jointAngleCollection[i]['filter_max'] = stance[i] self.Filters.jointAngleCollection[i][range_min] = stance[i]-1 self.Filters.jointAngleCollection[i][range_max] = stance[i] elif stance[i] > self.Filters.jointAngleCollection[i][range_max] or self.Filters.jointAngleCollection[i][range_max] == None: if not referenceSpline: if self.Filters.jointAngleCollection[i]['filter_max'] == self.Filters.jointAngleCollection[i]['max1']: self.Filters.jointAngleCollection[i]['filter_max'] = stance[i] self.Filters.jointAngleCollection[i][range_max] = stance[i] elif stance[i] < self.Filters.jointAngleCollection[i][range_min] or self.Filters.jointAngleCollection[i][range_min] == None: if not referenceSpline: if self.Filters.jointAngleCollection[i]['filter_min'] == self.Filters.jointAngleCollection[i]['min1']: self.Filters.jointAngleCollection[i]['filter_min'] = stance[i] self.Filters.jointAngleCollection[i][range_min] = stance[i] if updatewidget == True: self.gui.widgets.UpdateWidgets() profileActor = self.CreateSplineObject(stance, updatewidget, referenceSpline) if self.baseSkeleton == -1: self.ResetSkeleton(blpositions) self.GeneratePhysique([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]) spline = {'stance' : stance, 'visible': False, 'splineActor' : profileActor, 'poseActor': None, 'shadedArm': None, 'reference': referenceSpline, 'blPos': blpositions} if referenceSpline == True: poseActorCollection = self.ShowPose(blpositions, 1, stance, showbones = (not referenceSpline and self.parent.parent!=None), shadedArm = True) else: poseActorCollection = self.ShowPose(blpositions, 0, stance, showbones = (not referenceSpline and self.parent.parent!=None), shadedArm = True) poseActor = poseActorCollection[0] shadedArm = poseActorCollection[1] spline['poseActor'] = poseActor spline['shadedArm'] = shadedArm if referenceSpline == True: splineNr = len(self.splineReferences) else: splineNr = len(self.splineCollection) visible = self.Filters.FilterSingleSpline(spline, referenceSpline, splineNr) spline['visible'] = visible if referenceSpline == True: self.splineReferences.append(spline) self.kdpoints2.InsertNextPoint(poseActor.GetMapper()\ .GetInput().GetPoints().GetPoint(11)) self.kdvertices2.InsertNextCell(1) self.kdvertices2.InsertCellPoint(self.kdpoints2.GetNumberOfPoints()-1) else: self.splineCollection.append(spline) self.kdpoints.InsertNextPoint(poseActor.GetMapper()\ .GetInput().GetPoints().GetPoint(11)) self.kdvertices.InsertNextCell(1) self.kdvertices.InsertCellPoint(self.kdpoints.GetNumberOfPoints()-1) self.kdtree_modified = True #~ for i in range(0, len(self.gui.sequenceplotters)): #~ self.gui.UpdateSequencePlot(i, self.gui.sequenceplotters[i].whichdata) def AddSkeleton(self): # 86 thorax: 0 1 2 3 4 14 # 85 hand:11 12 13 # 83 84 forearm: 10 11 12 13 # 82 humerus: 10 11 24 #81 schouderblad: 5 6 7 8 9 #80 clavicle: 0 14 4 6 appdir = self.ReadRootDirectory() bonelist = [80, 81, 82, 83, 84, 85, 86] self.bone_landmarks = [[0, 4, 6], [5,6,7,8,9],\ [10, 11, 24], [10, 11, 12, 13],\ [10, 11, 12, 13], [11, 12,13], [0,1,2,3,4]] #14? andere clavicle self.bone_actorList = [] self.bone_mapperList = [] self.bone_mapperListNormal = [] self.bone_readerList = [] for i in range(0, len(bonelist)): #~ if bonelist[i] != 81 and bonelist[i] != 82: fname = os.path.join(appdir, 'Skeleton', ('Bone_' + str(bonelist[i]) + '.vtk')) #~ else: #~ if bonelist[i] == 81: #~ ##~ fname = os.path.join(appdir, 'Skeleton', ('scap_emery.vtk')) #~ fname = os.path.join(appdir, 'Skeleton', ('scap_emery_env.vtk')) #~ else: #~ fname = os.path.join(appdir, 'Skeleton', ('hum_emery.vtk')) self.bone_actorList.append(vtk.vtkActor()) #~ self.bone_mapperList.append(vtk.vtkPolyDataMapper()) self.bone_mapperList.append(vtktudoss.vtktudExtendedOpenGLPolyDataMapper()) self.bone_mapperListNormal.append(vtk.vtkPolyDataMapper()) self.bone_readerList.append(vtk.vtkPolyDataReader()) self.bone_readerList[i].SetFileName(fname) self.bone_readerList[i].OpenVTKFile() obj = self.RecalcNormals(self.SmoothObject(\ self.bone_readerList[i].GetOutput())) #~ self.bone_mapperList[i].SetInput(self.bone_readerList[i].GetOutput()) self.bone_mapperList[i].SetInput(obj) self.bone_mapperListNormal[i].SetInput(obj) self.bone_actorList[i].SetMapper(self.bone_mapperListNormal[i]) #~ self.bone_actorList[i].SetProperty(self.xray_shader) self.gui.ren2.AddActor(self.bone_actorList[i]) self.bone_actorList[i].GetProperty().SetColor(1, .97, .85) self.bone_readerList[i].CloseVTKFile() def SetBones(self, blPos): for i in range(0, len(self.bone_actorList)): linkedBLs = self.bone_landmarks[i] mPoints = vtk.vtkPoints() rPoints = vtk.vtkPoints() for j in range(0, len(linkedBLs)): mPoints.InsertPoint(j, self.BLmeshList[linkedBLs[j]]) rPoints.InsertPoint(j, blPos[linkedBLs[j]]) transformer = vtk.vtkLandmarkTransform() transformer.SetSourceLandmarks(mPoints) transformer.SetTargetLandmarks(rPoints) self.bone_actorList[i].SetUserTransform(transformer) if self.pointWidget.GetEnabled(): self.pointWidget.SetPosition(blPos[13]) def PlayShader(self): #~ while True: #~ try: #~ wx.SafeYield(onlyIfNeeded = True) #~ except AssertionError: #~ pass #~ addedrate = -1 + float(self.lastStance[11])/180 self.shaderrate = self.shaderrate + 1 self.pulserate = self.pulserate + 0.3 self.exoblue_shader.AddShaderVariableFloat ("Rate", self.shaderrate) self.exoyellow_shader.AddShaderVariableFloat ("Rate", self.shaderrate) #~ print self.shaderrate #~ try: #~ wx.SafeYield(onlyIfNeeded = False) #~ except AssertionError: #~ pass #~ time.sleep(0.01) def InitializePointWidget(self): if self.pointwidgetinitialized == False: self.pointWidget = vtk.vtkPointWidget() self.pointWidget.PlaceWidget(-50, 50, -100, 100, 0, 100) self.pointWidget.AllOff() self.pointWidget.KeyPressActivationOff() self.pointWidget.GetProperty().SetColor(1,1,1) self.pointWidget.SetHandleSize(10) self.pointWidget.SetInteractor(self.gui.renwini2) #~ self.pointWidget.EnabledOn() self.pointwidgetinitialized = True self.pointWidget.AddObserver("InteractionEvent", self.ProbeData) #~ pointWidget.AddObserver("StartInteractionEvent", BeginInteraction) #~ self.pointWidget.AddObserver("EndInteractionEvent", self.ProbeData) def ProbeData(self, event, bla): if self.kdtree_modified == True: self.kdpolydata = vtk.vtkPolyData() self.kdpolydata.SetPoints(self.kdpoints) self.kdpolydata.SetVerts(self.kdvertices) self.kdpolydata2 = vtk.vtkPolyData() self.kdpolydata2.SetPoints(self.kdpoints2) self.kdpolydata2.SetVerts(self.kdvertices2) self.IK.Buildobbtree() self.kdtree_modified = False self.Filters.inversekinematicsOn = True newpos = self.pointWidget.GetPosition() oldpos = self.angleCalculations.blPos[13] #~ testpos1 = self.angleCalculations.blPos[13]#[-1.06, -58.3, 21.6] #~ testpos2 = [-1, -32, 49] laststancefound = self.IK.Queryobbtree(newpos, self.baseCalc.Average2Points(\ self.angleCalculations.blPos[10], self.angleCalculations.blPos[11])) # INVERSE KINEMATICS: if laststancefound == None: newstance = self.IK.Run(oldpos, newpos) else: newstance = laststancefound widgetposition = self.pointWidget.GetPosition() if newstance == -1: pass #~ self.pointWidget.SetPosition(oldpos) else: self.GeneratePhysique(newstance, showbones=True) self.pointWidget.SetPosition(widgetposition) self.gui.SetSliders(newstance) self.gui.Render(2) self.gui.Render(3) def ResetSkeleton(self, blPos): claviclevector = (numpy.array(blPos[6])-numpy.array(blPos[4])) norm = lambda x: numpy.sqrt(numpy.square(claviclevector).sum()) self.clavicle_length = norm(claviclevector) humerusvector = (((numpy.array(blPos[10])+numpy.array(blPos[11]))/2)-numpy.array(blPos[24])) norm = lambda x: numpy.sqrt(numpy.square(humerusvector).sum()) self.humerus_length = norm(humerusvector) new_blPos = self.CorrectBLsForStaticElements( blPos, useStableJointIndex = False) self.baseSkeleton = new_blPos self.SetBones(new_blPos) self.pointWidget.SetPosition(new_blPos[13]) def GeneratePhysique(self, stance, showbones = False, returnBLpos = False): #Given a stance (series of angles), we reconstruct a skeleton pose that meets the stance angle requirements. # Ideally, no full stance is required and we can for example reconstruct single angles. blPos = self.angleCalculations.SetupCoordinateSystems(self.baseSkeleton) self.lastStance = stance new_blPos = blPos[:] #SPINE t2_thorax = vtk.vtkTransform() t2_thorax.RotateWXYZ(stance[1], self.angleCalculations.OXYZThorax[2]) t2_thorax.Update() basicAxis = t2_thorax.TransformPoint(self.angleCalculations.OXYZThorax[1]) transfThorax = vtk.vtkTransform() #~ transfThorax.RotateWXYZ(-stance[0], basicAxis) #~ transfThorax.RotateWXYZ(stance[2], self.angleCalculations.OXYZThorax[2]) transfThorax.Update() #CLAVICLE t2_clavicle = vtk.vtkTransform() t2_clavicle.RotateWXYZ(stance[4], self.angleCalculations.Right_OXYZClavicle[2]) t2_clavicle.Update() basicAxis = t2_clavicle.TransformPoint(self.angleCalculations.Right_OXYZClavicle[1]) transfClavicle = vtk.vtkTransform() transfClavicle.RotateWXYZ(-stance[3], basicAxis) transfClavicle.RotateWXYZ(stance[5], self.angleCalculations.Right_OXYZClavicle[2]) transfClavicle.Update() #SCAPULA t2_scapula = vtk.vtkTransform() t2_scapula.RotateWXYZ(stance[7], self.angleCalculations.Right_OXYZScapula[2]) t2_scapula.Update() basicAxis = t2_scapula.TransformPoint(self.angleCalculations.Right_OXYZScapula[1]) transfScapula = vtk.vtkTransform() transfScapula.RotateWXYZ(-stance[6], basicAxis) transfScapula.RotateWXYZ(stance[8], self.angleCalculations.Right_OXYZScapula[2]) transfScapula.Update() #HUMERUS t2_humerus = vtk.vtkTransform() t2_humerus.RotateWXYZ(stance[10], self.angleCalculations.Right_OXYZHumerus[2]) t2_humerus.Update() basicAxis = t2_humerus.TransformPoint(self.angleCalculations.Right_OXYZHumerus[1]) transfHumerus = vtk.vtkTransform() transfHumerus.RotateWXYZ(-stance[9], basicAxis) transfHumerus.RotateWXYZ(stance[11], self.angleCalculations.Right_OXYZHumerus[2]) transfHumerus.Update() #FOREARM t2_forearm = vtk.vtkTransform() t2_forearm.RotateWXYZ(stance[13], self.angleCalculations.Right_OXYZForearm[2]) t2_forearm.Update() basicAxis = t2_forearm.TransformPoint(self.angleCalculations.Right_OXYZForearm[1]) transfForearm = vtk.vtkTransform() #~ transfForearm.RotateWXYZ(stance[12], basicAxis) #~ transfForearm.RotateWXYZ(stance[14], self.angleCalculations.Right_OXYZForearm[2]) transfForearm.RotateWXYZ(-stance[12], basicAxis) transfForearm.RotateWXYZ(stance[14], self.angleCalculations.Right_OXYZForearm[2]) transfForearm.Update() #SPINE spine = [0, 1, 2, 3, 4] for pt in spine: new_blPos[pt] = transfThorax.TransformFloatPoint(blPos[pt]) #CLAVICLE clavicle = [6] tmp = self.ApplyCorrectionTransform(transfClavicle, blPos[4], blPos[6]) new_blPos[6] = transfThorax.TransformFloatPoint(tmp) #SCAPULA scapula = [5, 7, 8, 9, 24] for pt in scapula: tmp1 = self.ApplyCorrectionTransform(transfScapula, blPos[6], blPos[pt]) tmp2 = self.ApplyCorrectionTransform(transfClavicle, blPos[4], tmp1) tmp3 = transfThorax.TransformFloatPoint(tmp2) new_blPos[pt] = tmp3 # HUMERUS humerus = [10, 11] for pt in humerus: tmp1 = self.ApplyCorrectionTransform(transfHumerus, blPos[24], blPos[pt]) tmp2 = self.ApplyCorrectionTransform(transfScapula, blPos[6], tmp1) tmp3 = self.ApplyCorrectionTransform(transfClavicle, blPos[4], tmp2) tmp4 = transfThorax.TransformFloatPoint(tmp3) new_blPos[pt] = tmp4 # FOREARM forearm = [12, 13] for pt in forearm: tmp1 = self.ApplyCorrectionTransform(transfForearm, self.angleCalculations.Right_midELEM, blPos[pt]) tmp2 = self.ApplyCorrectionTransform(transfHumerus, blPos[24], tmp1) tmp3 = self.ApplyCorrectionTransform(transfScapula, blPos[6], tmp2) tmp4 = self.ApplyCorrectionTransform(transfClavicle, blPos[4], tmp3) tmp5 = transfThorax.TransformFloatPoint(tmp4) new_blPos[pt] = tmp5 if returnBLpos: return new_blPos else: poseActor = self.ShowPose(new_blPos, type = 2, showbones = showbones) #type = mean return poseActor def MedianMeanSpline(self, mean = True): try: self.gui.ren3.RemoveActor(self.statisticsActor) except AttributeError: pass try: self.gui.ren2.RemoveActor(self.customPose) except AttributeError: pass stancelist = [] stancelength = len(self.splineCollection[0]['stance']) for i in range(0,len(self.splineCollection)): totalstance = [] if self.splineCollection[i]['visible'] == True: for j in range(0, stancelength): totalstance.append(self.splineCollection[i]['stance'][j]) stancelist.append(tuple(totalstance)) if stancelist == []: return -1 meanlist = [] meanpluslist = [] meanminlist = [] medianlist = [] lowerlist = [] upperlist = [] for i in range(0, stancelength): stats = statistics.stats(numpy.array(stancelist)[:,i].tolist(), confidence_interval = 0.25) meanlist.append(stats[0]) meanminlist.append(stats[0]-stats[2]) meanpluslist.append(stats[0]+stats[2]) medianlist.append(stats[1]) lowerlist.append(stats[5]) upperlist.append(stats[6]) #~ lowerlist.append(stats[1]-stats[5]) #~ upperlist.append(stats[1]+stats[5]) if mean: lowerConfActor = self.GeneratePhysique(meanminlist) medianActor = self.GeneratePhysique(meanlist, showbones = True) upperConfActor = self.GeneratePhysique(meanpluslist) lowerConfActor.GetMapper().Update() medianActor.GetMapper().Update() upperConfActor.GetMapper().Update() else: lowerConfActor = self.GeneratePhysique(lowerlist) medianActor = self.GeneratePhysique(medianlist, showbones = True) upperConfActor = self.GeneratePhysique(upperlist) lowerConfActor.GetMapper().Update() medianActor.GetMapper().Update() upperConfActor.GetMapper().Update() #~ self.StoreImage() return 1 obj1 = lowerConfActor.GetMapper().GetInput() obj2 = medianActor.GetMapper().GetInput() obj3 = upperConfActor.GetMapper().GetInput() # Generate the polyline for the spline. points = vtk.vtkPoints() profileData = vtk.vtkPolyData() # Number of points on the spline numberOfOutputPoints = 14# * 3 #14 punten per pose, 3 poses ptlist1 = obj1.GetPoints() ptlist2 = obj2.GetPoints() ptlist3 = obj3.GetPoints() interpolatedDensity = 31 splineColors = vtk.vtkFloatArray() splineColors.SetName("statistics") for i in range(0, numberOfOutputPoints): SplineX = vtk.vtkCardinalSpline() SplineY = vtk.vtkCardinalSpline() SplineZ = vtk.vtkCardinalSpline() SplineX.AddPoint(0, ptlist1.GetPoint(i)[0]) # SplineX.AddPoint(1, ptlist2.GetPoint(i)[0]) SplineX.AddPoint(2, ptlist3.GetPoint(i)[0]) SplineY.AddPoint(0, ptlist1.GetPoint(i)[1]) SplineY.AddPoint(1, ptlist2.GetPoint(i)[1]) # SplineY.AddPoint(2, ptlist3.GetPoint(i)[1]) SplineZ.AddPoint(0, ptlist1.GetPoint(i)[2]) SplineZ.AddPoint(1, ptlist2.GetPoint(i)[2]) SplineZ.AddPoint(2, ptlist3.GetPoint(i)[2]) # for j in range(0, interpolatedDensity): t = (j*1.0) / (0.5 * interpolatedDensity) points.InsertNextPoint(SplineX.Evaluate(t), SplineY.Evaluate(t), SplineZ.Evaluate(t)) splineColors.InsertTuple1(i*interpolatedDensity + j, 60*abs(j - (0.5 * interpolatedDensity))/(0.5 * interpolatedDensity)) surface = vtk.vtkCellArray() for i in range(0, numberOfOutputPoints-1): if i not in [1, 3, 9, 11]: for j in range(0, interpolatedDensity-1): surface.InsertNextCell(4) surface.InsertCellPoint(i * interpolatedDensity + j) surface.InsertCellPoint(i * interpolatedDensity + j + 1) surface.InsertCellPoint((i+1) * interpolatedDensity + j + 1) surface.InsertCellPoint((i+1) * interpolatedDensity + j) profileData = vtk.vtkPolyData() profileData.SetPoints(points) profileData.SetPolys(surface) statisticsMapper = vtk.vtkPolyDataMapper() statisticsMapper.SetInput(profileData) statisticsMapper.ScalarVisibilityOn() statisticsMapper.GetInput().GetPointData().AddArray(splineColors) statisticsMapper.GetInput().GetPointData().SetActiveScalars("statistics") statisticsMapper.SetUseLookupTableScalarRange(1) statisticsMapper.SetScalarModeToUsePointData() ##~ statisticsMapper.SetScalarMaterialModeToAmbientAndDiffuse() statisticsMapper.SetLookupTable(self.colorscales.LUT_Statistics) self.customPose.SetMapper(statisticsMapper) ##~ self.customPose.GetProperty().SetAmbient(0.5) ##~ self.customPose.GetProperty().SetDiffuse(0.5) #~ self.gui.ren2.AddActor(self.customPose) self.gui.Render(2) if mean: stdspline1 = self.CreateSplineObject(meanminlist).GetMapper().GetInput() meanspline = self.CreateSplineObject(meanlist).GetMapper().GetInput() stdspline2 = self.CreateSplineObject(meanpluslist).GetMapper().GetInput() else: stdspline1 = self.CreateSplineObject(upperlist).GetMapper().GetInput() meanspline = self.CreateSplineObject(medianlist).GetMapper().GetInput() stdspline2 = self.CreateSplineObject(lowerlist).GetMapper().GetInput() # Generate the polyline for the spline. points = vtk.vtkPoints() profileData = vtk.vtkPolyData() # Number of points on the spline numberOfOutputPoints = 50 # Interpolate x, y and z by using the three spline filters and # create new points ptlist = stdspline1[0].GetPoints() for i in range(0, numberOfOutputPoints): points.InsertNextPoint(ptlist.GetPoint(i)) ptlist = meanspline[0].GetPoints() for i in range(0, numberOfOutputPoints): points.InsertNextPoint(ptlist.GetPoint(i)) ptlist = stdspline2[0].GetPoints() for i in range(0, numberOfOutputPoints): points.InsertNextPoint(ptlist.GetPoint(i)) splineColors = vtk.vtkFloatArray() splineColors.SetName("statistics") for i in range(0, numberOfOutputPoints): splineColors.InsertTuple1(i, 60) for i in range(0, numberOfOutputPoints): splineColors.InsertTuple1(i+numberOfOutputPoints, 0) for i in range(0, numberOfOutputPoints): splineColors.InsertTuple1(i+2*numberOfOutputPoints, 60) #~ # Create the polyline. surface = vtk.vtkCellArray() for i in range(0, numberOfOutputPoints-1): surface.InsertNextCell(4) surface.InsertCellPoint(i) surface.InsertCellPoint(i + 1) surface.InsertCellPoint(i + numberOfOutputPoints + 1) surface.InsertCellPoint(i + numberOfOutputPoints) surface.InsertNextCell(4) surface.InsertCellPoint(i + numberOfOutputPoints + 1) surface.InsertCellPoint(i + numberOfOutputPoints) surface.InsertCellPoint(i + 2*numberOfOutputPoints) surface.InsertCellPoint(i + 2*numberOfOutputPoints + 1) profileData = vtk.vtkPolyData() profileData.SetPoints(points) profileData.SetPolys(surface) statisticsMapper = vtk.vtkPolyDataMapper() statisticsMapper.SetInput(profileData) statisticsMapper.ScalarVisibilityOn() statisticsMapper.GetInput().GetPointData().AddArray(splineColors) statisticsMapper.GetInput().GetPointData().SetActiveScalars("statistics") statisticsMapper.SetUseLookupTableScalarRange(1) statisticsMapper.SetScalarModeToUsePointData() statisticsMapper.SetLookupTable(self.colorscales.LUT_Statistics) self.statisticsActor.SetMapper(statisticsMapper) self.statisticsActor.SetPosition(0,0,-1) self.gui.ren3.AddActor(self.statisticsActor) self.gui.Render(3) def StoreImage(self, whichone=1): pngWriter = vtk.vtkPNGWriter() w2i = vtk.vtkWindowToImageFilter() w2i.SetInput(self.gui.renwini2.GetRenderWindow()) #~ if whichone==2: #~ w2i.SetInput(self.main.renwini2.GetRenderWindow()) #~ else: #~ w2i.SetInput(self.main.renwini.GetRenderWindow()) pngWriter.SetInput(w2i.GetOutput()) w2i.Modified() self.imagenumber = self.imagenumber+1 pngWriter.SetFileName('Screenshots/image%04d.png' % self.imagenumber) pngWriter.Write() def ExportSplines(self, whichone): filename = "" dlg = wx.FileDialog(self.gui, message="Save splines", defaultDir=os.getcwd(), defaultFile="", wildcard="txt file (*.txt)|*.txt", style=wx.SAVE | wx.CHANGE_DIR) if dlg.ShowModal() == wx.ID_OK: filename = dlg.GetPath() dlg.Destroy() exportfile = open(filename, 'wb', 1) if whichone==0: for i in range (0, len (self.splineCollection)): if self.Filters.FilterSingleSpline_WithoutVisualisation(\ self.splineCollection[i], whichone, i): exportfile.write(str(self.splineCollection[i]['stance'])+"\n") exportfile.write(str(self.splineCollection[i]['blPos'])+"\n") else: for i in range (0, len (self.splineReferences)): if self.Filters.FilterSingleSpline_WithoutVisualisation(\ self.splineReferences[i], whichone, i): exportfile.write(str(self.splineReferences[i]['stance'])+"\n") exportfile.write(str(self.splineReferences[i]['blPos'])+"\n") exportfile.close() return os.path.split(filename)[1] def ReadRootDirectory(self): if hasattr(sys, 'frozen') and sys.frozen: appdir, exe = os.path.split(sys.executable) else: dirname = os.path.dirname(sys.argv[0]) if dirname and dirname != os.curdir: appdir = dirname else: appdir = os.getcwd() return appdir def ActivateCellpicker(self): # Create a cell picker. if (self.cellpickercreated==True): self.cellpickercreated = True else: self.cellpickercreated = True self.cellpicker = vtk.vtkPointPicker() self.cellpicker.SetTolerance(0.0025) print "Cellpicker tolerance: ", self.cellpicker.GetTolerance() self.cellpicker.InitializePickList() self.cellpicker.PickFromListOn() def ActivateAngleRollOver(self, event): #print "activate" if self.rollover_activated == False: self.ActivateCellpicker() self.rollover_activated = True def DeactivateAngleRollOver(self, event): #print "deactivate" if self.rollover_activated == True: self.gui.renwini1.RemoveObserver(self.lbpe) self.rollover_activated = False def AngleRollOver(self, event, bla): x, y = self.gui.renwini3.GetEventPosition() self.cellpicker.Pick(x, y, 0, self.gui.ren3) if self.cellpicker.GetPointId() < 0: pass else: #print self.cellpicker.GetPointId() act = self.cellpicker.GetActor() #~ activescalars = act.GetMapper().GetInput().GetPointData().GetActiveScalars() #~ print act.GetMapper().GetInput().GetPointData().GetScalars()#"splinecolors_reference") #~ print act.GetMapper().GetInput().GetPointData().GetScalars(splineColors) try: self.gui.ren3.RemoveActor(self.TubeActor) except AttributeError: pass self.TubeActor = vtk.vtkActor() profileTubes = vtk.vtkTubeFilter() profileTubes.SetNumberOfSides(3) profileTubes.SetInput(act.GetMapper().GetInput()) profileTubes.SetRadius(.005) self.TubeMapper = vtk.vtkPolyDataMapper() self.TubeActor.SetMapper(self.TubeMapper) self.TubeActor.GetProperty().SetAmbient(1.0) self.TubeMapper.SetInput(profileTubes.GetOutput()) self.gui.ren3.AddActor(self.TubeActor) if not act.GetMapper().GetInput().GetPointData().GetScalars("splinecolors_reference"): for i in range(0, len(self.splineCollection)): if self.splineCollection[i]['splineActor'] == act: blPos = self.splineCollection[i]['blPos'] new_blPos = self.CorrectBLsForStaticElements(blPos) self.lastStance = self.splineCollection[i]['stance'] try: self.gui.ren2.RemoveActor(self.PoseActor9) except AttributeError: pass self.PoseActor9.SetMapper(act.GetMapper()) act = self.ShowPose(new_blPos, type = 2) self.gui.SetSliders(self.splineCollection[i]['stance']) else: for i in range(0, len(self.splineReferences)): if self.splineReferences[i]['splineActor'] == act: blPos = self.splineReferences[i]['blPos'] new_blPos = self.CorrectBLsForStaticElements(blPos) self.lastStance = self.splineReferences[i]['stance'] try: self.gui.ren2.RemoveActor(self.PoseActor9) except AttributeError: pass self.PoseActor9.SetMapper(act.GetMapper()) act = self.ShowPose(new_blPos, type = 2) self.gui.SetSliders(self.splineReferences[i]['stance']) self.gui.Render() class MyApp(wx.App): def OnInit(self): patternviewer = PatternViewer(None, None) #~ patternviewer.Show() self.SetTopWindow(patternviewer.gui) #frame.AddSpline([120, 100, 50, 140, 10, 12, 90, 180, 180], ['None', 'None', 'None', 'None'], None) patternviewer.ImportSplines() patternviewer.ImportSplines2() #~ frame.SwitchClavicleTransform() #~ frame.GenerateReachObject() return 1 if __name__ == "__main__": app = MyApp(0) app.MainLoop()
Python
#Boa:FramePanel:WXVISPANEL import wx import os, sys import shutil import time import math import vtk import vtktudoss import superthread try: import extended.BaseCalc as BaseCalc except ImportError: import BaseCalc import pdb def create(parent, root, renderwindow, primaryrenderer): return Annotation(parent, root, renderwindow, primaryrenderer) class Annotation: _pointsList = [] _lineList = [] _arcList = [] _floatingLabelList = [] initiateLabelTimer = True def __init__(self, parent, bla, renderwindow, primaryrenderer): self._root = bla self.baseCalc = BaseCalc.create(self, self) self.renderwindow = renderwindow self.renX = primaryrenderer self.InitializeAnnotationLayer() def InitializeAnnotationLayer(self): try: self.renderwindow.RemoveRenderer(self.renXannotation) except AttributeError: pass self.renderwindow.SetNumberOfLayers(2) self.renXannotation = vtk.vtkRenderer() self.renXannotation.SetLayer(1) self.renXannotation.InteractiveOff() self.renderwindow.AddRenderer(self.renXannotation) def VisualiseLine(self, point1, point2, opacity = 0.5, color = (1.0, 1.0, 1.0), actorcollection = None): polys = vtk.vtkCellArray() points = vtk.vtkPoints() points.InsertPoint(0, point1) points.InsertPoint(1, point2) polys.InsertNextCell(2) polys.InsertCellPoint(0) polys.InsertCellPoint(1) lijntje = vtk.vtkPolyData() lijntje.SetPoints(points) lijntje.SetLines(polys) ca = vtk.vtkActor() ma = vtk.vtkPolyDataMapper() ma.SetInput(lijntje) ca.SetMapper(ma) ca.GetProperty().SetColor(color) ca.GetProperty().SetOpacity(opacity) ca_transparent = vtk.vtkActor() ca_transparent.SetMapper(ma) ca_transparent.GetProperty().SetColor(1.0, 1.0, 1.0) ca_transparent.GetProperty().SetOpacity(0.33) self.renX.AddActor(ca) self.renXannotation.AddActor(ca_transparent) self.renXannotation.SetActiveCamera (self.renX.GetActiveCamera()) self._lineList.append({'Actor' : ca}) self._lineList.append({'Actor' : ca_transparent}) if actorcollection != None: actorcollection.AddItem(ca) actorcollection.AddItem(ca_transparent) return actorcollection #pdb.set_trace() def VisualiseCoordinateSystem(self, OXYZ): O = OXYZ[0] X = OXYZ[1] Y = OXYZ[2] Z = OXYZ[3] self.VisualiseLine(O, self.baseCalc.AddPoints(O, self.baseCalc.MultiplyVector(X, 10)), color = (0.5, 0.0, 0.0), opacity = 1.0) #~ #self._root.annotation_renwin1.VisualisePoint(self.baseCalc.AddPoints(coordScapula_O, self.baseCalc.MultiplyVector(coordScapula_Z, 50)), "Zs" ,(1.00,1.00,0.15)) self.VisualiseLine(O, self.baseCalc.AddPoints(O, self.baseCalc.MultiplyVector(Y, 10)), color = (0.0, 0.5, 0.0), opacity = 1.0) #~ #self._root.annotation_renwin1.VisualisePoint(self.baseCalc.AddPoints(coordScapula_O, self.baseCalc.MultiplyVector(coordScapula_X, 50)), "Xs" ,(1.00,1.00,0.15)) self.VisualiseLine(O, self.baseCalc.AddPoints(O, self.baseCalc.MultiplyVector(Z, 10)), color = (0.0, 0.0, 0.5), opacity = 1.0) #~ #self._root.annotation_renwin1.VisualisePoint(self.baseCalc.AddPoints(coordScapula_O, self.baseCalc.MultiplyVector(coordScapula_Y, 50)), "Ys" ,(1.00,1.00,0.15)) def VisualiseArc(self, point1, point2, point3, opacity = 0.5, color = (1.0, 1.0, 1.0)): points = vtk.vtkPoints() points.InsertPoint(0, point1) points.InsertPoint(1, point2) points.InsertPoint(2, point3) polys = vtk.vtkCellArray() polys.InsertNextCell(3) polys.InsertCellPoint(0) polys.InsertCellPoint(1) polys.InsertCellPoint(2) lines = vtk.vtkCellArray() lines.InsertNextCell(2) lines.InsertCellPoint(0) lines.InsertCellPoint(1) lines.InsertNextCell(2) lines.InsertCellPoint(0) lines.InsertCellPoint(2) arcparts = 20 vector1 = self.baseCalc.SubtractPoints(point2, point1) axis_length = self.baseCalc.Length3DVector(vector1) vtk.vtkMath().Normalize(vector1) vector2 = self.baseCalc.SubtractPoints(point3, point1) L2 = self.baseCalc.Length3DVector(vector2) if L2<axis_length: axis_length = L2 vtk.vtkMath().Normalize(vector2) cross = [0,0,0] vtk.vtkMath().Cross(vector1, vector2, cross) dottie = math.acos(vtk.vtkMath.Dot(vector1,vector2) / (math.sqrt(math.pow(vector1[0],2)\ + math.pow(vector1[1],2) + math.pow(vector1[2],2))\ *math.sqrt(math.pow(vector2[0],2) + math.pow(vector2[1],2) \ + math.pow(vector2[2],2)))) dottie = vtk.vtkMath.DegreesFromRadians(dottie) deel_dottie = dottie / (arcparts) transf = vtk.vtkTransform() triangleStripPoints = vtk.vtkPoints() triangleStripPoints.SetNumberOfPoints(arcparts*2+2) punt1 = self.baseCalc.AddPoints(point1, self.baseCalc.MultiplyVector(vector1, axis_length)) punt2 = self.baseCalc.AddPoints(point1, self.baseCalc.MultiplyVector(vector1, 0.8*axis_length)) triangleStripPoints.InsertPoint(0, punt1) triangleStripPoints.InsertPoint(1, punt2) for i in range(0,arcparts): transf.RotateWXYZ(deel_dottie, cross[0], cross[1], cross[2]) transf.Update() a1_b = transf.TransformFloatPoint(vector1[0], vector1[1], vector1[2]) punt1 = self.baseCalc.AddPoints(point1, self.baseCalc.MultiplyVector(a1_b, axis_length)) punt2 = self.baseCalc.AddPoints(point1, self.baseCalc.MultiplyVector(a1_b, 0.8*axis_length)) triangleStripPoints.InsertPoint(i*2+2, punt1) triangleStripPoints.InsertPoint(i*2+3, punt2) aTriangleStrip = vtk.vtkTriangleStrip() aTriangleStrip.GetPointIds().SetNumberOfIds((arcparts+1)*2) for i in range(0,arcparts+1): aTriangleStrip.GetPointIds().SetId(i*2, i*2) aTriangleStrip.GetPointIds().SetId(i*2+1, i*2+1) aTriangleStripGrid = vtk.vtkUnstructuredGrid() aTriangleStripGrid.Allocate(1, 1) aTriangleStripGrid.InsertNextCell(aTriangleStrip.GetCellType(), aTriangleStrip.GetPointIds()) aTriangleStripGrid.SetPoints(triangleStripPoints) aTriangleStripMapper = vtk.vtkDataSetMapper() aTriangleStripMapper.SetInput(aTriangleStripGrid) vlakje = vtk.vtkPolyData() vlakje.SetPoints(points) vlakje.SetLines(lines) ma = vtk.vtkPolyDataMapper() ma.SetInput(vlakje) ca = vtk.vtkActor() ca.SetMapper(aTriangleStripMapper) ca.GetProperty().SetColor(color) ca.GetProperty().SetOpacity(opacity) ca_transparent = vtk.vtkActor() ca_transparent.SetMapper(aTriangleStripMapper) ca_transparent.GetProperty().SetColor(1.0, 1.0, 1.0) ca_transparent.GetProperty().SetOpacity(0.33) ca2 = vtk.vtkActor() ca2.SetMapper(ma) ca2.GetProperty().SetColor(color) ca2.GetProperty().SetOpacity(opacity) ca2_transparent = vtk.vtkActor() ca2_transparent.SetMapper(ma) ca2_transparent.GetProperty().SetColor(1.0, 1.0, 1.0) ca2_transparent.GetProperty().SetOpacity(0.33) self.renX.AddActor(ca) self.renX.AddActor(ca2) try: self.renderwindow.RemoveRenderer(self.renXannotation) except AttributeError: pass self.renderwindow.SetNumberOfLayers(2) self.renXannotation = vtk.vtkRenderer() self.renXannotation.SetLayer(1) self.renderwindow.AddRenderer(self.renXannotation) self.renXannotation.AddActor(ca_transparent) self.renXannotation.AddActor(ca2_transparent) self.renXannotation.SetActiveCamera (self.renX.GetActiveCamera()) self._arcList.append({'Actor' : ca}) self._arcList.append({'Actor' : ca_transparent}) self._arcList.append({'Actor' : ca2}) self._arcList.append({'Actor' : ca2_transparent}) def VisualisePoint(self, point, pointName, color): ca = vtk.vtkCaptionActor2D() ca.GetProperty().SetColor(0.8,0.8,1) ca.GetCaptionTextProperty().SetColor(color) ca.GetCaptionTextProperty().ShadowOn() ca.SetPickable(0) ca.SetAttachmentPoint(point) ca.SetPosition(25,10) ca.BorderOff() ca.SetWidth(0.3) ca.SetHeight(0.04) ca.SetMaximumLeaderGlyphSize(10) coneSource = vtk.vtkConeSource() coneSource.SetResolution(6) # we want the cone's very tip to be at 0,0,0 coneSource.SetCenter(- coneSource.GetHeight() / 2.0, 0, 0) ca.SetLeaderGlyph(coneSource.GetOutput()) ca.GetProperty().SetColor(color) if len(pointName) > 0: ca.SetCaption(pointName) else: ca.SetCaption("n/a") self.renX.AddActor(ca) self._pointsList.append({'point' : tuple(point), 'name' : pointName, 'sphereActor' : ca}) def ClearArcList(self): for i in range(len(self._arcList)): # remove the actor from the renderer self.renX.RemoveActor(self._arcList[0]['Actor']) self.renXannotation.RemoveActor(self._arcList[0]['Actor']) del self._arcList[0] #~ try: #~ self.renderwindow.RemoveRenderer(self.renXannotation) #~ except AttributeError: #~ pass #~ self.renderwindow.SetNumberOfLayers(1) def ClearLineList(self): for i in range(len(self._lineList)): # remove the actor from the renderer self.renX.RemoveActor(self._lineList[0]['Actor']) self.renXannotation.RemoveActor(self._lineList[0]['Actor']) del self._lineList[0] #~ try: #~ self.renderwindow.RemoveRenderer(self.renXannotation) #~ except AttributeError: #~ pass #~ self.renderwindow.SetNumberOfLayers(1) def ClearPointList(self): for i in range(len(self._pointsList)): # remove the actor from the renderer self.renX.RemoveActor(self._pointsList[0]['sphereActor']) del self._pointsList[0] def ClearAll(self): self.ClearPointList() self.ClearLineList() self.ClearArcList() def AddFloatingLabel(self, _id = -1, _text = "", _position = [0,0],\ _color = [1.0, 1.0, 1.0], _extinguish = 30): #time in 1/10 th sec. textActor = vtk.vtkTextActor() textActor.SetInput(_text) textActor.SetPosition(_position[0], _position[1]) tprop = textActor.GetTextProperty() tprop.SetFontSize(32) tprop.SetFontFamilyToArial() tprop.SetJustificationToCentered() tprop.ShadowOn() tprop.SetColor(_color) tprop.SetOpacity(0) self.renX.AddActor(textActor) try: self._root.Render() except RuntimeError: pass self._floatingLabelList.append({'id': _id, 'actor': textActor, 'text' : _text, 'position' : _position, 'color' : _color, 'extinguish' : _extinguish, 'time': 0.0}) if self.initiateLabelTimer == True: self.FloatingLabelTimer() def FloatingLabelTimer(self): self.initiateLabelTimer = False while len(self._floatingLabelList) > 0: i = len(self._floatingLabelList)-1 terminationlist = [] while i >= 0: label = self._floatingLabelList[i] if label['time'] < 15: #Attack a = label['time'] pos = label['position'] ratesqr = 2*(a/15.0) label['actor'].SetPosition(pos[0], (pos[1] - ratesqr)) label['position'] = [pos[0], pos[1] - ratesqr] tprop = label['actor'].GetTextProperty() tprop.SetOpacity(a/15.0) tprop.SetColor(label['color']) elif label['time'] > label['extinguish']: #Decay a = (label['time'] - label['extinguish']) pos = label['position'] label['actor'].SetPosition(pos[0], (pos[1] - 2)) label['position'] = [pos[0], (pos[1] - 2)] tprop = label['actor'].GetTextProperty() tprop.SetOpacity(1-a/15.0) tprop.SetColor(label['color']) if label['time'] == (label['extinguish'] + 15): self.renX.RemoveActor(label['actor']) label = self._floatingLabelList.pop(i) else: pos = label['position'] label['actor'].SetPosition(pos[0], (pos[1] - 2)) label['position'] = [pos[0], (pos[1] - 2)] i = i - 1 label['time'] = label['time'] + 1 time.sleep(0.05) try: wx.Yield() except AssertionError: pass try: self._root.Render() except RuntimeError: pass self.initiateLabelTimer = True
Python
import time import wx import vtk import math import numpy try: import extended.BaseCalc as BaseCalc except ImportError: import BaseCalc def create(parent): return CoordinateSystems(parent) class CoordinateSystems: def __init__(self, parent): print "CoordinateSystems module loaded." self.parent = parent self.baseCalc = BaseCalc.create(self, self) def DefineXYZThorax(self, IJ, C7, midIJC7, midPXT8): #Ot: The origin coincident with IJ coordThorax_O = IJ #Yt: The line connecting the midpoint between PX and T8 # and the midpoint between IJ and C7, pointing upward. coordThorax_Y = self.baseCalc.SubtractPoints(midIJC7, midPXT8) coordThorax_Y = self.baseCalc.Normalize(coordThorax_Y) #Zt: The line perpendicular to the plane formed by #IJ, C7, and the midpoint between PX and T8, pointing to the Right. TempA = self.baseCalc.SubtractPoints(IJ, midPXT8) TempB = self.baseCalc.SubtractPoints(IJ, C7) TempA = self.baseCalc.Normalize(TempA) TempB = self.baseCalc.Normalize(TempB) coordThorax_Z = [0,0,0] vtk.vtkMath.Cross(TempB, TempA, coordThorax_Z) coordThorax_Z = self.baseCalc.Normalize(coordThorax_Z) #Xt: The common line perpendicular to the Zt- and #Yt-axis, pointing forwards. coordThorax_X = [0,0,0] vtk.vtkMath.Cross(coordThorax_Y, coordThorax_Z, coordThorax_X) coordThorax_X = self.baseCalc.Normalize(coordThorax_X) self.OXYZThorax = [coordThorax_O, coordThorax_X, coordThorax_Y, coordThorax_Z] return self.OXYZThorax def DefineXYZClavicle(self, side): #The origin coincident with SC coordClavicle_O = self.GetCoords("Right_SC") #Zc: The line connecting SC and AC, pointing to AC coordClavicle_Z = self._root.baseCalc.SubtractPoints(self.GetCoords("Right_AC"), self.GetCoords("Right_SC")) coordClavicle_Z = self._root.baseCalc.Normalize(coordClavicle_Z) #Xc: The line perpendicular to Zc and Yt, pointing forward #Note that the Xc-axis is defined with #respect to the vertical axis of the thorax (Ytaxis) #because only two bonylandmarks can be discerned at the clavicle. TempA = self._root.baseCalc.SubtractPoints(self.midIJC7, self.midPXT8) TempA = self._root.baseCalc.Normalize(TempA) #(Yt) coordClavicle_X = [0,0,0] vtk.vtkMath.Cross(TempA, coordClavicle_Z, coordClavicle_X) coordClavicle_X = self._root.baseCalc.Normalize(coordClavicle_X) #Yc: The common line perpendicular to the Xc- and Zc-axis, pointing upward. coordClavicle_Y = [0,0,0] vtk.vtkMath.Cross(coordClavicle_Z, coordClavicle_X, coordClavicle_Y) coordClavicle_Y = self._root.baseCalc.Normalize(coordClavicle_Y) self.Right_OXYZClavicle = [coordClavicle_O, coordClavicle_X, coordClavicle_Y, coordClavicle_Z] def DefineXYZScapula(self, side): #The origin coincident with AA. coordScapula_O = self.GetCoords("Right_AA") #Zs: The line connecting TS and AA, pointing to AA. coordScapula_Z = self._root.baseCalc.SubtractPoints(self.GetCoords("Right_AA"), self.GetCoords("Right_TS")) #coordScapula_Z = self._root.baseCalc.Normalize(coordScapula_Z) vtk.vtkMath.Normalize(coordScapula_Z) #Xs: The line perpendicular to the plane formed by AI, AA, and TS, pointing forward. TempA = self._root.baseCalc.SubtractPoints(self.GetCoords("Right_AI"), self.GetCoords("Right_TS")) TempB = self._root.baseCalc.SubtractPoints(self.GetCoords("Right_AI"), self.GetCoords("Right_AA")) TempA = self._root.baseCalc.Normalize(TempA) TempB = self._root.baseCalc.Normalize(TempB) coordScapula_X = [0,0,0] vtk.vtkMath.Cross(TempA, TempB, coordScapula_X) coordScapula_X = self._root.baseCalc.Normalize(coordScapula_X) #Ys: The common line perpendicular to the Xs- and Zs-axis, pointing upward. coordScapula_Y = [0,0,0] vtk.vtkMath.Cross(coordScapula_Z, coordScapula_X, coordScapula_Y) coordScapula_Y = self._root.baseCalc.Normalize(coordScapula_Y) #~ #Faulty FOB coords...: #~ tmp = coordScapula_Z #~ coordScapula_Z = self._root.baseCalc.MultiplyVector(coordScapula_X, -1) #~ coordScapula_X = tmp self.Right_OXYZScapula = [coordScapula_O, coordScapula_X, coordScapula_Y, coordScapula_Z] def DefineXYZHumerus(self, side): coordHumerus_O = self.GetCoords("Right_GH") #Yh1: The line connecting GH and the midpoint of EL and EM, pointing to GH. coordHumerus_Y = self._root.baseCalc.SubtractPoints(self.GetCoords("Right_GH"), self.Right_midELEM) coordHumerus_Y = self._root.baseCalc.Normalize(coordHumerus_Y) #Xh1: The line perpendicular to the plane formed by EL, EM, and GH, pointing forward. coordHumerus_Ya = self._root.baseCalc.SubtractPoints(self.GetCoords("Right_GH"), self.GetCoords("Right_EL")) coordHumerus_Yb = self._root.baseCalc.SubtractPoints(self.GetCoords("Right_GH"), self.GetCoords("Right_EM")) coordHumerus_Ya = self._root.baseCalc.Normalize(coordHumerus_Ya) coordHumerus_Yb = self._root.baseCalc.Normalize(coordHumerus_Yb) coordHumerus_X = [0,0,0] vtk.vtkMath.Cross(coordHumerus_Yb, coordHumerus_Ya, coordHumerus_X) coordHumerus_X = self._root.baseCalc.Normalize(coordHumerus_X) #Zh1: The common line perpendicular to the Yh1- and Xh1-axis, pointing to the Right. coordHumerus_Z = [0,0,0] vtk.vtkMath.Cross(coordHumerus_X, coordHumerus_Y, coordHumerus_Z) coordHumerus_Z = self._root.baseCalc.Normalize(coordHumerus_Z) #Faulty FOB coords...: tmp = coordHumerus_Z coordHumerus_Z = self._root.baseCalc.MultiplyVector(coordHumerus_X, -1) coordHumerus_X = tmp self.Right_OXYZHumerus = [coordHumerus_O, coordHumerus_X, coordHumerus_Y, coordHumerus_Z] def DefineXYZForearm(self, side): coordForearm_O = self.GetCoords("Right_US") #Yf : The line connecting US and the midpoint #between EL and EM, pointing proximally. coordForearm_Y = self._root.baseCalc.SubtractPoints(self.Right_midELEM, self.GetCoords("Right_US")) coordForearm_Y = self._root.baseCalc.Normalize(coordForearm_Y) #Xf : The line perpendicular to the plane through US, #RS, and the midpoint between EL and EM, pointing forward. TempA = self._root.baseCalc.SubtractPoints(self.Right_midELEM, self.GetCoords("Right_US")) TempB = self._root.baseCalc.SubtractPoints(self.Right_midELEM, self.GetCoords("Right_RS")) TempA = self._root.baseCalc.Normalize(TempA) TempB = self._root.baseCalc.Normalize(TempB) coordForearm_X = [0,0,0] vtk.vtkMath.Cross(TempB, TempA, coordForearm_X) coordForearm_X = self._root.baseCalc.Normalize(coordForearm_X) #*Hoe zorgen dat coordForearm_X naar voren wijst?? #Zf : The common line perpendicular to the Xf and #Yf -axis, pointing to the Right. coordForearm_Z = [0,0,0] vtk.vtkMath.Cross(coordForearm_X, coordForearm_Y, coordForearm_Z) coordForearm_Z = self._root.baseCalc.Normalize(coordForearm_Z) self.Right_OXYZForearm = [coordForearm_O, coordForearm_X, coordForearm_Y, coordForearm_Z] def MatchCoordinateSystemAtoB(self, oxyzFirst, oxyzSecond): #returns a transform that, when applied, transforms coordinate system xyzFirst #to xyzSecond, i.e. x=x, y=y, z=z. total_lmtransf = vtk.vtkLandmarkTransform() assen1 = vtk.vtkPoints() assen1.SetNumberOfPoints(4) assen1.SetPoint(0, oxyzFirst[0]) assen1.SetPoint(1, oxyzFirst[1]) assen1.SetPoint(2, oxyzFirst[2]) assen1.SetPoint(3, oxyzFirst[3]) assen2 = vtk.vtkPoints() assen2.SetNumberOfPoints(4) assen2.SetPoint(0, oxyzSecond[0]) assen2.SetPoint(1, oxyzSecond[1]) assen2.SetPoint(2, oxyzSecond[2]) assen2.SetPoint(3, oxyzSecond[3]) total_lmtransf.SetSourceLandmarks(assen1) total_lmtransf.SetTargetLandmarks(assen2) total_lmtransf.Update() total_matrix1 = total_lmtransf.GetMatrix() total_newtransf = vtk.vtkTransform() total_newtransf.SetMatrix(total_matrix1) return total_newtransf
Python
import time import wx import vtk import math import numpy import vtktudoss try: import extended.BaseCalc as BaseCalc except ImportError: import BaseCalc def create(parent): return Filters(parent) class Filters: def __init__(self, parent): print "Filters module loaded." self.parent = parent self.baseCalc = BaseCalc.create(self, self) self.initiateFilterTimer = True self.initiateFilterReferencesTimer = True self.filtercounter = 0 self.filterreferencescounter = 0 self.sessionvisible_A = True self.sessionvisible_B = True self.widgetFiltersOn = True self.inversekinematicsOn = False self.sequenceFilterOn = False self.visibleSplines = 0 self.visibleReferences = 0 #FILTERS self.jointAngleCollection = [] min = None max = None filter_min = None filter_max = None Thorax1 = {'stanceID': 0, 'description' : "Thorax\nflexion", 'min1': min, 'max1': max, 'min2': min, 'max2': max, 'filter_min': filter_min, 'filter_max': filter_max, 'widget': self.parent.gui.widgets.spineWidget_elevation} Thorax2 = {'stanceID': 1, 'description' : "Thorax\nlateral\nflexion", 'min1': min, 'max1': max, 'min2': min, 'max2': max, 'filter_min': filter_min, 'filter_max': filter_max, 'widget': self.parent.gui.widgets.spineWidget_plane} Thorax3 = {'stanceID': 2, 'description' : "Thorax\naxial\nrotation", 'min1': min, 'max1': max, 'min2': min, 'max2': max, 'filter_min': filter_min, 'filter_max': filter_max, 'widget': self.parent.gui.widgets.spineWidget_axial} AC1 = {'stanceID': 3, 'description' : "Clavicle\nprotraction", 'min1': min, 'max1': max, 'min2': min, 'max2': max, 'filter_min': filter_min, 'filter_max': filter_max, 'widget': self.parent.gui.widgets.clavicleWidget_elevation} AC2 = {'stanceID': 4, 'description' : "Clavicle\nelevation", 'min1': min, 'max1': max, 'min2': min, 'max2': max, 'filter_min': filter_min, 'filter_max': filter_max, 'widget': self.parent.gui.widgets.clavicleWidget_plane} AC3 = {'stanceID': 5, 'description' : "Clavicle\naxial\nrotation", 'min1': min, 'max1': max, 'min2': min, 'max2': max, 'filter_min': filter_min, 'filter_max': filter_max, 'widget': self.parent.gui.widgets.clavicleWidget_axial} SCAP1 = {'stanceID': 6, 'description' : "Scapula\nprotraction", 'min1': min, 'max1': max, 'min2': min, 'max2': max, 'filter_min': filter_min, 'filter_max': filter_max, 'widget': self.parent.gui.widgets.scapulaWidget_elevation} SCAP2 = {'stanceID': 7, 'description' : "Scapula\nlateral\nrotation", 'min1': min, 'max1': max, 'min2': min, 'max2': max, 'filter_min': filter_min, 'filter_max': filter_max, 'widget': self.parent.gui.widgets.scapulaWidget_plane} SCAP3 = {'stanceID': 8, 'description' : "Scapula\ntilt", 'min1': min, 'max1': max, 'min2': min, 'max2': max, 'filter_min': filter_min, 'filter_max': filter_max, 'widget': self.parent.gui.widgets.scapulaWidget_axial} GHabduction = {'stanceID': 9, 'description' : "Humerus\nelevation", 'min1': min, 'max1': max, 'min2': min, 'max2': max, 'filter_min': filter_min, 'filter_max': filter_max, 'widget': self.parent.gui.widgets.GHWidget_elevation} GHplane = {'stanceID': 10, 'description' : "Humerus\nelevation\nplane", 'min1': min, 'max1': max, 'min2': min, 'max2': max, 'filter_min': filter_min, 'filter_max': filter_max, 'widget': self.parent.gui.widgets.GHWidget_plane} GHaxial = {'stanceID': 11, 'description' : "Humerus\nexo-rotation", 'min1': min, 'max1': max, 'min2': min, 'max2': max, 'filter_min': filter_min, 'filter_max': filter_max, 'widget': self.parent.gui.widgets.GHWidget_axial}# ELflexion = {'stanceID': 12, 'description' : "Elbow\nflexion", 'min1': min, 'max1': max, 'min2': min, 'max2': max, 'filter_min': filter_min, 'filter_max': filter_max, 'widget': self.parent.gui.widgets.ELWidget_elevation} ELplane = {'stanceID': 13, 'description' : "Elbow\nflexion\nplane", 'min1': min, 'max1': max, 'min2': min, 'max2': max, 'filter_min': filter_min, 'filter_max': filter_max, 'widget': self.parent.gui.widgets.ELWidget_plane} ELaxial = {'stanceID': 14, 'description' : "Elbow\npronation", 'min1': min, 'max1': max, 'min2': min, 'max2': max, 'filter_min': filter_min, 'filter_max': filter_max, 'widget': self.parent.gui.widgets.ELWidget_axial} HumThorax1 = {'stanceID': 15, 'description' : "Humerus\nglobal\nelevation", 'min1': min, 'max1': max, 'min2': min, 'max2': max, 'filter_min': filter_min, 'filter_max': filter_max, 'widget': self.parent.gui.widgets.GHGlobal_elevation} HumThorax2 = {'stanceID': 16, 'description' : "Humerus\nglobal\nelevation\nplane", 'min1': min, 'max1': max, 'min2': min, 'max2': max, 'filter_min': filter_min, 'filter_max': filter_max, 'widget': self.parent.gui.widgets.GHGlobal_plane} HumThorax3 = {'stanceID': 17, 'description' : "Humerus\nglobal\naxial\nrotation", 'min1': min, 'max1': max, 'min2': min, 'max2': max, 'filter_min': filter_min, 'filter_max': filter_max, 'widget': self.parent.gui.widgets.GHGlobal_axial} self.jointAngleCollection.append(Thorax1) self.jointAngleCollection.append(Thorax2) self.jointAngleCollection.append(Thorax3) self.jointAngleCollection.append(AC1) self.jointAngleCollection.append(AC2) self.jointAngleCollection.append(AC3) self.jointAngleCollection.append(SCAP1) self.jointAngleCollection.append(SCAP2) self.jointAngleCollection.append(SCAP3) self.jointAngleCollection.append(GHabduction) self.jointAngleCollection.append(GHplane) self.jointAngleCollection.append(GHaxial) self.jointAngleCollection.append(ELflexion) self.jointAngleCollection.append(ELplane) self.jointAngleCollection.append(ELaxial) self.jointAngleCollection.append(HumThorax1) self.jointAngleCollection.append(HumThorax2) self.jointAngleCollection.append(HumThorax3) self.plottedAngles = [] self.filteredAngles = [] def FilterSingleSpline_WithoutVisualisation(self, spline, isReferenceSpline, splineNr): # Not filtered until one of the filters returns False. valid = True if valid: # Second filter: check all the widgets for their filter ranges. if self.widgetFiltersOn: stance = spline['stance'] for j in range(0,len(self.filteredAngles)): #if any of the angles are outside of their respective filter ranges, break and return False. #~ print self.jointAngleCollection[self.filteredAngles[j]]['filter_min'], ' - ', self.jointAngleCollection[self.filteredAngles[j]]['filter_max'] if stance[self.filteredAngles[j]] < self.jointAngleCollection[self.filteredAngles[j]]['filter_min'] or \ stance[self.filteredAngles[j]] > self.jointAngleCollection[self.filteredAngles[j]]['filter_max']: valid = False break if valid: #Third filter: Inverse Kinematics? if self.inversekinematicsOn: if isReferenceSpline: if splineNr in self.parent.IK.previoussplines2: valid = True else: valid = False else: if splineNr in self.parent.IK.previoussplines: valid = True else: valid = False if valid: #sequence filter if self.sequenceFilterOn: for sequenceplotter in self.parent.gui.sequenceplotters: if (isReferenceSpline and sequenceplotter.whichdata==1) or \ (not isReferenceSpline and sequenceplotter.whichdata==0): for i in range(0, len(sequenceplotter.filtervalues)/2): if splineNr >= sequenceplotter.filtervalues[i*2] and\ splineNr <= sequenceplotter.filtervalues[i*2 + 1]: valid = False break if valid: return True else: return False def FilterSingleSpline(self, spline, isReferenceSpline, splineNr): # Not filtered until one of the filters returns False. valid = True # First filter: dataset visible? if isReferenceSpline: if not self.sessionvisible_B: valid = False else: if not self.sessionvisible_A: valid = False if valid: # Second filter: check all the widgets for their filter ranges. if self.widgetFiltersOn: stance = spline['stance'] for j in range(0,len(self.filteredAngles)): #if any of the angles are outside of their respective filter ranges, break and return False. #~ print self.jointAngleCollection[self.filteredAngles[j]]['filter_min'], ' - ', self.jointAngleCollection[self.filteredAngles[j]]['filter_max'] if stance[self.filteredAngles[j]] < self.jointAngleCollection[self.filteredAngles[j]]['filter_min'] or \ stance[self.filteredAngles[j]] > self.jointAngleCollection[self.filteredAngles[j]]['filter_max']: valid = False break if valid: #Third filter: Inverse Kinematics? if self.inversekinematicsOn: if isReferenceSpline: if splineNr in self.parent.IK.previoussplines2: valid = True else: valid = False else: if splineNr in self.parent.IK.previoussplines: valid = True else: valid = False if valid: #sequence filter if self.sequenceFilterOn: for sequenceplotter in self.parent.gui.sequenceplotters: if (isReferenceSpline and sequenceplotter.whichdata==1) or \ (not isReferenceSpline and sequenceplotter.whichdata==0): for i in range(0, len(sequenceplotter.filtervalues)/2): if splineNr >= sequenceplotter.filtervalues[i*2] and\ splineNr <= sequenceplotter.filtervalues[i*2 + 1]: valid = False break if valid: self.ShowSpline(spline, splineNr) return True else: self.HideSpline(spline, splineNr) return False def ShowSpline(self, spline, splineNr=None): if spline['visible'] == False: if spline['reference']: self.visibleReferences = self.visibleReferences + 1 else: self.visibleSplines = self.visibleSplines + 1 self.parent.gui.ren3.AddActor(spline['splineActor']) try: self.parent.cellpicker.DeletePickList(spline['splineActor']) except AttributeError: pass self.parent.cellpicker.AddPickList(spline['splineActor']) if self.parent.gui.posesOn == True: self.parent.gui.ren2.AddActor(spline['poseActor']) self.parent.gui.ren2.AddActor(spline['shadedArm']) for scatterplot in self.parent.gui.scatterplotlist: if spline['reference']: scatterplot.xyValues2.append([spline['stance'][scatterplot.stanceID1],\ spline['stance'][scatterplot.stanceID2]]) else: scatterplot.xyValues1.append([spline['stance'][scatterplot.stanceID1],\ spline['stance'][scatterplot.stanceID2]]) spline['visible'] = True def HideSpline(self, spline, splineNr=None): if spline['visible'] == True: if spline['reference']: self.visibleReferences = self.visibleReferences - 1 else: self.visibleSplines = self.visibleSplines - 1 try: self.parent.cellpicker.DeletePickList(spline['splineActor']) except AttributeError: pass self.parent.gui.ren3.RemoveActor(spline['splineActor']) self.parent.gui.ren2.RemoveActor(spline['poseActor']) self.parent.gui.ren2.RemoveActor(spline['shadedArm']) spline['visible'] = False for scatterplot in self.parent.gui.scatterplotlist: try: if spline['reference']: scatterplot.xyValues2.remove([spline['stance'][scatterplot.stanceID1],\ spline['stance'][scatterplot.stanceID2]]) else: scatterplot.xyValues1.remove([spline['stance'][scatterplot.stanceID1],\ spline['stance'][scatterplot.stanceID2]]) except ValueError: pass #~ print self.removeditems #~ print "New number of pick items: ", self.parent.cellpicker.GetPickList().GetNumberOfItems() def RestartFiltering(self): self.filterEnd = self.filtercounter -1 if self.filterEnd < 0: self.filterEnd = len(self.parent.splineCollection) self.initiateFilterTimer = False #~ print "Number of pick items: ", self.parent.cellpicker.GetPickList().GetNumberOfItems() self.removeditems = 0 def RestartFilteringReferences(self): self.filterReferencesEnd = self.filterreferencescounter -1 if self.filterReferencesEnd < 0: self.filterReferencesEnd = len(self.parent.splineReferences) self.initiateFilterReferencesTimer = False def FilterAllStepper(self): i = 0 if self.filtercounter == self.filterEnd: self.initiateFilterTimer = True while self.filtercounter != self.filterEnd and i < 200: self.FilterSingleSpline(self.parent.splineCollection[self.filtercounter], False, self.filtercounter) #~ self.parent.splineCollection[self.filtercounter]['visible'] = True #~ else: #~ self.parent.splineCollection[self.filtercounter]['visible'] = False self.filtercounter = self.filtercounter + 1 if self.filtercounter >= len(self.parent.splineCollection): if self.filtercounter == self.filterEnd: self.filtercounter = 0 self.initiateFilterTimer = True break else: self.filtercounter = 0 i = i+1 #self.parent.MedianMeanSpline() self.UpdateShaderOpacity() def FilterAllReferenceStepper(self): i = 0 if self.filterreferencescounter == self.filterReferencesEnd: self.initiateFilterReferencesTimer = True while self.filterreferencescounter != self.filterReferencesEnd and i < 200: self.FilterSingleSpline(self.parent.splineReferences[self.filterreferencescounter], True, self.filterreferencescounter) #~ self.parent.splineReferences[self.filterreferencescounter]['visible'] = True #~ else: #~ self.parent.splineReferences[self.filterreferencescounter]['visible'] = False self.filterreferencescounter = self.filterreferencescounter + 1 if self.filterreferencescounter >= len(self.parent.splineReferences): if self.filterreferencescounter == self.filterReferencesEnd: self.filterreferencescounter = 0 self.initiateFilterReferencesTimer = True break else: self.filterreferencescounter = 0 i = i+1 self.UpdateShaderOpacity() def UpdateShaderOpacity(self): #bluealphamultiplier = 1.0-(min(0.5, self.visibleSplines/2000.0)) #1000 splines = 0.0, 60 splines = 0.0, 1 spline = 1.0 bluealphamultiplier = max(1.0, 5.0 - self.visibleSplines/40.0) + (float(self.parent.gui.editorpanel.slider_1.GetValue())/2.0) yellowalphamultiplier = max(1.0, 5.0 - self.visibleReferences/40.0) + (float(self.parent.gui.editorpanel.slider_2.GetValue())/2.0) self.parent.blue_shader.AddShaderVariableFloat("alphamultiplier", bluealphamultiplier) self.parent.yellow_shader.AddShaderVariableFloat("alphamultiplier", yellowalphamultiplier) self.parent.exoblue_shader.AddShaderVariableFloat("alphamultiplier", bluealphamultiplier) self.parent.exoyellow_shader.AddShaderVariableFloat("alphamultiplier", yellowalphamultiplier) self.parent.bluespline_shader.AddShaderVariableFloat("alphamultiplier", bluealphamultiplier) self.parent.yellowspline_shader.AddShaderVariableFloat("alphamultiplier", yellowalphamultiplier) class MyApp(wx.App): def OnInit(self): applic = Filters(None) return 1 if __name__ == "__main__": app = MyApp(0) app.MainLoop()
Python
import time import wx import vtk import math import numpy try: import extended.BaseCalc as BaseCalc except ImportError: import BaseCalc def create(parent): return CoordinateSystems(parent) class CoordinateSystems: def __init__(self, parent): print "CoordinateSystems module loaded." self.parent = parent self.baseCalc = BaseCalc.create(self, self) def DefineXYZThorax(self, IJ, C7, midIJC7, midPXT8): #Ot: The origin coincident with IJ coordThorax_O = IJ #Yt: The line connecting the midpoint between PX and T8 # and the midpoint between IJ and C7, pointing upward. coordThorax_Y = self.baseCalc.SubtractPoints(midIJC7, midPXT8) coordThorax_Y = self.baseCalc.Normalize(coordThorax_Y) #Zt: The line perpendicular to the plane formed by #IJ, C7, and the midpoint between PX and T8, pointing to the Right. TempA = self.baseCalc.SubtractPoints(IJ, midPXT8) TempB = self.baseCalc.SubtractPoints(IJ, C7) TempA = self.baseCalc.Normalize(TempA) TempB = self.baseCalc.Normalize(TempB) coordThorax_Z = [0,0,0] vtk.vtkMath.Cross(TempB, TempA, coordThorax_Z) coordThorax_Z = self.baseCalc.Normalize(coordThorax_Z) #Xt: The common line perpendicular to the Zt- and #Yt-axis, pointing forwards. coordThorax_X = [0,0,0] vtk.vtkMath.Cross(coordThorax_Y, coordThorax_Z, coordThorax_X) coordThorax_X = self.baseCalc.Normalize(coordThorax_X) self.OXYZThorax = [coordThorax_O, coordThorax_X, coordThorax_Y, coordThorax_Z] return self.OXYZThorax def DefineXYZClavicle(self, side): #The origin coincident with SC coordClavicle_O = self.GetCoords("Right_SC") #Zc: The line connecting SC and AC, pointing to AC coordClavicle_Z = self._root.baseCalc.SubtractPoints(self.GetCoords("Right_AC"), self.GetCoords("Right_SC")) coordClavicle_Z = self._root.baseCalc.Normalize(coordClavicle_Z) #Xc: The line perpendicular to Zc and Yt, pointing forward #Note that the Xc-axis is defined with #respect to the vertical axis of the thorax (Ytaxis) #because only two bonylandmarks can be discerned at the clavicle. TempA = self._root.baseCalc.SubtractPoints(self.midIJC7, self.midPXT8) TempA = self._root.baseCalc.Normalize(TempA) #(Yt) coordClavicle_X = [0,0,0] vtk.vtkMath.Cross(TempA, coordClavicle_Z, coordClavicle_X) coordClavicle_X = self._root.baseCalc.Normalize(coordClavicle_X) #Yc: The common line perpendicular to the Xc- and Zc-axis, pointing upward. coordClavicle_Y = [0,0,0] vtk.vtkMath.Cross(coordClavicle_Z, coordClavicle_X, coordClavicle_Y) coordClavicle_Y = self._root.baseCalc.Normalize(coordClavicle_Y) self.Right_OXYZClavicle = [coordClavicle_O, coordClavicle_X, coordClavicle_Y, coordClavicle_Z] def DefineXYZScapula(self, side): #The origin coincident with AA. coordScapula_O = self.GetCoords("Right_AA") #Zs: The line connecting TS and AA, pointing to AA. coordScapula_Z = self._root.baseCalc.SubtractPoints(self.GetCoords("Right_AA"), self.GetCoords("Right_TS")) #coordScapula_Z = self._root.baseCalc.Normalize(coordScapula_Z) vtk.vtkMath.Normalize(coordScapula_Z) #Xs: The line perpendicular to the plane formed by AI, AA, and TS, pointing forward. TempA = self._root.baseCalc.SubtractPoints(self.GetCoords("Right_AI"), self.GetCoords("Right_TS")) TempB = self._root.baseCalc.SubtractPoints(self.GetCoords("Right_AI"), self.GetCoords("Right_AA")) TempA = self._root.baseCalc.Normalize(TempA) TempB = self._root.baseCalc.Normalize(TempB) coordScapula_X = [0,0,0] vtk.vtkMath.Cross(TempA, TempB, coordScapula_X) coordScapula_X = self._root.baseCalc.Normalize(coordScapula_X) #Ys: The common line perpendicular to the Xs- and Zs-axis, pointing upward. coordScapula_Y = [0,0,0] vtk.vtkMath.Cross(coordScapula_Z, coordScapula_X, coordScapula_Y) coordScapula_Y = self._root.baseCalc.Normalize(coordScapula_Y) #~ #Faulty FOB coords...: #~ tmp = coordScapula_Z #~ coordScapula_Z = self._root.baseCalc.MultiplyVector(coordScapula_X, -1) #~ coordScapula_X = tmp self.Right_OXYZScapula = [coordScapula_O, coordScapula_X, coordScapula_Y, coordScapula_Z] def DefineXYZHumerus(self, side): coordHumerus_O = self.GetCoords("Right_GH") #Yh1: The line connecting GH and the midpoint of EL and EM, pointing to GH. coordHumerus_Y = self._root.baseCalc.SubtractPoints(self.GetCoords("Right_GH"), self.Right_midELEM) coordHumerus_Y = self._root.baseCalc.Normalize(coordHumerus_Y) #Xh1: The line perpendicular to the plane formed by EL, EM, and GH, pointing forward. coordHumerus_Ya = self._root.baseCalc.SubtractPoints(self.GetCoords("Right_GH"), self.GetCoords("Right_EL")) coordHumerus_Yb = self._root.baseCalc.SubtractPoints(self.GetCoords("Right_GH"), self.GetCoords("Right_EM")) coordHumerus_Ya = self._root.baseCalc.Normalize(coordHumerus_Ya) coordHumerus_Yb = self._root.baseCalc.Normalize(coordHumerus_Yb) coordHumerus_X = [0,0,0] vtk.vtkMath.Cross(coordHumerus_Yb, coordHumerus_Ya, coordHumerus_X) coordHumerus_X = self._root.baseCalc.Normalize(coordHumerus_X) #Zh1: The common line perpendicular to the Yh1- and Xh1-axis, pointing to the Right. coordHumerus_Z = [0,0,0] vtk.vtkMath.Cross(coordHumerus_X, coordHumerus_Y, coordHumerus_Z) coordHumerus_Z = self._root.baseCalc.Normalize(coordHumerus_Z) #Faulty FOB coords...: tmp = coordHumerus_Z coordHumerus_Z = self._root.baseCalc.MultiplyVector(coordHumerus_X, -1) coordHumerus_X = tmp self.Right_OXYZHumerus = [coordHumerus_O, coordHumerus_X, coordHumerus_Y, coordHumerus_Z] def DefineXYZForearm(self, side): coordForearm_O = self.GetCoords("Right_US") #Yf : The line connecting US and the midpoint #between EL and EM, pointing proximally. coordForearm_Y = self._root.baseCalc.SubtractPoints(self.Right_midELEM, self.GetCoords("Right_US")) coordForearm_Y = self._root.baseCalc.Normalize(coordForearm_Y) #Xf : The line perpendicular to the plane through US, #RS, and the midpoint between EL and EM, pointing forward. TempA = self._root.baseCalc.SubtractPoints(self.Right_midELEM, self.GetCoords("Right_US")) TempB = self._root.baseCalc.SubtractPoints(self.Right_midELEM, self.GetCoords("Right_RS")) TempA = self._root.baseCalc.Normalize(TempA) TempB = self._root.baseCalc.Normalize(TempB) coordForearm_X = [0,0,0] vtk.vtkMath.Cross(TempB, TempA, coordForearm_X) coordForearm_X = self._root.baseCalc.Normalize(coordForearm_X) #*Hoe zorgen dat coordForearm_X naar voren wijst?? #Zf : The common line perpendicular to the Xf and #Yf -axis, pointing to the Right. coordForearm_Z = [0,0,0] vtk.vtkMath.Cross(coordForearm_X, coordForearm_Y, coordForearm_Z) coordForearm_Z = self._root.baseCalc.Normalize(coordForearm_Z) self.Right_OXYZForearm = [coordForearm_O, coordForearm_X, coordForearm_Y, coordForearm_Z] def MatchCoordinateSystemAtoB(self, oxyzFirst, oxyzSecond): #returns a transform that, when applied, transforms coordinate system xyzFirst #to xyzSecond, i.e. x=x, y=y, z=z. total_lmtransf = vtk.vtkLandmarkTransform() assen1 = vtk.vtkPoints() assen1.SetNumberOfPoints(4) assen1.SetPoint(0, oxyzFirst[0]) assen1.SetPoint(1, oxyzFirst[1]) assen1.SetPoint(2, oxyzFirst[2]) assen1.SetPoint(3, oxyzFirst[3]) assen2 = vtk.vtkPoints() assen2.SetNumberOfPoints(4) assen2.SetPoint(0, oxyzSecond[0]) assen2.SetPoint(1, oxyzSecond[1]) assen2.SetPoint(2, oxyzSecond[2]) assen2.SetPoint(3, oxyzSecond[3]) total_lmtransf.SetSourceLandmarks(assen1) total_lmtransf.SetTargetLandmarks(assen2) total_lmtransf.Update() total_matrix1 = total_lmtransf.GetMatrix() total_newtransf = vtk.vtkTransform() total_newtransf.SetMatrix(total_matrix1) return total_newtransf
Python
import time import os, sys import wx import vtk import math import numpy import vtktudoss try: import extended.BaseCalc as BaseCalc except ImportError: import BaseCalc def create(parent): return WidgetCollection(parent) class WidgetCollection: def __init__(self, parent): print "WidgetCollection module loaded." self.parent = parent self.baseCalc = BaseCalc.create(self, self) self.InitializeWidgets() def InitializeWidgets(self): xoffset = [-5.5, 0.0, 0] yoffset = [0.0, 5.5, 0] zoffset = [0.0, 0.0, 5.5] widgetscale = 6 modelfilename = os.path.join(self.parent.appdir, "jointnudge.stl") #Spine elevation self.spineWidget_elevation = vtktudoss.vtkAdvancedAngleWidget() self.spineWidget_elevation.SetFileName(modelfilename) self.spineWidget_elevation.KeyPressActivationOff() self.spineWidget_elevation.SetInput(self.parent.torsiactor.GetMapper().GetInput()) self.spineWidget_elevation.SetInteractor(self.parent.renwini1) self.spineWidget_elevation.Setaxis_length(0.8) self.spineWidget_elevation.SetshowContext(False) self.spineWidget_elevation.SetColor(self.parent.ren1overlay.spineact.GetProperty().GetColor()) self.spineWidget_elevation.PlaceWidget() self.spineWidget_elevation.SetScale(widgetscale) self.spineWidget_elevation.Setmirrorfonts(-1.0) self.spineWidget_elevation.SetInitialAxis([1.0,0.0,0.0]) #~ self.spineWidget_elevation.Rotate(90.0, [0,1,0]) self.spineWidget_elevation.Setposoffset(xoffset) position = self.parent.ren1overlay.spineact.GetPosition() self.spineWidget_elevation.SetInitialPosition(position) self.spineWidget_elevation.AddObserver("InteractionEvent",self.ArcWidgetModified) self.spineWidget_elevation.SetLabelsEnabled(1) #Spine plane self.spineWidget_plane = vtktudoss.vtkAdvancedAngleWidget() self.spineWidget_plane.SetFileName(modelfilename) self.spineWidget_plane.KeyPressActivationOff() self.spineWidget_plane.SetInput(self.parent.torsiactor.GetMapper().GetInput()) self.spineWidget_plane.SetInteractor(self.parent.renwini1) self.spineWidget_plane.Setaxis_length(0.8) self.spineWidget_plane.SetshowContext(False) self.spineWidget_plane.SetColor(self.parent.ren1overlay.spineact.GetProperty().GetColor()) self.spineWidget_plane.PlaceWidget() self.spineWidget_plane.SetScale(widgetscale) self.spineWidget_plane.SetInitialAxis([0.0,-1.0,0.0]) self.spineWidget_plane.Rotate(90.0, [1,0,0]) self.spineWidget_plane.Setposoffset(zoffset) position = self.parent.ren1overlay.spineact.GetPosition() self.spineWidget_plane.SetInitialPosition(position) self.spineWidget_plane.AddObserver("InteractionEvent",self.ArcWidgetModified) self.spineWidget_plane.SetLabelsEnabled(1) #Spine axial self.spineWidget_axial = vtktudoss.vtkAdvancedAngleWidget() self.spineWidget_axial.SetFileName(modelfilename) self.spineWidget_axial.KeyPressActivationOff() self.spineWidget_axial.SetInput(self.parent.torsiactor.GetMapper().GetInput()) self.spineWidget_axial.SetInteractor(self.parent.renwini1) self.spineWidget_axial.Setaxis_length(0.8) self.spineWidget_elevation.SetshowContext(False) self.spineWidget_axial.SetColor(self.parent.ren1overlay.spineact.GetProperty().GetColor()) self.spineWidget_axial.PlaceWidget() self.spineWidget_axial.SetScale(widgetscale) self.spineWidget_axial.SetInitialAxis([0.0,1.0,0.0]) self.spineWidget_axial.Setposoffset(yoffset) position = self.parent.ren1overlay.spineact.GetPosition() self.spineWidget_axial.SetInitialPosition(position) self.spineWidget_axial.AddObserver("InteractionEvent",self.ArcWidgetModified) self.spineWidget_axial.SetLabelsEnabled(1) #clavicle elevation self.clavicleWidget_elevation = vtktudoss.vtkAdvancedAngleWidget() self.clavicleWidget_elevation.SetFileName(modelfilename) self.clavicleWidget_elevation.KeyPressActivationOff() self.clavicleWidget_elevation.SetInput(self.parent.torsiactor.GetMapper().GetInput()) self.clavicleWidget_elevation.SetInteractor(self.parent.renwini1) self.clavicleWidget_elevation.Setaxis_length(0.8) self.clavicleWidget_elevation.SetshowContext(False) self.clavicleWidget_elevation.SetColor(self.parent.ren1overlay.clavact.GetProperty().GetColor()) self.clavicleWidget_elevation.PlaceWidget() self.clavicleWidget_elevation.SetScale(widgetscale) self.clavicleWidget_elevation.Setmirrorfonts(-1.0) self.clavicleWidget_elevation.SetInitialAxis([1.0,0.0,0.0]) #~ self.clavicleWidget_elevation.Rotate(90.0, [0,1,0]) self.clavicleWidget_elevation.Setposoffset(xoffset) position = self.parent.ren1overlay.clavact.GetPosition() self.clavicleWidget_elevation.SetInitialPosition(position) self.clavicleWidget_elevation.AddObserver("InteractionEvent",self.ArcWidgetModified) self.clavicleWidget_elevation.SetLabelsEnabled(1) #clavicle plane self.clavicleWidget_plane = vtktudoss.vtkAdvancedAngleWidget() self.clavicleWidget_plane.SetFileName(modelfilename) self.clavicleWidget_plane.KeyPressActivationOff() self.clavicleWidget_plane.SetInput(self.parent.torsiactor.GetMapper().GetInput()) self.clavicleWidget_plane.SetInteractor(self.parent.renwini1) self.clavicleWidget_plane.Setaxis_length(0.8) self.clavicleWidget_plane.SetshowContext(False) self.clavicleWidget_plane.SetColor(self.parent.ren1overlay.clavact.GetProperty().GetColor()) self.clavicleWidget_plane.PlaceWidget() self.clavicleWidget_plane.SetScale(widgetscale) self.clavicleWidget_plane.SetInitialAxis([0.0,-1.0,0.0]) self.clavicleWidget_plane.Rotate(90.0, [1,0,0]) self.clavicleWidget_plane.Setposoffset(zoffset) position = self.parent.ren1overlay.clavact.GetPosition() self.clavicleWidget_plane.SetInitialPosition(position) self.clavicleWidget_plane.AddObserver("InteractionEvent",self.ArcWidgetModified) self.clavicleWidget_plane.SetLabelsEnabled(1) #clavicle axial self.clavicleWidget_axial = vtktudoss.vtkAdvancedAngleWidget() self.clavicleWidget_axial.SetFileName(modelfilename) self.clavicleWidget_axial.KeyPressActivationOff() self.clavicleWidget_axial.SetInput(self.parent.torsiactor.GetMapper().GetInput()) self.clavicleWidget_axial.SetInteractor(self.parent.renwini1) self.clavicleWidget_axial.Setaxis_length(0.8) self.clavicleWidget_axial.SetshowContext(False) self.clavicleWidget_axial.SetColor(self.parent.ren1overlay.clavact.GetProperty().GetColor()) self.clavicleWidget_axial.PlaceWidget() self.clavicleWidget_axial.SetScale(widgetscale) self.clavicleWidget_axial.SetInitialAxis([0.0,1.0,0.0]) self.clavicleWidget_axial.Setposoffset(yoffset) position = self.parent.ren1overlay.clavact.GetPosition() self.clavicleWidget_axial.SetInitialPosition(position) self.clavicleWidget_axial.AddObserver("InteractionEvent",self.ArcWidgetModified) self.clavicleWidget_axial.SetLabelsEnabled(1) #scapula elevation self.scapulaWidget_elevation = vtktudoss.vtkAdvancedAngleWidget() self.scapulaWidget_elevation.SetFileName(modelfilename) self.scapulaWidget_elevation.KeyPressActivationOff() self.scapulaWidget_elevation.SetInput(self.parent.torsiactor.GetMapper().GetInput()) self.scapulaWidget_elevation.SetInteractor(self.parent.renwini1) self.scapulaWidget_elevation.Setaxis_length(0.8) self.scapulaWidget_elevation.SetshowContext(False) self.scapulaWidget_elevation.SetColor(self.parent.ren1overlay.scapact.GetProperty().GetColor()) self.scapulaWidget_elevation.PlaceWidget() self.scapulaWidget_elevation.SetScale(widgetscale) self.scapulaWidget_elevation.Setmirrorfonts(-1.0) self.scapulaWidget_elevation.SetInitialAxis([1.0,0.0,0.0]) #~ self.scapulaWidget_elevation.Rotate(90.0, [0,1,0]) self.scapulaWidget_elevation.Setposoffset(xoffset) position = self.parent.ren1overlay.scapact.GetPosition() self.scapulaWidget_elevation.SetInitialPosition(position) self.scapulaWidget_elevation.AddObserver("InteractionEvent",self.ArcWidgetModified) self.scapulaWidget_elevation.SetLabelsEnabled(1) #scapula plane self.scapulaWidget_plane = vtktudoss.vtkAdvancedAngleWidget() self.scapulaWidget_plane.SetFileName(modelfilename) self.scapulaWidget_plane.KeyPressActivationOff() self.scapulaWidget_plane.SetInput(self.parent.torsiactor.GetMapper().GetInput()) self.scapulaWidget_plane.SetInteractor(self.parent.renwini1) self.scapulaWidget_plane.Setaxis_length(0.8) self.scapulaWidget_plane.SetshowContext(False) self.scapulaWidget_plane.SetColor(self.parent.ren1overlay.scapact.GetProperty().GetColor()) self.scapulaWidget_plane.PlaceWidget() self.scapulaWidget_plane.SetScale(widgetscale) self.scapulaWidget_plane.SetInitialAxis([0.0,-1.0,0.0]) self.scapulaWidget_plane.Rotate(90.0, [1,0,0]) self.scapulaWidget_plane.Setposoffset(zoffset) position = self.parent.ren1overlay.scapact.GetPosition() self.scapulaWidget_plane.SetInitialPosition(position) self.scapulaWidget_plane.AddObserver("InteractionEvent",self.ArcWidgetModified) self.scapulaWidget_plane.SetLabelsEnabled(1) #scapula axial self.scapulaWidget_axial = vtktudoss.vtkAdvancedAngleWidget() self.scapulaWidget_axial.SetFileName(modelfilename) self.scapulaWidget_axial.KeyPressActivationOff() self.scapulaWidget_axial.SetInput(self.parent.torsiactor.GetMapper().GetInput()) self.scapulaWidget_axial.SetInteractor(self.parent.renwini1) self.scapulaWidget_axial.Setaxis_length(0.8) self.scapulaWidget_axial.SetshowContext(False) self.scapulaWidget_axial.SetColor(self.parent.ren1overlay.scapact.GetProperty().GetColor()) self.scapulaWidget_axial.PlaceWidget() self.scapulaWidget_axial.SetScale(widgetscale) self.scapulaWidget_axial.SetInitialAxis([0.0,1.0,0.0]) self.scapulaWidget_axial.Setposoffset(yoffset) position = self.parent.ren1overlay.scapact.GetPosition() self.scapulaWidget_axial.SetInitialPosition(position) self.scapulaWidget_axial.AddObserver("InteractionEvent",self.ArcWidgetModified) self.scapulaWidget_axial.SetLabelsEnabled(1) #GH elevation self.GHWidget_elevation = vtktudoss.vtkAdvancedAngleWidget() self.GHWidget_elevation.SetFileName(modelfilename) self.GHWidget_elevation.KeyPressActivationOff() self.GHWidget_elevation.SetInput(self.parent.torsiactor.GetMapper().GetInput()) self.GHWidget_elevation.SetInteractor(self.parent.renwini1) self.GHWidget_elevation.Setaxis_length(0.8) self.GHWidget_elevation.SetshowContext(False) self.GHWidget_elevation.SetColor(self.parent.ren1overlay.GHact.GetProperty().GetColor()) self.GHWidget_elevation.PlaceWidget() self.GHWidget_elevation.SetScale(widgetscale) self.GHWidget_elevation.Setmirrorfonts(-1.0) self.GHWidget_elevation.SetInitialAxis([1.0,0.0,0.0]) #~ self.GHWidget_elevation.Rotate(90.0, [0,1,0]) self.GHWidget_elevation.Setposoffset(xoffset) position = self.parent.ren1overlay.GHact.GetPosition() self.GHWidget_elevation.SetInitialPosition(position) self.GHWidget_elevation.AddObserver("InteractionEvent",self.ArcWidgetModified) self.GHWidget_elevation.SetLabelsEnabled(1) #GH plane self.GHWidget_plane = vtktudoss.vtkAdvancedAngleWidget() self.GHWidget_plane.SetFileName(modelfilename) self.GHWidget_plane.KeyPressActivationOff() self.GHWidget_plane.SetInput(self.parent.torsiactor.GetMapper().GetInput()) self.GHWidget_plane.SetInteractor(self.parent.renwini1) self.GHWidget_plane.PlaceWidget() self.GHWidget_plane.Setaxis_length(0.8) self.GHWidget_plane.SetshowContext(False) self.GHWidget_plane.SetColor(self.parent.ren1overlay.GHact.GetProperty().GetColor()) self.GHWidget_plane.SetScale(widgetscale) self.GHWidget_plane.SetInitialAxis([0.0,-1.0,0.0]) self.GHWidget_plane.Rotate(90.0, [1,0,0]) self.GHWidget_plane.Setposoffset(zoffset) position =self.parent.ren1overlay.GHact.GetPosition() self.GHWidget_plane.SetInitialPosition(position) self.GHWidget_plane.AddObserver("InteractionEvent",self.ArcWidgetModified) self.GHWidget_plane.SetLabelsEnabled(1) #GH axial self.GHWidget_axial = vtktudoss.vtkAdvancedAngleWidget() self.GHWidget_axial.SetFileName(modelfilename) self.GHWidget_axial.KeyPressActivationOff() self.GHWidget_axial.SetInput(self.parent.torsiactor.GetMapper().GetInput()) self.GHWidget_axial.SetInteractor(self.parent.renwini1) self.GHWidget_axial.Setaxis_length(0.8) self.GHWidget_axial.SetshowContext(False) self.GHWidget_axial.SetColor(self.parent.ren1overlay.GHact.GetProperty().GetColor()) self.GHWidget_axial.PlaceWidget() self.GHWidget_axial.SetScale(widgetscale) self.GHWidget_axial.SetInitialAxis([0.0,1.0,0.0]) position = self.parent.ren1overlay.GHact.GetPosition() self.GHWidget_axial.Setposoffset(yoffset) self.GHWidget_axial.SetInitialPosition(position) self.GHWidget_axial.AddObserver("InteractionEvent",self.ArcWidgetModified) self.GHWidget_axial.SetLabelsEnabled(1) #EL elevation self.ELWidget_elevation = vtktudoss.vtkAdvancedAngleWidget() self.ELWidget_elevation.SetFileName(modelfilename) self.ELWidget_elevation.KeyPressActivationOff() self.ELWidget_elevation.SetInput(self.parent.torsiactor.GetMapper().GetInput()) self.ELWidget_elevation.SetInteractor(self.parent.renwini1) self.ELWidget_elevation.Setaxis_length(0.8) self.ELWidget_elevation.SetshowContext(False) self.ELWidget_elevation.SetColor(self.parent.ren1overlay.ELact.GetProperty().GetColor()) self.ELWidget_elevation.PlaceWidget() self.ELWidget_elevation.SetScale(widgetscale) self.ELWidget_elevation.Setmirrorfonts(-1.0) self.ELWidget_elevation.SetInitialAxis([1.0,0.0,0.0]) #~ self.ELWidget_elevation.Rotate(90.0, [0,1,0]) self.ELWidget_elevation.Setposoffset(xoffset) position = self.parent.ren1overlay.ELact.GetPosition() self.ELWidget_elevation.SetInitialPosition(position) self.ELWidget_elevation.AddObserver("InteractionEvent",self.ArcWidgetModified) self.ELWidget_elevation.SetLabelsEnabled(1) #EL plane self.ELWidget_plane = vtktudoss.vtkAdvancedAngleWidget() self.ELWidget_plane.SetFileName(modelfilename) self.ELWidget_plane.KeyPressActivationOff() self.ELWidget_plane.SetInput(self.parent.torsiactor.GetMapper().GetInput()) self.ELWidget_plane.SetInteractor(self.parent.renwini1) self.ELWidget_plane.PlaceWidget() self.ELWidget_plane.Setaxis_length(0.8) self.spineWidget_elevation.SetshowContext(False) self.ELWidget_plane.SetColor(self.parent.ren1overlay.ELact.GetProperty().GetColor()) self.ELWidget_plane.SetScale(widgetscale) self.ELWidget_plane.SetInitialAxis([0.0,-1.0,0.0]) self.ELWidget_plane.Rotate(90.0, [1,0,0]) self.ELWidget_plane.Setposoffset(zoffset) position = self.parent.ren1overlay.ELact.GetPosition() self.ELWidget_plane.SetInitialPosition(position) self.ELWidget_plane.AddObserver("InteractionEvent",self.ArcWidgetModified) self.ELWidget_plane.SetLabelsEnabled(1) #EL axial self.ELWidget_axial = vtktudoss.vtkAdvancedAngleWidget() self.ELWidget_axial.SetFileName(modelfilename) self.ELWidget_axial.KeyPressActivationOff() self.ELWidget_axial.SetInput(self.parent.torsiactor.GetMapper().GetInput()) self.ELWidget_axial.SetInteractor(self.parent.renwini1) self.ELWidget_axial.Setaxis_length(0.8) self.ELWidget_axial.SetshowContext(False) self.ELWidget_axial.SetColor(self.parent.ren1overlay.ELact.GetProperty().GetColor()) self.ELWidget_axial.PlaceWidget() self.ELWidget_axial.SetScale(widgetscale) self.ELWidget_axial.SetInitialAxis([0.0,1.0,0.0]) self.ELWidget_axial.Setposoffset(yoffset) position = self.parent.ren1overlay.ELact.GetPosition() self.ELWidget_axial.SetInitialPosition(position) self.ELWidget_axial.AddObserver("InteractionEvent",self.ArcWidgetModified) self.ELWidget_axial.SetLabelsEnabled(1) #HUM THORAX ELEVATION self.GHGlobal_elevation = vtktudoss.vtkAdvancedAngleWidget() self.GHGlobal_elevation.SetFileName(modelfilename) self.GHGlobal_elevation.KeyPressActivationOff() self.GHGlobal_elevation.SetInput(self.parent.torsiactor.GetMapper().GetInput()) self.GHGlobal_elevation.SetInteractor(self.parent.renwini1) self.GHGlobal_elevation.Setaxis_length(4.2) self.GHGlobal_elevation.SetshowContext(False) self.GHGlobal_elevation.SetColor(self.parent.ren1overlay.GHact.GetProperty().GetColor()) self.GHGlobal_elevation.PlaceWidget() self.GHGlobal_elevation.SetScale(widgetscale) self.GHGlobal_elevation.Setpiechart(False) self.GHGlobal_elevation.Setmirrorfonts(-1.0) self.GHGlobal_elevation.SetInitialAxis([1.0,0.0,0.0]) #~ self.GHGlobal_elevation.Rotate(90.0, [0,1,0]) self.GHGlobal_elevation.Setposoffset([-3.5, 0.0, 0]) position =self.parent.ren1overlay.GHact.GetPosition() self.GHGlobal_elevation.SetInitialPosition(position) self.GHGlobal_elevation.AddObserver("InteractionEvent",self.ArcWidgetModified) self.GHGlobal_elevation.SetLabelsEnabled(1) self.GHGlobal_plane = vtktudoss.vtkAdvancedAngleWidget() self.GHGlobal_plane.SetFileName(modelfilename) self.GHGlobal_plane.KeyPressActivationOff() self.GHGlobal_plane.SetInput(self.parent.torsiactor.GetMapper().GetInput()) self.GHGlobal_plane.SetInteractor(self.parent.renwini1) self.GHGlobal_plane.Setaxis_length(4.2) self.GHGlobal_plane.SetshowContext(False) self.GHGlobal_plane.SetColor(self.parent.ren1overlay.GHact.GetProperty().GetColor()) self.GHGlobal_plane.PlaceWidget() self.GHGlobal_plane.SetScale(widgetscale) self.GHGlobal_plane.Setpiechart(False) self.GHGlobal_plane.SetInitialAxis([0.0,-1.0,0.0]) self.GHGlobal_plane.Rotate(90.0, [1,0,0]) position = self.parent.ren1overlay.GHact.GetPosition() self.GHGlobal_plane.Setposoffset([0.0, 0.0, 3.5]) self.GHGlobal_plane.SetInitialPosition(position) self.GHGlobal_plane.AddObserver("InteractionEvent",self.ArcWidgetModified) self.GHGlobal_plane.SetLabelsEnabled(1) self.GHGlobal_axial = vtktudoss.vtkAdvancedAngleWidget() self.GHGlobal_axial.SetFileName(modelfilename) self.GHGlobal_axial.KeyPressActivationOff() self.GHGlobal_axial.SetInput(self.parent.torsiactor.GetMapper().GetInput()) self.GHGlobal_axial.SetInteractor(self.parent.renwini1) self.GHGlobal_axial.Setaxis_length(4.2) self.GHGlobal_axial.SetshowContext(False) self.GHGlobal_axial.SetColor(self.parent.ren1overlay.GHact.GetProperty().GetColor()) self.GHGlobal_axial.PlaceWidget() self.GHGlobal_axial.SetScale(widgetscale) self.GHGlobal_axial.Setpiechart(False) self.GHGlobal_axial.SetInitialAxis([0.0,1.0,0.0]) position =self.parent.ren1overlay.GHact.GetPosition() self.GHGlobal_axial.Setposoffset([0.0, 3.5, 0.0]) self.GHGlobal_axial.SetInitialPosition(position) self.GHGlobal_axial.AddObserver("InteractionEvent",self.ArcWidgetModified) self.GHGlobal_axial.SetLabelsEnabled(1) def EnableWidgets(self): self.arcWidget.EnabledOn() self.axialWidget1.EnabledOn() self.arcWidget2.EnabledOn() self.arcWidget3.EnabledOn() self.arcWidget4.EnabledOn() def DisableWidgets(self): self.arcWidget.EnabledOff() self.axialWidget1.EnabledOff() self.arcWidget2.EnabledOff() self.arcWidget3.EnabledOff() self.arcWidget4.EnabledOff() def UpdateWidgets(self): for i in self.parent.parent.Filters.filteredAngles: for filter in self.parent.parent.Filters.jointAngleCollection: if filter['stanceID'] == i: if filter['min1'] != None: filter['widget'].SetWidgetRange1(filter['min1'], filter['max1']) if filter['min2'] != None: filter['widget'].SetWidgetRange2(filter['min2'], filter['max2']) filter['widget'].UpdateRangeIndicators() self.parent.parent.Filters.UpdateShaderOpacity() def ArcWidgetModified(self, caller, event): Filters = self.parent.parent.Filters for i in range(0, len(Filters.jointAngleCollection)): try: Filters.jointAngleCollection[i]['filter_min'] = Filters.jointAngleCollection[i]['widget'].GetfilterRangeMin() Filters.jointAngleCollection[i]['filter_max'] = Filters.jointAngleCollection[i]['widget'].GetfilterRangeMax() ##~ print "filters: ", self.jointAngleCollection[i]['filter_min'], ' - ',self.jointAngleCollection[i]['filter_max'] except AttributeError: ##print "no widget defined" pass self.parent.kdtree_modified = True Filters.RestartFiltering() Filters.RestartFilteringReferences()
Python
import threading import ctypes def _async_raise(tid, excobj): res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes.py_object(excobj)) if res == 0: raise ValueError("nonexistent thread id") elif res > 1: # """if it returns a number greater than one, you're in trouble, # and you should call it again with exc=NULL to revert the effect""" ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, None) raise SystemError("PyThreadState_SetAsyncExc failed") class Thread(threading.Thread): def raise_exc(self, excobj): try: a = self.isAlive() except AssertionError: pass if a: for tid, tobj in threading._active.items(): if tobj is self: _async_raise(tid, excobj) return # the thread was alive when we entered the loop, but was not found # in the dict, hence it must have been already terminated. should we raise # an exception here? silently ignore? def terminate(self): # must raise the SystemExit type, instead of a SystemExit() instance # due to a bug in PyThreadState_SetAsyncExc self.raise_exc(SystemExit)
Python
import os, sys appdir = 'C:\Documents and Settings\Administrator\Mijn documenten\FobData\Frans2' fname = os.path.join(appdir, 'test_ab.txt') importfile = open(fname, 'r', 1) lines = importfile.readlines() for i in range (0, 1):#len (lines)): stance = (lines[i]).split() stanceflt = [0.0, 0.0, 0.0] for j in stance: stanceflt.append(float(j)) stanceflt.insert(15, 0.0) #stanceflt = [1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8] #for k in range(0, len(stanceflt)/3): # stanceflt.insert(k*3, stanceflt[k*3+1]) # stanceflt.pop(k*3+2) print stanceflt
Python
#Boa:FramePanel:WXVISPANEL import wx import os, sys import shutil import time import math import vtk import vtktudoss import superthread try: import extended.BaseCalc as BaseCalc except ImportError: import BaseCalc import pdb def create(parent, renderwindow, primaryrenderer): return TimeWindowTrace(parent, renderwindow, primaryrenderer) class TimeWindowTrace: def __init__(self, parent, renderwindow, primaryrenderer): self.parent = parent self.renderwindow = renderwindow.GetRenderWindow() #~ self.renX = primaryrenderer self.renXannotation = primaryrenderer #~ self.InitializeAnnotationLayer() self.bluetracelist=[] self.yellowtracelist=[] #~ self.filtertraces_0 = [] #~ self.filtertraces_1 = [] #~ self.filtertraces_0_keys = [[]] #~ self.filtertraces_1_keys = [[]] #~ self.firsttracerpoint_0 = True #~ self.firsttracerpoint_1 = True def InitializeAnnotationLayer(self): try: self.renderwindow.RemoveRenderer(self.renXannotation) except AttributeError: pass self.renderwindow.SetNumberOfLayers(2) self.renXannotation = vtk.vtkRenderer() self.renX.SetLayer(0) self.renXannotation.SetLayer(1) self.renXannotation.InteractiveOff() self.renXannotation.SetActiveCamera(self.renX.GetActiveCamera()) self.renderwindow.AddRenderer(self.renXannotation) def ClearTraces(self, whichone): if whichone==0: self.ClearBlueTraces() else: self.ClearYellowTraces() def ClearBlueTraces(self): for trace in self.bluetracelist: self.renXannotation.RemoveActor(trace) self.bluetracelist[:]=[] def ClearYellowTraces(self): for trace in self.yellowtracelist: self.renXannotation.RemoveActor(trace) self.yellowtracelist[:]=[] def DrawTrace(self, whichdata, posenr, window): if window == None: window = [self.parent.editorpanel.spin_ctrl_1.GetValue(), self.parent.editorpanel.spin_ctrl_2.GetValue()] if self.parent.editorpanel.tracercheckbox_1.GetValue(): #traces if self.parent.editorpanel.tracercheckbox_2.GetValue(): #clavicle self.DrawJointTrace(whichdata, posenr, 2, window) self.DrawJointTrace(whichdata, posenr, 3, window) #~ if self.parent.editorpanel.tracercheckbox_1_copy.GetValue(): #surfaces #~ self.ConnectLastTwoTraces() if self.parent.editorpanel.tracercheckbox_3.GetValue(): #scapula self.DrawJointTrace(whichdata, posenr, 4, window) self.DrawJointTrace(whichdata, posenr, 5, window) #~ if self.parent.editorpanel.tracercheckbox_1_copy.GetValue(): #surfaces #~ self.ConnectLastTwoTraces() #~ self.DrawJointTrace(whichdata, posenr, 6, window) self.DrawJointTrace(whichdata, posenr, 7, window) #~ if self.parent.editorpanel.tracercheckbox_1_copy.GetValue(): #surfaces #~ self.ConnectLastTwoTraces() #~ self.DrawJointTrace(whichdata, posenr, 9, window) #~ if self.parent.editorpanel.tracercheckbox_1_copy.GetValue(): #surfaces #~ self.ConnectLastTwoTraces() if self.parent.editorpanel.tracercheckbox_4.GetValue(): #humerus self.DrawJointTrace(whichdata, posenr, -1, window) self.DrawJointTrace(whichdata, posenr, 10, window) #~ if self.parent.editorpanel.tracercheckbox_1_copy.GetValue(): #surfaces #~ self.ConnectLastTwoTraces() if self.parent.editorpanel.tracercheckbox_5.GetValue(): #forearm #~ self.DrawJointTrace(whichdata, posenr, 10, window) self.DrawJointTrace(whichdata, posenr, 11, window) #~ if self.parent.editorpanel.tracercheckbox_1_copy.GetValue(): #surfaces #~ self.ConnectLastTwoTraces() def ConnectLastTwoTraces(self): input1 = self.tracelist[len(self.tracelist)-1].GetMapper().GetInput() input2 = self.tracelist[len(self.tracelist)-2].GetMapper().GetInput() #~ appendFilter2 = vtk.vtkAppendFilter() #~ appendFilter2.AddInput(input1.GetPointData()) #~ appendFilter2.AddInput(input2.GetPointData()) #~ appendFilter2.Update() print input1 print input2 newpolydata = vtk.vtkPolyData() newpointdata = vtk.vtkPoints() newcelldata = vtk.vtkCellArray() appendFilter = vtk.vtkAppendFilter() appendFilter.AddInput(input1) appendFilter.AddInput(input2) appendFilter.Update() print appendFilter.GetOutput() nrofpoints = input1.GetPoints().GetNumberOfPoints() for i in range(0, nrofpoints-1): newcelldata.InsertNextCell(4) newcelldata.InsertCellPoint(i) newcelldata.InsertCellPoint(i+1) newcelldata.InsertCellPoint(i+1 + nrofpoints) newcelldata.InsertCellPoint(i + nrofpoints) newpolydata.SetPoints(appendFilter.GetOutput().GetPoints()) newpolydata.SetPolys(newcelldata) newpolydata.GetPointData().SetActiveScalars("woosh") newpolydata.Update() tracemapper = vtktudoss.vtktudExtendedOpenGLPolyDataMapper() traceactor = vtk.vtkActor() traceactor.SetMapper(tracemapper) tracemapper.SetInput(newpolydata) tracemapper.SetUseLookupTableScalarRange(1) tracemapper.InterpolateScalarsBeforeMappingOn() tracemapper.SetScalarModeToUsePointData() tracemapper.SetScalarMaterialModeToAmbient() tracemapper.SetLookupTable(self.parent.parent.colorscales.LUT_Woosh) tracemapper.ScalarVisibilityOn() #~ traceactor.GetProperty().SetSpecular(.0) #~ traceactor.GetProperty().SetDiffuse(.1) #~ traceactor.GetProperty().SetAmbient(.5) #~ traceactor.GetProperty().SetSpecularPower(0) self.renXannotation.AddActor(traceactor) self.tracelist.append(traceactor) def DrawJointTrace(self, whichdata, posenr, vertexnr, window): newpolydata = vtk.vtkPolyData() newpointdata = vtk.vtkPoints() newcelldata = vtk.vtkCellArray() poseColors = vtk.vtkFloatArray() poseColors.SetName("woosh") base = posenr if whichdata == 0: numberofposes = len(self.parent.parent.splineCollection) else: numberofposes = len(self.parent.parent.splineReferences) for i in range(0, -window[0]): item = base - i if item >= 0: if whichdata == 0: if vertexnr!=-1: newpointdata.InsertNextPoint(\ self.parent.parent.splineCollection[item]['poseActor'].\ GetMapper().GetInput().GetPoints().\ GetPoint(vertexnr)) else: tr1 = self.parent.parent.splineCollection[item]['shadedArm'].GetUserTransform() point = tr1.TransformFloatPoint(\ self.parent.parent.splineCollection[item]['shadedArm'].\ GetMapper().GetInput().GetPoints().\ GetPoint(0)) newpointdata.InsertNextPoint(point) else: if vertexnr!=-1: newpointdata.InsertNextPoint(\ self.parent.parent.splineReferences[item]['poseActor'].\ GetMapper().GetInput().GetPoints().\ GetPoint(vertexnr)) else: tr1 = self.parent.parent.splineReferences[item]['shadedArm'].GetUserTransform() point = tr1.TransformFloatPoint(\ self.parent.parent.splineReferences[item]['shadedArm'].\ GetMapper().GetInput().GetPoints().\ GetPoint(0)) newpointdata.InsertNextPoint(point) nrofpoints_back = newpointdata.GetNumberOfPoints() for i in range(0, window[1]): item = base + i if item <= numberofposes: if whichdata == 0: if vertexnr!=-1: newpointdata.InsertNextPoint(\ self.parent.parent.splineCollection[item]['poseActor'].\ GetMapper().GetInput().GetPoints().\ GetPoint(vertexnr)) else: tr1 = self.parent.parent.splineCollection[item]['shadedArm'].GetUserTransform() point = tr1.TransformFloatPoint(\ self.parent.parent.splineCollection[item]['shadedArm'].\ GetMapper().GetInput().GetPoints().\ GetPoint(0)) newpointdata.InsertNextPoint(point) else: if vertexnr!=-1: newpointdata.InsertNextPoint(\ self.parent.parent.splineReferences[item]['poseActor'].\ GetMapper().GetInput().GetPoints().\ GetPoint(vertexnr)) else: tr1 = self.parent.parent.splineReferences[item]['shadedArm'].GetUserTransform() point = tr1.TransformFloatPoint(\ self.parent.parent.splineReferences[item]['shadedArm'].\ GetMapper().GetInput().GetPoints().\ GetPoint(0)) newpointdata.InsertNextPoint(point) aSplineX = vtk.vtkCardinalSpline() aSplineY = vtk.vtkCardinalSpline() aSplineZ = vtk.vtkCardinalSpline() numberOfInputPoints = newpointdata.GetNumberOfPoints() for i in range(0, numberOfInputPoints): point = newpointdata.GetPoint(i) aSplineX.AddPoint(i, point[0]) aSplineY.AddPoint(i, point[1]) aSplineZ.AddPoint(i, point[2]) interpolatedpointdata = vtk.vtkPoints() numberOfOutputPoints = numberOfInputPoints * 4 totalbackpoints = float(nrofpoints_back*4) totalfrontpoints = float(numberOfInputPoints*4-(nrofpoints_back*4)) for i in range(0, numberOfOutputPoints): t = (numberOfInputPoints-1.0)/(numberOfOutputPoints-1.0)*i interpolatedpointdata.InsertPoint(i, aSplineX.Evaluate(t),\ aSplineY.Evaluate(t),aSplineZ.Evaluate(t)) if i <= nrofpoints_back*4: poseColors.InsertTuple1(i, (i/totalbackpoints)*20) else: poseColors.InsertTuple1(i, ((i-totalbackpoints)/totalfrontpoints)*20.0) for i in range(0, numberOfOutputPoints-1): newcelldata.InsertNextCell(2) newcelldata.InsertCellPoint(i) newcelldata.InsertCellPoint(i+1) newpolydata.SetPoints(interpolatedpointdata) newpolydata.SetLines(newcelldata) newpolydata.GetPointData().AddArray(poseColors) newpolydata.GetPointData().SetActiveScalars("woosh") newpolydata.Update() tracemapper = vtktudoss.vtktudExtendedOpenGLPolyDataMapper() traceactor = vtk.vtkActor() traceactor.SetMapper(tracemapper) tracemapper.SetInput(newpolydata) tracemapper.SetUseLookupTableScalarRange(1) if whichdata==0: tracemapper.SetLookupTable(self.parent.parent.colorscales.LUT_WooshBlue) else: tracemapper.SetLookupTable(self.parent.parent.colorscales.LUT_WooshYellow) tracemapper.ScalarVisibilityOn() self.renXannotation.AddActor(traceactor) if whichdata==0: self.bluetracelist.append(traceactor) else: self.yellowtracelist.append(traceactor) #~ def AddTraceFrame(self, whichdata, poseActor, splineNr): #~ if self.parent.editorpanel.tracercheckbox_5.GetValue(): #forearm #~ self.AddSinglePoint(whichdata, poseActor, 11, splineNr) #~ def AddSinglePoint(self, whichdata, poseActor, vertexnr, splineNr): #~ if whichdata == 0 and self.firsttracerpoint_0 == True: #~ newpolydata = vtk.vtkPolyData() #~ newpointdata = vtk.vtkPoints() #~ newcelldata = vtk.vtkCellArray() #~ newpolydata.SetPoints(newpointdata) #~ newpolydata.SetLines(newcelldata) #~ newpolydata.Update() #~ tracemapper = vtktud.vtktudExtendedOpenGLPolyDataMapper() #~ traceactor = vtk.vtkActor() #~ traceactor.SetMapper(tracemapper) #~ tracemapper.SetInput(newpolydata) #~ self.filtertraces_0.append(traceactor) #~ self.renXannotation.AddActor(traceactor) #~ self.firsttracerpoint_0 = False #~ self.filtertraces_0_keys[-1].append(splineNr) #~ if whichdata == 0: #~ self.filtertraces_0[-1].GetMapper().GetInput().GetPoints().InsertNextPoint(\ #~ poseActor.GetMapper().GetInput().GetPoints().\ #~ GetPoint(vertexnr)) #~ nrofpoints = self.filtertraces_0[-1].GetMapper().GetInput().GetPoints().GetNumberOfPoints() #~ if nrofpoints>1: #~ self.filtertraces_0[-1].GetMapper().GetInput().GetLines().InsertNextCell(2) #~ self.filtertraces_0[-1].GetMapper().GetInput().GetLines().InsertCellPoint(nrofpoints-1) #~ self.filtertraces_0[-1].GetMapper().GetInput().GetLines().InsertCellPoint(nrofpoints) #~ self.filtertraces_0[-1].GetMapper().Update() #~ def TerminateTrace(self, whichdata, splineNr): #~ if whichdata == 0: #~ for i in range(0, len(self.filtertraces_0_keys)): #~ if splineNr in self.filtertraces_0_keys[i]: #~ self.renXannotation.RemoveActor(self.filtertraces_0[i]) #~ self.filtertraces_0.pop(i) #~ self.filtertraces_0_keys.pop(i) #~ i = i -1 #~ self.firsttracerpoint_0 = True #~ try: #~ if self.filtertraces_0_keys[-1] != []: #~ self.filtertraces_0_keys.append([]) #~ except IndexError: #~ self.filtertraces_0_keys.append([])
Python
#Boa:FramePanel:WXVISPANEL import wx import os, sys import shutil import time import math #from pysqlite2 import dbapi2 as sqlite import vtk import vtktudoss import superthread def create(parent, bla): return wxVisPanel(parent, bla) [wxID_WXVISPANEL, wxID_FRAME1SLICER, wxID_FRAME1VISUALISE, wxID_FRAME1ADJUSTVOLUME, wxID_FRAME1VISUALISEBONE,wxID_CLEARFEEDBACK, wxID_VOLUMEVISUALISE, wxID_VOLUMESHOWBONE, wxID_VOLUMESHOWMUSCLE, wxID_VOLUMESHOWSKIN, wxID_WXFRAME1VISPANEL1, wxID_FRAME1SHOWHUMERUS, wxID_FRAME1SHOWSCAPULA, wxID_FRAME1SHOWHUMERUSPROSTHESIS, wxID_FRAME1SHOWSCAPULAPROSTHESIS, wxID_FRAME1DECIMATEDBONE, wxID_FRAME1VOLLISTBOX, wxID_FRAME1STOREVOLUME, wxID_FRAME1ADDVOLUME, wxID_CAMKEYFRAME, wxID_CAMPLAY, wxID_CAMCLEAR, wxID_RECORD ] = [wx.NewId() for _init_ctrls in range(23)] class wxVisPanel(wx.Panel): volume_path = '' volume_changed = False volume_counter = 0 threshold=10.0 pathActor = vtk.vtkActor() polydata = vtk.vtkPolyData() picker = vtk.vtkCellPicker() picker.SetTolerance(0.005) outlineActor = vtk.vtkActor() def _init_ctrls(self, prnt): wx.Panel.__init__(self, id=wxID_WXVISPANEL, name='', parent=prnt, pos=wx.Point(0, 0), size=wx.Size(200, 500), style=wx.TAB_TRAVERSAL) self.SetClientSize(wx.Size(192, 73)) self.visualiseBone = wx.CheckBox(id=wxID_FRAME1VISUALISEBONE, label=u'Surface Models', name='ShowBone', parent=self, pos=wx.Point(10, 10), size=wx.Size(135, 24), style=0) self.visualiseBone.SetValue(False) self.visualiseBone.Enable(False) self.visualiseBone.Bind(wx.EVT_CHECKBOX, self.OnvisualiseBoneChange, self.visualiseBone) self.DecimatedBone = wx.CheckBox(id=wxID_FRAME1DECIMATEDBONE, label=u'Decimated', name='DecimatedBone', parent=self, pos=wx.Point(145, 10), size=wx.Size(90, 24), style=0) self.DecimatedBone.SetValue(True) self.DecimatedBone.Enable(True) self.DecimatedBone.Bind(wx.EVT_CHECKBOX, self.OnDecimatedChange, self.DecimatedBone) self.showHumerus = wx.CheckBox(id=wxID_FRAME1SHOWHUMERUS, label=u'Humerus', name='ShowHum', parent=self, pos=wx.Point(25, 30), size=wx.Size(100, 24), style=0) self.showHumerus.SetValue(True) self.showHumerus.Enable(False) self.showHumerus.Bind(wx.EVT_CHECKBOX, self.OnvisualiseBoneChange, self.showHumerus) self.showScapula = wx.CheckBox(id=wxID_FRAME1SHOWSCAPULA, label=u'Scapula', name='ShowScap', parent=self, pos=wx.Point(25, 50), size=wx.Size(100, 24), style=0) self.showScapula.SetValue(True) self.showScapula.Enable(False) self.showScapula.Bind(wx.EVT_CHECKBOX, self.OnvisualiseBoneChange, self.showScapula) self.showHumerusProsthesis = wx.CheckBox(id=wxID_FRAME1SHOWHUMERUSPROSTHESIS, label=u'Prosthesis', name='ShowHumPros', parent=self, pos=wx.Point(125, 30), size=wx.Size(130, 24), style=0) self.showHumerusProsthesis.SetValue(False) self.showHumerusProsthesis.Enable(False) self.showHumerusProsthesis.Bind(wx.EVT_CHECKBOX, self.OnvisualiseBoneChange, self.showHumerusProsthesis) self.showGlenoidProsthesis = wx.CheckBox(id=wxID_FRAME1SHOWSCAPULAPROSTHESIS, label=u'Prosthesis', name='ShowScapPros', parent=self, pos=wx.Point(125, 50), size=wx.Size(130, 24), style=0) self.showGlenoidProsthesis.SetValue(False) self.showGlenoidProsthesis.Enable(False) self.showGlenoidProsthesis.Bind(wx.EVT_CHECKBOX, self.OnvisualiseBoneChange, self.showGlenoidProsthesis) self.clearFeedback = wx.CheckBox(id=wxID_CLEARFEEDBACK, label=u'Landmarks', name='ShowCurv', parent=self, pos=wx.Point(10, 70), size=wx.Size(176, 24), style=0) self.clearFeedback.SetValue(False) #self.clearFeedback.Enable(False) self.clearFeedback.Bind(wx.EVT_CHECKBOX, self.OnclearFeedback, self.clearFeedback) self.showSlicer = wx.CheckBox(id=wxID_FRAME1SLICER, label=u'Show Slicer', name=u'Display Slicer', parent=self, pos=wx.Point(10, 90), size=wx.Size(176, 24), style=0) self.showSlicer.Bind(wx.EVT_CHECKBOX, self.OnShowSlicer, self.showSlicer) self.showSlicer.SetValue(False) self.showSlicer.Enable(False) self.showVolume = wx.CheckBox(id=wxID_VOLUMEVISUALISE, label=u'Display Volume', name='volume_check', parent=self, pos=wx.Point(10, 110), size=wx.Size(176, 24), style=0) self.showVolume.Bind(wx.EVT_CHECKBOX, self.OnShowVolumeChange, self.showVolume) self.showVolume.Enable(False) self.showVolume.SetValue(False) self.showBone = wx.CheckBox(id=wxID_VOLUMESHOWBONE, label=u'Show Bone Volume', name='ShowBone', parent=self, pos=wx.Point(25, 130), size=wx.Size(176, 24), style=0) self.showBone.Bind(wx.EVT_CHECKBOX, self.OnVolumeValuesChange, self.showBone) self.showMuscle = wx.CheckBox(id=wxID_VOLUMESHOWMUSCLE, label=u'Show Muscle Volume', name='ShowMuscle', parent=self, pos=wx.Point(25, 150), size=wx.Size(176, 24), style=0) self.showMuscle.Bind(wx.EVT_CHECKBOX, self.OnVolumeValuesChange, self.showMuscle) self.showSkin = wx.CheckBox(id=wxID_VOLUMESHOWSKIN, label=u'Show Skin Volume', name='ShowSkin', parent=self, pos=wx.Point(25, 170), size=wx.Size(176, 24), style=0) self.showSkin.Bind(wx.EVT_CHECKBOX, self.OnVolumeValuesChange, self.showSkin) self.showSlicer.SetValue(False) self.showVolume.SetValue(False) self.showMuscle.SetValue(True) self.showMuscle.Enable(False) self.showBone.SetValue(True) self.showBone.Enable(False) self.showSkin.SetValue(True) self.showSkin.Enable(False) #~ self.slider1 = wx.Slider(self, -1, 0, 0, 100, (10, 210), (210, 45), wx.SL_HORIZONTAL | wx.SL_AUTOTICKS | wx.SL_LABELS) #~ self.slider1.Bind(wx.EVT_SLIDER, self.OnValuesAdjusted) #~ self.slider2 = wx.Slider(self, -1, 0, 0, 100, (10, 260), (210, 45), wx.SL_HORIZONTAL | wx.SL_AUTOTICKS | wx.SL_LABELS) #~ self.slider2.Bind(wx.EVT_SLIDER, self.OnValuesAdjusted) #~ self.slider3 = wx.Slider(self, -1, 0, 0, 100, (10, 310), (210, 45), wx.SL_HORIZONTAL | wx.SL_AUTOTICKS | wx.SL_LABELS) #~ self.slider3.Bind(wx.EVT_SLIDER, self.OnValuesAdjusted) self.VolumeListbox = wx.ListBox(self, id=wxID_FRAME1VOLLISTBOX, pos=wx.Point(10, 370), size= wx.Size(200, 70), choices='', style=0, name=u'VolListbox') self.VolumeListbox.SetAutoLayout(False) self.VolumeListbox.Bind(wx.EVT_LISTBOX, self.VolumeListboxClicked, id = wxID_FRAME1VOLLISTBOX) self.StoreVolume = wx.Button(id=wxID_FRAME1STOREVOLUME, label=u'Save Volume', name=u'SaveVolume', parent=self, pos=wx.Point(10, 445), size=wx.Size(200, 24), style=0) self.StoreVolume.SetAutoLayout(False) self.StoreVolume.Bind(wx.EVT_BUTTON, self.OnStoreVolume, id=wxID_FRAME1STOREVOLUME) self.StoreVolume.Enable(False) self.AddVolume = wx.Button(id=wxID_FRAME1ADDVOLUME, label=u'Add Volume', name=u'LoadVolume', parent=self, pos=wx.Point(10, 470), size=wx.Size(200, 24), style=0) self.AddVolume.SetAutoLayout(False) self.AddVolume.Bind(wx.EVT_BUTTON, self.OnLoadVolume, id=wxID_FRAME1ADDVOLUME) self.AddVolume.Enable(False) self.CamKeyframe = wx.Button(id=wxID_CAMKEYFRAME, label=u'Cam Keyframe', name=u'camkey', parent=self, pos=wx.Point(10, 505), size=wx.Size(97, 24), style=0) self.CamKeyframe.SetAutoLayout(False) self.CamKeyframe.Bind(wx.EVT_BUTTON, self.OnCamKeyframe, id=wxID_CAMKEYFRAME) self.CamPlay = wx.Button(id=wxID_CAMPLAY, label=u'Play Motion', name=u'camplay', parent=self, pos=wx.Point(103, 505), size=wx.Size(107, 24), style=0) self.CamPlay.SetAutoLayout(False) self.CamPlay.Bind(wx.EVT_BUTTON, self.OnCamPlay, id=wxID_CAMPLAY) self.CamClear = wx.Button(id=wxID_CAMCLEAR, label=u'Clear', name=u'clear', parent=self, pos=wx.Point(10, 529), size=wx.Size(200, 24), style=0) self.CamClear.SetAutoLayout(False) self.CamClear.Bind(wx.EVT_BUTTON, self.OnCamClear, id=wxID_CAMCLEAR) self.RecordView = wx.ToggleButton(id=wxID_RECORD, label=u'Record View', name=u'record', parent=self, pos=wx.Point(10, 320), size=wx.Size(200, 24), style=0) self.RecordView.SetAutoLayout(False) self.RecordView.Bind(wx.EVT_TOGGLEBUTTON, self.OnRecordViewToggle, id=wxID_RECORD) def __init__(self, parent, id, pos, size, style, name, bla): self.parent = bla self._init_ctrls(parent) self.opacityTransferFunction = vtk.vtkPiecewiseFunction() self.rendervolume = vtk.vtkVolume() self.volumecollection = vtk.vtkCollection() self.volumecollectionwindowlevels = [] self.volumecollectioncolortables = [] self.previously_selected = 0 self.lastsliceindex = 0 self.planeWidget = vtk.vtkImagePlaneWidget() self.planeWidget2 = vtk.vtkImagePlaneWidget() self.planeWidget2.DisplayTextOff() self.planeWidget2.SetTextureInterpolate(1) self.planeWidget2.TextureVisibilityOn() intevent = self.planeWidget.AddObserver("InteractionEvent", self.UpdatePlaneWidget2) self.InitializeKeyframes() def OnValuesAdjusted(self, event): pass def InitializeKeyframes(self): self.posx = vtk.vtkCardinalSpline() self.posy = vtk.vtkCardinalSpline() self.posz = vtk.vtkCardinalSpline() self.clip1 = vtk.vtkCardinalSpline() self.clip2 = vtk.vtkCardinalSpline() self.viewangle = vtk.vtkCardinalSpline() self.viewupx = vtk.vtkCardinalSpline() self.viewupy = vtk.vtkCardinalSpline() self.viewupz = vtk.vtkCardinalSpline() self.focalx = vtk.vtkCardinalSpline() self.focaly = vtk.vtkCardinalSpline() self.focalz = vtk.vtkCardinalSpline() def OnCamClear(self, event): self.InitializeKeyframes() def StoreCamKeys(self): filename = os.path.dirname(sys.argv[0])+"/campath.txt" outputfile = open(filename,"w") outputfile.write("[main]\n") i = self.posx.GetNumberOfPoints() outputfile.write(i + "\n") for j in range(0,i): #mystr = ("posx[] = " '%3.9f' % self.glenoidcor[0]) outputfile.write(posx[j] + "\n") outputfile.close() def OnCamKeyframe(self, event): currentcam = self.parent.ren1.GetActiveCamera() position = currentcam.GetPosition() i = self.posx.GetNumberOfPoints() self.posx.AddPoint(i, position[0]) self.posy.AddPoint(i, position[1]) self.posz.AddPoint(i, position[2]) cliprange = currentcam.GetClippingRange() self.clip1.AddPoint(i, cliprange[0]) self.clip2.AddPoint(i, cliprange[1]) self.viewangle.AddPoint(i, currentcam.GetViewAngle()) viewup = currentcam.GetViewUp() self.viewupx.AddPoint(i, viewup[0]) self.viewupy.AddPoint(i, viewup[1]) self.viewupz.AddPoint(i, viewup[2]) focalpoint = currentcam.GetFocalPoint() self.focalx.AddPoint(i, focalpoint[0]) self.focaly.AddPoint(i, focalpoint[1]) self.focalz.AddPoint(i, focalpoint[2]) print position print cliprange print viewup print focalpoint #~ self.StoreCamKeys() def OnCamPlay(self, event): resolution_factor = 30 #frames per lijn for i in range(0, self.posx.GetNumberOfPoints()-1): for p in range(1,resolution_factor): position = [self.posx.Evaluate(i+((p*1.0)/resolution_factor)),\ self.posy.Evaluate(i+((p*1.0)/resolution_factor)),\ self.posz.Evaluate(i+((p*1.0)/resolution_factor))] cliprange = [self.clip1.Evaluate(i+((p*1.0)/resolution_factor)),\ self.clip2.Evaluate(i+((p*1.0)/resolution_factor))] viewangle = self.viewangle.Evaluate(i+((p*1.0)/resolution_factor)) viewup = [self.viewupx.Evaluate(i+((p*1.0)/resolution_factor)),\ self.viewupy.Evaluate(i+((p*1.0)/resolution_factor)),\ self.viewupz.Evaluate(i+((p*1.0)/resolution_factor))] focalpoint = [self.focalx.Evaluate(i+((p*1.0)/resolution_factor)),\ self.focaly.Evaluate(i+((p*1.0)/resolution_factor)),\ self.focalz.Evaluate(i+((p*1.0)/resolution_factor))] currentcam = self.parent.ren1.GetActiveCamera() currentcam.SetPosition(position) currentcam.SetClippingRange(cliprange) currentcam.SetViewAngle(viewangle) currentcam.SetViewUp(viewup) currentcam.SetFocalPoint(focalpoint) self.parent.Render() time.sleep(0.04) def UpdatePlaneWidget2(self, event, bla): newindex = self.planeWidget.GetSliceIndex() if self.lastsliceindex != newindex: self.lastsliceindex = newindex self.planeWidget2.SetSlicePosition(self.planeWidget.GetSlicePosition()+0.2) #self.planeWidget2.SetSliceIndex(newindex+1) def VolumeListboxClicked(self, event): sliceindex = self.planeWidget.GetSliceIndex() listboxindex = self.VolumeListbox.GetSelection() self.volumecollectionwindowlevels.pop(self.previously_selected) self.volumecollectioncolortables.pop(self.previously_selected) bla = [0,0] self.planeWidget.GetWindowLevel(bla) lut = self.planeWidget2.GetLookupTable() self.volumecollectionwindowlevels.insert(self.previously_selected, bla) self.volumecollectioncolortables.insert(self.previously_selected, lut) windowlevel = self.volumecollectionwindowlevels[listboxindex] colortable = self.volumecollectioncolortables[listboxindex] self.CreatePlaneWidget2(self.volumecollection.GetItemAsObject(listboxindex), windowlevel, colortable) self.previously_selected = listboxindex self.parent.Render() def SetColortable(self, lut): sliceindex = self.planeWidget.GetSliceIndex() listboxindex = self.VolumeListbox.GetSelection() windowlevel = self.volumecollectionwindowlevels[listboxindex] self.volumecollectioncolortables.pop(self.VolumeListbox.GetCount()-1) self.volumecollectioncolortables.append(lut) self.CreatePlaneWidget2(self.volumecollection.GetItemAsObject(listboxindex), windowlevel, lut) def AddVolumeToListbox(self, volume, name=None): self.volumecollection.AddItem(volume) self.volumecollectionwindowlevels.append(None) range = volume.GetScalarRange() self.volumecollectioncolortables.append(self.GetColorTable_green(range[0], range[1])) if name==None: self.VolumeListbox.Append("volume " + str(self.volume_counter)) else: self.VolumeListbox.Append(name) self.VolumeListbox.SetSelection(self.VolumeListbox.GetCount()-1) self.previously_selected = (self.VolumeListbox.GetCount()-1) self.volume_counter = self.volume_counter + 1 def CreatePlaneWidget2(self, volume, windowlevel = None, colortable = None): self.planeWidget2.SetInput(volume) self.planeWidget2.SetPlaneOrientationToZAxes() self.planeWidget2.SetInteractor(self.parent.main.renwini) if windowlevel != None: self.planeWidget2.SetWindowLevel(windowlevel[0], windowlevel[1]) if colortable != None: self.planeWidget2.SetLookupTable(colortable) else: range = volume.GetScalarRange() self.planeWidget2.SetLookupTable(self.GetColorTable_bw(range[0], range[1])) self.planeWidget2.SetSlicePosition(self.planeWidget.GetSlicePosition()+0.2) self.planeWidget2.SetEnabled(1) self.planeWidget2.InteractionOff() def CreatePlaneWidget1(self, volume, windowlevel = None, colortable = None): range = volume.GetScalarRange() self.planeWidget.SetInput(volume) self.planeWidget.SetPlaneOrientationToZAxes() #self.planeWidget1.SetInteractor(self.parent.main.renwini) self.planeWidget.SetEnabled(1) self.planeWidget.InteractionOn() def GetColorTable_bw(self, range1, range2): lut = vtk.vtkLookupTable() lut.SetNumberOfColors(256) lut.SetHueRange(1.0, 1.0 ) lut.SetAlphaRange(0.0,0.0) lut.SetSaturationRange(0, 1) lut.SetRange(range1, range2) lut.Build() return lut def GetColorTable_green(self, range1, range2): lut = vtk.vtkLookupTable() lut.SetNumberOfColors(256) lut.SetHueRange(.25, .25 ) lut.SetAlphaRange(0.0,1.0) lut.SetSaturationRange(0, 1) lut.SetRange(range1, range2) lut.Build() return lut def GetColorTable_greenlines(self, range1, range2): lut = vtk.vtkLookupTable() #lut.SetValueRange (range1, range2) lut.SetTableRange (0, 2000) lut.SetValueRange (0, 50) lut.SetNumberOfColors(10) for i in range(0,8): lut.SetTableValue( i, (0.0,1.0,0.0,1.0)) #lut.SetTableValue( 5, (0.0,1.0,0.0,1.0)) lut.SetTableValue( 0, (0.0,1.0,0.0,0.0)) lut.SetTableValue( 7, (0.0,1.0,0.0,1.0)) lut.SetTableValue( 8, (0.0,1.0,0.0,1.0)) lut.SetTableValue( 9, (0.0,1.0,0.0,1.0)) lut.Build() return lut def GetColorTable_blue(self, range1, range2): lut = vtk.vtkLookupTable() lut.SetNumberOfColors(256) lut.SetHueRange(.55, .55 ) lut.SetAlphaRange(0.0,0.7) lut.SetSaturationRange(0, 1) lut.SetRange(range1, range2) lut.Build() return lut def OnStoreVolume(self, event): dialog = wx.FileDialog(self, message='Choose a file', style=wx.SAVE|wx.OVERWRITE_PROMPT) if dialog.ShowModal() == wx.ID_OK: file = dialog.GetPath() #dir = dialog.GetDirectory() writer = vtk.vtkXMLImageDataWriter() writer.SetInput(self.volumecollection.GetItemAsObject(self.VolumeListbox.GetSelection())) writer.SetFileName(file) writer.Write() def OnLoadVolume(self, event): dialog = wx.FileDialog(self, message='Choose a file', style=wx.OPEN) if dialog.ShowModal() == wx.ID_OK: file = dialog.GetPath() #dir = dialog.GetDirectory() vti_reader = vtk.vtkXMLImageDataReader() vti_reader.SetFileName(file) vti_reader.Update() self.AddVolumeToListbox(vti_reader.GetOutput(), 'imported') def UnloadVolume(self): self.showSlicer.SetValue(False) self.showVolume.SetValue(False) self.showMuscle.Enable(False) self.showBone.Enable(False) self.showSkin.Enable(False) self.volumecollection.RemoveAllItems() self.VolumeListbox.Clear() def EnableVolume(self, bool): if bool == False: self.showVolume.Enable(False) self.showSlicer.Enable(False) else: self.showVolume.Enable(True) self.showSlicer.Enable(True) def OnclearFeedback(self, event): if(self.clearFeedback.IsChecked()==False): self.parent.geo_analysis.ClearLandmarks() else: self.parent.geo_analysis.ShowLandmarks() def OnvisualiseBoneChange(self, event, skiprender = False): self.parent.ren1.RemoveActor(self.parent.scapula_actor) self.parent.ren1.RemoveActor(self.parent.humerus_phantom) self.parent.ren1.RemoveActor(self.parent.actor_prosthesis_glenoid) self.parent.ren1.RemoveActor(self.parent.actor_prosthesis_humerus) self.parent.humerus_phantom.GetMapper().RemoveAllClippingPlanes() if self.visualiseBone.IsChecked()==False: self.showScapula.Enable(False) self.showHumerus.Enable(False) self.showGlenoidProsthesis.Enable(False) self.showHumerusProsthesis.Enable(False) else: if self.parent.modelloader.humerus_id != -1: self.showHumerus.Enable(True) if self.parent.modelloader.scapula_id != -1: self.showScapula.Enable(True) if self.parent.modelloader.humerus_prosthesis_id != -1: self.showHumerusProsthesis.Enable(True) if self.parent.modelloader.glenoid_prosthesis_id != -1: self.showGlenoidProsthesis.Enable(True) if (self.showScapula.IsChecked()==True and self.visualiseBone.IsChecked()==True): self.parent.ren1.AddActor(self.parent.scapula_actor) if (self.showHumerus.IsChecked()==True and self.visualiseBone.IsChecked()==True): self.parent.ren1.AddActor(self.parent.humerus_phantom) if (self.showGlenoidProsthesis.IsChecked()==True and self.visualiseBone.IsChecked()==True): self.parent.ren1.AddActor(self.parent.actor_prosthesis_glenoid) if (self.showHumerusProsthesis.IsChecked()==True and self.visualiseBone.IsChecked()==True): self.parent.ren1.AddActor(self.parent.actor_prosthesis_humerus) if self.parent.humerus_phantom.GetPosition()!=(0.0, 0.0, 0.0): self.parent.humerus_phantom.GetMapper().AddClippingPlane(self.parent.planningmodule.cp1_humerus) if skiprender == False: self.parent.Render() def OnDecimatedChange(self, event): self.parent.main.panel1.OnCTChoice(event) def OnShowVolumeChange(self, event, skiprender = False): if self.volume_path != '' and self.volume_changed == True and self.showVolume.IsChecked()==True: self.volume_changed = False self.LoadVTI(skiprender) #self.my_thread = superthread.Thread( group=None, target=self.LoadVTI, args=() ) #self.my_thread.start() if self.volume_path != '' and self.volume_changed == False: shifter = vtk.vtkImageShiftScale() shifter.SetInput(self.parent.volumedata_resampled) shifter.SetShift(1000.0) shifter.SetOutputScalarTypeToUnsignedShort() # Create transfer mapping scalar value to opacity self.opacityTransferFunction.AddPoint(-10000, 0.0) self.opacityTransferFunction.AddPoint(1600, 0.0) # Create transfer mapping scalar value to color colorTransferFunction = vtk.vtkColorTransferFunction() colorTransferFunction.AddRGBPoint(900.0, 0.9, 0.7, 0.5) colorTransferFunction.AddRGBPoint(1000.0, 1.0, 1.0, 1.0) colorTransferFunction.AddRGBPoint(1064.0, 1.0, 0.0, 0.0) colorTransferFunction.AddRGBPoint(1128.0, 0.9, 0.9, 0.8) colorTransferFunction.AddRGBPoint(1192.0, 0.9, 0.9, 0.5) colorTransferFunction.AddRGBPoint(1255.0, 0.9, 0.7, 0.4) # The property describes how the data will look volumeProperty = vtk.vtkVolumeProperty() volumeProperty.SetColor(colorTransferFunction) volumeProperty.SetScalarOpacity(self.opacityTransferFunction) volumeProperty.ShadeOn() volumeProperty.SetInterpolationTypeToLinear() # The mapper / ray cast function know how to render the data compositeFunction = vtk.vtkVolumeRayCastCompositeFunction() volumeMapper = vtk.vtkVolumeRayCastMapper() volumeMapper.SetMinimumImageSampleDistance(2.0) # higher = faster volumeMapper.SetMaximumImageSampleDistance(2.0) # higher = faster volumeMapper.SetVolumeRayCastFunction(compositeFunction) volumeMapper.SetInputConnection(shifter.GetOutputPort()) # The volume holds the mapper and the property and # can be used to position/orient the volume self.rendervolume.SetMapper(volumeMapper) self.rendervolume.SetProperty(volumeProperty) self.OnVolumeValuesChange(event) if(self.showVolume.IsChecked()==False): self.parent.ren1.RemoveVolume(self.rendervolume) self.showMuscle.Enable(False) self.showBone.Enable(False) self.showSkin.Enable(False) else: self.showMuscle.Enable(True) self.showBone.Enable(True) self.showSkin.Enable(True) self.parent.ren1.AddVolume(self.rendervolume) if skiprender == False: self.parent.Render() def OnVolumeValuesChange(self, event): self.opacityTransferFunction.RemoveAllPoints() self.opacityTransferFunction.AddPoint(-10000, 0.0) self.opacityTransferFunction.AddPoint(1600, 0.0) if(self.showBone.IsChecked()==False): self.opacityTransferFunction.AddPoint(1150, 0.0) self.opacityTransferFunction.AddPoint(1300, 0.0) self.opacityTransferFunction.AddPoint(1400, 0.0) else: self.opacityTransferFunction.AddPoint(1150, 1.0) self.opacityTransferFunction.AddPoint(1300, 1.0) self.opacityTransferFunction.AddPoint(1400, 0.2) if(self.showMuscle.IsChecked()==False): self.opacityTransferFunction.AddPoint(1000, 0.0) self.opacityTransferFunction.AddPoint(1100, 0.0) else: self.opacityTransferFunction.AddPoint(1000, 0.01) self.opacityTransferFunction.AddPoint(1100, 0.5) if(self.showSkin.IsChecked()==False): self.opacityTransferFunction.AddPoint(900, 0.0) else: self.opacityTransferFunction.AddPoint(900, 1.00) self.opacityTransferFunction.Update() self.parent.Render() def OnShowSlicer(self, event, skiprender = False): if self.volume_path != '' and self.volume_changed == True and self.showSlicer.IsChecked()==True: self.volume_changed = False self.LoadVTI(skiprender) if self.volume_path != '' and self.volume_changed == False: self.outline = vtk.vtkOutlineFilter() self.outline.SetInput(self.parent.volumedata) self.outlineMapper = vtk.vtkPolyDataMapper() self.outlineMapper.SetInputConnection(self.outline.GetOutputPort()) self.outlineActor.SetMapper(self.outlineMapper) self.planeWidget.DisplayTextOn() self.planeWidget.SetTextureInterpolate(1) self.planeWidget.TextureVisibilityOn() self.planeWidget.SetInput(self.parent.volumedata) self.planeWidget.SetInteractor(self.parent.main.renwini._Iren) self.planeWidget.PlaceWidget() self.planeWidget.SetWindowLevel(220,40,0) self.planeWidget.SetPlaneOrientationToZAxes() self.planeWidget.SetSliceIndex(0) self.planeWidget.SetPicker(self.picker) self.planeWidget.SetKeyPressActivationValue("x") if(self.showSlicer.IsChecked()==False): try: self.planeWidget.SetEnabled(0) except RuntimeError: #widget was not set up yet. pass self.parent.ren1.RemoveActor(self.outlineActor) else: self.planeWidget.SetEnabled(1) self.parent.ren1.AddActor(self.outlineActor) if skiprender == False: self.parent.Render() def OnActivated(self, event): self.parent.planningmodule.ResetPlanning() self.parent.ren1.RemoveActor(self.parent.humerus_phantom) self.parent.ren1.RemoveActor(self.parent.scapula_actor) self.parent.ren1.RemoveActor(self.parent.actor_prosthesis_humerus) self.parent.ren1.RemoveActor(self.parent.actor_prosthesis_glenoid) self.parent.humerus_phantom.GetMapper().RemoveAllClippingPlanes() mapper = vtk.vtkPolyDataMapper() mapper.SetInput(self.polydata) self.torsoactor = vtk.vtkActor() self.torsoactor.SetMapper(mapper) self.parent.ren1.AddActor(self.torsoactor) #self.LoadDICOM() self.LoadVTI() #self.LoadSTL() outline = vtk.vtkOutlineFilter() outline.SetInput(self.parent.volumedata) outlineMapper = vtk.vtkPolyDataMapper() outlineMapper.SetInputConnection(outline.GetOutputPort()) self.outlineActor = vtk.vtkActor() self.outlineActor.SetMapper(outlineMapper) self.parent.ren1.AddActor(self.outlineActor) self.parent.Render() def LoadDICOM(self): self.dicom = vtk.vtkDICOMImageReader() #self.dicom.SetDirectoryName('C:/Documents and Settings/Administrator/My Documents/Dicom/8528558-vogel/CT_STX6/SE0003') self.dicom.SetDirectoryName('C:/Documents and Settings/Administrator/My Documents/Dicom/5909563-romijn/CT_STX1/SE0003') #self.dicom.SetDirectoryName('C:/Documents and Settings/Administrator/My Documents/Dicom/1433007-vermeulen/CT_STX7/SE0002') self.dicom.Update() self.dicom.FileLowerLeftOff() self.dicom.Update() self.parent.volumedata = self.dicom.GetOutput() def LoadSTL(self): reader = vtk.vtkSTLReader() reader.SetFileName(self.parent.modelloader.path+"ct/torso/vogel_glenoidtest_export.stl") self.polydata = reader.GetOutput() self.RenewPolyData() def LoadVTI(self, skiprender = False): #*args, self.vti_reader = vtk.vtkXMLImageDataReader() filename = self.volume_path #filename = self.parent.modelloader.path+"ct/torso/vogel_glenoidtestsleutelbeen.vti" #filename = self.parent.modelloader.path+"ct/torso/vogel.vti" #filename = self.parent.modelloader.path+"ct/torso/romijn_glenoidtest.vti" #filename = self.parent.modelloader.path+"ct/torso/romijn.vti" #filename = self.parent.modelloader.path+"ct/torso/vermeulen.vti" self.vti_reader.SetFileName(filename) self.vti_reader.Update() #factor = 0.75 #factor = 0.65 self.parent.volumedata = self.vti_reader.GetOutput() self.parent.volumedata.Update() self.parent.volume_dimensions = self.parent.volumedata.GetDimensions() self.parent.volume_spacing = self.parent.volumedata.GetSpacing() self.parent.volume_extent = self.parent.volumedata.GetExtent() print "Dimensions: ", self.parent.volume_dimensions print "Spacing: ", self.parent.volume_spacing print "Extent: ", self.parent.volume_extent self.GaussianVolume() self.ResampleVolume() self.edgevolume = vtk.vtkImageData() self.edgevolume.SetDimensions(self.parent.volume_dimensions) self.edgevolume.SetSpacing(self.parent.volume_spacing) self.edgevolume.SetScalarTypeToFloat() self.edgevolume.AllocateScalars() self.AddVolumeToListbox(self.parent.volumedata, "original volume") self.AddVolumeToListbox(self.parent.volumedata_resampled, "resampled volume") if skiprender == False: self.parent.Render() def ResampleVolume(self): self.parent.resample_factor = 0.65 self.resample = vtk.vtkImageResample() self.resample.SetAxisMagnificationFactor(0, self.parent.resample_factor) self.resample.SetAxisMagnificationFactor(1, self.parent.resample_factor) self.resample.SetAxisMagnificationFactor(2, self.parent.resample_factor) self.resample.SetInput(self.parent.volumedata_gaussian) self.parent.volumedata_resampled = self.resample.GetOutput() self.parent.volumedata_resampled.Update() self.parent.resampled_dimensions = self.parent.volumedata_resampled.GetDimensions() self.parent.resampled_spacing = self.parent.volumedata_resampled.GetSpacing() self.parent.resampled_extent = self.parent.volumedata_resampled.GetExtent() def GaussianVolume(self): deviation = 1.0 radius = 1.0 smooth_vol = vtk.vtkImageGaussianSmooth() smooth_vol.SetDimensionality(3) smooth_vol.SetInput(self.parent.volumedata) smooth_vol.SetStandardDeviation (deviation, deviation, deviation) smooth_vol.SetRadiusFactors (radius, radius, radius) smooth_vol.Update() self.parent.volumedata_gaussian = self.SharpenVolume(smooth_vol.GetOutput()) #self.parent.volumedata_gaussian = smooth_vol.GetOutput() def SharpenVolume(self, volume): a1 = vtk.vtkImageGradientMagnitude() a1.SetDimensionality(3) a1.SetInput(volume) a1.Update() a2 = vtk.vtkImageMathematics() a2.SetOperationToAdd() a2.SetInput1(a1.GetOutput()) a2.SetInput2(volume) a2.Update() b1 = vtk.vtkImageGradientMagnitude() b1.SetDimensionality(3) b1.SetInput(a2.GetOutput()) b2 = vtk.vtkImageMathematics() b2.SetOperationToSubtract() b2.SetInput1(a2.GetOutput()) b2.SetInput2(b1.GetOutput()) b2.Update() c2 = vtk.vtkImageMathematics() c2.SetOperationToAdd() c2.SetInput1(a1.GetOutput()) c2.SetInput2(b2.GetOutput()) c2.Update() return c2.GetOutput() def RebuildPolydata(self, event=0, thresholdmin=125.0, thresholdmax=2500.0): threshold = vtk.vtkImageThreshold() threshold.SetInput(self.parent.volumedata) threshold.ThresholdBetween(thresholdmin, 2500.0) threshold.SetInValue(1.0) threshold.ReplaceInOn() threshold.SetOutValue(0.0) threshold.ReplaceOutOn() threshold.Update() print "Thresholding finished." mc = vtk.vtkMarchingContourFilter() mc.SetInput(threshold.GetOutput()) mc.ComputeScalarsOff() mc.ComputeGradientsOff() mc.ComputeNormalsOff() mc.Update() self.polydata = mc.GetOutput() self.RenewPolyData() print "Marching cubes finished." TriangleFilter = vtk.vtkTriangleFilter() TriangleFilter.SetInput(mc.GetOutput()) TriangleFilter.Update() self.polydata = TriangleFilter.GetOutput() self.RenewPolyData() print "Triangle filter finished." Decimated = vtk.vtkDecimatePro() Decimated.SetFeatureAngle(15.0) Decimated.SetTargetReduction(0.98) Decimated.PreserveTopologyOn() Decimated.SetInput(TriangleFilter.GetOutput()) Decimated.Update() self.polydata = Decimated.GetOutput() self.RenewPolyData() print "Decimate finished." Smooth = vtk.vtkSmoothPolyDataFilter() Smooth.SetInput(Decimated.GetOutput()) Smooth.SetNumberOfIterations(50) Smooth.SetRelaxationFactor(0.10) Smooth.Update() self.polydata = Smooth.GetOutput() self.RenewPolyData() print "Smooth finished." Normals = vtk.vtkPolyDataNormals() Normals.SetInput(Smooth.GetOutput()) #Normals.SetFeatureAngle(60.0) Normals.SplittingOff() Normals.ConsistencyOff() #Normals.AutoOrientNormalsOn() self.polydata = Normals.GetOutput() self.RenewPolyData() #~ self.splitextractor.SetUp() #~ print self.splitextractor.GetNeighbouringVertices(13882) #self.parent.VisualisePoint(self.polydata.GetPoint(13882), "1",(0.8,0.8,1),1) def OnRecordViewToggle(self, event): pass
Python
import time import wx import vtk import math import numpy import sys, os import BaseCalc import superthread try: import extended.PatternViewer as PatternViewer except ImportError: import PatternViewer def create(parent, root): return AngleCalculations(parent, root) class AngleCalculations: def __init__(self, parent, root): print "AngleCalculations module loaded." if parent == None: self.parent = self self._root = self else: self.parent = parent self._root = root self.isMain = False self.appdir = self.ReadRootDirectory() self.patternViewerCreated = False self.blPos = [] self.stanceCollectionBinnedRight = [] self.stanceCollectionBinnedLeft = [] def CreatePatternViewer(self): if not self.patternViewerCreated: self.patternViewer = PatternViewer.create(self, self._root, self.appdir) self.patternViewerCreated = True def Angles(self): #presumes that self.blPos has been set up correctly self.GlobalOXYZ = [[0,0,0], [1,0,0], [0,1,0], [0,0,1]] Thoraxstance = self.GenericAngleCalculation(self.GlobalOXYZ, self.OXYZThorax) #elevatie, elevatievlak, axial Claviclestance = self.GenericAngleCalculation(self.OXYZThorax, self.Right_OXYZClavicle) Scapulastance = self.GenericAngleCalculation(self.Right_OXYZClavicle, self.Right_OXYZScapula) Humerusstance = self.GenericAngleCalculation(self.Right_OXYZScapula, self.Right_OXYZHumerus) Forearmstance = self.GenericAngleCalculation(self.Right_OXYZHumerus, self.Right_OXYZForearm) #~ Forearmstance[1] = Forearmstance[1] - 90 # elevatievlak HumerusThorax = self.GenericAngleCalculation(self.OXYZThorax, self.Right_OXYZHumerus) stance_total_right = [] #relative to parent stance_total_right[len(stance_total_right):] = Thoraxstance stance_total_right[len(stance_total_right):] = Claviclestance stance_total_right[len(stance_total_right):] = Scapulastance stance_total_right[len(stance_total_right):] = Humerusstance stance_total_right[len(stance_total_right):] = Forearmstance #relative to thorax stance_total_right[len(stance_total_right):] = HumerusThorax stance_binned_right = [] stance_binned_right.append(Scapulastance[0]/10) stance_binned_right.append(Scapulastance[1]/10) stance_binned_right.append(Scapulastance[2]/10) stance_binned_right.append(Humerusstance[0]/10) stance_binned_right.append(Humerusstance[1]/10) stance_binned_right.append(Humerusstance[2]/10) stance_binned_right.append(Forearmstance[0]/10) stance_binned_right.append(Forearmstance[1]/10) stance_binned_right.append(Forearmstance[2]/10) #left side: ##~ Thoraxstance = self.GenericAngleCalculation(self.GlobalOXYZ, self.OXYZThorax) #elevatie, elevatievlak, axial Claviclestance = self.GenericAngleCalculation(self.OXYZThorax, self.Left_OXYZClavicle) Scapulastance = self.GenericAngleCalculation(self.Left_OXYZClavicle, self.Left_OXYZScapula) Humerusstance = self.GenericAngleCalculation(self.Left_OXYZScapula, self.Left_OXYZHumerus) Forearmstance = self.GenericAngleCalculation(self.Left_OXYZHumerus, self.Left_OXYZForearm) ##~ Forearmstance[1] = Forearmstance[1] - 90 # elevatievlak HumerusThorax = self.GenericAngleCalculation(self.OXYZThorax, self.Left_OXYZHumerus) stance_total_left = [] #relative to parent stance_total_left[len(stance_total_left):] = Thoraxstance stance_total_left[len(stance_total_left):] = Claviclestance stance_total_left[len(stance_total_left):] = Scapulastance stance_total_left[len(stance_total_left):] = Humerusstance stance_total_left[len(stance_total_left):] = Forearmstance #relative to thorax stance_total_left[len(stance_total_left):] = HumerusThorax stance_binned_left = [] stance_binned_left.append(Scapulastance[0]/10) stance_binned_left.append(Scapulastance[1]/10) stance_binned_left.append(Scapulastance[2]/10) stance_binned_left.append(Humerusstance[0]/10) stance_binned_left.append(Humerusstance[1]/10) stance_binned_left.append(Humerusstance[2]/10) stance_binned_left.append(Forearmstance[0]/10) stance_binned_left.append(Forearmstance[1]/10) stance_binned_left.append(Forearmstance[2]/10) blpositions = self.blPos[:] if stance_binned_right not in self.stanceCollectionBinnedRight: self.stanceCollectionBinnedRight.append(stance_binned_right) #~ print stance_total_right self.patternViewer.AddSpline(stance_total_right, blpositions) if stance_binned_left not in self.stanceCollectionBinnedLeft: self.stanceCollectionBinnedLeft.append(stance_binned_left) ##~ print stance_total_left ##~ print "" copiedblpositions = self.CopyBLLeftToRight(self.blPos) self.patternViewer.AddSpline(stance_total_left, copiedblpositions, updatewidget = False, referenceSpline = True) def GenericAngleCalculation(self, OXYZ1, OXYZ2, vis = False): #OXYZ1 = parent, OXYZ2=child #reference OXYZ1, measured angle OXYZ2 point1 = OXYZ1[0] v1 = OXYZ1[2] #y-as v2 = OXYZ2[2] #~ print "v1: ", v1 #~ print "v2: ", v2 dottie = math.acos(vtk.vtkMath.Dot(v1,v2) / (math.sqrt(math.pow(v1[0],2) + math.pow(v1[1],2) + math.pow(v1[2],2))*\ math.sqrt(math.pow(v2[0],2) + math.pow(v2[1],2) + math.pow(v2[2],2)))) # we kunnen geen controle hoek invoeren omdat de overgang tussen bijv. abductie / anteflexie / adductie ill-defined is. # dus dan maar gewoon absoluut houden. dottie_axis = [0,0,0] vtk.vtkMath.Cross(v1, v2, dottie_axis) vtk.vtkMath().Normalize(dottie_axis) #~ controlehoek = -vtk.vtkMath.Dot(OXYZ1[3], dottie_axis) #determines (+) or (-) angle. OXYZ1 = Z-axis #~ elevatie = int(controlehoek * dottie*vtk.vtkMath.RadiansToDegrees()) elevatie = vtk.vtkMath.DegreesFromRadians(dottie) point2 = self._root.baseCalc.AddPoints(point1, self._root.baseCalc.MultiplyVector(v2, 10)) if vis and False: self.parent.playbackState.panel.annotation.\ VisualiseArc(point1, point2, self._root.baseCalc.AddPoints(point1, self._root.baseCalc.MultiplyVector(v1, 10)), color = (0.0, 1.0, 0.0)) #print "Elevation: ", elevatie #DO SIDE CHECK: #cross-product van v1 en v2 = Q #hoek tussen Q en humerus-X < 0 => elevatie = negatief, anders positief #~ v2_projected = self.ProjectedVectorOnPlane(OXYZ2, OXYZ1, 2, 2) #y-axis of child OXYZ2 on normal_y-plane of parent OXYZ 1 v2_projected = dottie_axis v3 = OXYZ1[3] #Z-axis point2 = self._root.baseCalc.AddPoints(point1, self._root.baseCalc.MultiplyVector(v2_projected, 20)) dottie = math.acos(vtk.vtkMath.Dot(v3,v2_projected) / (math.sqrt(math.pow(v3[0],2) + math.pow(v3[1],2)+ math.pow(v3[2],2))*\ math.sqrt(math.pow(v2_projected[0],2) + math.pow(v2_projected[1],2)+ math.pow(v2_projected[2],2)))) dottie_axis = [0,0,0] vtk.vtkMath.Cross(v3, v2_projected, dottie_axis) vtk.vtkMath().Normalize(dottie_axis) controlehoek = round(vtk.vtkMath.Dot(v1, dottie_axis)) #determines + or - angle elevatievlak = (vtk.vtkMath.DegreesFromRadians(dottie) * controlehoek) + 90 if vis and False: point_temp = self._root.baseCalc.AddPoints(point1, self._root.baseCalc.MultiplyVector(v3, 20)) # BLAUW self.parent.playbackState.panel.annotation.\ VisualiseLine(point1, point2, opacity = 1.0, color = (0.0, 0.0, 1.0)) #ROOD: self.parent.playbackState.panel.annotation.\ VisualiseLine(point1, point_temp, opacity = 1.0, color = (1.0, 0.0, 0.0)) #ROOD: self.parent.playbackState.panel.annotation.\ VisualiseArc(point1, point2, self._root.baseCalc.AddPoints(point1, self._root.baseCalc.MultiplyVector(OXYZ1[1], 20)), color = (1.0, 0.0, 0.0)) #~ print elevatievlak #~ print controlehoek #print "Plane of elevation: ", elevatievlak #~ bepaal exorotatie: # corrigeer elevatie/elevatievlak t2_tmp = vtk.vtkTransform() t2_tmp.RotateWXYZ(elevatievlak, OXYZ1[2]) #elevatie-as roteren om de axiale as van parent (y) t2_tmp.Update() basicAxis = t2_tmp.TransformPoint(OXYZ1[1]) #elevatie-as X van parent #~ if vis: #~ print basicAxis #~ point3 = self._root.baseCalc.AddPoints(point1, self._root.baseCalc.MultiplyVector(basicAxis, 10)) #~ self.parent.playbackState.panel.annotation.\ #~ VisualiseArc(point1, point3, self._root.baseCalc.AddPoints(point1, self._root.baseCalc.MultiplyVector(OXYZ1[1], 10)), color = (0.0, 1.0, 0.0)) transftmp = vtk.vtkTransform() transftmp.RotateWXYZ(elevatie, basicAxis) transftmp.Update() v1_axial = OXYZ1[3] v2_axial = transftmp.TransformPoint(OXYZ2[3]) #~ if vis: #~ point3 = self._root.baseCalc.AddPoints(point1, self._root.baseCalc.MultiplyVector(v1_axial, 10)) #~ self.parent.playbackState.panel.annotation.\ #~ VisualiseArc(point1, point3, self._root.baseCalc.AddPoints(point1, self._root.baseCalc.MultiplyVector(v2_axial, 10)), color = (0.0, 1.0, 1.0)) dottie = math.acos(vtk.vtkMath.Dot(v1_axial,v2_axial) / (math.sqrt(math.pow(v1_axial[0],2) + math.pow(v1_axial[1],2) + math.pow(v1_axial[2],2))*\ math.sqrt(math.pow(v2_axial[0],2) + math.pow(v2_axial[1],2) + math.pow(v2_axial[2],2)))) dottie_axis = [0,0,0] vtk.vtkMath.Cross(v1_axial, v2_axial, dottie_axis) vtk.vtkMath().Normalize(dottie_axis) controlehoek = round(vtk.vtkMath.Dot(v1, dottie_axis)) axialerotatie = vtk.vtkMath.DegreesFromRadians(dottie) * controlehoek #~ if vis: #~ print "elevatie: ", elevatie #~ print "elevatievlak: ", elevatievlak #~ print "axiale rotatie: ", axialerotatie return [int(elevatie), int(elevatievlak), int(axialerotatie)] # in principe: z-axis projecteren op y-vlak en dan de hoek nemen tussen z-projected en z-parent # dichtbij 90 graden elevatie geeft dit Gimbal Lock. Te detecteren door de vectorlengte te meten # Deze is bij 0 graden elevatie 1, bij 90 graden is deze 0. Kleiner dan, zeg 0.25, dan moeten we op # zoek naar een veiligere maat # x-as projecteren op vlak y-parent. hoek tussen x-projected en x-parent. projection = self.ProjectedVectorOnPlane(OXYZ2, OXYZ1, 3, 2) #z-axis on normal_y plane : z-axis parent v4_projected = projection[0] v4_length = projection[1] if vis: print "v4_length: ", v4_length if v4_length < 0.3: #overstappen op x-as, ter vermijding van Gimbal Lock projection = self.ProjectedVectorOnPlane(OXYZ2, OXYZ1, 1, 2) #x-axis on normal_y plane : x-axis parent v4_projected = projection[0] v4_length = projection[1] v5 = OXYZ1[1] if vis: print "New v4_length: ", v4_length else: v5 = OXYZ1[3] #z-axis vtk.vtkMath().Normalize(v4_projected) #~ point2 = self._root.baseCalc.AddPoints(point1, self._root.baseCalc.MultiplyVector(v4_projected, 10)) #~ self.patternViewer.annotation2.\ #~ VisualiseArc(point1, point2, self._root.baseCalc.AddPoints(point1, self._root.baseCalc.MultiplyVector(OXYZ1[3], 10)), color = (0.0, 0.0, 1.0)) dottie = math.acos(vtk.vtkMath.Dot(v5,v4_projected) /\ (math.sqrt(math.pow(v5[0],2) + math.pow(v5[1],2) + math.pow(v5[2],2))\ *math.sqrt(math.pow(v4_projected[0],2) + math.pow(v4_projected[1],2) + math.pow(v4_projected[2],2)))) #~ if (v4_projected[0] * v5[1] - v4_projected[1] * v5[0]) < 0: #~ dottie = -dottie #Side-check... dottie_axis = [0,0,0] vtk.vtkMath.Cross(v5, v4_projected, dottie_axis) vtk.vtkMath().Normalize(dottie_axis) controlehoek = round(vtk.vtkMath.Dot(v1, dottie_axis)) #determines + or - angle #~ if abs(elevatie)>90: #~ controlehoek = -controlehoek axialerotatie = int(vtk.vtkMath.DegreesFromRadians(dottie) * controlehoek) if vis: print "Elevation: ", elevatie print "Axial rotation: ", axialerotatie return [elevatie, elevatievlak, axialerotatie] def CopyBLLeftToRight(self, blPos): for i in range(4, 14): blPos[i] = blPos[i+10] blPos[24] = blPos[25] return blPos def SetupCoordinateSystems(self, blPos, side=2): #side = 0: Right #side = 1: Left #side = 2: both try: self.parent.playbackState.panel.annotation.ClearAll() except AttributeError: pass self.blPos = blPos self.DetermineMidPoints(blPos) self.DefineXYZThorax() self.blPos = self.FlipLeft(blPos) self.DefineXYZClavicle(side) self.DefineXYZScapula(side) self.DefineXYZHumerus(side) self.DefineXYZForearm(side) return self.blPos #~ print "" #~ print self.OXYZThorax #~ print self.Right_OXYZClavicle #~ print self.Left_OXYZClavicle #~ print self.Right_OXYZScapula #~ print self.Left_OXYZScapula #~ print self.Right_OXYZHumerus #~ print self.Left_OXYZHumerus #~ print self.Right_OXYZForearm #~ print self.Left_OXYZForearm #~ return 1 def VisualizeCoordinateSystems(self): #~ self.parent.playbackState.panel.annotation.\ #~ VisualiseCoordinateSystem(self.OXYZThorax) self.parent.playbackState.panel.annotation.\ VisualiseCoordinateSystem(self.Right_OXYZClavicle) self.parent.playbackState.panel.annotation.\ VisualiseCoordinateSystem(self.Right_OXYZScapula) self.parent.playbackState.panel.annotation.\ VisualiseCoordinateSystem(self.Right_OXYZHumerus) self.parent.playbackState.panel.annotation.\ VisualiseCoordinateSystem(self.Right_OXYZForearm) self.parent.playbackState.panel.annotation.\ VisualiseCoordinateSystem(self.Left_OXYZForearm) self.parent.playbackState.panel.annotation.\ VisualiseCoordinateSystem(self.Left_OXYZHumerus) self.parent.playbackState.panel.annotation.\ VisualiseCoordinateSystem(self.Left_OXYZScapula) self.parent.playbackState.panel.annotation.\ VisualiseCoordinateSystem(self.Left_OXYZClavicle) #~ pass def GetBLPos(self): blPos = [] for landmark in self.landmarks: blPos.append(landmark['coords']) return blPos def DetermineMidPoints(self, blPos): #~ #run every frame #~ for landmark in self.landmarks: #~ landmark['coords'] = blPos[landmark['id']] self.midPXT8 = self._root.baseCalc.Average2Points(blPos[0], blPos[3]) self.midIJC7 = self._root.baseCalc.Average2Points(blPos[1], blPos[2]) self.Right_midELEM = self._root.baseCalc.Average2Points(blPos[10], blPos[11]) def FlipLeft(self, blPos): matrix1 = numpy.matrix([self.OXYZThorax[1], self.OXYZThorax[2], self.OXYZThorax[3]]) matrix2 = numpy.transpose(matrix1) test = matrix1 * matrix2 #~ print test BL_invertionlist = [14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 25] for i in BL_invertionlist: v = numpy.matrix(self._root.baseCalc.SubtractPoints(blPos[i], self.OXYZThorax[0])) v = v.transpose() #v = coords #~ self.parent.playbackState.panel.annotation.VisualisePoint((self._root.baseCalc.SubtractPoints(landmark['coords'], self.OXYZThorax[0])), "Start", (0,0,0)) #v = numpy.invert(v)#v.transpose() #~ print "v: ", v v2 = matrix1 * v v2[2,0] = -v2[2,0] v2_flipped = matrix2 * v2 #~ print "v2_flipped: ", v2_flipped v2_flipped = v2_flipped.transpose() v2_flipped = v2_flipped.tolist()[0] #~ self.parent.playbackState.panel.annotation.VisualisePoint([0,0,0], "origin", (0,0,0)) #~ self.parent.playbackState.panel.annotation.VisualisePoint(v2_flipped, "eind", (0,0,0)) coords_out = self._root.baseCalc.AddPoints(v2_flipped, self.OXYZThorax[0]) blPos[i] = coords_out #~ self.parent.playbackState.panel.annotation.VisualisePoint(coords_out, landmark['s_name'], (0,0,0)) self.Left_midELEM = self._root.baseCalc.Average2Points(blPos[20], blPos[21]) return blPos def DefineXYZThorax(self): #Ot: The origin coincident with IJ coordThorax_O = self.blPos[1] #Yt: The line connecting the midpoint between PX and T8 # and the midpoint between IJ and C7, pointing upward. coordThorax_Y = self._root.baseCalc.SubtractPoints(self.midIJC7, self.midPXT8) coordThorax_Y = self._root.baseCalc.Normalize(coordThorax_Y) #Zt: The line perpendicular to the plane formed by #IJ, C7, and the midpoint between PX and T8, pointing to the Right. TempA = self._root.baseCalc.SubtractPoints(self.blPos[1], self.midPXT8) TempB = self._root.baseCalc.SubtractPoints(self.blPos[1], self.blPos[2]) TempA = self._root.baseCalc.Normalize(TempA) TempB = self._root.baseCalc.Normalize(TempB) coordThorax_Z = [0,0,0] vtk.vtkMath.Cross(TempB, TempA, coordThorax_Z) coordThorax_Z = self._root.baseCalc.Normalize(coordThorax_Z) #Xt: The common line perpendicular to the Zt- and #Yt-axis, pointing forwards. coordThorax_X = [0,0,0] vtk.vtkMath.Cross(coordThorax_Y, coordThorax_Z, coordThorax_X) coordThorax_X = self._root.baseCalc.Normalize(coordThorax_X) #~ print "coordThorax_X: ", self._root.baseCalc.Length3DVector(coordThorax_X) #~ print "coordThorax_Y: ", self._root.baseCalc.Length3DVector(coordThorax_Y) #~ print "coordThorax_Z: ", self._root.baseCalc.Length3DVector(coordThorax_Z) self.OXYZThorax = [coordThorax_O, coordThorax_X, coordThorax_Y, coordThorax_Z] def DefineXYZClavicle(self, side): if side == 0 or side == 2: #The origin coincident with SC coordClavicle_O = self.blPos[4] #Zc: The line connecting SC and AC, pointing to AC coordClavicle_Z = self._root.baseCalc.SubtractPoints(self.blPos[6], self.blPos[4]) coordClavicle_Z = self._root.baseCalc.Normalize(coordClavicle_Z) #Xc: The line perpendicular to Zc and Yt, pointing forward #Note that the Xc-axis is defined with #respect to the vertical axis of the thorax (Ytaxis) #because only two bonylandmarks can be discerned at the clavicle. TempA = self._root.baseCalc.SubtractPoints(self.midIJC7, self.midPXT8) TempA = self._root.baseCalc.Normalize(TempA) #(Yt) coordClavicle_X = [0,0,0] vtk.vtkMath.Cross(TempA, coordClavicle_Z, coordClavicle_X) coordClavicle_X = self._root.baseCalc.Normalize(coordClavicle_X) #Yc: The common line perpendicular to the Xc- and Zc-axis, pointing upward. coordClavicle_Y = [0,0,0] vtk.vtkMath.Cross(coordClavicle_Z, coordClavicle_X, coordClavicle_Y) coordClavicle_Y = self._root.baseCalc.Normalize(coordClavicle_Y) self.Right_OXYZClavicle = [coordClavicle_O, coordClavicle_X, coordClavicle_Y, coordClavicle_Z] if side == 1 or side == 2: #The origin coincident with SC coordClavicle_O = self.blPos[14] #Zc: The line connecting SC and AC, pointing to AC coordClavicle_Z = self._root.baseCalc.SubtractPoints(self.blPos[16], self.blPos[14]) coordClavicle_Z = self._root.baseCalc.Normalize(coordClavicle_Z) #Xc: The line perpendicular to Zc and Yt, pointing forward #Note that the Xc-axis is defined with #respect to the vertical axis of the thorax (Ytaxis) #because only two bonylandmarks can be discerned at the clavicle. TempA = self._root.baseCalc.SubtractPoints(self.midIJC7, self.midPXT8) TempA = self._root.baseCalc.Normalize(TempA) #(Yt) coordClavicle_X = [0,0,0] vtk.vtkMath.Cross(TempA, coordClavicle_Z, coordClavicle_X) coordClavicle_X = self._root.baseCalc.Normalize(coordClavicle_X) #Yc: The common line perpendicular to the Xc- and Zc-axis, pointing upward. coordClavicle_Y = [0,0,0] vtk.vtkMath.Cross(coordClavicle_Z, coordClavicle_X, coordClavicle_Y) coordClavicle_Y = self._root.baseCalc.Normalize(coordClavicle_Y) self.Left_OXYZClavicle = [coordClavicle_O, coordClavicle_X, coordClavicle_Y, coordClavicle_Z] def DefineXYZScapula(self, side): if side == 0 or side == 2: #The origin coincident with AA. coordScapula_O = self.blPos[7] #Zs: The line connecting TS and AA, pointing to AA. coordScapula_Z = self._root.baseCalc.SubtractPoints(self.blPos[7], self.blPos[8]) #coordScapula_Z = self._root.baseCalc.Normalize(coordScapula_Z) vtk.vtkMath.Normalize(coordScapula_Z) #Xs: The line perpendicular to the plane formed by AI, AA, and TS, pointing forward. TempA = self._root.baseCalc.SubtractPoints(self.blPos[9], self.blPos[8]) TempB = self._root.baseCalc.SubtractPoints(self.blPos[9], self.blPos[7]) TempA = self._root.baseCalc.Normalize(TempA) TempB = self._root.baseCalc.Normalize(TempB) coordScapula_X = [0,0,0] vtk.vtkMath.Cross(TempA, TempB, coordScapula_X) coordScapula_X = self._root.baseCalc.Normalize(coordScapula_X) #Ys: The common line perpendicular to the Xs- and Zs-axis, pointing upward. coordScapula_Y = [0,0,0] vtk.vtkMath.Cross(coordScapula_Z, coordScapula_X, coordScapula_Y) coordScapula_Y = self._root.baseCalc.Normalize(coordScapula_Y) #~ #Faulty FOB coords...: #~ tmp = coordScapula_Z #~ coordScapula_Z = self._root.baseCalc.MultiplyVector(coordScapula_X, -1) #~ coordScapula_X = tmp self.Right_OXYZScapula = [coordScapula_O, coordScapula_X, coordScapula_Y, coordScapula_Z] if side == 1 or side == 2: #The origin coincident with AA. coordScapula_O = self.blPos[17] #Zs: The line connecting TS and AA, pointing to AA. coordScapula_Z = self._root.baseCalc.SubtractPoints(self.blPos[17], self.blPos[18]) #coordScapula_Z = self._root.baseCalc.Normalize(coordScapula_Z) vtk.vtkMath.Normalize(coordScapula_Z) #Xs: The line perpendicular to the plane formed by AI, AA, and TS, pointing forward. TempA = self._root.baseCalc.SubtractPoints(self.blPos[19], self.blPos[18]) TempB = self._root.baseCalc.SubtractPoints(self.blPos[19], self.blPos[17]) TempA = self._root.baseCalc.Normalize(TempA) TempB = self._root.baseCalc.Normalize(TempB) coordScapula_X = [0,0,0] vtk.vtkMath.Cross(TempA, TempB, coordScapula_X) coordScapula_X = self._root.baseCalc.Normalize(coordScapula_X) #Ys: The common line perpendicular to the Xs- and Zs-axis, pointing upward. coordScapula_Y = [0,0,0] vtk.vtkMath.Cross(coordScapula_Z, coordScapula_X, coordScapula_Y) coordScapula_Y = self._root.baseCalc.Normalize(coordScapula_Y) #~ #Faulty FOB coords...: #~ tmp = coordScapula_Z #~ coordScapula_Z = self._root.baseCalc.MultiplyVector(coordScapula_X, -1) #~ coordScapula_X = tmp self.Left_OXYZScapula = [coordScapula_O, coordScapula_X, coordScapula_Y, coordScapula_Z] def DefineXYZHumerus(self, side): if side == 0 or side == 2: coordHumerus_O = self.blPos[24] #Yh1: The line connecting GH and the midpoint of EL and EM, pointing to GH. coordHumerus_Y = self._root.baseCalc.SubtractPoints(self.blPos[24], self.Right_midELEM) coordHumerus_Y = self._root.baseCalc.Normalize(coordHumerus_Y) #Xh1: The line perpendicular to the plane formed by EL, EM, and GH, pointing forward. coordHumerus_Ya = self._root.baseCalc.SubtractPoints(self.blPos[24], self.blPos[10]) coordHumerus_Yb = self._root.baseCalc.SubtractPoints(self.blPos[24], self.blPos[11]) coordHumerus_Ya = self._root.baseCalc.Normalize(coordHumerus_Ya) coordHumerus_Yb = self._root.baseCalc.Normalize(coordHumerus_Yb) coordHumerus_X = [0,0,0] vtk.vtkMath.Cross(coordHumerus_Yb, coordHumerus_Ya, coordHumerus_X) coordHumerus_X = self._root.baseCalc.Normalize(coordHumerus_X) #Zh1: The common line perpendicular to the Yh1- and Xh1-axis, pointing to the Right. coordHumerus_Z = [0,0,0] vtk.vtkMath.Cross(coordHumerus_X, coordHumerus_Y, coordHumerus_Z) coordHumerus_Z = self._root.baseCalc.Normalize(coordHumerus_Z) #Faulty FOB coords...: #~ tmp = coordHumerus_Z coordHumerus_Z = self._root.baseCalc.MultiplyVector(coordHumerus_Z, -1) coordHumerus_X = self._root.baseCalc.MultiplyVector(coordHumerus_X, -1) #~ coordHumerus_X = tmp self.Right_OXYZHumerus = [coordHumerus_O, coordHumerus_X, coordHumerus_Y, coordHumerus_Z] if side == 1 or side == 2: coordHumerus_O = self.blPos[25] #Yh1: The line connecting GH and the midpoint of EL and EM, pointing to GH. coordHumerus_Y = self._root.baseCalc.SubtractPoints(self.blPos[25], self.Left_midELEM) coordHumerus_Y = self._root.baseCalc.Normalize(coordHumerus_Y) #Xh1: The line perpendicular to the plane formed by EL, EM, and GH, pointing forward. coordHumerus_Ya = self._root.baseCalc.SubtractPoints(self.blPos[25], self.blPos[20]) coordHumerus_Yb = self._root.baseCalc.SubtractPoints(self.blPos[25], self.blPos[21]) coordHumerus_Ya = self._root.baseCalc.Normalize(coordHumerus_Ya) coordHumerus_Yb = self._root.baseCalc.Normalize(coordHumerus_Yb) coordHumerus_X = [0,0,0] vtk.vtkMath.Cross(coordHumerus_Yb, coordHumerus_Ya, coordHumerus_X) coordHumerus_X = self._root.baseCalc.Normalize(coordHumerus_X) #Zh1: The common line perpendicular to the Yh1- and Xh1-axis, pointing to the Left. coordHumerus_Z = [0,0,0] vtk.vtkMath.Cross(coordHumerus_X, coordHumerus_Y, coordHumerus_Z) coordHumerus_Z = self._root.baseCalc.Normalize(coordHumerus_Z) #Faulty FOB coords...: #~ tmp = coordHumerus_Z coordHumerus_Z = self._root.baseCalc.MultiplyVector(coordHumerus_Z, -1) coordHumerus_X = self._root.baseCalc.MultiplyVector(coordHumerus_X, -1) #~ coordHumerus_X = tmp self.Left_OXYZHumerus = [coordHumerus_O, coordHumerus_X, coordHumerus_Y, coordHumerus_Z] def DefineXYZForearm(self, side): if side == 0 or side == 2: coordForearm_O = self.blPos[13] #Yf : The line connecting US and the midpoint #between EL and EM, pointing proximally. coordForearm_Y = self._root.baseCalc.SubtractPoints(self.Right_midELEM, self.blPos[13]) coordForearm_Y = self._root.baseCalc.Normalize(coordForearm_Y) #Xf : The line perpendicular to the plane through US, #RS, and the midpoint between EL and EM, pointing forward. TempA = self._root.baseCalc.SubtractPoints(self.Right_midELEM, self.blPos[13]) TempB = self._root.baseCalc.SubtractPoints(self.Right_midELEM, self.blPos[12]) TempA = self._root.baseCalc.Normalize(TempA) TempB = self._root.baseCalc.Normalize(TempB) coordForearm_X = [0,0,0] vtk.vtkMath.Cross(TempB, TempA, coordForearm_X) coordForearm_X = self._root.baseCalc.Normalize(coordForearm_X) #*Hoe zorgen dat coordForearm_X naar voren wijst?? #Zf : The common line perpendicular to the Xf and #Yf -axis, pointing to the Right. coordForearm_Z = [0,0,0] vtk.vtkMath.Cross(coordForearm_X, coordForearm_Y, coordForearm_Z) coordForearm_Z = self._root.baseCalc.Normalize(coordForearm_Z) self.Right_OXYZForearm = [coordForearm_O, coordForearm_X, coordForearm_Y, coordForearm_Z] if side == 1 or side == 2: coordForearm_O = self.blPos[23] #Yf : The line connecting US and the midpoint #between EL and EM, pointing proximally. coordForearm_Y = self._root.baseCalc.SubtractPoints(self.Left_midELEM, self.blPos[23]) coordForearm_Y = self._root.baseCalc.Normalize(coordForearm_Y) #Xf : The line perpendicular to the plane through US, #RS, and the midpoint between EL and EM, pointing forward. TempA = self._root.baseCalc.SubtractPoints(self.Left_midELEM, self.blPos[23]) TempB = self._root.baseCalc.SubtractPoints(self.Left_midELEM, self.blPos[22]) TempA = self._root.baseCalc.Normalize(TempA) TempB = self._root.baseCalc.Normalize(TempB) coordForearm_X = [0,0,0] vtk.vtkMath.Cross(TempB, TempA, coordForearm_X) coordForearm_X = self._root.baseCalc.Normalize(coordForearm_X) #*Hoe zorgen dat coordForearm_X naar voren wijst?? #Zf : The common line perpendicular to the Xf and #Yf -axis, pointing to the Left. coordForearm_Z = [0,0,0] vtk.vtkMath.Cross(coordForearm_X, coordForearm_Y, coordForearm_Z) coordForearm_Z = self._root.baseCalc.Normalize(coordForearm_Z) self.Left_OXYZForearm = [coordForearm_O, coordForearm_X, coordForearm_Y, coordForearm_Z] def ProjectedVectorOnPlane(self, oxyzFirst, oxyzSecond, axis, planenormal): # Projecting an axis (1,2,3) of oxyzFirst on a plane with normal (1,2,3) of oxyzSecond. # Returns normalized vector on plane m1 = numpy.matrix([oxyzSecond[1], oxyzSecond[2], oxyzSecond[3]]) m2 = m1.transpose() v1 = numpy.matrix([oxyzFirst[axis]]) v1 = v1.transpose() tmp2 = m1 * v1 tmp2[planenormal-1, 0] = 0.0 v2_projected = m2 * tmp2 v2_projected = v2_projected.transpose() norm = lambda x: numpy.sqrt(numpy.square(v2_projected).sum()) vectorlength = norm(v2_projected) v2_projected_list = v2_projected.tolist()[0] # UNNORMALIZED!!! on purpose. return [v2_projected_list, vectorlength] #~ origin = self.oxyzSecond[0] #origin #~ point2 = self._root.baseCalc.AddPoints(origin, self._root.baseCalc.MultiplyVector(v2_projected, 10)) #~ self.patternViewer.annotation2.\ #~ VisualiseLine(point1, point2, opacity = 1.0, color = (0.0, 0.0, 0.0)) #~ v3 = oxyzSecond[axis] #~ dottie = math.acos(vtk.vtkMath.Dot(v3,v2_projected) / (math.sqrt(math.pow(v3[0],2) + math.pow(v3[1],2) + math.pow(v3[2],2))*math.sqrt(math.pow(v2_projected[0],2) + math.pow(v2_projected[1],2) + math.pow(v2_projected[2],2)))) #~ dottie_degrees = dottie*vtk.vtkMath.RadiansToDegrees() #~ return dottie_degrees #print "elevatievlak: ", dottie_degrees def MatchCoordinateSystemAtoB(self, oxyzFirst, oxyzSecond): #returns a transform that, when applied, transforms coordinate system xyzFirst #to xyzSecond, i.e. x=x, y=y, z=z. total_lmtransf = vtk.vtkLandmarkTransform() assen1 = vtk.vtkPoints() assen1.SetNumberOfPoints(4) assen1.SetPoint(0, oxyzFirst[0]) assen1.SetPoint(1, oxyzFirst[1]) assen1.SetPoint(2, oxyzFirst[2]) assen1.SetPoint(3, oxyzFirst[3]) assen2 = vtk.vtkPoints() assen2.SetNumberOfPoints(4) assen2.SetPoint(0, oxyzSecond[0]) assen2.SetPoint(1, oxyzSecond[1]) assen2.SetPoint(2, oxyzSecond[2]) assen2.SetPoint(3, oxyzSecond[3]) total_lmtransf.SetSourceLandmarks(assen1) total_lmtransf.SetTargetLandmarks(assen2) total_lmtransf.Update() total_matrix1 = total_lmtransf.GetMatrix() total_newtransf = vtk.vtkTransform() total_newtransf.SetMatrix(total_matrix1) return total_newtransf def ReadRootDirectory(self): if hasattr(sys, 'frozen') and sys.frozen: appdir, exe = os.path.split(sys.executable) else: dirname = os.path.dirname(sys.argv[0]) if dirname and dirname != os.curdir: appdir = dirname else: appdir = os.getcwd() return appdir def ImportSplinesSmall(self): fname = os.path.join(self.appdir, 'splines_elbow.txt') importfile = open(fname, 'r', 1) lines = importfile.readlines() for i in range (0, len (lines)/2): stance = eval(lines[i*2]) blPos = eval(lines[i*2+1]) self.patternViewer.AddSpline(stance, blPos, updatewidget = False, referenceSpline = False) importfile.close() self.patternViewer.gui.widgets.UpdateWidgets() self.patternViewer.gui.UpdateSequencePlot(9) #~ print self.patternViewer.Filters.jointAngleCollection[9] def ImportSplines1(self): fname = os.path.join(self.appdir, 'splines.txt') #~ fname = os.path.join(self.appdir, 'splines_elbow.txt') importfile = open(fname, 'r', 1) lines = importfile.readlines() for i in range (0, len (lines)/2): stance = eval(lines[i*2]) blPos = eval(lines[i*2+1]) self.patternViewer.AddSpline(stance, blPos, updatewidget = False, referenceSpline = False) importfile.close() self.patternViewer.gui.widgets.UpdateWidgets() self.patternViewer.gui.UpdateSequencePlot(9) def ImportSplines2(self): fname = os.path.join(self.appdir, 'splines_passief.txt') #~ fname = os.path.join(self.appdir, 'splines_passief_short.txt') importfile = open(fname, 'r', 1) lines = importfile.readlines() for i in range (0, len (lines)/2): stance = eval(lines[i*2]) blPos = eval(lines[i*2+1]) self.patternViewer.AddSpline(stance, blPos, updatewidget = False, referenceSpline = True) importfile.close() self.patternViewer.gui.widgets.UpdateWidgets() def ReadAngleFile(self, fname): importfile = open(fname, 'r', 1) lines = importfile.readlines() stancelist = [] for i in range (0, len (lines)): stance = (lines[i]).split() stanceflt = [] for j in stance: stanceflt.append(float(j)) #elbow elevation plane not present in data stanceflt.insert(12, 0.0) #humerus-global angles not present in data stanceflt.append(0.0) stanceflt.append(0.0) stanceflt.append(0.0) #swap elevation and elevationplane for k in range(0, len(stanceflt)/3): stanceflt.insert(k*3, stanceflt[k*3+1]) stanceflt.pop(k*3+2) #~ #clavicle angle may be flipped? #~ stanceflt[5] = -stanceflt[5] stancelist.append(stanceflt) return stancelist def AngleFiles(self): blPos_GenericSkeleton = [[112.0170752018814, 1.2942639374899696, 10.864873678096608],\ [110.40771338957992, 1.9925669659434697, -4.6983268907973557],\ [104.17419623891995, 3.7878726012110415, -15.40384202012592],\ [94.999424758214758, 3.5293192897876215, 3.5045948263617586],\ [110.53152652553526, 4.8646938632774566, -6.831116604254218],\ [109.43318402993354, 17.037239972304867, -4.5305175872666599],\ [109.78178754978204, 21.755615974354601, -6.7684137794569397],\ [106.75205876719453, 23.105028309424345, -5.6459772829054975],\ [99.148296487411216, 12.958210148467339, -7.5821107093384725],\ [95.637864949303875, 13.839828031874202, 3.4522271706941279],\ [102.5036233495958, 25.271488851532347, 26.27990416414816],\ [102.46214664669861, 20.374542235794447, 26.939802533159135],\ [111.03715508038803, 26.883934292485414, 52.351379968684689],\ [107.75626381347377, 25.422313503800616, 54.181314916262998],\ [109.75582826756268, 5.5777415653361402, -4.6864746758040381],\ [108.81178197246609, 18.016754758656596, -4.2760757670688934],\ [109.05551946108935, 21.612268201800749, -5.400613300882573],\ [107.40872984648813, 23.284383912895052, -4.2049826313827872],\ [99.248369642052154, 13.36978476428367, -5.3218347492054772],\ [97.243158592270035, 15.239545826901447, 5.1814993097675419],\ [110.38014942008698, 23.761123070506795, 29.731441484429581],\ [107.61530111485308, 20.281164273344608, 29.651352763843853],\ [121.47533522367939, 19.780253333764321, 51.361429936224702],\ [120.18722060552903, 21.598985300192698, 52.46386136443202],\ [109.47954544191421, 21.996081120041861, -2.32384462886629],\ [106.83721641418667, -14.687957697267301, -2.8048070019125309]] self.patternViewer.ResetSkeleton(blPos_GenericSkeleton) fname = 'C:/Documents and Settings/Administrator/Mijn documenten/FobData/Frans2/test_ab.txt' stancelist = self.ReadAngleFile(fname) for stance in stancelist: blPos = self.patternViewer.GeneratePhysique(stance, showbones = False, returnBLpos = True) #~ self.patternViewer.AddSpline(stance, blPos, updatewidget = False, referenceSpline = False) self.SetupCoordinateSystems(blPos) self.Angles() #~ fname = 'C:/Documents and Settings/Administrator/Mijn documenten/FobData/Frans2/test_ab2.txt' #~ stancelist2 = self.ReadAngleFile(fname) #~ for stance in stancelist2: #~ blPos = self.patternViewer.GeneratePhysique(stance, showbones = False, returnBLpos = True) #~ ##~ self.patternViewer.AddSpline(stance, blPos, updatewidget = False, referenceSpline = True) #~ self.Angles(blPos) self.patternViewer.gui.widgets.UpdateWidgets() class MyApp(wx.App): def OnInit(self): angles = AngleCalculations(None, None) angles.isMain = True angles.appdir = angles.ReadRootDirectory() angles.CreatePatternViewer() angles.baseCalc = BaseCalc.create(self, self) #~ angles.patternViewer.gui.OnLoadData1(None) ##~ angles.ImportSplinesSmall() ##~ angles.ImportSplines2() ##~ angles.AngleFiles() return 1 if __name__ == "__main__": app = MyApp(0) app.MainLoop()
Python
#!/usr/bin/env python # This example demonstrates the use of vtkCardinalSpline. # It creates random points and connects them with a spline import os, sys import vtk import vtktudoss from wx import * import wx.lib.stattext import wx.aui from vtk.wx.wxVTKRenderWindow import * from vtk.wx.wxVTKRenderWindowInteractor import * from vtk.util.colors import tomato, banana import time try: import extended.Annotation as Annotation import extended.WidgetCollection as WidgetCollection import extended.WidgetOverlay as WidgetOverlay import extended.PlotOverlay as PlotOverlay import extended.Plotter as Plotter import extended.Scatter as Scatter import extended.TimeWindowTrace as TimeWindowTrace import extended.GUI_wxglade as GUI_wxglade except ImportError: import Annotation import WidgetCollection import WidgetOverlay import PlotOverlay import Plotter import Scatter import TimeWindowTrace import GUI_wxglade [wxID_FRAME, wxID_NOTEBOOK2, wxID_SAVE, wxID_QUIT ] = [wx.NewId() for _init_ctrls in range(4)] def create(parent, root): return wxFrame(parent, root) class wxFrame(wx.Frame): def _init_ctrls(self): dispsize = wx.DisplaySize() wx.Frame.__init__(self, id=wxID_FRAME, name='wxFrame', parent=None, pos=wx.Point(0, 0), size = (dispsize[0], dispsize[1]-100), style=wx.DEFAULT_FRAME_STYLE, title=u'PatternViewer') antialiasing = False self.showsliders = False showcaption = True showtraceroptions = True mainbackgroundcolor = [0.3, 0.3, 0.3] #~ mainbackgroundcolor = [1.0, 1.0, 1.0] self.cellpicker = vtk.vtkPointPicker() self.cellpicker.SetTolerance(0.0025) #~ self.cellpicker.InitializePickList() #~ self.cellpicker.PickFromListOn() color1 = [0.0, 0.0, 0.0] # [0.5,0.5,0.5]# self.ren1 = vtk.vtkRenderer() self.renwini1 = wxVTKRenderWindowInteractor(self, -1) self.renwini1.GetRenderWindow().AddRenderer(self.ren1) self.interactorstyle1 = vtk.vtkInteractorStyleTrackballCamera() self.renwini1.SetInteractorStyle(self.interactorstyle1) self.ren1.SetBackground(mainbackgroundcolor) cam1 = self.ren1.GetActiveCamera() cam1.SetViewUp(0, 0, 1) cam1.SetFocalPoint(13, 14, 12) cam1.SetPosition(-100, 20, 25) self.ren1.ResetCamera() self.renwini1.CreateRepeatingTimer(10) if antialiasing: self.renwini1.GetRenderWindow().SetAAFrames(12) self.timerobserver = self.renwini1.AddObserver("TimerEvent", self.timerCB) self.ren1overlay = WidgetOverlay.create(self, self.renwini1, self.ren1) #self.renwini1.AddObserver("LeftButtonPressEvent", self.JointClicked, 0.0) self.renwini1.Unbind(wx.EVT_LEFT_DOWN) self.renwini1.Bind(wx.EVT_LEFT_DOWN, self.JointClicked) color2 = [0.0, 0.0, 0.0] # [0.5,0.5,0.5]# #~ color2 = [0.0,0.0,0.0]#[0.4,0.4,0.4] self.ren2 = vtk.vtkRenderer() self.renwini2 = wxVTKRenderWindowInteractor(self, -1) self.renwini2.GetRenderWindow().AddRenderer(self.ren2) interactorstyle2 = vtk.vtkInteractorStyleTrackballCamera() self.renwini2.SetInteractorStyle(interactorstyle2) self.ren2.SetBackground(mainbackgroundcolor) self.annotation2 = Annotation.create(self, None, self.renwini2.GetRenderWindow(), self.ren2) currentcam = self.ren2.GetActiveCamera() currentcam.SetPosition(152, 43, -38) currentcam.SetClippingRange(40, 322) currentcam.SetViewUp(-0.34, 0.93, 0.027) currentcam.SetFocalPoint(0.614, -14.8, 36.8) interactionobserver2 = interactorstyle2.AddObserver("InteractionEvent",self.UpdateRenderer2) color3 = [0.0, 0.0, 0.0] # [0.5,0.5,0.5]# self.ren3 = vtk.vtkRenderer() self.renwini3 = wxVTKRenderWindowInteractor(self, -1) self.renwini3.GetRenderWindow().AddRenderer(self.ren3) interactorstyle3 = vtk.vtkInteractorStyleImage() self.renwini3.SetInteractorStyle(interactorstyle3) self.ren3.SetBackground(mainbackgroundcolor) cam1 = self.ren3.GetActiveCamera() cam1.SetViewUp(0, 1, 0) cam1.SetFocalPoint(4.75, -1.0, 0) cam1.SetPosition(4.75, -1.0, 4)#5.5, -0.5, 4) cam1.ParallelProjectionOn () self.ren3.ResetCamera() if antialiasing: self.renwini3.GetRenderWindow().SetAAFrames(12) self.ren3overlay = PlotOverlay.create(self, self.renwini3, self.ren3) interactionobserver3 = interactorstyle3.AddObserver("InteractionEvent",self.UpdateRenderer3) #1680 self.mgr = wx.aui.AuiManager(self) leftpanel = wx.Panel(self, -1, size = (0, 0)) self.paneInfo1 = wx.aui.AuiPaneInfo() self.paneInfo1.Bottom().Layer(0) #1 self.paneInfo1.Row(200) self.paneInfo1.BestSize([dispsize[0] - 200, 300]) self.paneInfo1.MinSize([200, 50]) self.paneInfo1.CaptionVisible(showcaption) self.paneInfo2 = wx.aui.AuiPaneInfo() self.paneInfo2.Left().Layer(1 ) #2 #~ self.paneInfo2.Position(0) self.paneInfo2.Row(0) self.paneInfo2.Resizable(False) #~ self.paneInfo2.MinSize([200, 300]) #~ self.paneInfo2.BestSize([200, 300]) self.paneInfo2.CaptionVisible(showcaption) self.paneInfo3 = wx.aui.AuiPaneInfo() self.paneInfo3.Center().Layer(2) #0 #~ self.paneInfo3.Position(0) self.paneInfo3.Row(1) self.paneInfo3.MinSize([50, 50]) self.paneInfo3.BestSize([700, 400]) #~ self.paneInfo3.BestSize([int((dispsize[0] - 200)/2), 200]) self.paneInfo3.CaptionVisible(showcaption) self.paneInfo4 = wx.aui.AuiPaneInfo() self.paneInfo4.Right().Layer(0) #0 #~ self.paneInfo4.Position(1) self.paneInfo4.Row(1) self.paneInfo4.CaptionVisible(showcaption) self.paneInfo4.BestSize([700, 400]) self.mgr.AddPane(self._create_pane1(), self.paneInfo2) self.mgr.AddPane(self.renwini1, self.paneInfo3) self.mgr.AddPane(self.renwini3, self.paneInfo1) self.mgr.AddPane(self.renwini2, self.paneInfo4) self.AddSequencePlotter() def _create_pane1(self): # instantiate the wxGlade-created frame ipf = GUI_wxglade.MyFrame(None, -1, "") # reparent the panel to us editorpanel = ipf.panel_1 editorpanel.Reparent(self) editorpanel.bitmap_button_1 = ipf.bitmap_button_1 editorpanel.bitmap_button_1_copy = ipf.bitmap_button_1_copy editorpanel.bitmap_button_3 = ipf.bitmap_button_3 editorpanel.bitmap_button_4 = ipf.bitmap_button_4 editorpanel.button_3 = ipf.button_3 editorpanel.button_3_copy = ipf.button_3_copy editorpanel.button_1 = ipf.button_1 editorpanel.button_2 = ipf.button_2 editorpanel.button_4 = ipf.button_4 editorpanel.radio_btn_1 = ipf.radio_btn_1 editorpanel.radio_btn_2 = ipf.radio_btn_2 editorpanel.radio_btn_3 = ipf.radio_btn_3 editorpanel.radio_btn_4 = ipf.radio_btn_4 editorpanel.radio_btn_5 = ipf.radio_btn_5 editorpanel.checkbox_6 = ipf.checkbox_6 editorpanel.checkbox_7 = ipf.checkbox_7 editorpanel.checkbox_8 = ipf.checkbox_8 editorpanel.tracercheckbox_1 = ipf.tracercheckbox_1 editorpanel.tracercheckbox_2 = ipf.tracercheckbox_2 editorpanel.tracercheckbox_3 = ipf.tracercheckbox_3 editorpanel.tracercheckbox_4 = ipf.tracercheckbox_4 editorpanel.tracercheckbox_5 = ipf.tracercheckbox_5 editorpanel.spin_ctrl_1 = ipf.spin_ctrl_1 editorpanel.spin_ctrl_2 = ipf.spin_ctrl_2 editorpanel.slider_1 = ipf.slider_1 editorpanel.slider_2 = ipf.slider_2 editorpanel.radio_btn_6 = ipf.radio_btn_6 editorpanel.radio_btn_7 = ipf.radio_btn_7 ipf.Destroy() self.editorpanel = editorpanel return self.editorpanel def BindEvents(self): self.editorpanel.bitmap_button_1.Bind(wx.EVT_BUTTON, self.OnSave1) self.editorpanel.bitmap_button_1_copy.Bind(wx.EVT_BUTTON, self.OnSave2) self.editorpanel.button_3.Bind(wx.EVT_BUTTON, self.OnLoad1) self.editorpanel.button_3_copy.Bind(wx.EVT_BUTTON, self.OnLoad2) self.editorpanel.bitmap_button_3.Bind(wx.EVT_BUTTON, self.OnHideBlue) self.editorpanel.bitmap_button_4.Bind(wx.EVT_BUTTON, self.OnHideYellow) self.editorpanel.button_1.Bind(wx.EVT_TOGGLEBUTTON, self.OnChangeFilters) self.editorpanel.button_2.Bind(wx.EVT_TOGGLEBUTTON, self.OnChangeFilters) self.editorpanel.button_4.Bind(wx.EVT_TOGGLEBUTTON, self.OnChangeFilters) self.editorpanel.checkbox_6.Bind(wx.EVT_CHECKBOX, self.OnShowBones) self.editorpanel.checkbox_7.Bind(wx.EVT_CHECKBOX, self.OnShowBonesXRAY) self.editorpanel.checkbox_8.Bind(wx.EVT_CHECKBOX, self.OnShowExorotation) self.editorpanel.radio_btn_1.Bind(wx.EVT_RADIOBUTTON, self.RegeneratePoses) self.editorpanel.radio_btn_2.Bind(wx.EVT_RADIOBUTTON, self.RegeneratePoses) self.editorpanel.radio_btn_3.Bind(wx.EVT_RADIOBUTTON, self.RegeneratePoses) self.editorpanel.radio_btn_4.Bind(wx.EVT_RADIOBUTTON, self.RegeneratePoses) self.editorpanel.radio_btn_5.Bind(wx.EVT_RADIOBUTTON, self.RegeneratePoses) self.editorpanel.slider_1.Bind(wx.EVT_SLIDER, self.OnSlider) self.editorpanel.slider_2.Bind(wx.EVT_SLIDER, self.OnSlider) self.editorpanel.tracercheckbox_1.Bind(wx.EVT_CHECKBOX, self.OnShowTracers) self.editorpanel.radio_btn_6.Bind(wx.EVT_RADIOBUTTON, self.RegeneratePCP) self.editorpanel.radio_btn_7.Bind(wx.EVT_RADIOBUTTON, self.RegeneratePCP) def _init_menubar(self): self.menu1 = wx.Menu() self.menu2 = wx.Menu() self.menu3 = wx.Menu() self.menuBar1 = wx.MenuBar() self.menu1.Append(help='Save blue collection', id=wxID_SAVE, kind=wx.ITEM_NORMAL, text='Save blue collection') self.Bind(wx.EVT_MENU, self.OnSave1, id=wxID_SAVE) tmpid = wx.NewId() self.menu1.Append(help='Save yellow collection', id=tmpid, kind=wx.ITEM_NORMAL, text='Save yellow collection') self.Bind(wx.EVT_MENU, self.OnSave2, id=tmpid) self.menu1.Append(help='Quit Application', id=wxID_QUIT, kind=wx.ITEM_NORMAL, text='Quit') self.Bind(wx.EVT_MENU, self.OnQuit, id=wxID_QUIT) tmp_id = wx.NewId() self.menu2.Append(help='Screenshot 1', id=tmp_id, kind=wx.ITEM_NORMAL, text='Screenshot 1') self.Bind(wx.EVT_MENU, self.StoreImage, id=tmp_id) self.menuBar1.Append(menu=self.menu1, title='File') self.menuBar1.Append(menu=self.menu2, title='Edit') self.menuBar1.Append(menu=self.menu3, title='Help') return self.menuBar1 def __init__(self, parent, root): self.parent = parent self._root = root self.timerCBcount = 0 self.appdir = self.ReadRootDirectory() self.timerbugged = False self.sequenceplotters = [] self.sequenceplotters_selectionboxes = [] self.sequenceplotcount = 0 self.scatterplotlist = [] self.imagenumber = 0 self.posesOn = True self.tracersOn = True self._init_ctrls() self.fillScene() self.widgets = WidgetCollection.create(self) self.tracer = TimeWindowTrace.create(self, self.renwini2, self.ren2) menuBar1 = self._init_menubar() self.SetMenuBar(menuBar1) self.BindEvents() self.Layout() self.Show() #~ def _init_coll_notebook2_Pages(self, parent): #~ parent.AddPage(imageId=-1, page=self.panel_1, select=True, #~ text='Default') #~ parent.AddPage(imageId=-1, page=self.measurepanel, select=True, #~ text='Measure Tools') def flip_y(self, y): return (self.renwini1.GetSize()[1] - y - 1) def StoreImage(self, whichone=1, high_res=1): newren = vtk.vtkRenderWindow() newren.OffScreenRenderingOn() newren.SetSize(2340, 1800) newren.AddRenderer(self.ren2) newren.Render() w2i = vtk.vtkWindowToImageFilter() w2i.SetInput(newren) w2i.SetMagnification(1) w2i.Update() pngWriter = vtk.vtkPNGWriter() pngWriter.SetInput(w2i.GetOutput()) #w2i.Modified() self.imagenumber = self.imagenumber+1 pngWriter.SetFileName('Screenshots/image%04d.png' % self.imagenumber) pngWriter.Write() newren.RemoveRenderer(self.ren2) def AddSequencePlotter(self): dispsize = wx.DisplaySize() paneInfoTime = wx.aui.AuiPaneInfo() paneInfoTime.Bottom().Layer(0) #1 paneInfoTime.Row(199 - self.sequenceplotcount) paneInfoTime.BestSize([dispsize[0] - 200, 50]) paneInfoTime.MinSize([200, 50]) paneInfoTime.CaptionVisible(False) self.sequenceplotcount = self.sequenceplotcount+1 sequenceplotter = Plotter.create(self, self._root) self.mgr.AddPane(sequenceplotter.iren, paneInfoTime) self.mgr.Update() self.sequenceplotters.append(sequenceplotter) sequenceplotter.ShowPlot() def AddScatter(self, plot1, plot2): stanceID1 = self.parent.Filters.plottedAngles[plot1] stanceID2 = self.parent.Filters.plottedAngles[plot2] xyValues1 = [] for i in range(0, len(self.parent.splineCollection)): if self.parent.Filters.FilterSingleSpline_WithoutVisualisation(\ self.parent.splineCollection[i], 0, i): xyValues1.append([self.parent.splineCollection[i]['stance'][stanceID1], self.parent.splineCollection[i]['stance'][stanceID2]]) xLabel1 = self.parent.Filters.jointAngleCollection[stanceID1]['description'] yLabel1 = self.parent.Filters.jointAngleCollection[stanceID2]['description'] xLabel1 = xLabel1.replace('\n', ' ') yLabel1 = yLabel1.replace('\n', ' ') xyValues2 = [] for i in range(0, len(self.parent.splineReferences)): if self.parent.Filters.FilterSingleSpline_WithoutVisualisation(\ self.parent.splineReferences[i], 1, i): xyValues2.append([self.parent.splineReferences[i]['stance'][stanceID1], self.parent.splineReferences[i]['stance'][stanceID2]]) xLabel2 = self.parent.Filters.jointAngleCollection[stanceID1]['description'] yLabel2 = self.parent.Filters.jointAngleCollection[stanceID2]['description'] xLabel2 = xLabel2.replace('\n', ' ') yLabel2 = yLabel2.replace('\n', ' ') data1 = xyValues1, xLabel1, yLabel1 data2 = xyValues2, xLabel2, yLabel2 scatter = Scatter.Scatter(self, data1, data2, stanceID1, stanceID2) self.scatterplotlist.append(scatter) def RemoveSequencePlotter(self, id): self.mgr.DetachPane(self.sequenceplotters[id].iren) self.sequenceplotters.pop(id) self.parent.Filters.RestartFiltering() self.parent.Filters.RestartFilteringReferences() def ReadRootDirectory(self): if hasattr(sys, 'frozen') and sys.frozen: appdir, exe = os.path.split(sys.executable) else: dirname = os.path.dirname(sys.argv[0]) if dirname and dirname != os.curdir: appdir = dirname else: appdir = os.getcwd() return appdir def fillScene(self): reader = vtk.vtkSTLReader() fname = os.path.join(self.appdir, 'torso.stl') reader.SetFileName(fname) output = reader.GetOutput() Normals = vtk.vtkPolyDataNormals() Normals.SetInput(output)#.GetOutput()) Normals.SplittingOff() Normals.ConsistencyOff() TriangleFilter = vtk.vtkTriangleFilter() TriangleFilter.SetInput(Normals.GetOutput()) TriangleFilter.Update() torsimapper = vtk.vtkPolyDataMapper() torsimapper.SetInput(TriangleFilter.GetOutput()) self.torsiactor = vtk.vtkActor() self.torsiactor.SetMapper(torsimapper) self.torsiactor.GetProperty().SetAmbientColor(1.0, 1.0, 1.0) self.torsiactor.GetProperty().SetAmbient(1.0) self.ren1.AddActor(self.torsiactor) def UpdateRenderer2(self, event, bla): a = self.ren2.GetActiveCamera().GetViewTransformMatrix() campos = self.ren2.GetActiveCamera().GetPosition() self.parent.blue_shader.AddShaderVariableFloat ("camPos", campos[0], campos[1], campos[2]) self.parent.blue_shader.AddShaderVariableFloat ("camproj1", a.GetElement(0,0), a.GetElement(1,0), a.GetElement(2,0), a.GetElement(3,0)) self.parent.blue_shader.AddShaderVariableFloat ("camproj2", a.GetElement(0,1), a.GetElement(1,1), a.GetElement(2,1), a.GetElement(3,1)) self.parent.blue_shader.AddShaderVariableFloat ("camproj3", a.GetElement(0,2), a.GetElement(1,2), a.GetElement(2,2), a.GetElement(3,2)) self.parent.blue_shader.AddShaderVariableFloat ("camproj4", a.GetElement(0,3), a.GetElement(1,3), a.GetElement(2,3), a.GetElement(3,3)) self.parent.yellow_shader.AddShaderVariableFloat ("camPos", campos[0], campos[1], campos[2]) self.parent.yellow_shader.AddShaderVariableFloat ("camproj1", a.GetElement(0,0), a.GetElement(1,0), a.GetElement(2,0), a.GetElement(3,0)) self.parent.yellow_shader.AddShaderVariableFloat ("camproj2", a.GetElement(0,1), a.GetElement(1,1), a.GetElement(2,1), a.GetElement(3,1)) self.parent.yellow_shader.AddShaderVariableFloat ("camproj3", a.GetElement(0,2), a.GetElement(1,2), a.GetElement(2,2), a.GetElement(3,2)) self.parent.yellow_shader.AddShaderVariableFloat ("camproj4", a.GetElement(0,3), a.GetElement(1,3), a.GetElement(2,3), a.GetElement(3,3)) def UpdateRenderer3(self, event, bla): self.ren3overlay.RefreshOverlay() def RegeneratePCP(self, event): self.parent.RegenerateSplineObjects() def RegeneratePoses(self, event): if self.editorpanel.radio_btn_5.GetValue() == True: sj = -1 elif self.editorpanel.radio_btn_1.GetValue() == True: sj = 0 elif self.editorpanel.radio_btn_2.GetValue() == True: sj = 1 elif self.editorpanel.radio_btn_3.GetValue() == True: sj = 2 elif self.editorpanel.radio_btn_4.GetValue() == True: sj = 3 #~ try: self.parent.stablejointindex = sj #0 = spine only, 1 = spine and clavicle etc. self.parent.RegeneratePoses() self.parent.Filters.RestartFiltering() self.parent.Filters.RestartFilteringReferences() #~ try: #~ self.Render() #~ except RuntimeError: #~ pass #~ except AttributeError: #~ print "Parent probably not linked. E31082009 A" def OnHideBlue(self, event): if self.parent.Filters.sessionvisible_A == True: fname = os.path.join(self.appdir, 'data_gray.jpg') self.editorpanel.bitmap_button_3.SetBitmapLabel(wx.Bitmap(fname)) self.editorpanel.button_3.Enabled = False self.parent.Filters.sessionvisible_A = False else: fname = os.path.join(self.appdir, 'data_blue.jpg') self.editorpanel.bitmap_button_3.SetBitmapLabel(wx.Bitmap(fname)) self.editorpanel.button_3.Enabled = True self.parent.Filters.sessionvisible_A = True self.parent.Filters.RestartFiltering() def OnHideYellow(self, event): if self.parent.Filters.sessionvisible_B == True: fname = os.path.join(self.appdir, 'data_gray.jpg') self.editorpanel.bitmap_button_4.SetBitmapLabel(wx.Bitmap(fname)) self.editorpanel.button_3_copy.Enabled = False self.parent.Filters.sessionvisible_B = False else: fname = os.path.join(self.appdir, 'data_yellow.jpg') self.editorpanel.bitmap_button_4.SetBitmapLabel(wx.Bitmap(fname)) self.editorpanel.button_3_copy.Enabled = True self.parent.Filters.sessionvisible_B = True self.parent.Filters.RestartFilteringReferences() def SetSliders(self, stance): if self.showsliders: for i in range(0,15): self.sliderlist[i].SetValue(stance[i]) def CustomPose(self, event): stance = [] if self.showsliders: for i in range(0,15): stance.append(self.sliderlist[i].GetValue()) try: act = self.parent.GeneratePhysique(stance, showbones = True) self.parent.pointWidget.SetPosition(self.parent.parent.blPos[13]) try: self.ren2.RemoveActor(self.parent.PoseActor9) except AttributeError: pass self.parent.PoseActor9.SetMapper(act.GetMapper()) self.ren2.AddActor(self.parent.PoseActor9) except AttributeError: print "Parent probably not linked. E31082009 B" self.Render(2) def Render(self, whichone = 0): if whichone == 0 or whichone == 1: self.renwini1.Render() if whichone == 0 or whichone == 2: self.renwini2.Render() if whichone == 0 or whichone == 3: self.renwini3.Render() def OnSave1(self, event): filename = self.parent.ExportSplines(0) self.editorpanel.button_3.SetLabel(filename) def OnSave2(self, event): filename = self.parent.ExportSplines(1) self.editorpanel.button_3_copy.SetLabel(filename) def OnQuit(self, event): self.parent.quit() def OnMean(self, event): self.parent.MedianMeanSpline(True) def OnMedian(self, event): self.parent.MedianMeanSpline(False) def OnShowBones(self, event): for bone in self.parent.bone_actorList: bone.SetVisibility(self.editorpanel.checkbox_6.GetValue()) self.Render(2) def OnShowBonesXRAY(self, event): if self.editorpanel.checkbox_7.GetValue(): for i in range(0, len(self.parent.bone_actorList)): self.parent.bone_actorList[i].SetMapper(self.parent.bone_mapperList[i]) self.parent.bone_actorList[i].SetProperty(self.parent.xray_shader) else: for i in range(0, len(self.parent.bone_actorList)): self.parent.bone_actorList[i].SetMapper(self.parent.bone_mapperListNormal[i]) self.parent.bone_actorList[i].SetProperty(vtk.vtkProperty()) self.parent.bone_actorList[i].GetProperty().SetColor(1, .97, .85) def OnShowExorotation(self, event): value = self.editorpanel.checkbox_8.GetValue() * 1.0 self.parent.exoblue_shader.AddShaderVariableFloat("Amplitude", value) self.parent.exoyellow_shader.AddShaderVariableFloat("Amplitude", value) self.AddScatter() def OnResetBones(self, event): self.SetSliders([0 for x in range(15)]) self.CustomPose(None) self.widgets.UpdateWidgets() def OnChangeFilters(self, event): self.parent.Filters.widgetFiltersOn = self.editorpanel.button_1.GetValue() self.parent.Filters.sequenceFilterOn = self.editorpanel.button_4.GetValue() if self.editorpanel.button_2.GetValue(): self.parent.pointWidget.SetEnabled(1) self.parent.pointWidget.SetPosition(self.parent.parent.blPos[13]) self.parent.ProbeData(event, None) else: self.parent.pointWidget.SetEnabled(0) self.parent.Filters.inversekinematicsOn = False self.parent.Filters.RestartFiltering() self.parent.Filters.RestartFilteringReferences() def OnLoad1(self, event): dlg = wx.FileDialog(self, message="Load motion collection", defaultDir=os.getcwd(), defaultFile="", wildcard="FoB file (*.txt)|*.txt", style=wx.OPEN | wx.CHANGE_DIR) if dlg.ShowModal() == wx.ID_OK: filename = dlg.GetPath() self.LoadFile1(filename) dlg.Destroy() def OnSlider(self, event): self.parent.Filters.UpdateShaderOpacity() def LoadFile1(self, path): self.parent.ClearData(0) importfile = open(path, 'r', 1) lines = importfile.readlines() for i in range (0, len (lines)/2): stance = eval(lines[i*2]) blPos = eval(lines[i*2+1]) self.parent.AddSpline(stance, blPos, updatewidget = False, referenceSpline = False) importfile.close() splitpath = os.path.split(path) self.editorpanel.button_3.SetLabel(splitpath[len(splitpath)-1]) self.widgets.UpdateWidgets() def OnLoad2(self, event): dlg = wx.FileDialog(self, message="Load motion collection", defaultDir=os.getcwd(), defaultFile="", wildcard="FoB file (*.txt)|*.txt", style=wx.OPEN | wx.CHANGE_DIR) if dlg.ShowModal() == wx.ID_OK: filename = dlg.GetPath() self.LoadFile2(filename) dlg.Destroy() def LoadFile2(self, path): self.parent.ClearData(1) importfile = open(path, 'r', 1) lines = importfile.readlines() for i in range (0, len (lines)/2): stance = eval(lines[i*2]) stance[6] = stance[6] + 13 stance[8] = stance[8] + 10 stance[9] = stance[9] - 7 blPos = eval(lines[i*2+1]) self.parent.AddSpline(stance, blPos, updatewidget = False, referenceSpline = True) importfile.close() splitpath = os.path.split(path) self.editorpanel.button_3_copy.SetLabel(splitpath[len(splitpath)-1]) self.widgets.UpdateWidgets() def JointClicked(self, event):# calledBy, event): x,y = event.GetX(), event.GetY() vtk_y = self.flip_y(y) self.cellpicker.Pick(x, vtk_y, 0, self.ren1overlay.renXannotation) if self.cellpicker.GetPointId() < 0: self.renwini1.OnButtonDown(event) else: act = self.cellpicker.GetActor() #if act!=None: if act in [self.ren1overlay.spineact,\ self.ren1overlay.clavact,\ self.ren1overlay.scapact,\ self.ren1overlay.GHact,\ self.ren1overlay.ELact]: self.ren1overlay.ShowMenu(act) else: self.renwini1.OnButtonDown(event) def UpdateSequencePlot(self, stanceIndex, whichplot=0, whichdata=0): label = self.parent.Filters.jointAngleCollection[stanceIndex]['description'] label = label.replace('\n', ' ') if whichdata==0: self.sequenceplotters[whichplot].plotcolor = (0.7, 0.7, 1.0) else: self.sequenceplotters[whichplot].plotcolor = (1.0, 1.0, 0.7) self.sequenceplotters[whichplot].label = label self.sequenceplotters[whichplot].yValues1 = [] self.sequenceplotters[whichplot].whichdata = whichdata if whichdata==0: for i in range(0, len(self.parent.splineCollection)): self.sequenceplotters[whichplot].yValues1.append(self.parent.splineCollection[i]['stance'][stanceIndex]/90.0) else: for i in range(0, len(self.parent.splineReferences)): self.sequenceplotters[whichplot].yValues1.append(self.parent.splineReferences[i]['stance'][stanceIndex]/90.0) #~ print self.sequenceplotters[whichplot].yValues1 self.sequenceplotters[whichplot].CreatePlot() self.sequenceplotters[whichplot].ShowPlot() self.sequenceplotters[whichplot].iren.Render() def UpdateSequencePlotOverlays(self): for sequenceplotter in self.sequenceplotters: sequenceplotter.ShowOverlay() def OnShowTracers(self, event): if self.editorpanel.tracercheckbox_1.GetValue()==False: self.tracer.ClearTraces(0) self.tracer.ClearTraces(1) self.Render() def timerCB(self, calledBy, event): if not self.timerbugged: self.timerCBcount = self.timerCBcount + 1 try: self.parent.PlayShader() if self.parent.Filters.initiateFilterTimer == False: self.parent.Filters.FilterAllStepper() if self.parent.Filters.initiateFilterReferencesTimer == False: self.parent.Filters.FilterAllReferenceStepper() try: self.Render(2) self.Render(3) except RuntimeError: pass if self.timerCBcount%10 ==0: for scatterplot in self.scatterplotlist: scatterplot.UpdatePlot() except AttributeError: self.timerbugged = True print "Timed events not working. The parent is probably not linked. E13102009" else: time.sleep(1) class MyApp(wx.App): def OnInit(self): frame = wxFrame(None, None) #~ frame.sequenceplotter.yValues1 = [0.3, 0.1, 0.4, 0.5, 0.9] #~ frame.sequenceplotter.label = "Hello there!" #~ frame.sequenceplotter.CreatePlot() #~ frame.sequenceplotter.ShowPlot() frame.Show() self.SetTopWindow(frame) return 1 if __name__ == "__main__": app = MyApp(0) app.MainLoop()
Python
import time import wx import vtk import math import numpy import vtktudoss try: import extended.BaseCalc as BaseCalc except ImportError: import BaseCalc def create(parent): return InverseKinematics(parent) class InverseKinematics: constantangle = 0.5 def __init__(self, parent): print "InverseKinematics module loaded." self.parent = parent self.baseCalc = BaseCalc.create(self, self) def SingleGradient(self, cor, axis, tip, target): ToTip = tip - cor CorToTarget = target - cor ToTarget = target - tip movement_vector = numpy.cross(ToTip, axis) movement_vector = movement_vector/ numpy.linalg.norm(movement_vector) ToTarget = ToTarget/ numpy.linalg.norm(ToTarget) gradient = numpy.dot(movement_vector, ToTarget) #~ controle_as = numpy.cross(CorToTarget, ToTip) #determines + or - angle #~ print "controle_as: ", controle_as #~ controle_as = controle_as/ numpy.linalg.norm(controle_as) #~ print "controle_as: ", controle_as #~ controle_hoek = numpy.dot(controle_as, axis) #~ if controle_hoek>0: #~ ch = 1 #~ else : #~ ch = -1 return gradient def Distance(self, a, b): return numpy.linalg.norm(a-b) #~ def DetermineGradients(self, start, target, OXYZ): #~ for i in range(0, len(stance_rates)/3): #~ stance_rates[0] = self.SingleGradient(c, a, X_axis, b) #~ stance_rates[1] = self.SingleGradient(c, a, Y_axis, b) #~ stance_rates[2] = self.SingleGradient(c, a, Z_axis, b) #~ for i in range(0, len(stance_rates)): #~ if numpy.isnan(stance_rates[i]): #~ stance_rates[i] = 0.0 #~ elif stance_rates[i] < self.stance_min[i]: #~ stance_rates[i] = self.stance_min[i] #~ elif stance_rates[i] > self.stance_max[i]: #~ stance_rates[i] = self.stance_max[i] #~ print stance_rates[0] #~ print stance_rates[1] #~ print stance_rates[2] #~ for i in range(0, len(stance)): #~ stance[i] = stance[i] + stance_rates[i] * self.constantangle #~ return stance_rate def Run(self, start, target): start = numpy.array(start) target = numpy.array(target) dist = self.Distance(start, target) k = 85 old_gradients = [0.0]*15 speed = [0.0]*15 newStance = self.parent.lastStance[:] while dist>2 and k>0: #~ print "" #~ for i in range(0, 15): stance_rate = [0.0]*15 origin = numpy.array([0,0,0]) current_elevation_plane_of_child = self.parent.lastStance[1] x_parent = [1,0,0] #self.parent.parent.OXYZThorax[1] t = vtk.vtkTransform() t.RotateY(current_elevation_plane_of_child) rotationaxis = t.TransformPoint(x_parent) stance_rate[0] = self.SingleGradient(origin, rotationaxis, start, target) rotationaxis = numpy.array(self.parent.parent.OXYZThorax[2]) stance_rate[2] = -self.SingleGradient(origin, rotationaxis, start, target) rotationaxis = numpy.array([0,1,0]) stance_rate[1] = self.SingleGradient(origin, rotationaxis, start, target) origin = numpy.array(self.parent.parent.blPos[4]) current_elevation_plane_of_child = self.parent.lastStance[4] x_parent = self.parent.parent.OXYZThorax[1] t = vtk.vtkTransform() t.RotateY(current_elevation_plane_of_child) rotationaxis = t.TransformPoint(x_parent) stance_rate[3] = self.SingleGradient(origin, rotationaxis, start, target) rotationaxis = numpy.array(self.parent.parent.Right_OXYZClavicle[2]) stance_rate[5] = -self.SingleGradient(origin, rotationaxis, start, target) stance_rate[4] = stance_rate[2] origin = numpy.array(self.parent.parent.blPos[6]) current_elevation_plane_of_child = self.parent.lastStance[7] x_parent = self.parent.parent.Right_OXYZClavicle[1] t = vtk.vtkTransform() t.RotateY(current_elevation_plane_of_child) rotationaxis = t.TransformPoint(x_parent) stance_rate[6] = self.SingleGradient(origin, rotationaxis, start, target) rotationaxis = numpy.array(self.parent.parent.Right_OXYZScapula[2]) stance_rate[8] = -self.SingleGradient(origin, rotationaxis, start, target) stance_rate[7] = stance_rate[5] origin = numpy.array(self.parent.parent.blPos[24]) current_elevation_plane_of_child = self.parent.lastStance[10] x_parent = self.parent.parent.Right_OXYZScapula[1] t = vtk.vtkTransform() t.RotateY(current_elevation_plane_of_child) rotationaxis = t.TransformPoint(x_parent) stance_rate[9] = self.SingleGradient(origin, rotationaxis, start, target) rotationaxis = numpy.array(self.parent.parent.Right_OXYZHumerus[2]) stance_rate[11] = -self.SingleGradient(origin, rotationaxis, start, target) stance_rate[10] = stance_rate[8] origin = numpy.array(self.parent.parent.Right_midELEM) current_elevation_plane_of_child = self.parent.lastStance[13] x_parent = self.parent.parent.Right_OXYZHumerus[1] t = vtk.vtkTransform() t.RotateY(current_elevation_plane_of_child) rotationaxis = t.TransformPoint(x_parent) stance_rate[12] = self.SingleGradient(origin, rotationaxis, start, target) rotationaxis = numpy.array(self.parent.parent.Right_OXYZForearm[2]) stance_rate[14] = -self.SingleGradient(origin, rotationaxis, start, target) stance_rate[13] = stance_rate[11] for i in range(0,3): stance_rate[i] = 0 newStance = self.parent.lastStance[:] for i in range(0, len(stance_rate)): if numpy.isnan(stance_rate[i]): stance_rate[i] = 0 #~ have we gone past it? if cmp(stance_rate[i], 0) != cmp(old_gradients[i], 0): #~ newStance[i] = newStance[i] - speed[i] * old_gradients[i] / (stance_rate[i]-old_gradients[i]) #~ newStance[i] = newStance[i] - speed[i] speed[i] = 0# speed[i] / 2 else: speed[i] = speed[i] + stance_rate[i] newStance[i] = newStance[i] + speed[i] old_gradients[i] = stance_rate[i] if i == 3: if newStance[i] < 0: newStance[i] = 0 elif newStance[i] > 20: newStance[i] = 20 if i == 4: if newStance[i] < -15: newStance[i] = -15 elif newStance[i] > 15: newStance[i] = 15 if i == 5: if newStance[i] < -30: newStance[i] = -30 elif newStance[i] > -12: newStance[i] = -12 for j in range(0, len(self.parent.Filters.jointAngleCollection)): if self.parent.Filters.jointAngleCollection[j]['stanceID']==i: if newStance[i] < self.parent.Filters.jointAngleCollection[j]['min1']: newStance[i] = self.parent.Filters.jointAngleCollection[j]['min1'] elif newStance[i] > self.parent.Filters.jointAngleCollection[j]['max1']: newStance[i] = self.parent.Filters.jointAngleCollection[j]['max1'] #~ print newStance #~ self.parent.GeneratePhysique(newStance, showbones=True) self.parent.GeneratePhysique(newStance, showbones=False) #~ self.parent.gui.Render(2) start = numpy.array(self.parent.parent.blPos[13]) dist = self.Distance(self.parent.parent.blPos[13], target) #~ print dist k = k-1 if k == 0: return -1 else: return newStance def Buildobbtree(self): self.parent.kdpolydata.Update() self.cKdTree = vtktudoss.vtkCKdTree() self.cKdTree.SetInput(0, self.parent.kdpolydata) self.cKdTree.SetBoxsize(7.0) self.cKdTree.BuildKdTree() idlist = 0 for i in range(0, len(self.parent.splineCollection)): spline = self.parent.splineCollection[i] self.parent.Filters.HideSpline(spline) self.previoussplines = [] if self.parent.splineReferences != []: self.parent.kdpolydata2.Update() self.cKdTree2 = vtktudoss.vtkCKdTree() self.cKdTree2.SetInput(0, self.parent.kdpolydata2) self.cKdTree2.SetBoxsize(7.0) self.cKdTree2.BuildKdTree() idlist = 0 for i in range(0, len(self.parent.splineReferences)): spline = self.parent.splineReferences[i] self.parent.Filters.HideSpline(spline) self.previoussplines2 = [] def Queryobbtree(self, point, currentelbowposition): previoussplineslength = len(self.previoussplines) for i in range(0, previoussplineslength): splineNr = self.previoussplines[0] spline = self.parent.splineCollection[splineNr] self.previoussplines.pop(0) self.parent.Filters.FilterSingleSpline(spline, False, splineNr) #Find new poses that are within range... laststance = None laststance_minimum_elbowdistance2 = 100000.0 self.cKdTree.QueryRegion(point) typearray = self.cKdTree.Getptidtypearray() if typearray.GetNumberOfTuples()>0: for i in range(0, typearray.GetNumberOfTuples()): splineNr = typearray.GetValue(i) self.previoussplines.append(splineNr) spline = self.parent.splineCollection[splineNr] if self.parent.Filters.FilterSingleSpline(spline, False, splineNr): poseActor = spline['poseActor'] elbowposition = poseActor.GetMapper()\ .GetInput().GetPoints().GetPoint(10) elbowdistance2 = vtk.vtkMath().Distance2BetweenPoints(currentelbowposition, elbowposition) if laststance_minimum_elbowdistance2 > elbowdistance2: laststance = spline['stance'] laststance_minimum_elbowdistance2 = elbowdistance2 if self.parent.splineReferences != []: previoussplines2length = len(self.previoussplines2) for i in range(0, previoussplines2length): splineNr = self.previoussplines2[0] spline = self.parent.splineReferences[self.previoussplines2[0]] self.previoussplines2.pop(0) self.parent.Filters.FilterSingleSpline(spline, True, splineNr) self.cKdTree2.QueryRegion(point) typearray = self.cKdTree2.Getptidtypearray() for i in range(0, typearray.GetNumberOfTuples()): splineNr = typearray.GetValue(i) self.previoussplines2.append(splineNr) spline = self.parent.splineReferences[splineNr] if self.parent.Filters.FilterSingleSpline(spline, True, splineNr): poseActor = spline['poseActor'] elbowposition = poseActor.GetMapper()\ .GetInput().GetPoints().GetPoint(10) elbowdistance2 = vtk.vtkMath().Distance2BetweenPoints(currentelbowposition, elbowposition) if laststance_minimum_elbowdistance2 > elbowdistance2: laststance = spline['stance'] laststance_minimum_elbowdistance2 = elbowdistance2 return laststance class MyApp(wx.App): def OnInit(self): applic = InverseKinematics(None) elbowOXYZ = [[0,0,0], [1,0,0], [0,1,0], [0,0,1]] GHpos = [0, 0, -10] elbowpos = [0,0,0] handpos = [10,0,0] handtarget = [7.07,0,7.07] stance = [0, 0, 90] applic.stance_min = [0,-10,0] applic.stance_max = [0,10,0] stance_rates = applic.DetermineGradients(handpos, handtarget, elbowOXYZ) print stance_rates return 1 if __name__ == "__main__": app = MyApp(0) app.MainLoop()
Python
import time import wx import vtk import math import numpy import vtktudoss import os, sys try: import extended.BaseCalc as BaseCalc except ImportError: import BaseCalc #~ [wxID1] = [wx.NewId() for __init__ in range(1)] def create(parent, renderwindow, primaryrenderer): return WidgetOverlay(parent, renderwindow, primaryrenderer) class WidgetOverlay: def __init__(self, parent, renderwindow, primaryrenderer): print "WidgetOverlay module loaded." self.parent = parent self.renderwindow = renderwindow.GetRenderWindow() self.interactorstyle = renderwindow.GetInteractorStyle() self.renX = primaryrenderer self.baseCalc = BaseCalc.create(self, self) self.windowsize = renderwindow.GetSize() self.delayRegeneration = False #~ self.Bind(wx.EVT_RIGHT_DCLICK, self.OnRightClick, mitem) self.InitializeAnnotationLayer() self.InitializeSubdrawLayer() self.FillOverlay() def InitializeAnnotationLayer(self): try: self.renderwindow.RemoveRenderer(self.renXannotation) except AttributeError: pass self.renderwindow.SetNumberOfLayers(2) self.renXannotation = vtk.vtkRenderer() self.renX.SetLayer(1) self.renXannotation.SetLayer(2) self.renXannotation.InteractiveOff() self.renXannotation.SetActiveCamera(self.renX.GetActiveCamera()) self.renderwindow.AddRenderer(self.renXannotation) def InitializeSubdrawLayer(self): try: self.renderwindow.RemoveRenderer(self.renXsubdraw) except AttributeError: pass self.renderwindow.SetNumberOfLayers(3) self.renXsubdraw = vtk.vtkRenderer() self.renXsubdraw.SetLayer(0) self.renXsubdraw.SetBackground([0.3, 0.3, 0.3]) self.renXsubdraw.InteractiveOff() self.renXsubdraw.SetActiveCamera(self.renX.GetActiveCamera()) self.renderwindow.AddRenderer(self.renXsubdraw) reader = vtk.vtkSTLReader() fname = os.path.join(self.parent.appdir, 'torso_shell.stl') reader.SetFileName(fname) output = reader.GetOutput() Normals = vtk.vtkPolyDataNormals() Normals.SetInput(output)#.GetOutput()) Normals.SplittingOff() Normals.ConsistencyOff() TriangleFilter = vtk.vtkTriangleFilter() TriangleFilter.SetInput(Normals.GetOutput()) TriangleFilter.Update() torsimapper = vtk.vtkPolyDataMapper() torsimapper.SetInput(TriangleFilter.GetOutput()) self.torsiactor = vtk.vtkActor() self.torsiactor.SetMapper(torsimapper) #~ self.torsiactor.SetPosition(0, -0.7, 0) #self.torsiactor.GetProperty().SetDiffuseColor(0.6, 0.6, 0.6) #self.torsiactor.GetProperty().SetDiffuseColor(1.6, 0.6, 0.6) self.torsiactor.GetProperty().SetDiffuse(0) self.torsiactor.GetProperty().SetAmbientColor(0.0, 0.0, 0.0) self.torsiactor.GetProperty().SetAmbient(1.0) self.renXsubdraw.AddActor(self.torsiactor) def FillOverlay(self): #~ sph = vtk.vtkSphereSource() #~ sph.SetPhiResolution(32) #~ sph.SetThetaResolution(32) #~ sph.SetRadius(0.1) stlreader = vtk.vtkSTLReader() stlreader.SetFileName("jointnudge.stl") stlreader.Update() t = vtk.vtkTransform() t.Scale([10, 10, 10]) #~ t.RotateX(90) #~ t.Translate(7,20,-15) t.Update() tf = vtk.vtkTransformFilter() tf.SetTransform(t) tf.SetInput(stlreader.GetOutput()) normalout = vtk.vtkPolyDataNormals() normalout.SetInput(tf.GetOutput()) normalout.SetFeatureAngle(60.0) sph = normalout offset = 0.8 #spine spinemap = vtk.vtkPolyDataMapper() self.spineact = vtk.vtkActor() self.spineact.SetMapper(spinemap) self.spineact.GetProperty().SetColor(1.0, 1.0, 0.0) spinemap.SetInput(sph.GetOutput()) self.spineact.SetPosition(0, 1.73, 9.615)#offset,1,1.4) self.renXannotation.AddActor(self.spineact) #~ self.parent.cellpicker.AddPickList(self.spineact) #clavicle clavmap = vtk.vtkPolyDataMapper() self.clavact = vtk.vtkActor() self.clavact.GetProperty().SetColor(0.0, 1.0, 1.0) self.clavact.SetMapper(clavmap) clavmap.SetInput(sph.GetOutput()) self.clavact.SetPosition(-3.531, 3.594, 23.757)#offset - 0.2,-0.1,1.5) self.renXannotation.AddActor(self.clavact) #~ self.parent.cellpicker.AddPickList(self.clavact) #scapula scapmap = vtk.vtkPolyDataMapper() self.scapact = vtk.vtkActor() self.scapact.SetMapper(scapmap) self.scapact.GetProperty().SetColor(0.0, 1.0, 0.0) scapmap.SetInput(sph.GetOutput()) self.scapact.SetPosition(4.441, 7.518, 25.701)#offset + 0.4,-0.2,1.75) self.renXannotation.AddActor(self.scapact) #~ self.parent.cellpicker.AddPickList(self.scapact) #GH ghmap = vtk.vtkPolyDataMapper() self.GHact = vtk.vtkActor() self.GHact.SetMapper(ghmap) self.GHact.GetProperty().SetColor(1.0, 0.0, 1.0) ghmap.SetInput(sph.GetOutput()) self.GHact.SetPosition(1.583, 10.187, 22.778)#offset + 0.2,0,1.9) self.renXannotation.AddActor(self.GHact) #~ self.parent.cellpicker.AddPickList(self.GHact) #EL ELmap = vtk.vtkPolyDataMapper() self.ELact = vtk.vtkActor() self.ELact.GetProperty().SetColor(1.0, 0.0, 0.0) self.ELact.SetMapper(ELmap) ELmap.SetInput(sph.GetOutput()) self.ELact.SetPosition(2.188, 20.051, 21.824)#offset + 0.17, -0.13, 3.0) self.renXannotation.AddActor(self.ELact) #~ self.parent.cellpicker.AddPickList(self.ELact) wristpos = (2.942, 32.59, 22.129)#offset -0.1, -0.13, 4.0) self.GHGlobal = vtk.vtkActor() #SpanLines linelength = 2.0 verticalPoints = vtk.vtkPoints() verticalPoints.SetNumberOfPoints(6) verticalPoints.InsertPoint(0, self.spineact.GetPosition()) verticalPoints.InsertPoint(1, self.clavact.GetPosition()) verticalPoints.InsertPoint(2, self.scapact.GetPosition()) verticalPoints.InsertPoint(3, self.GHact.GetPosition()) verticalPoints.InsertPoint(4, self.ELact.GetPosition()) verticalPoints.InsertPoint(5, wristpos) verticalLines = vtk.vtkCellArray() for i in range(0,5): verticalLines.InsertNextCell(2) verticalLines.InsertCellPoint(i) verticalLines.InsertCellPoint(i+1) verticalGuideline = vtk.vtkPolyData() verticalGuideline.SetLines(verticalLines) verticalGuideline.SetPoints(verticalPoints) verticalGuideline.Update() profileTubes = vtk.vtkTubeFilter() profileTubes.SetNumberOfSides(12) profileTubes.SetInput(verticalGuideline) profileTubes.SetRadius(.1) #~ self.TubeMapper = vtk.vtkPolyDataMapper() #~ self.TubeActor.SetMapper(self.TubeMapper) #~ self.TubeActor.GetProperty().SetAmbient(1.0) #~ self.TubeMapper.SetInput(profileTubes.GetOutput()) Linemap = vtk.vtkPolyDataMapper() Lineact = vtk.vtkActor() Lineact.SetMapper(Linemap) Lineact.GetProperty().SetDiffuse(0) Lineact.GetProperty().SetAmbientColor(0,0,0.4) Lineact.GetProperty().SetAmbient(1) Linemap.SetInput(profileTubes.GetOutput()) self.renXannotation.AddActor(Lineact) def ShowMenu(self, act): self.selectedJoint = act if self.selectedJoint == self.spineact: keyword = 'Thorax' elif self.selectedJoint == self.clavact: keyword = 'Clavicle' elif self.selectedJoint == self.scapact: keyword = 'Scapula' elif self.selectedJoint == self.GHact: keyword = 'Humerus' elif self.selectedJoint == self.ELact: keyword = 'Elbow' jAngles = self.parent.parent.Filters.jointAngleCollection Filters = self.parent.parent.Filters menuFiltersAdd = wx.Menu() for i in jAngles: verhaal = i['description'] verhaal = verhaal.replace('\n', ' ') if verhaal.find(keyword) != -1: tmpid = wx.NewId() menuFiltersAdd.Append(id = tmpid, text=verhaal) self.parent.Bind(wx.EVT_MENU, lambda evt, temp=verhaal,\ adding=1: self.OnMenuFilters(evt, temp, adding), id = tmpid ) menuFiltersRemove = wx.Menu() nr_of_filters = len(Filters.filteredAngles) for i in jAngles: verhaal = i['description'] verhaal = verhaal.replace('\n', ' ') if verhaal.find(keyword) != -1: for j in range(0, nr_of_filters): if Filters.filteredAngles[j] == i['stanceID']: tmpid = wx.NewId() menuFiltersRemove.Append(id = tmpid, text=verhaal) self.parent.Bind(wx.EVT_MENU, lambda evt, temp=verhaal,\ adding=0: self.OnMenuFilters(evt, temp, adding), id = tmpid ) tmpid = wx.NewId() menuFiltersRemove.Append(id = tmpid, text='All') self.parent.Bind(wx.EVT_MENU, self.OnMenuRemoveAllFilters, id = tmpid) menuPlotAdd = wx.Menu() for i in jAngles: verhaal = i['description'] verhaal = verhaal.replace('\n', ' ') if verhaal.find(keyword) != -1: tmpid = wx.NewId() menuPlotAdd.Append(id = tmpid, text=verhaal) self.parent.Bind(wx.EVT_MENU, lambda evt, temp=verhaal,\ adding=1: self.OnMenuPlot(evt, temp, adding), id = tmpid ) menuPlotRemove = wx.Menu() nr_of_plots = len(Filters.plottedAngles) for i in jAngles: verhaal = i['description'] verhaal = verhaal.replace('\n', ' ') if verhaal.find(keyword) != -1: for j in range(0, nr_of_plots): if Filters.plottedAngles[j] == i['stanceID']: tmpid = wx.NewId() menuPlotRemove.Append(id = tmpid, text=verhaal) self.parent.Bind(wx.EVT_MENU, lambda evt, temp=verhaal,\ adding=0: self.OnMenuPlot(evt, temp, adding), id = tmpid ) tmpid = wx.NewId() menuPlotRemove.Append(id = tmpid, text='All') self.parent.Bind(wx.EVT_MENU, self.OnMenuRemoveAllPlot, id = tmpid) menuBothAdd = wx.Menu() for i in jAngles: verhaal = i['description'] verhaal = verhaal.replace('\n', ' ') if verhaal.find(keyword) != -1: tmpid = wx.NewId() menuBothAdd.Append(id = tmpid, text=verhaal) self.parent.Bind(wx.EVT_MENU, lambda evt, temp=verhaal,\ adding=1: self.OnMenuBoth(evt, temp, adding), id = tmpid ) menuBothRemove = wx.Menu() nr_of_filters = len(Filters.filteredAngles) nr_of_plots = len(Filters.plottedAngles) for i in jAngles: verhaal = i['description'] verhaal = verhaal.replace('\n', ' ') if verhaal.find(keyword) != -1: already_added = False for j in range(0, nr_of_filters): if Filters.filteredAngles[j] == i['stanceID']: tmpid = wx.NewId() menuBothRemove.Append(id = tmpid, text=verhaal) self.parent.Bind(wx.EVT_MENU, lambda evt, temp=verhaal,\ adding=0: self.OnMenuBoth(evt, temp, adding), id = tmpid ) already_added = True if not already_added: for j in range(0, nr_of_plots): if Filters.plottedAngles[j] == i['stanceID']: tmpid = wx.NewId() menuBothRemove.Append(id = tmpid, text=verhaal) self.parent.Bind(wx.EVT_MENU, lambda evt, temp=verhaal,\ adding=0: self.OnMenuBoth(evt, temp, adding), id = tmpid ) tmpid = wx.NewId() menuBothRemove.Append(id = tmpid, text='All') self.parent.Bind(wx.EVT_MENU, self.OnMenuRemoveAllBoth, id = tmpid) menuFilters = wx.Menu() menuFilters.AppendSubMenu(submenu=menuFiltersAdd, text='Add') menuFilters.AppendSubMenu(submenu=menuFiltersRemove, text='Remove') menuPlot = wx.Menu() menuPlot.AppendSubMenu(submenu=menuPlotAdd, text='Add') menuPlot.AppendSubMenu(submenu=menuPlotRemove, text='Remove') menuBoth = wx.Menu() menuBoth.AppendSubMenu(submenu=menuBothAdd, text='Add') menuBoth.AppendSubMenu(submenu=menuBothRemove, text='Remove') menu4 = wx.Menu() menu4.AppendSubMenu(submenu=menuFilters, text='Filter') menu4.AppendSubMenu(submenu=menuPlot, text='Plot') menu4.AppendSubMenu(submenu=menuBoth, text='Filter and Plot') mouseposition = wx.GetMousePosition() self.parent.PopupMenu( menu4, (mouseposition[0], mouseposition[1] - 48)) menu4.Destroy() def OnMenuFilters(self, event, descript, adding): jAngles = self.parent.parent.Filters.jointAngleCollection for i in range(0, len(jAngles)): verhaal = jAngles[i]['description'] verhaal = verhaal.replace('\n', ' ') if verhaal == descript: stanceID = jAngles[i]['stanceID'] if adding: self.OnAddFilter(stanceID) else: self.OnRemoveFilter(stanceID) def OnMenuPlot(self, event, descript, adding): jAngles = self.parent.parent.Filters.jointAngleCollection for i in range(0, len(jAngles)): verhaal = jAngles[i]['description'] verhaal = verhaal.replace('\n', ' ') if verhaal == descript: stanceID = jAngles[i]['stanceID'] if adding: self.OnAddPlot(stanceID) else: self.OnRemovePlot(stanceID) def OnMenuBoth(self, event, descript, adding): self.OnMenuFilters(event, descript, adding) self.OnMenuPlot(event, descript, adding) def OnMenuRemoveAllBoth(self, event): self.OnMenuRemoveAllFilters(event) self.OnMenuRemoveAllPlot(event) def OnMenuRemoveAllFilters(self, event): self.delayRegeneration = True for i in range(0, 18): self.OnRemoveFilter(i) self.delayRegeneration = False self.OnRemoveFilter(-1) def OnMenuRemoveAllPlot(self, event): self.delayRegeneration = True for i in range(0, 18): self.OnRemovePlot(i) self.delayRegeneration = False self.OnRemovePlot(-1) def OnAddFilter(self, stanceID): Filters = self.parent.parent.Filters for filter in Filters.jointAngleCollection: if filter['stanceID'] == stanceID: Filters.filteredAngles.append(filter['stanceID']) filter['widget'].EnabledOn() self.parent.widgets.UpdateWidgets() self.parent.Render() def OnAddPlot(self, stanceID): Filters = self.parent.parent.Filters for filter in Filters.jointAngleCollection: if filter['stanceID'] == stanceID: Filters.plottedAngles.append(filter['stanceID']) self.parent.parent.RegenerateSplineObjects() self.parent.ren3overlay.RefreshOverlay() self.parent.Render() def OnRemoveFilter(self, stanceID): Filters = self.parent.parent.Filters nr_of_plots = len(Filters.filteredAngles) for i in range(0, nr_of_plots): j = nr_of_plots - i - 1 if Filters.filteredAngles[j] == stanceID or stanceID==-1: Filters.jointAngleCollection[Filters.filteredAngles[j]]['widget'].EnabledOff() Filters.filteredAngles.pop(j) self.parent.widgets.UpdateWidgets() if not self.delayRegeneration: self.parent.parent.Filters.RestartFiltering() self.parent.Render() def OnRemovePlot(self, stanceID): Filters = self.parent.parent.Filters nr_of_plots = len(Filters.plottedAngles) for i in range(0, nr_of_plots): j = nr_of_plots - i - 1 if Filters.plottedAngles[j] == stanceID or stanceID==-1: Filters.plottedAngles.pop(j) if not self.delayRegeneration: self.parent.parent.RegenerateSplineObjects() self.parent.ren3overlay.RefreshOverlay() self.parent.Render()
Python
import matplotlib matplotlib.use('Agg') from matplotlib.figure import Figure from matplotlib.backends.backend_agg import FigureCanvasAgg import pylab as p import time import vtk import wx from vtk.wx.wxVTKRenderWindowInteractor import * def create(parent, root): return Plotter(parent, root) class Plotter(): def __init__(self, parent, root): self.parent = parent self._root = root self.whichdata = 0 self.filtervalues = [] self.yValues1 = [0] self.lastclicktime = 0 self.label = "Values-over-time plot, right-click to select parameter." self.plotcolor = (1.0, 1.0, 1.0) self.cursor = -1 self.DefineLookupTable() self.SetupRenderWindow() #~ self.ShowPlot() def SetupRenderWindow(self): renwini4 = wxVTKRenderWindowInteractor(self.parent, -1) self.iren = renwini4 self.renWin = renwini4.GetRenderWindow() self.iren.Unbind(wx.EVT_LEFT_DOWN) self.iren.Unbind(wx.EVT_RIGHT_DOWN) self.iren.Bind(wx.EVT_LEFT_DOWN, self.PlotSelected) self.iren.Bind(wx.EVT_RIGHT_DOWN, self.ShowMenu) self.ren = vtk.vtkRenderer() self.renWin.AddRenderer(self.ren) def ShowMenu(self, event): #~ x, y = self.iren.GetEventPosition() #add parameter menu jAngles = self.parent.parent.Filters.jointAngleCollection menu2 = wx.Menu() for i in jAngles: tmpid = wx.NewId() verhaal = i['description'] verhaal = verhaal.replace('\n', ' ') menu2.Append(id = tmpid, text=verhaal) self.parent.Bind(wx.EVT_MENU, lambda evt, temp=verhaal, dataset=0: self.OnMenu(evt, temp, dataset), id = tmpid ) menu1 = wx.Menu() menu1.AppendSubMenu(submenu=menu2, text='Dataset 1') if len(self.parent.parent.splineReferences) > 0: menu3 = wx.Menu() for i in jAngles: tmpid = wx.NewId() verhaal = i['description'] verhaal = verhaal.replace('\n', ' ') menu3.Append(id = tmpid, text=verhaal) self.parent.Bind(wx.EVT_MENU, lambda evt, temp=verhaal, dataset=1: self.OnMenu(evt, temp, dataset), id = tmpid ) menu1.AppendSubMenu(submenu=menu3, text='Dataset 2') menuMain = wx.Menu() menuMain.AppendSubMenu(submenu=menu1, text='Change parameter') tmpid = wx.NewId() menuMain.Append(id = tmpid, text='Play Sequence') self.parent.Bind(wx.EVT_MENU, lambda evt, temp='Play Sequence', dataset=-1: self.OnMenu(evt, temp, dataset), id = tmpid ) tmpid = wx.NewId() menuMain.Append(id = tmpid, text='Trace Sequence') self.parent.Bind(wx.EVT_MENU, lambda evt, temp='Trace Sequence', dataset=-1: self.OnMenu(evt, temp, dataset), id = tmpid ) tmpid = wx.NewId() menuMain.Append(id = tmpid, text='Clear Filter') self.parent.Bind(wx.EVT_MENU, lambda evt, temp='Clear Filter', dataset=-1: self.OnMenu(evt, temp, dataset), id = tmpid ) tmpid = wx.NewId() menuMain.Append(id = tmpid, text='Add Parameter Plot') self.parent.Bind(wx.EVT_MENU, lambda evt, temp='Add Parameter Plot', dataset=-1: self.OnMenu(evt, temp, dataset), id = tmpid ) if len(self.parent.sequenceplotters)>1: tmpid = wx.NewId() menuMain.Append(id = tmpid, text='Remove Parameter Plot') self.parent.Bind(wx.EVT_MENU, lambda evt, temp='Remove Parameter Plot', dataset=0: self.OnMenu(evt, temp, dataset), id = tmpid ) mouseposition = wx.GetMousePosition() self.parent.PopupMenu( menuMain, (mouseposition[0], mouseposition[1] - 48)) #~ menu2.Destroy() menuMain.Destroy() def OnMenu(self, event, descript, dataset): whichdata = dataset whichplot = -1 for i in range(0, len(self.parent.sequenceplotters)): if self == self.parent.sequenceplotters[i]: whichplot = i if descript == 'Play Sequence': self.PlayPlot() if descript == 'Trace Sequence': self.TracePlot() if descript == 'Clear Filter': if whichdata == 0: self.parent.parent.splineCollection_seqfilter = [] elif whichdata == 1: self.parent.parent.splineReferences_seqfilter = [] if descript == 'Add Parameter Plot': self.parent.AddSequencePlotter() self.parent.mgr.Update() elif descript == 'Remove Parameter Plot': self.parent.RemoveSequencePlotter(whichplot) self.parent.mgr.Update() else: jAngles = self.parent.parent.Filters.jointAngleCollection for i in range(0, len(jAngles)): verhaal = jAngles[i]['description'] verhaal = verhaal.replace('\n', ' ') if verhaal == descript: self.parent.UpdateSequencePlot(i, whichplot, whichdata) self.parent.UpdateSequencePlotOverlays() def DefineLookupTable(self): whitening = 0.7 self.dynamic_generic = vtk.vtkLookupTable() self.dynamic_generic.SetNumberOfColors(4) self.dynamic_generic.SetRange(0, 4) self.dynamic_generic.SetTableValue( 0, (whitening, whitening, whitening ,0.0)) self.dynamic_generic.SetTableValue( 1, (0.0, 0.0, 0.0 ,0.7)) self.dynamic_generic.SetTableValue( 2, (1.0, 1.0, 1.0 ,1.0)) self.dynamic_generic.SetTableValue( 3, (whitening, whitening, whitening ,1.0)) self.dynamic_generic.Build() def ShowOverlay(self): try: self.ren.RemoveActor(self.selectionActor) except AttributeError: pass self.canvas = vtk.vtkImageCanvasSource2D() self.canvas.SetNumberOfScalarComponents(4) self.canvas.SetScalarTypeToUnsignedChar() self.canvas.SetExtent(0, self.windowsize[0]-1, 0, self.windowsize[1]-1, 0, 0) self.canvas.SetDrawColor(0,0,0) self.canvas.FillBox(0, self.windowsize[0], 0, 50) self.canvas.SetDrawColor(1,0,0) #~ print "self.whichdata: ", self.whichdata if self.whichdata == 0: sortedlist = self.parent.parent.splineCollection_seqfilter[:] elif self.whichdata == 1: sortedlist = self.parent.parent.splineReferences_seqfilter[:] sortedlist.sort() for i in range(0, len(sortedlist)/2): self.canvas.FillBox(sortedlist[i*2], sortedlist[i*2+1], 0, 50) self.canvas.SetDrawColor(2,0,0) if self.cursor > -1: self.canvas.FillBox(self.cursor, self.cursor+1, 0, 50) imagemaptocolors = vtk.vtkImageMapToColors() imagemaptocolors.SetOutputFormatToRGBA () imagemaptocolors.SetLookupTable(self.dynamic_generic) imagemaptocolors.SetInput(self.canvas.GetOutput()) bbmap = vtk.vtkImageMapper() bbmap.SetColorWindow(255.5) bbmap.SetColorLevel(127.5) bbmap.SetInput(imagemaptocolors.GetOutput()) self.selectionActor = vtk.vtkActor2D() self.selectionActor.SetMapper(bbmap) self.ren.AddActor(self.selectionActor) self.renWin.Render() def PlotSelected(self, event): try: self.iren.RemoveObserver(self.lbpf) self.iren.RemoveObserver(self.lbpg) except AttributeError: pass x, y = self.iren.GetEventPosition() index =0 if self.whichdata == 0: index = int(float(x)/float(self.windowsize[0]) * \ len(self.parent.parent.splineCollection)) act = self.parent.parent.ShowPose(self.parent.parent.splineCollection[index]['blPos'], type = 2) self.parent.SetSliders(self.parent.parent.splineCollection[index]['stance']) else: index = int(float(x)/float(self.windowsize[0]) * \ len(self.parent.parent.splineReferences)) act = self.parent.parent.ShowPose(self.parent.parent.splineReferences[index]['blPos'], type = 2) self.parent.SetSliders(self.parent.parent.splineReferences[index]['stance']) self.parent.tracer.ClearTraces(self.whichdata) self.parent.tracer.DrawTrace(self.whichdata, index, None) self.clicktime = time.clock() if self.clicktime - self.lastclicktime < 1: if self.whichdata == 0: sortedlist = self.parent.parent.splineCollection_seqfilter[:] else: sortedlist = self.parent.parent.splineReferences_seqfilter[:] sortedlist.sort() for i in range(0, len(sortedlist)): try: if x >= sortedlist[i] and\ x <= sortedlist[i + 1]: sortedlist.pop(i+1) sortedlist.pop(i) if self.whichdata == 0: self.parent.parent.splineCollection_seqfilter = sortedlist elif self.whichdata == 1: self.parent.parent.splineReferences_seqfilter = sortedlist break except IndexError: pass self.parent.UpdateSequencePlotOverlays() self.UpdateFilters() else: if self.whichdata == 0: if self.parent.parent.splineCollection_seqfilter == []: self.parent.parent.splineCollection_seqfilter.append(0) self.parent.parent.splineCollection_seqfilter.append(x) self.parent.parent.splineCollection_seqfilter.append(x) self.parent.parent.splineCollection_seqfilter.append(self.windowsize[0]) else: self.parent.parent.splineCollection_seqfilter.append(x) self.parent.parent.splineCollection_seqfilter.append(x) elif self.whichdata == 1: if self.parent.parent.splineReferences_seqfilter == []: self.parent.parent.splineReferences_seqfilter.append(0) self.parent.parent.splineReferences_seqfilter.append(x) self.parent.parent.splineReferences_seqfilter.append(x) self.parent.parent.splineReferences_seqfilter.append(self.windowsize[0]) else: self.parent.parent.splineReferences_seqfilter.append(x) self.parent.parent.splineReferences_seqfilter.append(x) self.lbpf = self.iren.AddObserver("MouseMoveEvent", \ self.PlotMove, 2.0) self.lbpg = self.iren.AddObserver("LeftButtonReleaseEvent", \ self.PlotRelease, 2.0) self.parent.editorpanel.button_4.SetValue(True) self.parent.OnChangeFilters(None) self.lastclicktime = self.clicktime def PlotMove(self, event, bla): x, y = self.iren.GetEventPosition() if self.whichdata == 0: if len(self.parent.parent.splineCollection_seqfilter)==4: self.parent.parent.splineCollection_seqfilter.pop(2) self.parent.parent.splineCollection_seqfilter.insert(2, x) else: self.parent.parent.splineCollection_seqfilter.pop(len(self.parent.parent.splineCollection_seqfilter)-1) self.parent.parent.splineCollection_seqfilter.append(x) elif self.whichdata == 1: if len(self.parent.parent.splineReferences_seqfilter)==4: self.parent.parent.splineReferences_seqfilter.pop(2) self.parent.parent.splineReferences_seqfilter.insert(2, x) else: self.parent.parent.splineReferences_seqfilter.pop(len(self.parent.parent.splineReferences_seqfilter)-1) self.parent.parent.splineReferences_seqfilter.append(x) self.parent.UpdateSequencePlotOverlays() def PlotRelease(self, event, bla): self.iren.RemoveObserver(self.lbpf) self.iren.RemoveObserver(self.lbpg) if self.whichdata == 0: if self.parent.parent.splineCollection_seqfilter[len(self.parent.parent.splineCollection_seqfilter)-1] == self.parent.parent.splineCollection_seqfilter[len(self.parent.parent.splineCollection_seqfilter)-2]: self.parent.parent.splineCollection_seqfilter.pop(len(self.parent.parent.splineCollection_seqfilter)-1) self.parent.parent.splineCollection_seqfilter.pop(len(self.parent.parent.splineCollection_seqfilter)-1) elif self.whichdata == 1: if self.parent.parent.splineReferences_seqfilter[len(self.parent.parent.splineReferences_seqfilter)-1] == self.parent.parent.splineReferences_seqfilter[len(self.parent.parent.splineReferences_seqfilter)-2]: self.parent.parent.splineReferences_seqfilter.pop(len(self.parent.parent.splineReferences_seqfilter)-1) self.parent.parent.splineReferences_seqfilter.pop(len(self.parent.parent.splineReferences_seqfilter)-1) self.UpdateFilters() def UpdateFilters(self): self.filtervalues = [] if self.whichdata == 0: sortedlist = self.parent.parent.splineCollection_seqfilter[:] elif self.whichdata == 1: sortedlist = self.parent.parent.splineReferences_seqfilter[:] sortedlist.sort() if self.whichdata == 0: for i in range(0, len(sortedlist)): self.filtervalues.append(int(float(sortedlist[i])/float(self.windowsize[0]) * \ len(self.parent.parent.splineCollection))) self.parent.parent.Filters.RestartFiltering() else: for i in range(0, len(sortedlist)): self.filtervalues.append(int(float(sortedlist[i])/float(self.windowsize[0]) * \ len(self.parent.parent.splineReferences))) self.parent.parent.Filters.RestartFilteringReferences() def ShowPlot(self): self.windowsize = self.iren.GetSize()#(1370, 50) # The vtkImageImporter will treat a python string as a void pointer importer = vtk.vtkImageImport() importer.SetDataScalarTypeToUnsignedChar() importer.SetNumberOfScalarComponents(4) canvasset = self.CreatePlot() canvas = canvasset[0] w = canvasset[1] h = canvasset[2] # This is where we tell the image importer about the mpl image #~ extent = (0, w - 1, 0, h - 1, 0, 0) extent = (0, w-1, 0, h-1, 0, 0) importer.SetWholeExtent(extent) importer.SetDataExtent(extent) importer.SetImportVoidPointer(canvas.buffer_rgba(0,0), 1) importer.Update() #~ for i in range(0,256): #~ print importer.GetOutput().GetScalarComponentAsFloat (i, i, 0, 0) #~ time.sleep(0.1) # It's upside-down when loaded, so add a flip filter imflip = vtk.vtkImageFlip() imflip.SetInput(importer.GetOutput()) imflip.SetFilteredAxis(1) bbmap = vtk.vtkImageMapper() bbmap.SetColorWindow(255.5) bbmap.SetColorLevel(127.5) bbmap.SetInput(imflip.GetOutput()) bbact = vtk.vtkActor2D() bbact.SetMapper(bbmap) bbact.SetDisplayPosition (int(-0.16*self.windowsize[0]),-6) #~ bbact.SetDisplayPosition (-220, -6) ##width = 1348 = -220, #width = 692 = -110 self.ren.AddActor(bbact) def CreatePlot(self): # Now create our plot fig = Figure() fig.frameon = False #fig.set_autoscaley_on(False) canvas = FigureCanvasAgg(fig) ax = fig.add_subplot(111)#, autoscaley_on = True, autoscalex_on = False) ax.set_ybound (-2, 2) ax.set_xbound (0, len(self.yValues1)) ax.set_xticklabels('bla', visible=False) ax.set_yticklabels('bla', visible=False) ax.annotate(self.label, xy=(24, 24), xycoords='axes pixels', horizontalalignment='left', verticalalignment='center', fontsize=20, color=(0.0, 0.0, 0.0)) ax.annotate(self.label, xy=(25, 25), xycoords='axes pixels', horizontalalignment='left', verticalalignment='center', fontsize=20, color=(1.0, 1.0, 1.0)) rect = ax.patch # a Rectangle instance rect.set_facecolor((0.3, 0.3, 0.3)) pointsx = matplotlib.numpy.arange(0, len(self.yValues1)).tolist() pointsy = self.yValues1#.tolist() pointsx.insert(0, 0.0) pointsy.insert(0, 0.0) pointsx.append(0.0) pointsy.append(0.0) #~ ax.bar(pointsx, pointsy, color=self.plotcolor) #color= self.plotcolor, ax.fill(pointsx, pointsy, edgecolor=(1.0, 1.0, 1.0),\ facecolor= self.plotcolor, antialiased=True) ax.set_xbound (0, len(self.yValues1)) # Powers of 2 image to be clean #w,h = 1024, 1024 w,h = int(self.windowsize[0] * 1.29), int(self.windowsize[1] * 1.3) dpi = canvas.figure.get_dpi() fig.set_size_inches(1.0*w / dpi, 1.0*h / dpi) canvas.draw() # force a draw return [canvas, w, h] def PlayPlot(self): for i in range(0, (len(self.filtervalues)/2) -1): for j in range(self.filtervalues[i*2+1], self.filtervalues[i*2+2]): if self.whichdata == 0: self.cursor = int(float(j) / len(self.parent.parent.splineCollection)\ * (self.windowsize[0])) self.ShowOverlay() self.parent.parent.ShowPose(self.\ parent.parent.splineCollection[j]['blPos'], type = 2) elif self.whichdata == 1: self.cursor = int(float(j) / len(self.parent.parent.splineReferences)\ * (self.windowsize[0])) self.ShowOverlay() self.parent.parent.ShowPose(self.\ parent.parent.splineReferences[j]['blPos'], type = 2) #~ self.parent.tracer.ClearTraces(self.whichdata) #~ self.parent.tracer.DrawTrace(self.whichdata, j, None) time.sleep(0.01) self.parent.Render() self.cursor = -1 self.ShowOverlay() def TracePlot(self): self.parent.tracer.ClearTraces(self.whichdata) for i in range(0, (len(self.filtervalues)/2) -1): difference = self.filtervalues[i*2+1] - self.filtervalues[i*2+2] self.parent.tracer.DrawTrace(self.whichdata, self.filtervalues[i*2+2], [difference, 0]) class MyApp(wx.App): def OnInit(self): plotsie = Plotter(None, None) plotsie.Show() self.SetTopWindow(frame) return 1 if __name__ == "__main__": app = MyApp(0) app.MainLoop()
Python
import math import numpy def create(parent, root): return BaseCalc(parent) class BaseCalc: def __init__(self, parent): self.parent = parent def SubtractPoints(self, a, b): slotlijst = [] try: for i in range(0, len(a)): slotlijst.append(a[i]-b[i]) except TypeError: return (a-b) return slotlijst def AddPoints(self, a, b): slotlijst = [] try: for i in range(0, len(a)): slotlijst.append(a[i]+b[i]) except TypeError: return (a-b) return slotlijst def MultiplyVector(self, a, b): c = [] try: for i in range(0,len(a)): c[len(c):] = [a[i]*b] except TypeError: return (a*b) return c def MultiplyVector_int(self, a, b): c = [] for i in range(0,len(a)): c[len(c):] = [int(a[i]*b)] return c def Average2Points(self, a, b): return [(a[0]+b[0])/2,(a[1]+b[1])/2,(a[2]+b[2])/2] def Average2Points_int(self, a, b): return [int((a[0]+b[0])/2),int((a[1]+b[1])/2),int((a[2]+b[2])/2)] def Average3Points(self, a, b, c): return [(a[0]+b[0]+c[0])/3,(a[1]+b[1]+c[1])/3,(a[2]+b[2]+c[2])/3] def WeightedAverage2Points(self, a, b, w, y): return [(w*a[0]+y*b[0])/(y+w),(w*a[1]+y*b[1])/(y+w),(w*a[2]+y*b[2])/(y+w)] def Length3DVector(self, a): return math.sqrt((math.pow(a[0], 2)) + (math.pow(a[1], 2)) + (math.pow(a[2], 2))) def Length3DVector2(self, a): return (math.pow(a[0], 2)) + (math.pow(a[1], 2)) + (math.pow(a[2], 2)) def WorldToVoxel(self, a): return [int(a[0]/self.volumedata.GetSpacing()[0]), int(a[1]/self.volumedata.GetSpacing()[1]), int(a[2]/self.volumedata.GetSpacing()[2])] def VoxelToWorld(self, a): return [(a[0]*self.volumedata.GetSpacing()[0]), (a[1]*self.volumedata.GetSpacing()[1]), (a[2]*self.volumedata.GetSpacing()[2])] def Normalize(self, a): m1 = numpy.matrix([a]) m1 = m1 / numpy.linalg.norm(m1) return m1.tolist()[0] def Multiply3x3MatrixVector(self, matrix, b): output1 = [0,0,0] for j in range(0,3): tmp = 0 for i in range(0,3): tmp = tmp + matrix[j][i] * b[i] output1[j] = tmp return output1
Python
#!/usr/bin/python """Basic statistics utility functions. The implementation of Student's t distribution inverse CDF was ported to Python from JSci. The parameters are set to only be accurate to approximately 5 decimal places. The JSci port comes frist. "New" code is near the bottom. JSci information: http://jsci.sourceforge.net/ Original Author: Mark Hale Original Licence: LGPL """ import math # Relative machine precision. EPS = 2.22e-16 # The smallest positive floating-point number such that 1/xminin is machine representable. XMININ = 2.23e-308 # Square root of 2 * pi SQRT2PI = 2.5066282746310005024157652848110452530069867406099 LOGSQRT2PI = math.log(SQRT2PI); # Rough estimate of the fourth root of logGamma_xBig lg_frtbig = 2.25e76 pnt68 = 0.6796875 # lower value = higher precision PRECISION = 4.0*EPS def betaFraction(x, p, q): """Evaluates of continued fraction part of incomplete beta function. Based on an idea from Numerical Recipes (W.H. Press et al, 1992).""" sum_pq = p + q p_plus = p + 1.0 p_minus = p - 1.0 h = 1.0-sum_pq*x/p_plus; if abs(h) < XMININ: h = XMININ h = 1.0/h frac = h m = 1 delta = 0.0 c = 1.0 while m <= MAX_ITERATIONS and abs(delta-1.0) > PRECISION: m2 = 2*m # even index for d d=m*(q-m)*x/((p_minus+m2)*(p+m2)) h=1.0+d*h if abs(h) < XMININ: h=XMININ h=1.0/h; c=1.0+d/c; if abs(c) < XMININ: c=XMININ frac *= h*c; # odd index for d d = -(p+m)*(sum_pq+m)*x/((p+m2)*(p_plus+m2)) h=1.0+d*h if abs(h) < XMININ: h=XMININ; h=1.0/h c=1.0+d/c if abs(c) < XMININ: c = XMININ delta=h*c frac *= delta m += 1 return frac # The largest argument for which <code>logGamma(x)</code> is representable in the machine. LOG_GAMMA_X_MAX_VALUE = 2.55e305 # Log Gamma related constants lg_d1 = -0.5772156649015328605195174; lg_d2 = 0.4227843350984671393993777; lg_d4 = 1.791759469228055000094023; lg_p1 = [ 4.945235359296727046734888, 201.8112620856775083915565, 2290.838373831346393026739, 11319.67205903380828685045, 28557.24635671635335736389, 38484.96228443793359990269, 26377.48787624195437963534, 7225.813979700288197698961 ] lg_q1 = [ 67.48212550303777196073036, 1113.332393857199323513008, 7738.757056935398733233834, 27639.87074403340708898585, 54993.10206226157329794414, 61611.22180066002127833352, 36351.27591501940507276287, 8785.536302431013170870835 ] lg_p2 = [ 4.974607845568932035012064, 542.4138599891070494101986, 15506.93864978364947665077, 184793.2904445632425417223, 1088204.76946882876749847, 3338152.967987029735917223, 5106661.678927352456275255, 3074109.054850539556250927 ] lg_q2 = [ 183.0328399370592604055942, 7765.049321445005871323047, 133190.3827966074194402448, 1136705.821321969608938755, 5267964.117437946917577538, 13467014.54311101692290052, 17827365.30353274213975932, 9533095.591844353613395747 ] lg_p4 = [ 14745.02166059939948905062, 2426813.369486704502836312, 121475557.4045093227939592, 2663432449.630976949898078, 29403789566.34553899906876, 170266573776.5398868392998, 492612579337.743088758812, 560625185622.3951465078242 ] lg_q4 = [ 2690.530175870899333379843, 639388.5654300092398984238, 41355999.30241388052042842, 1120872109.61614794137657, 14886137286.78813811542398, 101680358627.2438228077304, 341747634550.7377132798597, 446315818741.9713286462081 ] lg_c = [ -0.001910444077728,8.4171387781295e-4, -5.952379913043012e-4, 7.93650793500350248e-4, -0.002777777777777681622553, 0.08333333333333333331554247, 0.0057083835261 ] def logGamma(x): """The natural logarithm of the gamma function. Based on public domain NETLIB (Fortran) code by W. J. Cody and L. Stoltz<BR> Applied Mathematics Division<BR> Argonne National Laboratory<BR> Argonne, IL 60439<BR> <P> References: <OL> <LI>W. J. Cody and K. E. Hillstrom, 'Chebyshev Approximations for the Natural Logarithm of the Gamma Function,' Math. Comp. 21, 1967, pp. 198-203. <LI>K. E. Hillstrom, ANL/AMD Program ANLC366S, DGAMMA/DLGAMA, May, 1969. <LI>Hart, Et. Al., Computer Approximations, Wiley and sons, New York, 1968. </OL></P><P> From the original documentation: </P><P> This routine calculates the LOG(GAMMA) function for a positive real argument X. Computation is based on an algorithm outlined in references 1 and 2. The program uses rational functions that theoretically approximate LOG(GAMMA) to at least 18 significant decimal digits. The approximation for X > 12 is from reference 3, while approximations for X < 12.0 are similar to those in reference 1, but are unpublished. The accuracy achieved depends on the arithmetic system, the compiler, the intrinsic functions, and proper selection of the machine-dependent constants. </P><P> Error returns:<BR> The program returns the value XINF for X .LE. 0.0 or when overflow would occur. The computation is believed to be free of underflow and overflow.""" y = x if y < 0.0 or y > LOG_GAMMA_X_MAX_VALUE: # Bad arguments return float("inf") if y <= EPS: return -math.log(y) if y <= 1.5: if (y < pnt68): corr = -math.log(y) xm1 = y else: corr = 0.0; xm1 = y - 1.0; if y <= 0.5 or y >= pnt68: xden = 1.0; xnum = 0.0; for i in xrange(8): xnum = xnum * xm1 + lg_p1[i]; xden = xden * xm1 + lg_q1[i]; return corr + xm1 * (lg_d1 + xm1 * (xnum / xden)); else: xm2 = y - 1.0; xden = 1.0; xnum = 0.0; for i in xrange(8): xnum = xnum * xm2 + lg_p2[i]; xden = xden * xm2 + lg_q2[i]; return corr + xm2 * (lg_d2 + xm2 * (xnum / xden)); if (y <= 4.0): xm2 = y - 2.0; xden = 1.0; xnum = 0.0; for i in xrange(8): xnum = xnum * xm2 + lg_p2[i]; xden = xden * xm2 + lg_q2[i]; return xm2 * (lg_d2 + xm2 * (xnum / xden)); if y <= 12.0: xm4 = y - 4.0; xden = -1.0; xnum = 0.0; for i in xrange(8): xnum = xnum * xm4 + lg_p4[i]; xden = xden * xm4 + lg_q4[i]; return lg_d4 + xm4 * (xnum / xden); assert y <= lg_frtbig res = lg_c[6]; ysq = y * y; for i in xrange(6): res = res / ysq + lg_c[i]; res /= y; corr = math.log(y); res = res + LOGSQRT2PI - 0.5 * corr; res += y * (corr - 1.0); return res def logBeta(p, q): """The natural logarithm of the beta function.""" assert p > 0 assert q > 0 if p <= 0 or q <= 0 or p + q > LOG_GAMMA_X_MAX_VALUE: return 0 return logGamma(p)+logGamma(q)-logGamma(p+q) def incompleteBeta(x, p, q): """Incomplete beta function. The computation is based on formulas from Numerical Recipes, Chapter 6.4 (W.H. Press et al, 1992). Ported from Java: http://jsci.sourceforge.net/""" assert 0 <= x <= 1 assert p > 0 assert q > 0 # Range checks to avoid numerical stability issues? if x <= 0.0: return 0.0 if x >= 1.0: return 1.0 if p <= 0.0 or q <= 0.0 or (p+q) > LOG_GAMMA_X_MAX_VALUE: return 0.0 beta_gam = math.exp(-logBeta(p,q) + p*math.log(x) + q*math.log(1.0-x)) if x < (p+1.0)/(p+q+2.0): return beta_gam*betaFraction(x, p, q)/p else: return 1.0-(beta_gam*betaFraction(1.0-x,q,p)/q) ACCURACY = 10**-7 MAX_ITERATIONS = 10000 def findRoot(value, x_low, x_high, function): """Use the bisection method to find root such that function(root) == value.""" guess = (x_high + x_low) / 2.0 v = function(guess) difference = v - value i = 0 while abs(difference) > ACCURACY and i < MAX_ITERATIONS: i += 1 if difference > 0: x_high = guess else: x_low = guess guess = (x_high + x_low) / 2.0 v = function(guess) difference = v - value return guess def StudentTCDF(degree_of_freedom, X): """Student's T distribution CDF. Returns probability that a value x < X. Ported from Java: http://jsci.sourceforge.net/""" A = 0.5 * incompleteBeta(degree_of_freedom/(degree_of_freedom+X*X), 0.5*degree_of_freedom, 0.5) if X > 0: return 1 - A return A def InverseStudentT(degree_of_freedom, probability): """Inverse of Student's T distribution CDF. Returns the value x such that CDF(x) = probability. Ported from Java: http://jsci.sourceforge.net/ This is not the best algorithm in the world. SciPy has a Fortran version (see special.stdtrit): http://svn.scipy.org/svn/scipy/trunk/scipy/stats/distributions.py http://svn.scipy.org/svn/scipy/trunk/scipy/special/cdflib/cdft.f Very detailed information: http://www.maths.ox.ac.uk/~shaww/finpapers/tdist.pdf """ assert 0 <= probability <= 1 if probability == 1: return float("inf") if probability == 0: return float("-inf") if probability == 0.5: return 0.0 def f(x): return StudentTCDF(degree_of_freedom, x) return findRoot(probability, -10**4, 10**4, f) def tinv(p, degree_of_freedom): """Similar to the TINV function in Excel p: 1-confidence (eg. 0.05 = 95% confidence)""" assert 0 <= p <= 1 confidence = 1 - p return InverseStudentT(degree_of_freedom, (1+confidence)/2.0) def memoize(function): cache = {} def closure(*args): if args not in cache: cache[args] = function(*args) return cache[args] return closure # Cache tinv results, since we typically call it with the same args over and over cached_tinv = memoize(tinv) def stats(r, confidence_interval=0.05): """Returns statistics about a sequence of numbers. By default it computes the 95% confidence interval. Returns (average, median, standard deviation, min, max, confidence interval)""" total = sum(r) average = total/float(len(r)) sum_deviation_squared = sum([(i-average)**2 for i in r]) standard_deviation = math.sqrt(sum_deviation_squared/(len(r)-1 or 1)) s = list(r) s.sort() median = s[len(s)/2] interval25 = s[len(s)/4] interval75 = s[3*len(s)/4] minimum = s[0] maximum = s[-1] # See: http://davidmlane.com/hyperstat/ # confidence_95 = 1.959963984540051 * standard_deviation / math.sqrt(len(r)) # We must estimate both using the t distribution: # http://davidmlane.com/hyperstat/B7483.html # s_m = s / sqrt(N) ###~ s_m = standard_deviation / math.sqrt(len(r)) # Degrees of freedom = n-1 # t = tinv(0.05, degrees_of_freedom) # confidence = +/- t * s_m ###~ confidence = cached_tinv(confidence_interval, len(r)-1) * s_m #~ return average, median, standard_deviation, minimum, maximum, confidence, interval25, interval75 return average, median, standard_deviation, minimum, maximum, interval25, interval75
Python
import matplotlib #~ matplotlib.use('Agg') from matplotlib.figure import Figure from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigCanvas import pylab as p import time import vtk import wx from vtk.wx.wxVTKRenderWindowInteractor import * class Scatter(wx.Frame): def __init__(self, parent, data1, data2, stanceID1, stanceID2): self.windowsize = [648, 512] self.xyValues1 = data1[0] self.xLabel1 = data1[1] self.yLabel1 = data1[2] self.xyValues2 = data2[0] self.xLabel2 = data2[1] self.yLabel2 = data2[2] self.stanceID1 = stanceID1 self.stanceID2 = stanceID2 self.plotcolor1 = (0.0, 0.0, 1.0) self.plotcolor2 = (1.0, 1.0, 0.0) self.parent = parent wx.Frame.__init__(self, None, -1, pos = wx.Point(100, 100),\ size = self.windowsize, style=wx.DEFAULT_FRAME_STYLE, title=u'Scatter Plot') self.Bind(wx.EVT_CLOSE, self.OnQuit) #~ self.Bind(wx.EVT_SIZE, self.OnResize) #~ self.canvas.Bind(wx.EVT_KEY_DOWN, self.onKeyEvent) self.SetupRenderWindow() self.ShowPlot() sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(self.iren, 1) self.SetSizer(sizer) self.Show(True) self.Fit() #~ self.Build_Menus() def OnResize(self, event): print self.GetSize() def SetupRenderWindow(self): self.iren = wxVTKRenderWindowInteractor(self, -1) self.iren.SetSize([self.windowsize[0], self.windowsize[1]]) self.renWin = self.iren.GetRenderWindow() self.ren = vtk.vtkRenderer() self.renWin.AddRenderer(self.ren) self.iren.Unbind(wx.EVT_LEFT_DOWN) #~ self.iren.Bind(wx.EVT_LEFT_DOWN, self.PlotSelected) self.iren.Unbind(wx.EVT_RIGHT_DOWN) #~ self.iren.Bind(wx.EVT_RIGHT_DOWN, self.ShowMenu) def DefineLookupTable(self): whitening = 0.7 self.dynamic_generic = vtk.vtkLookupTable() self.dynamic_generic.SetNumberOfColors(4) self.dynamic_generic.SetRange(0, 4) self.dynamic_generic.SetTableValue( 0, (whitening, whitening, whitening ,0.0)) self.dynamic_generic.SetTableValue( 1, (0.0, 0.0, 0.0 ,0.7)) self.dynamic_generic.SetTableValue( 2, (1.0, 1.0, 1.0 ,1.0)) self.dynamic_generic.SetTableValue( 3, (whitening, whitening, whitening ,1.0)) self.dynamic_generic.Build() #~ def ShowOverlay(self): #~ try: #~ self.ren.RemoveActor(self.selectionActor) #~ except AttributeError: #~ pass #~ self.canvas = vtk.vtkImageCanvasSource2D() #~ self.canvas.SetNumberOfScalarComponents(4) #~ self.canvas.SetScalarTypeToUnsignedChar() #~ self.canvas.SetExtent(0, self.windowsize[0]-1, 0, self.windowsize[1]-1, 0, 0) #~ self.canvas.SetDrawColor(0,0,0) #~ self.canvas.FillBox(0, self.windowsize[0], 0, 50) #~ self.canvas.SetDrawColor(1,0,0) #~ if self.whichdata == 0: #~ sortedlist = self.parent.parent.splineCollection_seqfilter[:] #~ elif self.whichdata == 1: #~ sortedlist = self.parent.parent.splineReferences_seqfilter[:] #~ sortedlist.sort() #~ for i in range(0, len(sortedlist)/2): #~ self.canvas.FillBox(sortedlist[i*2], sortedlist[i*2+1], 0, 50) #~ self.canvas.SetDrawColor(2,0,0) #~ if self.cursor > -1: #~ self.canvas.FillBox(self.cursor, self.cursor+1, 0, 50) #~ imagemaptocolors = vtk.vtkImageMapToColors() #~ imagemaptocolors.SetOutputFormatToRGBA () #~ imagemaptocolors.SetLookupTable(self.dynamic_generic) #~ imagemaptocolors.SetInput(self.canvas.GetOutput()) #~ bbmap = vtk.vtkImageMapper() #~ bbmap.SetColorWindow(255.5) #~ bbmap.SetColorLevel(127.5) #~ bbmap.SetInput(imagemaptocolors.GetOutput()) #~ self.selectionActor = vtk.vtkActor2D() #~ self.selectionActor.SetMapper(bbmap) #~ self.ren.AddActor(self.selectionActor) #~ self.renWin.Render() #~ def PlotSelected(self, event): #~ try: #~ self.iren.RemoveObserver(self.lbpf) #~ self.iren.RemoveObserver(self.lbpg) #~ except AttributeError: #~ pass #~ x, y = self.iren.GetEventPosition() #~ index =0 #~ if self.whichdata == 0: #~ index = int(float(x)/float(self.windowsize[0]) * \ #~ len(self.parent.parent.splineCollection)) #~ act = self.parent.parent.ShowPose(self.parent.parent.splineCollection[index]['blPos'], type = 2) #~ self.parent.SetSliders(self.parent.parent.splineCollection[index]['stance']) #~ else: #~ index = int(float(x)/float(self.windowsize[0]) * \ #~ len(self.parent.parent.splineReferences)) #~ act = self.parent.parent.ShowPose(self.parent.parent.splineReferences[index]['blPos'], type = 2) #~ self.parent.SetSliders(self.parent.parent.splineReferences[index]['stance']) #~ self.parent.tracer.ClearTraces(self.whichdata) #~ self.parent.tracer.DrawTrace(self.whichdata, index, None) #~ self.clicktime = time.clock() #~ if self.clicktime - self.lastclicktime < 1: #~ if self.whichdata == 0: #~ sortedlist = self.parent.parent.splineCollection_seqfilter[:] #~ else: #~ sortedlist = self.parent.parent.splineReferences_seqfilter[:] #~ sortedlist.sort() #~ for i in range(0, len(sortedlist)): #~ try: #~ if x >= sortedlist[i] and\ #~ x <= sortedlist[i + 1]: #~ sortedlist.pop(i+1) #~ sortedlist.pop(i) #~ if self.whichdata == 0: #~ self.parent.parent.splineCollection_seqfilter = sortedlist #~ elif self.whichdata == 1: #~ self.parent.parent.splineReferences_seqfilter = sortedlist #~ break #~ except IndexError: #~ pass #~ self.parent.UpdateSequencePlotOverlays() #~ self.UpdateFilters() #~ else: #~ if self.whichdata == 0: #~ if self.parent.parent.splineCollection_seqfilter == []: #~ self.parent.parent.splineCollection_seqfilter.append(0) #~ self.parent.parent.splineCollection_seqfilter.append(x) #~ self.parent.parent.splineCollection_seqfilter.append(x) #~ self.parent.parent.splineCollection_seqfilter.append(self.windowsize[0]) #~ else: #~ self.parent.parent.splineCollection_seqfilter.append(x) #~ self.parent.parent.splineCollection_seqfilter.append(x) #~ elif self.whichdata == 1: #~ if self.parent.parent.splineReferences_seqfilter == []: #~ self.parent.parent.splineReferences_seqfilter.append(0) #~ self.parent.parent.splineReferences_seqfilter.append(x) #~ self.parent.parent.splineReferences_seqfilter.append(x) #~ self.parent.parent.splineReferences_seqfilter.append(self.windowsize[0]) #~ else: #~ self.parent.parent.splineReferences_seqfilter.append(x) #~ self.parent.parent.splineReferences_seqfilter.append(x) #~ self.lbpf = self.iren.AddObserver("MouseMoveEvent", \ #~ self.PlotMove, 2.0) #~ self.lbpg = self.iren.AddObserver("LeftButtonReleaseEvent", \ #~ self.PlotRelease, 2.0) #~ self.parent.editorpanel.button_4.SetValue(True) #~ self.parent.OnChangeFilters(None) #~ self.lastclicktime = self.clicktime #~ def PlotMove(self, event, bla): #~ x, y = self.iren.GetEventPosition() #~ if self.whichdata == 0: #~ if len(self.parent.parent.splineCollection_seqfilter)==4: #~ self.parent.parent.splineCollection_seqfilter.pop(2) #~ self.parent.parent.splineCollection_seqfilter.insert(2, x) #~ else: #~ self.parent.parent.splineCollection_seqfilter.pop(len(self.parent.parent.splineCollection_seqfilter)-1) #~ self.parent.parent.splineCollection_seqfilter.append(x) #~ elif self.whichdata == 1: #~ if len(self.parent.parent.splineReferences_seqfilter)==4: #~ self.parent.parent.splineReferences_seqfilter.pop(2) #~ self.parent.parent.splineReferences_seqfilter.insert(2, x) #~ else: #~ self.parent.parent.splineReferences_seqfilter.pop(len(self.parent.parent.splineReferences_seqfilter)-1) #~ self.parent.parent.splineReferences_seqfilter.append(x) #~ self.parent.UpdateSequencePlotOverlays() #~ def PlotRelease(self, event, bla): #~ self.iren.RemoveObserver(self.lbpf) #~ self.iren.RemoveObserver(self.lbpg) #~ if self.whichdata == 0: #~ if self.parent.parent.splineCollection_seqfilter[len(self.parent.parent.splineCollection_seqfilter)-1] == self.parent.parent.splineCollection_seqfilter[len(self.parent.parent.splineCollection_seqfilter)-2]: #~ self.parent.parent.splineCollection_seqfilter.pop(len(self.parent.parent.splineCollection_seqfilter)-1) #~ self.parent.parent.splineCollection_seqfilter.pop(len(self.parent.parent.splineCollection_seqfilter)-1) #~ elif self.whichdata == 1: #~ if self.parent.parent.splineReferences_seqfilter[len(self.parent.parent.splineReferences_seqfilter)-1] == self.parent.parent.splineReferences_seqfilter[len(self.parent.parent.splineReferences_seqfilter)-2]: #~ self.parent.parent.splineReferences_seqfilter.pop(len(self.parent.parent.splineReferences_seqfilter)-1) #~ self.parent.parent.splineReferences_seqfilter.pop(len(self.parent.parent.splineReferences_seqfilter)-1) #~ self.UpdateFilters() #~ def UpdateFilters(self): #~ self.filtervalues = [] #~ if self.whichdata == 0: #~ sortedlist = self.parent.parent.splineCollection_seqfilter[:] #~ elif self.whichdata == 1: #~ sortedlist = self.parent.parent.splineReferences_seqfilter[:] #~ sortedlist.sort() #~ if self.whichdata == 0: #~ for i in range(0, len(sortedlist)): #~ self.filtervalues.append(int(float(sortedlist[i])/float(self.windowsize[0]) * \ #~ len(self.parent.parent.splineCollection))) #~ self.parent.parent.Filters.RestartFiltering() #~ else: #~ for i in range(0, len(sortedlist)): #~ self.filtervalues.append(int(float(sortedlist[i])/float(self.windowsize[0]) * \ #~ len(self.parent.parent.splineReferences))) #~ self.parent.parent.Filters.RestartFilteringReferences() def ShowPlot(self): # The vtkImageImporter will treat a python string as a void pointer self.importer = vtk.vtkImageImport() self.importer.SetDataScalarTypeToUnsignedChar() self.importer.SetNumberOfScalarComponents(4) canvasset = self.CreatePlot() canvas = canvasset[0] w = canvasset[1] h = canvasset[2] extent = (0, w-1, 0, h-1, 0, 0) self.importer.SetWholeExtent(extent) self.importer.SetDataExtent(extent) self.importer.SetImportVoidPointer(canvas.buffer_rgba(0,0), 1) self.importer.Update() #~ for i in range(0,256): #~ print importer.GetOutput().GetScalarComponentAsFloat (i, i, 0, 0) #~ time.sleep(0.1) # It's upside-down when loaded, so add a flip filter imflip = vtk.vtkImageFlip() imflip.SetInput(self.importer.GetOutput()) imflip.SetFilteredAxis(1) self.bbmap = vtk.vtkImageMapper() self.bbmap.SetColorWindow(255.5) self.bbmap.SetColorLevel(127.5) self.bbmap.SetInput(imflip.GetOutput()) bbact = vtk.vtkActor2D() bbact.SetMapper(self.bbmap) #~ bbact.SetDisplayPosition (int(-0.16*self.windowsize[0]),-6) #~ bbact.SetDisplayPosition (-220, -6) ##width = 1348 = -220, #width = 692 = -110 self.ren.AddActor(bbact) self.iren.Render() def CreatePlot(self): self.fig = Figure() self.fig.frameon = True self.canvas = FigCanvas(self, -1, self.fig) w,h = int(self.windowsize[0]), int(self.windowsize[1]) dpi = self.canvas.figure.get_dpi() self.fig.set_size_inches(1.0*w / dpi, 1.0*h / dpi) self.UpdatePlot() #~ self.ax = self.fig.add_subplot(111) #~ self.ax.set_xlabel(self.xLabel1) #~ self.ax.set_ylabel(self.yLabel1) #~ rect = self.ax.patch #~ rect.set_facecolor((1, 1, 1)) #~ if self.xyValues1: #~ xy1_array = matplotlib.numpy.array(self.xyValues1) #~ columns1 = matplotlib.numpy.column_stack(self.xyValues1).tolist() #~ self.ax.plot(columns1[0], columns1[1], 'o', color=self.plotcolor1) #~ if self.xyValues2: #~ xy2_array = matplotlib.numpy.array(self.xyValues2) #~ columns2 = matplotlib.numpy.column_stack(self.xyValues2).tolist() #~ self.ax.plot(columns2[0], columns2[1], 'o', color=self.plotcolor2) #~ self.canvas.draw() return [self.canvas, w, h] def UpdatePlot(self): try: self.fig.delaxes(self.ax) except AttributeError: pass self.ax = self.fig.add_subplot(111) self.ax.set_xlabel(self.xLabel1) self.ax.set_ylabel(self.yLabel1) rect = self.ax.patch rect.set_facecolor((1, 1, 1)) if self.xyValues1: xy1_array = matplotlib.numpy.array(self.xyValues1) columns1 = matplotlib.numpy.column_stack(self.xyValues1).tolist() self.ax.plot(columns1[0], columns1[1], 'o', color=self.plotcolor1) if self.xyValues2: xy2_array = matplotlib.numpy.array(self.xyValues2) columns2 = matplotlib.numpy.column_stack(self.xyValues2).tolist() self.ax.plot(columns2[0], columns2[1], 'o', color=self.plotcolor2) self.ax.set_xbound (-180, 180) self.ax.set_ybound (-180, 180) self.ax.grid() self.canvas.draw() try: w,h = int(self.windowsize[0]), int(self.windowsize[1]) extent = (0, w-1, 0, h-1, 0, 0) self.importer.SetWholeExtent(extent) self.importer.SetDataExtent(extent) self.importer.SetImportVoidPointer(self.canvas.buffer_rgba(0,0), 1) self.importer.Update() self.bbmap.Update() except AttributeError: pass def OnQuit(self, event): for scatterplot in self.parent.scatterplotlist: if scatterplot == self: self.parent.scatterplotlist.remove(scatterplot) self.Destroy() class MyApp(wx.App): def OnInit(self): plotsie = Scatter(None, None) plotsie.Show() self.SetTopWindow(frame) return 1 if __name__ == "__main__": app = MyApp(0) app.MainLoop()
Python
import wx from SensorPanel import SensorPanel from BLPanel import BLPanel from GHJPanel import GHJPanel from VisualizationPanel import VisualizationPanel NEW = 101 OPEN = 102 IMPORT = 103 EXPORT = 104 QUIT = 106 SAVE = 107 ANALYSE = 108 PREFERENCES = 201 SHOW_SENSORS = 202 SHOW_BONYLANDMARKS = 203 SHOW_3DMODEL = 204 ADDBONYLANDMARKS = 205 CHECKCOMPORTS = 206 WRITERAWDATA = 207 FASTACQUISITION = 208 EXPORTBLVECS = 209 REPLACEBONE = 210 STOREABS = 211 MINIMIZE = 301 MAXIMIZE = 302 ABOUT = 401 NOTEBOOK = 800 ## The main class of the Graphical User Interface with the notebook and menubar. class GUI(wx.Frame): ## The constructor of GUI. Builds the GUI. # @param[in] main Main wx.App derived instance. # @param[in] *args Automatically passed parameter. # @param[in] **kwds Automatically passed parameter. def __init__(self, main, *args, **kwds) : kwds["style"] = wx.DEFAULT_FRAME_STYLE wx.Frame.__init__(self, *args, **kwds) ## Main wx.App derived instance. self.main = main ## wx.MenuBar() self.menubar = wx.MenuBar() self.SetMenuBar(self.menubar) wxglade_tmp_menu = wx.Menu() wxglade_tmp_menu.Append(NEW,"&New\tCtrl+N") wxglade_tmp_menu.Append(ANALYSE,"&Start Motion Analyser\tCtrl+M") wxglade_tmp_menu.AppendSeparator() wxglade_tmp_menu.Append(QUIT,"&Quit\tCtrl+Q") self.menubar.Append(wxglade_tmp_menu, "&File") wxglade_tmp_menu = wx.Menu() wxglade_tmp_menu.Append(SHOW_SENSORS,"Show &Sensors", kind=wx.ITEM_CHECK) wxglade_tmp_menu.Append(SHOW_BONYLANDMARKS,"Show &Bony &Landmarks", kind=wx.ITEM_CHECK) wxglade_tmp_menu.Append(SHOW_3DMODEL,"Show &3D &Model", kind=wx.ITEM_CHECK) wxglade_tmp_menu.AppendSeparator() wxglade_tmp_menu.Append(ADDBONYLANDMARKS,"&Add Bony Landmarks") wxglade_tmp_menu.Append(CHECKCOMPORTS,"&Check COM Ports") wxglade_tmp_menu.Append(PREFERENCES,"&Preferences") self.menubar.Append(wxglade_tmp_menu, "&Edit") wxglade_tmp_menu.AppendSeparator() wxglade_tmp_menu.Append(WRITERAWDATA,"&Write Raw Data", kind=wx.ITEM_CHECK) wxglade_tmp_menu.Append(FASTACQUISITION,"&Write Raw Data Fast", kind=wx.ITEM_CHECK) wxglade_tmp_menu.AppendSeparator() wxglade_tmp_menu.Append(EXPORTBLVECS,"Export BL vectors") wxglade_tmp_menu.Append(REPLACEBONE,"Replace Bone by Custom Model") wxglade_tmp_menu.Append(STOREABS,"Store absolute matrices") wxglade_tmp_menu = wx.Menu() wxglade_tmp_menu.Append(ABOUT,"&About") self.menubar.Append(wxglade_tmp_menu, "&Help") ## wx.BoxSizer() self.sizer_1 = wx.BoxSizer(wx.VERTICAL) ## wx.Notebook() self.notebook = wx.Notebook(self, NOTEBOOK, style=0) self.sizer_1.Add(self.notebook, 1, wx.EXPAND, 0) self.SetSizer(self.sizer_1) self.__SetProperties() self.__DoLayout() self.__BindEvents() def rightclick(self, event): print event ## Sets properties for the panel. def __SetProperties(self): self.SetTitle("Flock of Birds Visualizer") self.SetSize((915, 760)) self.SetBackgroundColour(wx.Colour(255, 255, 255)) self.SetIcon(wx.Icon("Images/icon.ico", wx.BITMAP_TYPE_ICO, 32, 32)) self.menubar.Check(SHOW_SENSORS, True) self.menubar.Check(SHOW_BONYLANDMARKS, True) self.menubar.Check(SHOW_3DMODEL, True) self.menubar.Check(WRITERAWDATA, True) self.menubar.Check(FASTACQUISITION, False) ## Sets layout for the panel. def __DoLayout(self): self.Layout() self.Centre() ## Loads the notebook with its pages. Deletes the existing pages first. def LoadNotebook(self): self.notebook.DeleteAllPages() ## only add these pages when the fob is running if self.main.FOB_RUNNING: self.notebook.AddPage(SensorPanel(self.notebook, self.main.states.sensors), "Sensors") self.notebook.AddPage(BLPanel(self.notebook, self.main.states.bony_landmark), "Bony Landmarks") self.notebook.AddPage(GHJPanel(self.notebook, self.main.states.gh_cor), "GH-Joint") else: ## Disable or enable the comport check menu option according to if the fob is running self.menubar.GetMenu(1).FindItemByPosition(5).Enable(self.main.FOB_RUNNING) ## The visualization is always added, even when the fob is not running, the playback can still be used self.notebook.AddPage(VisualizationPanel(self.notebook, self.main.states.visualization), "Visualization") self.Layout() ## Controls the events to be fired when tab changing takes place, this is needed when the tabs are used instead of the next and back buttons. # The event handlers of those are called through this method, as they are needed for the checking. # # This works by checking the difference between the current page and the newly selected page. Is one, then the next page or the page # before is set depending on the sign of the difference (+ or -). # # If the difference is larger than 1, the event handlers of the pages in between are triggered as well through the while loop. # This makes sure that the checking for each page is done. def OnPageChanged(self, event): old = event.GetOldSelection() new = event.GetSelection() difference = new - old NAVIGATION_TO_NEXT = True if( old != -1 and difference == 1 ): self.notebook.GetPage(old).OnNext(None) if( old != -1 and difference <= -1 ): self.notebook.GetPage(old).OnBack(None,new) if( old != -1 and difference > 1 ): # Each OnNext method returns True when navigation to the following panel occurs. # If this does not occur, navigation to the next panel should not happen, so the loop will stop. while difference > 0 and NAVIGATION_TO_NEXT: NAVIGATION_TO_NEXT = self.notebook.GetPage(old).OnNext(None) old += 1 difference = new - old ## Checks whether or not "Show Sensors" in the menu is checked. # @return[boolean] True if SHOW_SENSORS is checked, else False. def IsSensorsChecked(self): return self.menubar.IsChecked(SHOW_SENSORS) ## Returns whether or not "Show Bony Landmarks" in the menu is checked. def IsBonyLandmarksChecked(self): return self.menubar.IsChecked(SHOW_BONYLANDMARKS) ## Returns whether or not "Show 3D Model" in the menu is checked. def Is3DModelChecked(self): return self.menubar.IsChecked(SHOW_3DMODEL) ## Binds GUI menu items to methods in the main class. def __BindEvents(self): self.Bind(wx.EVT_MENU, self.main.OnNew, id=NEW) self.Bind(wx.EVT_MENU, self.main.OnStartAnalyser, id=ANALYSE) self.Bind(wx.EVT_MENU, self.main.OnAddBonyLandmark, id=ADDBONYLANDMARKS) self.Bind(wx.EVT_MENU, self.main.OnPreferences, id=PREFERENCES) self.Bind(wx.EVT_MENU, self.main.OnCheckCOMports, id=CHECKCOMPORTS) self.Bind(wx.EVT_MENU, self.main.OnToggleSensors, id=SHOW_SENSORS) self.Bind(wx.EVT_MENU, self.main.OnToggleBonyLandmarks, id=SHOW_BONYLANDMARKS) self.Bind(wx.EVT_MENU, self.main.OnToggle3DModel, id=SHOW_3DMODEL) self.Bind(wx.EVT_MENU, self.main.OnAbout, id=ABOUT) self.Bind(wx.EVT_MENU, self.main.OnDataWrite, id=WRITERAWDATA) self.Bind(wx.EVT_MENU, self.main.OnFastAcquisition, id=FASTACQUISITION) self.Bind(wx.EVT_MENU, self.main.OnExportBlVecs, id=EXPORTBLVECS) self.Bind(wx.EVT_MENU, self.main.OnReplaceBone, id=REPLACEBONE) self.Bind(wx.EVT_MENU, self.main.OnStoreAbsMatrices, id=STOREABS) self.Bind(wx.EVT_CLOSE, self.main.OnQuit) self.Bind(wx.EVT_MENU, self.main.OnQuit, id=QUIT) self.Bind(wx.EVT_NOTEBOOK_PAGE_CHANGED, self.OnPageChanged, id=NOTEBOOK) #~ self.Unbind(wx.EVT_RIGHT_DOWN) #~ self.Bind(wx.EVT_RIGHT_DOWN, self.rightclick)
Python
from DriverInterface import DriverInterface from math import * from numpy import * from numpy.linalg import * from BonyLandmark import BonyLandmark from Sensor import Sensor import fake_fob import time import wx ## Handles communication with the Flock of Birds system through the serial port. # This class uses the fake_fob.py to simulate the FoB hardware. class FoBDriverOld(DriverInterface): ## The constructor of FoBDriver. You may only call this method if you inherit from DriverInterface. def __init__(self, main, comport = 0, baudrate = 19200, timeout = 5, numbirds = 10): if not isinstance(self, DriverInterface): raise TypeError("FoBDriver.__init__ requires DriverInterface.") ## Opens a workfile to write the raw data to. self.fileWriter = open('workfile.txt', 'w') # Set paramaters that are specific to the FoB hardware. ## COM port to be used = 0 self.comport = comport ## The Baudrate = 19200. self.baudrate = baudrate ## Default timeout in seconds. self.timeout = timeout ## Number of connected birds including XRC. self.numbirds = numbirds ## Initialize the FoB simulator. self.fobbie = fake_fob.FOB() self.fobbie.open(self.comport, self.baudrate, self.timeout) self.fobbie.fbbAutoConfig(self.numbirds) self.fobbie.fbbReset() time.sleep(1) # Attributes used to make matrix calculations. ## Main wx.App derived instance. self.main = main ## The list with five position measurements of each sensor connected to the corresponding bony landmarks. self.imSensors = [[] for i in range(len(self.main.bonyLandmarks) - len(self.main.GHJoints))] ## The list with five position measurements of each bony landmark as measured with the stylus. # Each entry in the list represents a bony landmark. self.stylus = [[] for i in range(len(self.main.bonyLandmarks) - len(self.main.GHJoints))] stylfile = main.prefReader.stylusFile try: stylusData = open(stylfile,'r').read() except: msg = "An error ocurred while opening %s." % stylfile dlg = wx.MessageDialog(self.main.gui, msg, 'Warning', wx.OK | wx.NO_DEFAULT | wx.ICON_EXCLAMATION) dlg.ShowModal() ## The length of the stylus. self.__stylusLength = transpose(matrix("["+stylusData+"]"))/10 ## Puts FoB to sleep. You may only call this method if you inherit from DriverInterface. def sleep(self): if not isinstance(self, DriverInterface): raise TypeError("FoBDriver.sleep requires DriverInterface.") self.fobbie.sleep() ## Runs Fob. You may only call this method if you inherit from DriverInterface. def run(self): if not isinstance(self, DriverInterface): raise TypeError("FoBDriver.run requires DriverInterface.") self.fobbie.run() ## Closes communication. You may only call this method if you inherit from DriverInterface. def close(self): if not isinstance(self, DriverInterface): raise TypeError("FoBDriver.close requires DriverInterface.") self.fobbie.sleep() self.fobbie.close() self.fileWriter.close() def closeBLFile(self): self.fileWriter.close() ## Returns raw FoB data of the sensor with the corresponding ID. You may only call this method if you inherit from DriverInterface. # @param[in] id The sensor ID from which we are requesting data. def get_sample(self, id): if not isinstance(self, DriverInterface): raise TypeError("FoBDriver.get_sample requires DriverInterface.") sensorstring = id.split('_') sample = self.fobbie.point(int(sensorstring[1])) # Write the rawData to a file if self.main.DATA_WRITE or self.main.FAST_ACQUISITION: self.fileWriter.write(sensorstring[1] + ' %.2f %.2f %.2f \r\n %.2f %.2f %.2f \r\n %.2f %.2f %.2f \r\n %.2f %.2f %.2f \r\n\r\n' % (sample[0], sample[1], sample[2], sample[3], sample[4],sample[5], sample[6], sample[7], sample[8], sample[9],sample[10],sample[11])) self.fileWriter.flush() return sample ## Calculates the rotations x, y, and z resp. around the x-, y-, and z-axis from matrix R. # You may only call this method if you inherit from DriverInterface. def __RotXYZ(self, R): if not isinstance(self, DriverInterface): raise TypeError("FoBDriver.__init__ requires DriverInterface.") y1 = asin(R[0,2]) sz = -R[0,1] / cos(y1) cz = R[0,0] / cos(y1) z1 = atan2(sz,cz) sx = -R[1,2] / cos(y1) cx = R[2,2] / cos(y1) x1 = atan2(sx,cx) if y1 >= 0: y2 = pi - y1 else: y2 = -pi -y1 sz = -R[0,1] / cos(y2) cz = R[0,0] / cos(y2) z2 = atan2(sz,cz) sx = -R[1,2] / cos(y2) cx = R[2,2] / cos(y2) x2 = atan2(sx,cx) if (-pi/2 <= y1) and (y1 <= pi/2): return (x1, y1, z1) else: return (x2, y2, z2) ## Calculates the endpoint of the stylus. # You may only call this method if you inherit from DriverInterface. def __StylusCompensation(self, sensorPosition, sensorRotation): if not isinstance(self, DriverInterface): raise TypeError("FoBDriver.__init__ requires DriverInterface.") return sensorPosition + transpose(sensorRotation) * self.__stylusLength ## Calculates the relative vector of the bony landmark w.r.t. the sensor. # You may only call this method if you inherit from DriverInterface. def __CalcBLVec(self, bonyLandmarkPosition, sensorPosition, sensorRotation): if not isinstance(self, DriverInterface): raise TypeError("FoBDriver.__init__ requires DriverInterface.") return sensorRotation * (bonyLandmarkPosition - sensorPosition) ## Calculate position vector of bony landmark relative to its sensors. # You may only call this method if you inherit from DriverInterface. def GetBLRelativePosition(self, stylusSensor, sampleSensor): if not isinstance(self, DriverInterface): raise TypeError("FoBDriver.__init__ requires DriverInterface.") relativeSensor = None globalBLpos = self.__StylusCompensation(stylusSensor.position,stylusSensor.rotation) blvec = self.__CalcBLVec(globalBLpos, sampleSensor.position, sampleSensor.rotation) return blvec.mean(axis=1) ## Calculates the global vector of the bony landmark w.r.t. the transmitter coordinate system, # using the local vector of the bony landmark and global vector of the sensor. # You may only call this method if you inherit from DriverInterface. def RelativeToGlobal(self, relativePosition, sensorPosition, sensorRotation): if not isinstance(self, DriverInterface): raise TypeError("FoBDriver.__init__ requires DriverInterface.") return sensorPosition + transpose(sensorRotation) * relativePosition ## Gets raw position and rotation data for all sensors. # You may only call this method if you inherit from DriverInterface. def SampleSensors(self): if not isinstance(self, DriverInterface): raise TypeError("FoBDriver.__init__ requires DriverInterface.") for sensor in self.main.sensors: m = self.main.driver.get_sample(sensor.ID) if not self.main.FAST_ACQUISITION: sensor.rawPosition = m[0:3] sensor.rawRotation = m[3:13] sensor = self.CalibrateSingleSensor(sensor) ## Append a new 'OnPedal transform' to the "bony landmark - sensor mapping": imSensor. # You may only call this method if you inherit from DriverInterface. # @param[in] blIndex The bony landmark number. # @param[in] sensorID The sensor number. def FetchBL_SensorPositionRotation(self, blIndex, sensorID): if not isinstance(self, DriverInterface): raise TypeError("FoBDriver.__init__ requires DriverInterface.") # Get the stylus. stylusSample = self.get_sample(self.main.sensors[0].ID) outputStylusSensor = Sensor(self.main.sensors[0].ID) outputStylusSensor.rawPosition = stylusSample[0:3] outputStylusSensor.rawRotation = stylusSample[3:13] outputStylusSensor = self.CalibrateSingleSensor(outputStylusSensor) # Get the measurements for the bony landmark with sensorID id. sensorTransform = self.get_sample(sensorID) outputSensor = Sensor(sensorID) outputSensor.rawPosition = sensorTransform[0:3] outputSensor.rawRotation = sensorTransform[3:13] outputSensor = self.CalibrateSingleSensor(outputSensor) # Outputsensor now has a calibrated position and rotation, add it to imSensors. if len(self.imSensors[blIndex]) == 0: self.imSensors[blIndex] = [outputSensor] self.stylus[blIndex] = [outputStylusSensor] else: self.imSensors[blIndex].append(outputSensor) self.stylus[blIndex].append(outputStylusSensor) ## This is the new version of CalibrateSensorSSS, because we are only going to calibrate one sensor now. # You may only call this method if you inherit from DriverInterface. # @param[in] singleSensor The sensor we are calibrating. def CalibrateSingleSensor(self, singleSensor): if not isinstance(self, DriverInterface): raise TypeError("FoBDriver.__init__ requires DriverInterface.") sensorstring = singleSensor.ID.split('_') sensornr = int(sensorstring[1]) # Insert the rawpositions in a matrix. rawData = matrix("[%f %f %f]" % (singleSensor.rawPosition[0],singleSensor.rawPosition[1],singleSensor.rawPosition[2])) # Include the rawrotations in the same matrix. rawData = vstack((rawData, matrix("[%f %f %f;%f %f %f;%f %f %f]" % (singleSensor.rawRotation[0], singleSensor.rawRotation[1], singleSensor.rawRotation[2], singleSensor.rawRotation[3], singleSensor.rawRotation[4], singleSensor.rawRotation[5], singleSensor.rawRotation[6], singleSensor.rawRotation[7], singleSensor.rawRotation[8])))) # Calibrate the data. newData = self.__CalibrateRawData(rawData) # Set the newly caclulated positions and rotation in the sensor. pos = transpose(newData[0]) # When using the data sets of the fob visualizer of 2007-2008, don't transpose this for a correct visualization. rot = transpose(newData[1:4]) singleSensor.position = pos singleSensor.rotation = rot return singleSensor ## Used by the CalibrateSingleSensor method. # Applies the calibration procedure on the raw FoB data using the given calibration file path. # # This is called by CalibrateSensors after having built up the rawData structure. # The /10 at the very end, and the *25.4 at the beginning, seem to imply that this method returns the position in centimetres. # You may only call this method if you inherit from DriverInterface. # # @param[in] rawData Matrix with 4 columns of 'raw' fob data (sensor_id, pos, pos, pos) or (sensor_id, rot, rot, rot). # For each sensor id, there is one line with position, and three with the complete rotation matrix. # After a complete sequence of all sensor IDs, the next frame is added. def __CalibrateRawData(self, rawData): if not isinstance(self, DriverInterface): raise TypeError("FoBDriver.__init__ requires DriverInterface.") # First iterate through all the POSITION lines (the skip=4) in # the range skips all the rotation matrices. for i in range(0,size(rawData,0),4): # Convert SensorPosition inches to millimetres (in place). rawData[i,0:3] = rawData[i,0:3] # Transpose rotation matrix, determine rotations x,y,z # around x-, y- and z- axes. (x,y,z) = self.__RotXYZ(transpose(rawData[i:i+3,0:3])) # Create matrix c [posx, posy, posz, rotx, roty rotz] #a = [[-2.256526, -1.493317, -1.056877]] a = matrix("[%f %f %f]" % (x,y,z)) b = rawData[i,0:3] c = concatenate((b,a),1) # Append matrix c to reg. if i > 0: reg = concatenate((reg,c)) else: reg = c # for EACH row (of 6 elements) do: # aa ab ac bb bc cc (done here for 3; just determine all combinations) # and store result vector / matrix in T_cross # we could do this per sample... for i in range(0,6): for j in range(i,6): if (i==0) and (j==0): T_cross = multiply(reg[:,i],reg[:,j]) else: T_cross = concatenate((T_cross, multiply(reg[:,i],reg[:,j])),1) # Determine magnitude of position vector. # sqrt(x^2 + y^2 + z^2) af = sqrt(multiply(reg[:,0],reg[:,0]) + multiply(reg[:,1],reg[:,1]) + multiply(reg[:,2],reg[:,2])) # T has 29 columns. # # 1 x y z magpos rotx roty rotz aa bb cc bb bc cc # 1 x y z magpos rotx roty rotz ... # 1 x y z magpos rotx roty rotz ... T = hstack((ones((size(reg,0),1)), reg[:,0:3], af, reg[:,3:6], T_cross)) # th_nonline has 29 rows and 3 columns th_nonlin = self.main.calibrationMatrix # error has size(reg,0) rows and 3 columns error = T * th_nonlin # Copy complete rawData (only positions have been converted to millimetres). newData = rawData.copy() # For each position (note the skip=4), add x, y and z error to # the position, divide the whole thing by 10 to get centimetres. for i in range(0, size(rawData,0), 4): newData[i,0:3] = (rawData[i,0:3] +error[(i)/4,:])/10 return newData
Python
from vtk import vtkSTLReader, vtkTextActor, vtkPoints, vtkLandmarkTransform, vtkRenderer, vtkPolyDataMapper, vtkSphereSource, vtkConeSource, vtkPolyDataReader, vtkPolyDataReader, vtkActor, vtkTriangleFilter, vtkPolyDataNormals, vtkPolyData from RecordingState import RecordingState from PlaybackState import PlaybackState from Sensor import Sensor from RecordingsProcessor import RecordingsProcessor from numpy import * from time import strftime import wx import os, sys ## VisualizationState contains the functionality behind the VisualizationPanel. # This state ensures with for every frame the bones of the skeleton model are set between the calculated bony landmarks. # It also takes care of the playback of these frames. class VisualizationState: ## The constructor of VisualizationState. # @param[in] main Main wx.App derived instance. def __init__(self, main): ## Main wx.App derived instance. self.main = main ## The framerate of the visualization. self.frameRate = self.main.config.ReadFramerate() ## Used to test between the Playback and Recording subpanel of VisualizationPanel. self.panel = None ## Instantiation of the PlaybackState. self.playbackState = PlaybackState(self,main) ## Instantiation of the RecordingState. self.recordingState = RecordingState(self, main) ## Instantiation of the RecordingProcessor. self.recordingsProcessor = RecordingsProcessor(self, main) self.__meshPos = self.__GetMeshPositions() def get_actor_matrices(self): actorList = self.playbackState.actorList scap = actorList[81].GetUserTransform().GetMatrix() # scapula hum = actorList[82].GetUserTransform().GetMatrix() # humerus return [scap, hum] ## Sets the state to the current visualization subpanel. # Updates the bony landmarks to their current position, using the sensor positions. # Also takes care of the rendering of the current position. def update_actor_positions(self): if self.panel.visNotebook.GetCurrentPage().name=="Playback" and self.playbackState.selectedRecording != None: state = self.playbackState recording = state.selectedRecording sensorsUpdate = recording.GetSensorsCurrentFrame() bonyLandmarksUpdate = recording.bonyLandmarksRecorded timeStampUpdate = recording.GetCurrentTimeStamp() else: state = self.recordingState sensorsUpdate = self.main.sensors bonyLandmarksUpdate = self.main.bonyLandmarks timeStampUpdate = strftime("%Y-%m-%d %H:%M:%S") # Update the time stamp display. #state.timeStampActor.SetInput(timeStampUpdate) ## List containing the current bony landmark positions in the visualization. self.__blPos = [] for i in range(0, len(bonyLandmarksUpdate)): # This bony landmark has a sensor that determines its position. if bonyLandmarksUpdate[i].ID != -1: state.blActorList[i].AddPosition( -state.blActorList[i].GetCenter()[0], -state.blActorList[i].GetCenter()[1], -state.blActorList[i].GetCenter()[2] ) relativeSensor = None for sensor in sensorsUpdate: if sensor.ID == bonyLandmarksUpdate[i].sensorID: relativeSensor = sensor blPos = self.main.driver.RelativeToGlobal(bonyLandmarksUpdate[i].relativePosition, relativeSensor.position, relativeSensor.rotation) state.blActorList[i].AddPosition(blPos[0], blPos[1], blPos[2]) self.__blPos.append(blPos) # Update sensors. for i in range(0, len(sensorsUpdate)): state.sensorActorList[i].AddPosition( -state.sensorActorList[i].GetCenter()[0], -state.sensorActorList[i].GetCenter()[1], -state.sensorActorList[i].GetCenter()[2] ) state.sensorActorList[i].AddPosition( sensorsUpdate[i].position[0], sensorsUpdate[i].position[1], sensorsUpdate[i].position[2] ) self.SetBones() if state.FIRST_TIME: state.ren.ResetCamera() self.InitCamera(state) state.FIRST_TIME = False if self.main.motion_analysis_started: if self.__blPos[12].tolist() != self.__blPos[13].tolist()\ and self.__blPos[22].tolist() != self.__blPos[23].tolist(): blPosList = [] for i in range(0, len(self.__blPos)): blPosList.append( [self.__blPos[i].tolist()[0][0],\ self.__blPos[i].tolist()[1][0],\ self.__blPos[i].tolist()[2][0]] ) self.main.angleCalculations.SetupCoordinateSystems(blPosList) self.main.angleCalculations.Angles() state.panel.widget.Render() ## Maps every bone of the skeletal model to the actual bony landmark coordinates. def SetBones(self): # Read the 3d model bones and bony landmark connection from the config file. modelConnectionList = self.main.config.Read3DModelConnection() # Call the SetBones method for each connection. for i in range(0, len(modelConnectionList)): self.SetBone(modelConnectionList[i][0], modelConnectionList[i][1]) ## Maps coordinates of the bony landmarks in the model to the actual coordinates of the bony landmarks. # @param[in] boneIndices The bone to be mapped to the bony landmark positions. # @param[in] blIndices The bony landmark. def SetBone(self, boneIndices, blIndices): if self.panel.visNotebook.GetCurrentPage().name=="Playback" and self.playbackState.selectedRecording != None: actorList = self.playbackState.actorList state = self.playbackState bonyLandmarksUpdate = self.playbackState.selectedRecording.bonyLandmarksRecorded else: actorList = self.recordingState.actorList state = self.recordingState bonyLandmarksUpdate = self.main.bonyLandmarks for j in range(0, len(boneIndices)): if self.main.gui.Is3DModelChecked(): actorList[boneIndices[j]].VisibilityOn() mPoints = vtkPoints() rPoints = vtkPoints() # Because the bony landmark ID won't be the same as the index anymore, the blIDToIndex is used to map the bony landmark ID to its index. # This was done to improve on the generic aspects of the program. blIDToIndex = self.main.GetBonyLandmarkDict(True) for i in range(0, len(blIndices)): ID = blIndices[i] if self.main.gui.IsBonyLandmarksChecked(): state.blActorList[blIDToIndex[ID]].VisibilityOn() # If there are no measurements available for the bony landmark, turn visibility off. if bonyLandmarksUpdate[blIDToIndex[ID]].relativePosition[0]==0.0 and \ bonyLandmarksUpdate[blIDToIndex[ID]].relativePosition[1]==0.0 and \ bonyLandmarksUpdate[blIDToIndex[ID]].relativePosition[2]==0.0: for j in range(0, len(boneIndices)): actorList[boneIndices[j]].VisibilityOff() state.blActorList[blIDToIndex[ID]].VisibilityOff() # Don't use the bl ID to Index mapping for the meshPos. The Bony landmark ID corresponds with its position index in the blpositions.ini file. mPoints.InsertPoint(i, self.__meshPos[ID]) rPoints.InsertPoint(i, self.__blPos[blIDToIndex[ID]]) transformer = vtkLandmarkTransform() transformer.SetSourceLandmarks(mPoints) transformer.SetTargetLandmarks(rPoints) for i in range(0, len(boneIndices)): actorList[boneIndices[i]].SetUserTransform(transformer) ## Toggles the visualization of the sensor on the model on and off. def ToggleSensors(self): visible = self.main.gui.IsSensorsChecked() for actor in self.playbackState.sensorActorList: actor.SetVisibility(visible) for actor in self.recordingState.sensorActorList: actor.SetVisibility(visible) try: self.playbackState.panel.widget.Render() self.recordingState.panel.widget.Render() except: pass ## Toggles the visualization of the bony landmarks on the model on and off. def ToggleBonyLandmarks(self): visable = self.main.gui.IsBonyLandmarksChecked() for actor in self.playbackState.blActorList: actor.SetVisibility(visable) for actor in self.recordingState.blActorList: actor.SetVisibility(visable) try: self.playbackState.panel.widget.Render() self.recordingState.panel.widget.Render() except: pass ## Toggles the visualization of the 3D the model on and off. def Toggle3DModel(self): visable = self.main.gui.Is3DModelChecked() for actor in self.playbackState.actorList: actor.SetVisibility(visable) for actor in self.recordingState.actorList: actor.SetVisibility(visable) try: self.playbackState.panel.widget.Render() self.recordingState.panel.widget.Render() except: pass ## Method used for stopping animation. A check is done whether visualization is playing. # If so, it is stopped using onTogglePlayPause. def Stop(self): if self.playbackState.PLAYING: self.playbackState.OnTogglePlayPause() if self.recordingState.PLAYING: self.recordingState.OnTogglePlayPause() ## Event handler, starts or stops the playback of the visualization in the opened VTK window. def OnTogglePlayPause(self): if self.panel.visNotebook.GetCurrentPage().name == "Recording": self.recordingState.OnTogglePlayPause() else: self.playbackState.OnTogglePlayPause() ## Reads the mesh positions out of a file. # @return[matrix] The mesh positions. def __GetMeshPositions(self): try: file = open(self.main.prefReader.blPositionsFile, 'r') except: msg = "Could not open %s." % self.main.prefReader.blPositionsFile dlg = wx.MessageDialog(self.main.gui, msg, 'Warning', wx.OK | wx.NO_DEFAULT | wx.ICON_EXCLAMATION) dlg.ShowModal() lines = file.read().split('\n') meshPos = [] for line in lines: line = line.split() meshPos.append([float(x) for x in line]) return meshPos ## Initiates the VTK screen and the needed models and camera. # @param[in] state An instantiation of VisualizationState, PlaybackState or RecordingState. def InitiateVTK(self, state): state.ren = vtkRenderer() state.ren.SetBackground(.92, .93, .95) state.ren.ResetCamera() state.ren.GetActiveCamera().Azimuth(90) state.ren.GetActiveCamera().Roll(90) ## Bony Landmark Actor List used for rendering bony landmarks spheres. state.blActorList = [] ## Sensor Actor List used for rendering sensors spheres. state.sensorActorList = [] ## Actor List used for rendering the 3d skeleton model. state.actorList = [] ## Set the timeStamp Actor for the state, and the text format properties. state.timeStampActor = vtkTextActor() state.timeStampActor.SetTextScaleModeToViewport() state.timeStampActor.SetDisplayPosition(20,20) state.timeTextProperty = state.timeStampActor.GetTextProperty() state.timeTextProperty.SetColor(255,255,255) state.timeTextProperty.SetFontSize(7) state.timeStampActor.SetTextProperty(state.timeTextProperty) state.ren.AddActor(state.timeStampActor) ## Sets the actors for the according state and its render window. # Always called after VTK is initiated. # @param[in] state The state using this method. # @param[in] numBLActors The number of bony landmarks to be displayed by the renderer. # @param[in] numSensorActors The number of Sensors to be displayed by the renderer. # @param[in] numGHJoints The number of GH Joints the renderer works with. def SetRenderActors(self, state, numBLActors, numSensorActors, numGHJoints): ## Remove Actors if they have been added to the state renderer, re-add the timeStampActor. allActors = concatenate((state.blActorList, state.sensorActorList, state.actorList),1) for actor in allActors: state.ren.RemoveActor(actor) state.ren.AddActor(state.timeStampActor) blMapperList = [] blSphereList = [] sensorMapperList = [] sensorSphereList = [] for i in range(0,numBLActors): state.blActorList.append(vtkActor()) blMapperList.append(vtkPolyDataMapper()) blSphereList.append(vtkSphereSource()) blMapperList[i].SetInput(blSphereList[i].GetOutput()) state.blActorList[i].SetMapper(blMapperList[i]) # Colour BLs Yellow state.blActorList[i].GetProperty().SetColor(1,1,0) state.ren.AddActor(state.blActorList[i]) # Colour GH-Joints Green. # Assuming the last bony landmarks are the two GH-Joints that have been appended to the end of the bony landmark list. for i in range(1,numGHJoints+1): state.blActorList[len(state.blActorList)-i].GetProperty().SetColor(0,1,0) #state.blActorList[len(state.blActorList)-2].GetProperty().SetColor(0,1,0) #state.blActorList[len(state.blActorList)-1].GetProperty().SetColor(0,1,0) for i in range(0,numSensorActors): state.sensorActorList.append(vtkActor()) sensorMapperList.append(vtkPolyDataMapper()) sensorSphereList.append(vtkSphereSource()) sensorMapperList[i].SetInput(sensorSphereList[i].GetOutput()) state.sensorActorList[i].SetMapper(sensorMapperList[i]) # Colour Sensors Red. state.sensorActorList[i].GetProperty().SetColor(1,0,0) if i != 0: state.ren.AddActor(state.sensorActorList[i]) mapperList = [] readerList = [] triangleList = [] normalList = [] for i in range(0, self.main.config.Read3DModelParts()): state.actorList.append(vtkActor()) mapperList.append(vtkPolyDataMapper()) filename = self.main.config.Read3DFileName() for j in self.main.replacement_tuples: if i == j[0]: filename = j[1] print 'Replacing: ', filename if os.path.splitext(filename)[-1]=='.vtk': readerList.append(vtkPolyDataReader()) readerList[i].SetFileName(filename % (i+1)) #if i == readerList[i].OpenVTKFile() else: readerList.append(vtkSTLReader()) readerList[i].SetFileName(filename) #if i == readerList[i].Update() if self.main.Smooth3DModel: readerList[i].Update() p1 = readerList[i].GetOutput() p2 = vtkPolyData() p2.DeepCopy(p1) triangleList.append(vtkTriangleFilter()) triangleList[i].SetInputConnection(readerList[i].GetOutputPort()) normalList.append(vtkPolyDataNormals()) normalList[i].SetInput(triangleList[i].GetOutput()) normalList[i].SplittingOff() normalList[i].ConsistencyOff() mapperList[i].SetInput(normalList[i].GetOutput()) else: mapperList[i].SetInput(readerList[i].GetOutput()) mapperList[i].Update() state.actorList[i].SetMapper(mapperList[i]) state.ren.AddActor(state.actorList[i]) state.actorList[i].GetProperty().SetColor(1, .97, .85) state.actorList[i].VisibilityOff() if os.path.splitext(filename)[-1]=='.vtk': readerList[i].CloseVTKFile() ## Initialises the camera position, used when it is reset. # @param[in] state The state in which the camera will be initialized. def InitCamera(self,state): state.initCamPosition = state.ren.GetActiveCamera().GetPosition() state.initCamFocalPoint = state.ren.GetActiveCamera().GetFocalPoint() state.initCamViewUp = state.ren.GetActiveCamera().GetViewUp() ## Resets the camera for the state passed. # @param[in] state The state in which the camera will be reset. def ResetCamera(self,state): state.ren.GetActiveCamera().SetPosition(state.initCamPosition) state.ren.GetActiveCamera().SetFocalPoint(state.initCamFocalPoint) state.ren.GetActiveCamera().SetViewUp(state.initCamViewUp) state.ren.ResetCamera() def UpdateBL(self, index, bl): self.__meshPos[index] = bl def GetBL(self, index): return self.__meshPos[index]
Python
from vtk import vtkRenderer, vtkPolyDataMapper, vtkSphereSource, vtkPolyDataReader, vtkActor from time import sleep, clock from numpy import matrix import wx import os ## PlaybackState provides the functionality for the Recording panel. # Plays the recorded movements. class PlaybackState: ## The constructor of PlaybackState. # @param[in] parent The wx window (VisualizationState) of this panel. def __init__(self, parent, main): ## The wx window (VisualizationState) of this panel. self.parent = parent ## Main wx.App derived instance. self.main = main ## Flag indicating whether the playback is on or off. self.PLAYING = False ## Flag indicating whether this is the first session or not. self.FIRST_TIME = True ## The list of recordings in the recordingslist. self.loadedRecordings = [] ## Variable for the current selected recording. self.selectedRecording = None # Initiate VTK render window for this state. self.parent.InitiateVTK(self) ## Toggles the playback on or off. def OnTogglePlayPause(self): if self.PLAYING: self.PLAYING = False elif self.selectedRecording != None: self.PLAYING = True self.Play() ## Plays recording when the PLAYING flag is On, until the recording has reached its end. def Play(self): while self.PLAYING: if self.selectedRecording.currentFrame < self.selectedRecording.numberOfFrames: startTime = clock() self.parent.update_actor_positions() self.selectedRecording.currentFrame += 1 self.SetSlider(self.selectedRecording.currentFrame) endTime = clock() self.parent.main.Yield() if (endTime - startTime) < (1.0/self.parent.frameRate): sleep((1.0/self.parent.frameRate) - (endTime - startTime)) else: self.panel.OnTogglePlayPause(None) def GetRowVectors(self, matrix): row_vectors = [[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]] for row in range(0, 4): for col in range(0, 4): row_vectors[row][col] = matrix.GetElement(row, col) return row_vectors ## Stores the matrices of the humerus and scapula def PlayAndStore(self): self.selectedRecording.currentFrame = 0 scapula_list = [] humerus_list = [] while self.selectedRecording.currentFrame < self.selectedRecording.numberOfFrames: startTime = clock() self.parent.update_actor_positions() matrices = self.parent.get_actor_matrices() scapula_list.append( self.GetRowVectors(matrices[0])) humerus_list.append( self.GetRowVectors(matrices[1])) self.selectedRecording.currentFrame += 1 self.SetSlider(self.selectedRecording.currentFrame) endTime = clock() self.WriteTransformsToFile(scapula_list) self.WriteTransformsToFile(humerus_list) def WriteTransformsToFile(self, matrix_list): dlg = wx.FileDialog(self.panel, message="Save Matrix File", defaultDir=os.getcwd(), defaultFile="", wildcard="Txt-file (*.txt)|*.txt", style=wx.SAVE | wx.CHANGE_DIR | wx.OVERWRITE_PROMPT) if dlg.ShowModal() == wx.ID_OK: txtpath = dlg.GetPath() fileWriter = open(txtpath, 'w') blRange = len(matrix_list) for i in range(0, blRange): for j in range(0,4): fileWriter.write('%.3f %.3f %.3f %.3f\n' % (matrix_list[i][j][0], matrix_list[i][j][1], matrix_list[i][j][2], matrix_list[i][j][3])) fileWriter.write('\n') fileWriter.close() ## Event handler, stops playback of the recording. def OnStop(self, event): if self.PLAYING: self.panel.OnTogglePlayPause(None) elif self.selectedRecording != None: self.SetSlider(0) self.selectedRecording.currentFrame = 0 self.parent.update_actor_positions() ## Event handler, goes back one frame. def OnBackward(self, event): if self.selectedRecording != None: index = self.panel.recordingList.GetSelection() self.selectedRecording.currentFrame = max(self.selectedRecording.currentFrame-1, 0) self.parent.update_actor_positions() self.SetSlider(self.selectedRecording.currentFrame) ## Event handler, goes one frame forward. def OnForward(self, event): if self.selectedRecording != None: index = self.panel.recordingList.GetSelection() self.selectedRecording.currentFrame = min(self.selectedRecording.currentFrame + 1, self.selectedRecording.numberOfFrames - 1) self.parent.update_actor_positions() self.SetSlider(self.selectedRecording.currentFrame) ## Event handler, Sets the framenumber of the selected recording to the value of the scrollbar. def OnSlide(self, event): if self.selectedRecording != None: self.selectedRecording.currentFrame = self.panel.slider.GetValue() self.parent.update_actor_positions() ## Event handler, deletes the selected recording. def OnDelete(self, event): if self.selectedRecording != None: index = self.panel.recordingList.GetSelection() msg = "Are you sure you want to delete '%s'?" % self.panel.recordingList.GetString(index) dlg = wx.MessageDialog(self.panel, msg, 'Warning', wx.YES_NO | wx.NO_DEFAULT | wx.ICON_EXCLAMATION) if(dlg.ShowModal() == wx.ID_YES): if self.PLAYING: self.panel.OnTogglePlayPause(None) try: os.remove(self.selectedRecording.filename) self.loadedRecordings.__delitem__(index) self.panel.recordingList.Delete(index) except OSError: msg = "Could not delete file '%s'" %self.selectedRecording.filename dlgError = wx.MessageDialog(self.panel, msg, 'Error', wx.OK | wx.ICON_ERROR) dlgError.ShowModal() dlgError.Destroy() # If the list is empty, the selectedRecording will be set back to None value. if len(self.loadedRecordings) == 0: self.selectedRecording = None self.SetSlider(0) self.panel.DisableFunctions() else: self.panel.recordingList.Select(0) self.OnItemSelected(None) dlg.Destroy() ## Event handler for clicking the rename button. def OnRename(self, event): if self.selectedRecording != None: msg = "Enter a file name" dlg = wx.TextEntryDialog(self.panel,msg,'Rename',self.selectedRecording.filename) if dlg.ShowModal() == wx.ID_OK: index = self.panel.recordingList.GetSelection() string = dlg.GetValue() if self.panel.recordingList.GetStrings().__contains__(string): msg = "'%s' already exists" % string dlgError = wx.MessageDialog(self.panel, msg, 'Error', wx.OK | wx.ICON_ERROR) dlgError.ShowModal() dlgError.Destroy() else: try: os.rename(self.selectedRecording.filename, string) self.selectedRecording.filename = string string = string.split("\\") self.panel.recordingList.SetString(index, string[len(string)-1]) except OSError: msg = "Could not rename file '%s'" % string dlgError = wx.MessageDialog(self.panel, msg, 'Error', wx.OK | wx.ICON_ERROR) dlgError.ShowModal() dlgError.Destroy() dlg.Destroy() ## Event handler for clicking the import button. # Shows open file dialog with given message and wildcards on the given dir. def OnImport(self, event): # store the working directory defaultWorkingDir = os.getcwd() msg = "Select a recording to open" wildcard = "FOB file (*.fob)|*.fob|" \ "All files (*.*)|*.*" dlg = wx.FileDialog(self.panel, msg, os.getcwd(), "", wildcard, wx.FD_OPEN|wx.FD_CHANGE_DIR) if dlg.ShowModal() == wx.ID_OK: try: path = dlg.GetPath() importedRecording = self.parent.recordingsProcessor.LoadRecording(path) importedRecording.filename = dlg.GetPath() self.addRecording(importedRecording) except IOError: msg = "Could not import file" dlgError = wx.MessageDialog(self.panel, msg, 'Error', wx.OK | wx.ICON_ERROR) dlgError.ShowModal() dlgError.Destroy() # Restore the working directory. os.chdir(defaultWorkingDir) ## Event handler for the changing of selection in the recordings list. def OnItemSelected(self, event): newlySelectedRecording = self.loadedRecordings[self.panel.recordingList.GetSelection()] self.main.bonyLandmarks = newlySelectedRecording.bonyLandmarksRecorded if self.selectedRecording != newlySelectedRecording: self.selectedRecording = newlySelectedRecording self.panel.slider.SetMax(self.selectedRecording.numberOfFrames - 1) self.selectedRecording.currentFrame = 0 self.panel.slider.SetValue(self.selectedRecording.currentFrame) self.panel.EnableFunctions() self.parent.SetRenderActors(self, len(self.selectedRecording.bonyLandmarksRecorded), len(self.selectedRecording.sensorsRecorded), len(self.selectedRecording.GHJointsRecorded)) if self.PLAYING: self.panel.OnTogglePlayPause(None) self.parent.update_actor_positions() ## Sets the frame number of the selected recording on the value of the slider. # @param[in] frameNumber The current frame number of the selected recording. def SetSlider(self, frameNumber): self.panel.slider.SetValue(frameNumber) ## Adds a new recording to the list. # @param[in] newRecording The new recording to add to the list. def addRecording(self, newRecording): self.loadedRecordings.append(newRecording) filename = newRecording.filename.split("\\") self.panel.recordingList.Append(filename[len(filename)-1])
Python
import wx from wx.lib.hyperlink import HyperLinkCtrl ## Displays information concerning the application in a dialog class AboutDialog(wx.Dialog): ## The constructor of AboutDialog. GUI elements of the dialog are setup here. # @param[in] gui GUI instance. # @param[in] **kwds Automatically passed parameter. def __init__(self, gui, **kwds): kwds["style"] = wx.DEFAULT_DIALOG_STYLE wx.Dialog.__init__(self, gui, **kwds) image = wx.StaticBitmap(self, -1, wx.Bitmap("Images/About.png", wx.BITMAP_TYPE_PNG)) tudelft = HyperLinkCtrl(self, wx.ID_ANY, "www.tudelft.nl", URL="http://www.tudelft.nl/") lumc = HyperLinkCtrl(self, wx.ID_ANY, "www.lumc.nl", URL="http://www.lumc.nl/") okButton = wx.Button(self, wx.ID_OK) # Set Properties self.SetTitle("About Flock of Birds Visualizer") self.SetIcon(wx.Icon(gui.main.config.root+"\\Images\\icon.ico", wx.BITMAP_TYPE_ICO, 32, 32)) # Do Layout wrapperSizer = wx.FlexGridSizer(3, 1, 0, 0) hyperlinkSizer = wx.GridSizer(1, 2, 0, 0) wrapperSizer.Add(image, 0, 0, 0) hyperlinkSizer.Add(tudelft, 0, wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL, 0) hyperlinkSizer.Add(lumc, 0, wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL, 0) wrapperSizer.Add(hyperlinkSizer, 1, wx.ALL|wx.EXPAND, 5) wrapperSizer.Add(okButton, 0, wx.ALL|wx.ALIGN_RIGHT, 5) self.SetSizer(wrapperSizer) wrapperSizer.Fit(self) self.Layout() self.Centre()
Python
import wx from wx.lib.filebrowsebutton import FileBrowseButton ## Contains the preferences window, in which the location of the files can be specified. class PreferencesDialog(wx.Dialog): ## The contructor of PreferencesDialog. GUI elements of the window are setup here. # @param[in] gui Gui instance. # @param[in] **kwds Automatically passed parameter. def __init__(self, gui, **kwds): kwds["style"] = wx.DEFAULT_DIALOG_STYLE|wx.RESIZE_BORDER|wx.THICK_FRAME wx.Dialog.__init__(self, gui, **kwds) wildcardDat = "DAT file (*.dat)|*.dat|" \ "All files (*.*)|*.*" wildcardIni = "INI file (*.ini)|*.ini|" \ "All files (*.*)|*.*" # Initialize components. stylusLabel = wx.StaticText(self, -1, "Stylus file:") ## Location of the stylusFile, contains data for the pointer sensor. # Default location: Data\Stylus.dat. self.stylusFile = FileBrowseButton(self, -1, labelText = "", fileMask = wildcardDat, size = (450,-1)) calibrationLabel = wx.StaticText(self, -1, "Calibration file:") ## Location of the calibration file, containing data concerning calibration data for the elektromagnetic field of the Flock of Birds system. # Default location: Data\Calibration.dat. self.calibrationFile = FileBrowseButton(self, -1, labelText = "", fileMask = wildcardDat, size = (450,-1)) blPositionsLabel = wx.StaticText(self, -1, "3D Bony landmark positions file:") ## Location of the bony landmark position file, containing coordinates for the bony landmarks in the bone models. # Default location: \BLPositions.ini. self.blPositionsFile = FileBrowseButton(self, -1, labelText = "", fileMask = wildcardIni, size = (450,-1)) configLabel = wx.StaticText(self, -1, "Configuration file:") ## Location of the confid file, containing coordinates for the bony landmarks in the bone models. # Default location: \Config.ini. self.configFile = FileBrowseButton(self, -1, labelText = "", fileMask = wildcardIni, size = (450,-1)) static_line_1 = wx.StaticLine(self, -1) saveButton = wx.Button(self, wx.ID_OK, "Save") cancelButton = wx.Button(self, wx.ID_CANCEL) # Set Properties. self.SetTitle("Preferences") self.SetIcon(wx.Icon(gui.main.config.root+"\\Images\\icon.ico", wx.BITMAP_TYPE_ICO, 32, 32)) self.stylusFile.SetValue(gui.main.prefReader.stylusFile) self.calibrationFile.SetValue(gui.main.prefReader.calibrationFile) self.blPositionsFile.SetValue(gui.main.prefReader.blPositionsFile) self.configFile.SetValue(gui.main.prefReader.configFile) # Do Layout. sizer_1 = wx.BoxSizer(wx.HORIZONTAL) grid_sizer_1 = wx.FlexGridSizer(4, 1, 0, 0) sizer_2 = wx.BoxSizer(wx.HORIZONTAL) grid_sizer_1_copy = wx.FlexGridSizer(2, 2, 10, 10) grid_sizer_1_copy.Add(stylusLabel, 0, wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_RIGHT, 0) grid_sizer_1_copy.Add(self.stylusFile, 0, wx.EXPAND, 0) grid_sizer_1_copy.Add(calibrationLabel, 0, wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_RIGHT, 0) grid_sizer_1_copy.Add(self.calibrationFile, 0, wx.EXPAND, 0) grid_sizer_1_copy.Add(blPositionsLabel, 0, wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_RIGHT, 0) grid_sizer_1_copy.Add(self.blPositionsFile, 0, wx.EXPAND, 0) # Watch out here. grid_sizer_1_copy.Add(configLabel, 0, wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_RIGHT, 0) grid_sizer_1_copy.Add(self.configFile, 0, wx.EXPAND, 0) grid_sizer_1_copy.AddGrowableCol(1) grid_sizer_1.Add(grid_sizer_1_copy, 1, wx.ALL|wx.EXPAND, 10) grid_sizer_1.Add(static_line_1, 0, wx.EXPAND, 0) sizer_2.Add(saveButton, 0, wx.RIGHT|wx.ALIGN_BOTTOM, 5) sizer_2.Add(cancelButton, 0, wx.ALIGN_BOTTOM, 0) grid_sizer_1.Add(sizer_2, 1, wx.ALL|wx.ALIGN_RIGHT|wx.ALIGN_BOTTOM, 5) grid_sizer_1.AddGrowableRow(0) grid_sizer_1.AddGrowableCol(0) sizer_1.Add(grid_sizer_1, 1, wx.EXPAND, 0) self.SetSizer(sizer_1) sizer_1.Fit(self) self.Layout() self.Bind(wx.EVT_BUTTON, self.OnSave, saveButton) ## Event handler. Saves the preference file locations. def OnSave(self, event): if self.stylusFile.GetValue() == '' or self.calibrationFile.GetValue() == '' or self.blPositionsFile.GetValue() == '': msg = "Not all fields are filled in." dlg = wx.MessageDialog(self, msg, 'Error', wx.OK | wx.ICON_ERROR) dlg.ShowModal() dlg.Destroy() else: event.Skip()
Python
from distutils.core import setup import py2exe ## setup(windows=['Main.py']) setup( windows = [ { "script": "Main.py", "icon_resources": [(1, "Images\icon.ico")] } ], )
Python
import wx import ConfigfileReader ## Contains a visual representation of the location of all sensors on the body. The location of all the sensors is validated in this panel. class SensorPanel(wx.Panel): ## The constructor of SensorPanel. GUI elements of the panel are setup here. # @param[in] parent The wx window parent (notebook) of this panel. # @param[in] state SensorState instance attached to this panel. def __init__(self, parent, state): wx.Panel.__init__(self, parent) ## SensorState instance attached to this panel. self.state = state ## The wx window parent (notebook) of this panel. self.parent = parent ## The name of this notebook panel. self.name = "Sensors" self.sensorHelp_staticbox = wx.StaticBox(self, -1, "Help") self.sensorsLocations_staticbox = wx.StaticBox(self, -1, "Locations") # We want to show a table of GSI - position string. # Here the sensors read from the file are placed in a list and added to the interface. # These sensors are the "Active sensors" in the confi.ini file. gp_dict = state.get_sensor_positions() gsi_list = gp_dict.keys() gsi_list.sort() ## Sensor number on the GUI. self.gsi_labels = [] ## Sensor description of the sensors in gsi_labels. self.pos_labels = [] for gsi in gsi_list: sensornumber = gsi.split('_') self.gsi_labels.append(wx.StaticText(self, -1, "Sensor "+sensornumber[1])) self.pos_labels.append(wx.StaticText(self, -1, gp_dict[gsi])) helpText = "Place the sensors on the patients body according to the locations displayed in the diagram. " self.label_help = wx.StaticText(self, -1, helpText) self.body_picture = wx.StaticBitmap(self, -1, wx.Bitmap("Images/Body.png", wx.BITMAP_TYPE_ANY)) self.panel_1 = wx.Panel(self, -1) self.panel_2 = wx.Panel(self, -1) self.panel_3 = wx.Panel(self, -1) self.panel_4 = wx.Panel(self, -1) self.panel_5 = wx.Panel(self, -1) self.panel_6 = wx.Panel(self, -1) self.static_line_5 = wx.StaticLine(self, -1) self.static_line_6 = wx.StaticLine(self, -1) self.static_line_7 = wx.StaticLine(self, -1) ## Goes to the previous panel. self.sensorsBackButton = wx.Button(self, -1, "< Back") ## Goes to the next panel. self.sensorsNextButton = wx.Button(self, -1, "Next >") # The sensor positions on the body. coord_labels = [] coord_dict = self.state.main.sensorPictPos for position, coord in coord_dict.items(): coord_labels.append(wx.StaticText(self, -1, position, coord, (-1,-1))) self.__SetProperties() self.__DoLayout() #Sets an event handles for the next button self.sensorsNextButton.Bind(wx.EVT_BUTTON, self.OnNext) ## Sets several properties of the panel. def __SetProperties(self): self.sensorsBackButton.Disable() self.label_help.SetMinSize((150, 254)) ## Sets layout of the panel. def __DoLayout(self): sizer_1 = wx.BoxSizer(wx.VERTICAL) grid_sizer_1 = wx.FlexGridSizer(4, 3, 0, 0) grid_sizer_3 = wx.FlexGridSizer(1, 2, 0, 10) sensorHelp = wx.StaticBoxSizer(self.sensorHelp_staticbox, wx.HORIZONTAL) sensorsLocations = wx.StaticBoxSizer(self.sensorsLocations_staticbox, wx.HORIZONTAL) sensorsGrid = wx.FlexGridSizer(len(self.gsi_labels), 2, 5, 10) for gsi_label, pos_label in zip(self.gsi_labels,\ self.pos_labels): sensorsGrid.Add(gsi_label, 0, 0, 0) sensorsGrid.Add(pos_label, 0, 0, 0) sensorsLocations.Add(sensorsGrid, 1, wx.ALL|wx.EXPAND, 10) sensorsLocations.Add(self.body_picture, 0, wx.ALL, 10) grid_sizer_1.Add(sensorsLocations, 1, wx.ALL, 10) grid_sizer_1.Add(self.panel_1, 1, wx.EXPAND, 0) sensorHelp.Add(self.label_help, 0, wx.ALL, 10) grid_sizer_1.Add(sensorHelp, 1, wx.ALL|wx.ALIGN_RIGHT, 10) grid_sizer_1.Add(self.panel_4, 1, wx.EXPAND, 0) grid_sizer_1.Add(self.panel_6, 1, wx.EXPAND, 0) grid_sizer_1.Add(self.panel_2, 1, wx.EXPAND, 0) grid_sizer_1.Add(self.static_line_5, 0, wx.EXPAND, 0) grid_sizer_1.Add(self.static_line_6, 0, wx.EXPAND, 0) grid_sizer_1.Add(self.static_line_7, 0, wx.EXPAND, 0) grid_sizer_1.Add(self.panel_3, 1, wx.EXPAND, 0) grid_sizer_1.Add(self.panel_5, 1, wx.EXPAND, 0) grid_sizer_3.Add(self.sensorsBackButton, 0, wx.ALIGN_RIGHT, 0) grid_sizer_3.Add(self.sensorsNextButton, 0, wx.RIGHT|wx.ALIGN_RIGHT, 10) grid_sizer_1.Add(grid_sizer_3, 1, wx.TOP|wx.BOTTOM|wx.ALIGN_RIGHT|wx.ALIGN_BOTTOM, 5) grid_sizer_1.AddGrowableRow(1) grid_sizer_1.AddGrowableCol(2) sizer_1.Add(grid_sizer_1, 1, wx.EXPAND, 0) self.SetSizer(sizer_1) sizer_1.Fit(self) self.Layout() ## Handles events when the next button is pressed. # @param[in] new The tab index to go to. # @return[boolean] False when navigation to following panel is somehow cancelled, else True. def OnNext(self, event, new=1): NAVIGATED_TO_NEXT = False # Check using the rulebase if the sensors are placed correctly relative to eachother. # If they are not, a checkbox asking whether the user wants to continue or not is displayed. if self.state.CheckSensors() == False: msg = "The actual sensor positions do not correspond with the given positions.\nAre you sure you want to continue?" dlg = wx.MessageDialog(self, msg, 'Warning', wx.YES_NO | wx.NO_DEFAULT | wx.ICON_EXCLAMATION) # User wants to continue even though the sensors are placed incorrectly. if(dlg.ShowModal() == wx.ID_YES): self.parent.ChangeSelection(new) NAVIGATED_TO_NEXT = True # User doesn't want to continue to next panel. else: self.parent.ChangeSelection(0) dlg.Destroy() # Sensors have been place correctly, and next menu panel is selected. else: NAVIGATED_TO_NEXT = True self.parent.ChangeSelection(new) return NAVIGATED_TO_NEXT
Python
import math import numpy def create(parent, root): return BaseCalc(parent) class BaseCalc: def __init__(self, parent): self.parent = parent def SubtractPoints(self, a, b): slotlijst = [] try: for i in range(0, len(a)): slotlijst.append(a[i]-b[i]) except TypeError: return (a-b) return slotlijst def AddPoints(self, a, b): slotlijst = [] try: for i in range(0, len(a)): slotlijst.append(a[i]+b[i]) except TypeError: return (a-b) return slotlijst def MultiplyVector(self, a, b): c = [] try: for i in range(0,len(a)): c[len(c):] = [a[i]*b] except TypeError: return (a*b) return c def MultiplyVector_int(self, a, b): c = [] for i in range(0,len(a)): c[len(c):] = [int(a[i]*b)] return c def Average2Points(self, a, b): return [(a[0]+b[0])/2,(a[1]+b[1])/2,(a[2]+b[2])/2] def Average2Points_int(self, a, b): return [int((a[0]+b[0])/2),int((a[1]+b[1])/2),int((a[2]+b[2])/2)] def Average3Points(self, a, b, c): return [(a[0]+b[0]+c[0])/3,(a[1]+b[1]+c[1])/3,(a[2]+b[2]+c[2])/3] def WeightedAverage2Points(self, a, b, w, y): return [(w*a[0]+y*b[0])/(y+w),(w*a[1]+y*b[1])/(y+w),(w*a[2]+y*b[2])/(y+w)] def Length3DVector(self, a): return math.sqrt((math.pow(a[0], 2)) + (math.pow(a[1], 2)) + (math.pow(a[2], 2))) def Length3DVector2(self, a): return (math.pow(a[0], 2)) + (math.pow(a[1], 2)) + (math.pow(a[2], 2)) def WorldToVoxel(self, a): return [int(a[0]/self.volumedata.GetSpacing()[0]), int(a[1]/self.volumedata.GetSpacing()[1]), int(a[2]/self.volumedata.GetSpacing()[2])] def VoxelToWorld(self, a): return [(a[0]*self.volumedata.GetSpacing()[0]), (a[1]*self.volumedata.GetSpacing()[1]), (a[2]*self.volumedata.GetSpacing()[2])] def Normalize(self, a): m1 = numpy.matrix([a]) m1 = m1 / numpy.linalg.norm(m1) return m1.tolist()[0] def Multiply3x3MatrixVector(self, matrix, b): output1 = [0,0,0] for j in range(0,3): tmp = 0 for i in range(0,3): tmp = tmp + matrix[j][i] * b[i] output1[j] = tmp return output1
Python
import os import sys # Get application directory of Main.py, use that to find the data files. if hasattr(sys, 'frozen') and sys.frozen: appdir, exe = os.path.split(sys.executable) else: dirname = os.path.dirname(sys.argv[0]) if dirname and dirname != os.curdir: appdir = dirname else: appdir = os.getcwd() M_DIR = os.path.join(appdir, 'Matlab Data') IM_FILENAME = os.path.join(M_DIR, "datfile2.DAT") MOV_FILENAME = os.path.join(M_DIR, "movfile2.DAT") # NOTE: A duplicate of the first frame is needed for successfull simulation, because the Sensors panel needs a frame to check # the position of the sensors, otherwise the pointer of the parser reaches an EOF. ## This class simulates the FoB driver using exisiting calibration and motion files. # After finishing the calibration steps in the program, # change the mode to movement mode by setting f.mode = 1 where f is an instance of the fake_fob.FOB class. class FOB: ## Constructs a simulator class for the FoBDriver class. def __init__(self): ## Serial() instance. self.ser = "FakeFOB SER queried" ## Dat file. self.im_file = file(IM_FILENAME) ## Mov file. self.mov_file = file(MOV_FILENAME) ## Calibration mode = 0. Movement mode = 1. self.mode = 0 ## Pass. def open(self, p1, p2, p3): pass ## Pass. def fbbAutoConfig(self, numbirds): pass ## Pass. def fbbReset(self): pass ## Pass. def position_matrix(self, idx): pass ## Pass. def run(self): pass ## Pass. def sleep(self): pass ## Pass. def close(self): pass ## This returns a 12-element list: first 3 are the position, next 9 represent a 3x3 transformation matrix. # During the calibration phase, we only return the data belonging to sensor 2. # During the movement phase we return any data that is requested (we know which indexes to return). def point(self, idx): # Keep on reading lines until we reach a line with 4 elements, the first element is the sensor index. # Keep on reading until we have a 4 x 3 matrix. cur_sidx = -1 # Current sensor idx cur_row = 0 # Current row in 4 x 3 matrix. m = [0] * 12 if self.mode == 0: for l in self.im_file: elems = [float(i) for i in l.split()] # Eerste rij van matrix aangetroffen. if len(elems) == 4: cur_sidx = int(elems[0]) # Opslitsen en toevoegen aan onze 3x4 matrix. m[0:3] = elems[1:4] cur_row = 1 # Alleen als de sensor ook de opgevraagde sensor is, dan gaan we de rotatie ook toevoegen. elif len(elems) == 3 and cur_sidx == idx: blat = cur_row * 3 m[blat:blat+3] = elems[0:3] cur_row += 1 # cur_row wordt nooit 4 als we niet met de opgevraagde sensor te maken hebben. if cur_row == 4: break else: for l in self.mov_file: elems = [float(i) for i in l.split()] if len(elems) == 4: cur_sidx = int(elems[0]) m[0:3] = elems[1:4] cur_row = 1 elif len(elems) == 3 and cur_sidx == idx: blat = cur_row * 3 m[blat:blat+3] = elems[0:3] cur_row += 1 if cur_row == 4: break if cur_row != 4: if self.mode == 0: raise RuntimeError, "Reached end of file while parsing" else: self.mov_file.seek(0) return self.point(idx) else: return m
Python
from GUI import GUI import wx import os from ConfigfileReader import ConfigfileReader from PreferencesFileReader import PreferencesFileReader from SensorState import SensorState from BLState import BLState from GHJState import GHJState from VisualizationState import VisualizationState from DriverInterface import DriverInterface from FoBDriver import FoBDriver from numpy import size from PreferencesDialog import PreferencesDialog from AboutDialog import AboutDialog from AddBonyLandmark import AddBonyLandmark from Sensor import Sensor from ComportCheck import ComportCheck import BaseCalc import replacebone ## The main class to run the program. class Main(wx.App): try: import MotionVA.AngleCalculations as AngleCalculations motion_analyser_available = True except ImportError: motion_analyser_available = False pass motion_analysis_started = False ## Initializes the GUI, resets the system. # @return[int] 1 if initialization is successful. def OnInit(self): self.replacement_tuples = [] wx.InitAllImageHandlers() self.baseCalc = BaseCalc.create(self, self) splash = wx.SplashScreen(wx.Bitmap("images/Splash.png"), wx.SPLASH_CENTRE_ON_SCREEN|wx.SPLASH_TIMEOUT, 1000, None, style=wx.STAY_ON_TOP) ## Indicates whether OnNew has been used yet. self.FIRST_TIME = True ## Set to true when the FoB system has successfully started. self.FOB_RUNNING = False ## Indicates whether data is written to a file. self.DATA_WRITE = True ## Indicates whether fast data acquisition is used or not self.FAST_ACQUISITION = False ## Instantiation of the GUI class. self.gui = GUI(self, None, -1, "") self.SetTopWindow(self.gui) self.Reset() self.OnNew(self) self.gui.Show() return 1 ## Resets all attributes. def Reset(self): ## Instantiation of the PreferencesFileReader which contains references to all the three preference files. self.prefReader = PreferencesFileReader(self.gui) ## Instantiation of the ConfigfileReader which parses the configuration file. self.config = ConfigfileReader(self.gui,self.prefReader.configFile) ## The GSI mapping from fob0_x to COM[port]_[address] as read from the config.ini file. self.coms = self.config.ReadComports() ## A matrix representation of the calibration file. self.calibrationMatrix = self.prefReader.ReadCalibration(self.prefReader.calibrationFile) ## The list containing the bony landmarks. self.bonyLandmarks = self.config.ReadBonyLandmarks() ## A dictionary containing the sensor and corresponding coordinates on the body. self.sensorPictPos = self.config.ReadSensorPictPos() ## A dictionary containing the number and names of GH-Joints. self.GHJoints = self.config.ReadGHJoints(False) ## Indicates whether 3D smoothing of the model is activated or not. self.Smooth3DModel = self.config.Read3DSmoothing() #~ self.InitiateFOBConnection() #~ self.Reset() #~ self.gui.LoadNotebook() #~ self.states.visualization.ToggleSensors() #~ self.states.visualization.ToggleBonyLandmarks() #~ self.gui.notebook.ChangeSelection(0) #~ self.driver = FoBDriver(self,10,False) ## A (key,value) mapping from sensor name to position, e.g. ('fob0_3', 'Thorax'). dp_dict = self.config.ReadDefaultPositions() ## The list of Sensor objects taken from dp_dict. self.sensors = [0] for gsi, position in dp_dict.items(): if position == "Pointer": self.sensors[0] = Sensor(gsi, position) else: self.sensors.append(Sensor(gsi, position)) ## Object containing all the four states in the program. # Create 'States' class on the fly. self.states = type('States', (object,), {}) ## The Sensorstate. self.states.sensors = SensorState(self) # Sensors, tab 0 ## The BLState. self.states.bony_landmark = BLState(self) # Bony Landmarks, tab 1 ## The GHJState. self.states.gh_cor = GHJState(self) # GH-Joint, tab 2 ## The VisualizationState. self.states.visualization = VisualizationState(self) # Visualization, tab 3 def InitiateFOBConnection(self): ## Error checking to see whether or not the fob hardware can be run try: ## The current hardware driver used in the system. self.driver = FoBDriver(self) self.FOB_RUNNING = True except RuntimeError: #~ msg = "Could not open a Fob hardware connection. Only the playback panel will be available for use." #~ dlg = wx.MessageDialog(self.gui, msg, 'Warning', wx.OK | wx.NO_DEFAULT | wx.ICON_EXCLAMATION | wx.STAY_ON_TOP) #~ dlg.ShowModal() self.driver = FoBDriver(self,10,False) ## Starts a new measurement session. def OnNew(self, event): ## Makes sure the visualization loop is stopped, otherwise errors will occur once the FOB has been reset if not self.FIRST_TIME: self.states.visualization.Stop() try: self.driver.close() self.InitiateFOBConnection() except AttributeError: print "No tracking system connected (yet)." print "Connecting..." self.InitiateFOBConnection() else: self.driver = FoBDriver(self,10,False) #~ else: #~ self.InitiateFOBConnection() self.FIRST_TIME = False self.Reset() self.gui.LoadNotebook() self.states.visualization.ToggleSensors() self.states.visualization.ToggleBonyLandmarks() self.gui.notebook.ChangeSelection(0) self.replacement_tuples = [] ## Opens the preferences dialog window. def OnPreferences(self, event): dlg = PreferencesDialog(self.gui) dlg.CenterOnScreen() #New preferences are now saved in the preferences.ini file. if dlg.ShowModal() == wx.ID_OK: self.prefReader.SavePreferences(dlg) #Dialog asking user to reset the system once the preferences have been saved. msg = "The preferences have been saved.\n\n For these changes to take effect the Flock Of Birds Visualizer needs to reset.\n By resetting, all current measurement data and imported recordings will be lost.\n\n Do you want to reset the Flock Of Birds Visualizer?" dlg2 = wx.MessageDialog(self.gui, msg, 'Warning', wx.YES_NO | wx.NO_DEFAULT | wx.ICON_EXCLAMATION) if(dlg2.ShowModal() == wx.ID_YES): self.OnNew(self) dlg2.Destroy() dlg.Destroy() def OnStoreAbsMatrices(self, event): self.states.visualization.playbackState.PlayAndStore() ## Opens the about dialog window. def OnAbout(self, event): dlg = AboutDialog(self.gui) dlg.ShowModal() dlg.CenterOnScreen() dlg.Destroy() ## Toggles the sensor spheres in the visualization on or off. def OnToggleSensors(self, event): self.states.visualization.ToggleSensors() ## Toggles the bony landmark spheres in the visualization on or off. def OnToggleBonyLandmarks(self, event): self.states.visualization.ToggleBonyLandmarks() ## Toggles the 3D model in the visualization on or off. def OnToggle3DModel(self, event): self.states.visualization.Toggle3DModel() ## Exits the program. def OnQuit(self, event): self.states.visualization.Stop() self.gui.Destroy() self.driver.close() ## Opens the menu for adding bony landmarks. def OnAddBonyLandmark(self, event): AddBonyLandmark(self.gui.notebook,self.gui) ## Opens the menu for checking the COM ports. def OnCheckCOMports(self, event): #import ComportCheck frame = ComportCheck(None, -1, 'COM-Port Check', self.config, self.driver.fob_dict) frame.Show(True) self.SetTopWindow(frame) ## Enables writing raw data to a file def OnDataWrite(self, event): self.DATA_WRITE = not self.DATA_WRITE print self.DATA_WRITE ## Enables the optimal efficiency for acquiring data, disabling any calculations of visualizations. aka TurboMode def OnFastAcquisition(self, event): self.FAST_ACQUISITION = not self.FAST_ACQUISITION print self.FAST_ACQUISITION def OnExportBlVecs(self, event): dlg = wx.FileDialog(self.gui, message="Save Bony Landmark Vectors", defaultDir=os.getcwd(), defaultFile="", wildcard="Txt-file (*.txt)|*.txt", style=wx.SAVE | wx.CHANGE_DIR | wx.OVERWRITE_PROMPT) if dlg.ShowModal() == wx.ID_OK: txtpath = dlg.GetPath() fileWriter = open(txtpath, 'w') blRange = len(self.bonyLandmarks) for i in range(0, blRange): a = self.bonyLandmarks[i].relativePosition#.ToList() fileWriter.write('%.3f %.3f %.3f\n' % (a[0], a[1], a[2])) fileWriter.close() def GetPath(self, event): dlg = wx.FileDialog(None, message="Select STL file", defaultDir=os.getcwd(), defaultFile="", wildcard="STL file (*.stl)|*.stl", style=wx.OPEN | wx.CHANGE_DIR) if dlg.ShowModal() == wx.ID_OK: self.replaceDlg.text_ctrl_1.SetValue(dlg.GetPath()) def OnReplaceBone(self, event): self.replaceDlg = replacebone.MyDialog(None, -1, '') self.replaceDlg.button_browse.Bind(wx.EVT_BUTTON, self.GetPath) self.replaceDlg.choice_1.Bind(wx.EVT_CHOICE, self.OnSelectionChanged) if self.replaceDlg.ShowModal() == wx.ID_OK: if self.replaceDlg.text_ctrl_1.GetValue() != "": #Get the index of the bone. #In this version, bones 0-73 are excluded to make the drop down menu easier to use. boneindex = self.replaceDlg.choice_1.GetCurrentSelection() + 73 #Add the boneindex and its file path to the list of replacement tuples self.replacement_tuples.append([boneindex, self.replaceDlg.text_ctrl_1.GetValue()]) # Update the __meshPos for each BL that should be replaced for i in range(0, self.replaceDlg.grid_1.GetNumberRows()-1): #Check if the row actually contains information if self.replaceDlg.grid_1.GetCellValue(i,1) != "": #Get the index of the current BL blIndex = int(self.replaceDlg.grid_1.GetCellValue(i,0).split('.')[0]) #Replace the BL self.states.visualization.UpdateBL(blIndex, [float(self.replaceDlg.grid_1.GetCellValue(i,1)), float(self.replaceDlg.grid_1.GetCellValue(i,2)), float(self.replaceDlg.grid_1.GetCellValue(i,3))]) self.replaceDlg.Destroy() print self.replacement_tuples #Called when a new bone is selected in the drop down menu of the bone replacement dialog def OnSelectionChanged(self, event): connections = self.config.Read3DModelConnection() boneindex = self.replaceDlg.choice_1.GetCurrentSelection() + 73 #Find the correct landmarks and update the table. for i in range(0, len(connections)): if (boneindex in connections[i][0]): landmarks = connections[i][1] #Get the names of all landmarks names = self.config.ReadBonyLandmarkNames() #Append the GH joints names.append((24, 'Right GH')) names.append((25, 'Left GH')) #For each landmark, update the table in the dialog with the correct name and current BL values. for j in range(0, len(landmarks)): self.replaceDlg.grid_1.SetCellValue(j, 0, str(names[landmarks[j]][0]) + '. ' + names[landmarks[j]][1]) self.replaceDlg.grid_1.SetCellValue(j, 1, str(self.states.visualization.GetBL(landmarks[j])[0])) self.replaceDlg.grid_1.SetCellValue(j, 2, str(self.states.visualization.GetBL(landmarks[j])[1])) self.replaceDlg.grid_1.SetCellValue(j, 3, str(self.states.visualization.GetBL(landmarks[j])[2])) #Clear all other cells for k in range(j+1, self.replaceDlg.grid_1.GetNumberRows()-1): self.replaceDlg.grid_1.SetCellValue(k, 0, '') self.replaceDlg.grid_1.SetCellValue(k, 1, '') self.replaceDlg.grid_1.SetCellValue(k, 2, '') self.replaceDlg.grid_1.SetCellValue(k, 3, '') def OnStartAnalyser(self, event): if self.motion_analyser_available: self.angleCalculations = self.AngleCalculations.create(self, self) self.angleCalculations.CreatePatternViewer() self.motion_analysis_started = True else: msg = "It seems that the Motion Analysis software is not installed. Please check your installation directory." dlg = wx.MessageDialog(self.gui, msg, 'Warning', wx.OK | wx.NO_DEFAULT | wx.ICON_EXCLAMATION | wx.STAY_ON_TOP) dlg.ShowModal() ## Returns a dictionary containing the the indices of the bony landmarks in as the key, and their ID as item. # @param[in] withGH A boolean value that is set to return a dictionary including or exclude GHJoint. # @return[dict] Dictionary of bony landmarks indices and ID's. def GetBonyLandmarkDict(self,withGH): bl_dict = {} blRange = len(self.bonyLandmarks) if not withGH: blRange -= len(self.GHJoints) for i in range(0, blRange): bl_dict[self.bonyLandmarks[i].ID] = i return bl_dict if __name__ == "__main__": app = Main(0) app.MainLoop()
Python
from Sensor import Sensor from BonyLandmark import BonyLandmark import cPickle import sys import numpy sys.modules['numpy.core.defmatrix'] = numpy.matrixlib.defmatrix ## Saves and loads recordings. class RecordingsProcessor: ## The constructor of RecordingsProcessor. # @param[in] parent The wx window parent (VisualizationState) of this Panel. # @param[in] main Main wx.App derived instance. def __init__(self, parent, main): ## The wx window parent (VisualizationState) of this Panel. self.parent = parent ## Main wx.App derived instance. self.main = main ## Saves the measurement and recordings to a .fob file. # @param[in] filename The name of the file to be saved. # @param[in] currentRecording The recording being saved. def SaveRecording(self, filename, currentRecording): output = open(filename, 'wb', 1) cPickle.dump(currentRecording, output, 0) output.close() ## Loads the recorded file specified. # @param[in] filename The file to be loaded. def LoadRecording(self, filename): inputFile = open(filename, 'rb', 1) loadedRecording = cPickle.load(inputFile) inputFile.close() return loadedRecording
Python
import wx from numpy import size, matrix import wx.lib.mixins.listctrl import os, sys import winsound ## Bony landmarks are measured in this panel. # The Bony Landmark panel consists of a list with bony landmarks, the five measurements and the description of the selected bony landmark. class BLPanel(wx.Panel): ## The constructor of BLPanel, sets up the panel interface. # @param[in] parent The wx window parent (notebook) of this panel. # @param[in] state BLState instance attached to this panel. def __init__(self, parent, state): wx.Panel.__init__(self, parent) ## BLState instance attached to this panel. self.state = state ## The wx window parent (notebook) of this panel. self.parent = parent ## The name of this notebook panel. self.name = "Bony Landmarks" ## Box containing the selected bony landmark. self.selectedItemSizer_staticbox = wx.StaticBox(self, -1, "Selected") ## Box with indications for the five measurements. self.measurementsSizer_staticbox = wx.StaticBox(self, -1, "Measurements") ## Help text. self.blHelpSizer_staticbox = wx.StaticBox(self, -1, "Help") ## List containing the bony landmarks and reset buttons. self.blListSizer_staticbox = wx.StaticBox(self, -1, "Protocol") ## List for the bony landmarks. self.blList = BlList(self, -1, style=wx.LC_REPORT|wx.LC_NO_HEADER|wx.LC_SINGLE_SEL|wx.SUNKEN_BORDER) ## Resets the selected bony landmark. self.resetSelectedButton = wx.Button(self, -1, "Reset selected") ## Resets all bony landmarks. self.resetAllButton = wx.Button(self, -1, "Reset all") ## The selected bony landmark name. self.selectedItemLabel = wx.StaticText(self, -1, "Bony Landmark Name") ## The selected bony landmark picture. self.selectedItemBitmap = wx.StaticBitmap(self, -1, wx.Bitmap("Images/BonyLandmarkImages/BonyLandmark 0.png", wx.BITMAP_TYPE_ANY)) ## The selected bony landmark description. self.selectedItemDescription = wx.StaticText(self, -1, "Bony Landmark description") measure1 = wx.StaticBitmap(self, -1, wx.Bitmap("Images/1.png", wx.BITMAP_TYPE_ANY)) measure2 = wx.StaticBitmap(self, -1, wx.Bitmap("Images/2.png", wx.BITMAP_TYPE_ANY)) measure3 = wx.StaticBitmap(self, -1, wx.Bitmap("Images/3.png", wx.BITMAP_TYPE_ANY)) measure4 = wx.StaticBitmap(self, -1, wx.Bitmap("Images/4.png", wx.BITMAP_TYPE_ANY)) measure5 = wx.StaticBitmap(self, -1, wx.Bitmap("Images/5.png", wx.BITMAP_TYPE_ANY)) ## Indicators for the five measurements. self.measureBitmaps = [measure1, measure2, measure3, measure4, measure5] helptxt = "Place the pointer sensor on the correct position on the patient's body," \ "and step on the pedal five times. Repeat this process for all the bony landmarks.\n\n " \ "A green indicator is a correct measurement, while orange indicates that the measurement " \ "is too far from other current measurements, or that the bony landmark " \ "is positioned wrong with respect to other bony landmarks.\n" \ "To repeat a measurement, use the reset buttons located below the list to clear the current measurements." ## Button for making a measurement. self.pedalButton = wx.Button(self, -1, "Pedal") self.pedalButton.Enable(False) self.panel_7 = wx.Panel(self, -1) self.helpLabel = wx.StaticText(self, -1, helptxt) self.static_line_5_copy = wx.StaticLine(self, -1) self.static_line_6_copy = wx.StaticLine(self, -1) self.static_line_7_copy = wx.StaticLine(self, -1) self.panel_3_copy = wx.Panel(self, -1) self.panel_1 = wx.Panel(self, -1) ## Goes to the previous panel. self.blBackButton = wx.Button(self, -1, "< Back") ## Goes to the next panel. self.blNextButton = wx.Button(self, -1, "Next >") self.__AssignBonyLandmarkList() self.__SetProperties() self.__BindEvents() self.__DoLayout() ## Sets properties for the panel. def __SetProperties(self): self.blList.SetMinSize((200, -1)) self.selectedItemLabel.SetFont(wx.Font(12, wx.DEFAULT, wx.NORMAL, wx.NORMAL, 0, "MS Shell Dlg 2")) self.selectedItemDescription.SetMinSize((160, 200)) self.helpLabel.SetMinSize((150, 254)) ## Sets layout for the panel. def __DoLayout(self): blWrapper = wx.FlexGridSizer(4, 3, 0, 0) backNextGridSizer = wx.FlexGridSizer(1, 2, 0, 10) blHelpSizer = wx.StaticBoxSizer(self.blHelpSizer_staticbox, wx.HORIZONTAL) selectedItemMeasurementsSizer = wx.FlexGridSizer(3, 1, 20, 0) measurementsSizer = wx.StaticBoxSizer(self.measurementsSizer_staticbox, wx.HORIZONTAL) measurementsGridSizer = wx.GridSizer(6, 1, 5, 0) selectedItemSizer = wx.StaticBoxSizer(self.selectedItemSizer_staticbox, wx.HORIZONTAL) selectedItemWrapper = wx.BoxSizer(wx.VERTICAL) selectedItemImageDescSizer = wx.BoxSizer(wx.HORIZONTAL) blListSizer = wx.StaticBoxSizer(self.blListSizer_staticbox, wx.HORIZONTAL) blListGridSizer = wx.FlexGridSizer(2, 1, 5, 0) blListGridSizer.Add(self.blList, 1, wx.EXPAND, 0) blListGridSizer.Add(self.resetSelectedButton, 0, wx.EXPAND|wx.ALIGN_BOTTOM, 0) blListGridSizer.Add(self.resetAllButton, 0, wx.EXPAND, 0) blListGridSizer.AddGrowableRow(0) blListSizer.Add(blListGridSizer, 1, wx.ALL|wx.EXPAND, 10) blWrapper.Add(blListSizer, 1, wx.ALL|wx.EXPAND, 10) selectedItemWrapper.Add(self.selectedItemLabel, 0, wx.ALL|wx.ALIGN_CENTER_HORIZONTAL, 10) selectedItemImageDescSizer.Add(self.selectedItemBitmap, 0, wx.LEFT|wx.BOTTOM, 10) selectedItemImageDescSizer.Add(self.selectedItemDescription, 0, wx.LEFT|wx.RIGHT|wx.BOTTOM, 10) selectedItemWrapper.Add(selectedItemImageDescSizer, 1, wx.EXPAND, 0) selectedItemSizer.Add(selectedItemWrapper, 1, wx.EXPAND, 0) selectedItemMeasurementsSizer.Add(selectedItemSizer, 1, wx.EXPAND, 10) for bitmap in self.measureBitmaps: measurementsGridSizer.Add(bitmap, 0, 0, 0) measurementsGridSizer.Add(self.pedalButton, 0, 0, 0) measurementsSizer.Add(measurementsGridSizer, 1, wx.ALL, 10) selectedItemMeasurementsSizer.Add(measurementsSizer, 1, 0, 10) selectedItemMeasurementsSizer.Add(self.panel_7, 1, wx.EXPAND, 0) selectedItemMeasurementsSizer.AddGrowableRow(1) selectedItemMeasurementsSizer.AddGrowableCol(0) blWrapper.Add(selectedItemMeasurementsSizer, 1, wx.ALL|wx.EXPAND, 10) blHelpSizer.Add(self.helpLabel, 0, wx.ALL, 10) blWrapper.Add(blHelpSizer, 1, wx.ALL|wx.ALIGN_RIGHT, 10) blWrapper.Add(self.static_line_5_copy, 0, wx.EXPAND, 0) blWrapper.Add(self.static_line_6_copy, 0, wx.EXPAND, 0) blWrapper.Add(self.static_line_7_copy, 0, wx.EXPAND, 0) blWrapper.Add(self.panel_3_copy, 1, wx.EXPAND, 0) blWrapper.Add(self.panel_1, 1, wx.EXPAND, 0) backNextGridSizer.Add(self.blBackButton, 0, wx.ALIGN_RIGHT, 0) backNextGridSizer.Add(self.blNextButton, 0, wx.RIGHT|wx.ALIGN_RIGHT, 10) blWrapper.Add(backNextGridSizer, 1, wx.TOP|wx.BOTTOM|wx.ALIGN_RIGHT|wx.ALIGN_BOTTOM, 5) self.SetSizer(blWrapper) blWrapper.AddGrowableRow(0) blWrapper.AddGrowableCol(1) #self.blList.Select(0) self.Layout() ## Binds items of the panel to event handlers def __BindEvents(self): self.Bind(wx.EVT_BUTTON, self.OnPedal, self.pedalButton) self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnItemSelected, self.blList) self.Bind(wx.EVT_BUTTON, self.OnResetSelected, self.resetSelectedButton) self.Bind(wx.EVT_BUTTON, self.OnResetAll, self.resetAllButton) self.Bind(wx.EVT_BUTTON, self.OnBack, self.blBackButton) self.Bind(wx.EVT_BUTTON, self.OnNext, self.blNextButton) #~ self.Unbind(wx.EVT_RIGHT_DOWN) self.Bind(wx.EVT_RIGHT_DOWN, self.OnPedal) ## Checks the bony landmark measurement and colours the indicator. def OnPedal(self, event=0): if hasattr(sys, 'frozen') and sys.frozen: appdir, exe = os.path.split(sys.executable) else: dirname = os.path.dirname(sys.argv[0]) if dirname and dirname != os.curdir: appdir = dirname else: appdir = os.getcwd() if self.pedalButton.Enabled == True: selectedBL = self.blList.GetFirstSelected() numberOfMeasurements = len(self.state.main.driver.imSensors[selectedBL]) if numberOfMeasurements == 5: winsound.PlaySound(os.path.join(appdir, "Sound", "attention.wav"), winsound.SND_ALIAS) msg = "You already have 5 measurements for this bony landmark.\nClick 'Reset Selected' to remeasure this landmark." dlg = wx.MessageDialog(self, msg, 'Error', wx.OK | wx.ICON_ERROR) dlg.ShowModal() dlg.Destroy() else: self.state.BL_CHECKED = False self.state.main.driver.FetchBL_SensorPositionRotation(selectedBL,\ self.state.main.bonyLandmarks[selectedBL].sensorID) self.state.CheckSelf(selectedBL) self.UpdateMeasureBitmaps(selectedBL) winsound.PlaySound(os.path.join(appdir, "Sound", "pointacquired.wav"), winsound.SND_ALIAS) if numberOfMeasurements == 4: winsound.PlaySound(os.path.join(appdir, "Sound", "Sound/bingheigh.wav"), winsound.SND_ALIAS) self.blList.Select(selectedBL + 1) self.state.setRelativeBL(selectedBL) ## Displays name, description, picture and measurement indicators of the selected bony landmark when it is selected in the bony landmark list. def OnItemSelected(self, event): self.pedalButton.Enable(True) selectedIndex = event.m_itemIndex # Get the bony landmark. selectedBL = self.state.main.bonyLandmarks[selectedIndex] self.selectedItemLabel.SetLabel(selectedBL.name) self.selectedItemDescription.SetLabel(self.state.descriptions[selectedBL.ID]) # Do a check for the existence of the bitmap, displays a blank image if no corresponding image is available. path = os.path.join(self.state.main.config.root, "Images", "BonyLandmarkImages", ("BonyLandmark %d.png" %selectedBL.ID)) if os.path.exists(path): self.selectedItemBitmap.SetBitmap(wx.Bitmap(path, wx.BITMAP_TYPE_ANY)) else: self.selectedItemBitmap.SetBitmap(wx.Bitmap(self.state.main.config.root+"\\Images\\BonyLandmarkImages\\BonyLandmarkNoImage.png", wx.BITMAP_TYPE_ANY)) self.Layout() self.UpdateMeasureBitmaps(selectedIndex) ## Resets the measurements of the selected bony landmark when the reset button is clicked. def OnResetSelected(self, event): msg = "Are you sure you want to reset the %s?" % self.bonyLandmarks[self.blList.GetFirstSelected()] dlg = wx.MessageDialog(self, msg, 'Warning', wx.YES_NO | wx.NO_DEFAULT | wx.ICON_EXCLAMATION) if(dlg.ShowModal() == wx.ID_YES): self.state.ResetBL(self.blList.GetFirstSelected()) self.UpdateMeasureBitmaps(self.blList.GetFirstSelected()) dlg.Destroy() ## Resets all bony landmark measurements when the reset all button is clicked. def OnResetAll(self, event): msg = "Are you sure you want to reset all bony landmarks?" dlg = wx.MessageDialog(self, msg, 'Warning', wx.YES_NO | wx.NO_DEFAULT | wx.ICON_EXCLAMATION) if(dlg.ShowModal() == wx.ID_YES): for i in range(self.blList.GetItemCount()): self.state.ResetBL(i) #Reset the bony landmarks which represent the GH-joints, in case they have already been calculated. #These are always the last bl's in the bonyLandmarks list for i in range(1,len(self.state.main.GHJoints)+1): self.state.main.bonyLandmarks[len(self.state.main.bonyLandmarks)-i].relativePosition = matrix("[0.0; 0.0; 0.0]") self.blList.Select(0) self.UpdateMeasureBitmaps(0) dlg.Destroy() ## Panel navigation, goes back in the panel navigation to the previous state. # @param[in] new The tab index to go to. def OnBack(self, event, new = 0): self.parent.ChangeSelection(new) ## Handles events when the next button is pressed. # @param[in] new The tab index to go to. # @return[boolean] False when navigation to following panel is somehow cancelled, else True. def OnNext(self, event, new=2): NAVIGATED_TO_NEXT = False #Checks whether the measurements for the bony landmark are correct, if false a dialogue asking to proceed is shown. if self.state.CheckBonyLandmarks() == False: msg = "Some bony landmarks appear to have been measured wrongfully or have not been measured.\nAre you sure you want to continue?" dlg = wx.MessageDialog(self, msg, 'Warning', wx.YES_NO | wx.NO_DEFAULT | wx.ICON_EXCLAMATION) self.UpdateMeasureBitmaps(self.blList.GetFirstSelected()) # If yes is chosen in dialog, set the new page. if(dlg.ShowModal() == wx.ID_YES): self.state.BL_CHECKED = True self.parent.ChangeSelection(new) #self.state.main.driver.fobbie.mode = 1 NAVIGATED_TO_NEXT = True try: self.state.main.driver.closeBLFile() except AttributeError: pass # Otherwise, stay on the same page. else: self.parent.ChangeSelection(1) self.state.BL_CHECKED = False dlg.Destroy() # Sensors have been place correctly, navigate to new page. else: self.state.StoreRawBLVecs() self.parent.ChangeSelection(new) #self.state.main.driver.fobbie.mode = 1 NAVIGATED_TO_NEXT = True return NAVIGATED_TO_NEXT ## Update the bitmaps of the measurements with their colour represented in the colours matrix. # @param[in] selectedBL The bony landmark for which the measurement indicators need to be updated. def UpdateMeasureBitmaps(self, selectedBL): # Update measurements of selected bony landmark. for i in range(0,5): if i < len(self.state.colours[selectedBL]): if self.state.colours[selectedBL][i] == True: path = os.path.join(self.state.main.config.root, "Images", ("%d+.png" % (i+1))) #self.measureBitmaps[i].SetBitmap(wx.Bitmap(self.state.main.config.root+"\\Images\\%d+.png" % (i+1), wx.BITMAP_TYPE_ANY)) else: path = os.path.join(self.state.main.config.root, "Images", ("%d-.png" % (i+1))) #self.measureBitmaps[i].SetBitmap(wx.Bitmap(self.state.main.config.root+"\\Images\\%d-.png" % (i+1), wx.BITMAP_TYPE_ANY)) elif i == len(self.state.colours[selectedBL]): path = os.path.join(self.state.main.config.root, "Images", ("%ds.png" % (i+1))) #self.measureBitmaps[i].SetBitmap(wx.Bitmap(self.state.main.config.root+"\\Images\\%ds.png" % (i+1), wx.BITMAP_TYPE_ANY)) else: path = os.path.join(self.state.main.config.root, "Images", ("%d.png" % (i+1))) #self.measureBitmaps[i].SetBitmap(wx.Bitmap(self.state.main.config.root+"\\Images\\%d.png" % (i+1), wx.BITMAP_TYPE_ANY)) self.measureBitmaps[i].SetBitmap(wx.Bitmap(path, wx.BITMAP_TYPE_ANY)) # Update BL List. for i in range(len(self.state.colours)): item = self.blList.GetItem(i,0) if len(self.state.colours[i]) == 5: if self.state.colours[i].__contains__(False): item.SetBackgroundColour(wx.Colour(232,100,27)) else: item.SetBackgroundColour(wx.Colour(30,170,57)) item.SetTextColour(wx.Colour(255,255,255)) else: item.SetBackgroundColour(wx.WHITE) item.SetTextColour(wx.BLACK) self.blList.SetItem(item) ## Assigns the items in the ListCtrl blList according to the configuration file. def __AssignBonyLandmarkList(self): self.blList.InsertColumn(0, "") ## The list of bony landmarks. self.bonyLandmarks = self.state.GetBonyLandmarkList() for b in range(len(self.bonyLandmarks)-1,-1,-1): self.blList.InsertStringItem(0, self.bonyLandmarks[b]) ## List for the bony landmarks. # Here, wx.ListCtrl is used with ListCtrlAutoWidthMixin to create fitting columns. class BlList(wx.ListCtrl, wx.lib.mixins.listctrl.ListCtrlAutoWidthMixin): ## The constructor of BlList. def __init__(self, parent, ID, pos=wx.DefaultPosition, size=wx.DefaultSize, style=0): wx.ListCtrl.__init__(self, parent, ID, pos, size, style) wx.lib.mixins.listctrl.ListCtrlAutoWidthMixin.__init__(self)
Python
from numpy import * from numpy.linalg import * from ConfigfileReader import ConfigfileReader ## GHJState contains the functionality behind the GHJPanel. # All estimation methods for calculating the GH-Joints are in this class. # All methods in this class ending with RegressionMethod are used for the calculation of the GH-Joint using the regression method. # All methods in this class ending with MovementMethod are used for the calculations of the GH-Joint using the movement method. class GHJState: ## The constructor of GHJState. # @param[in] main Main wx.App derived instance. def __init__(self, main): ## Main wx.App derived instance. self.main = main ## Calculates the two GH-Joints using the regression method. def CalcRegressionMethod(self): connections = self.main.config.ReadGHJointsRegressionConnection() # Acquire a dictionary list in which the keys are the bony landmark ID's and the items are their corresponding index in a list. # This is essentially mapping to make the code more generic. blDict = self.main.GetBonyLandmarkDict(True) # Using the GH-Joint data specified in the config file, The GH-Joints calculated using the 5 bony landmarks that are associated with it. for ghJointsIndex, blConnections in connections.items(): sPC = self.main.bonyLandmarks[blDict[blConnections[0]]].relativePosition sAC = self.main.bonyLandmarks[blDict[blConnections[1]]].relativePosition sAA = self.main.bonyLandmarks[blDict[blConnections[2]]].relativePosition sTS = self.main.bonyLandmarks[blDict[blConnections[3]]].relativePosition sAI = self.main.bonyLandmarks[blDict[blConnections[4]]].relativePosition if sPC.any() and sAC.any() and sAA.any() and sTS.any() and sAI.any(): if ghJointsIndex == 24: GH = self._GHEstimateRRegressionMethod(sPC, sAC, sAA, sTS, sAI) else: #ghJointsIndex == 25 GH = self._GHEstimateLRegressionMethod(sPC, sAC, sAA, sTS, sAI) self.main.bonyLandmarks[blDict[ghJointsIndex]].relativePosition = GH #~ if ghJointsIndex == 24: #~ self.LinkGHtoHumerus(GH) def LinkGHtoHumerus(self, GH_relativeToScapula): #If you want to link GH to the humerus rather than the scapula, use this function. #In the config.ini, link the GH-bonylandmark to the humerus sensor rather than the scapula sensor. #fetch Scapula sensor position & rotation sensorTransform = self.main.driver.get_sample("fob0_4") #fob0_4 outputSensor = Sensor("fob0_4") outputSensor.rawPosition = sensorTransform[0:3] outputSensor.rawRotation = sensorTransform[3:13] outputSensor = self.main.driver.CalibrateSingleSensor(outputSensor) #~ outputSensor.position/rotation hold our info #calculate GH-global GH_global = self.main.driver.RelativeToGlobal(GH_relativeToScapula, outputSensor.position, outputSensor.rotation) #fetch Humerus sensor position & rotation sensorTransform2 = self.main.driver.get_sample("fob0_5") #fob0_5 outputSensorHumerus = Sensor("fob0_5") outputSensorHumerus.rawPosition = sensorTransform2[0:3] outputSensorHumerus.rawRotation = sensorTransform2[3:13] outputSensorHumerus = self.main.driver.CalibrateSingleSensor(outputSensorHumerus) #~ outputSensorHumerus.position/rotation hold our info #calculate HumerusGH-relative GH_relativeToHumerus = self.main.driver.GetCalcBLVec(GH_global, outputSensorHumerus.position, outputSensorHumerus.rotation) #set self.main.bonyLandmarks[24].relativePosition self.main.bonyLandmarks[24].relativePosition = GH_relativeToHumerus ## Estimates right GH-Joint. # @param[in] (pc, ac, aa, ts, ai) The relative position of 5 bony landmarks. # @return[matrix] The right GH-Joint estimate. def _GHEstimateRRegressionMethod(self, pc, ac, aa, ts, ai): return self.__GHEstimateRegressionMethod(pc*10, ac*10, aa*10, ts*10, ai*10)/10 ## Estimates left GH-Joint. # @param[in] (pc, ac, aa, ts, ai) The relative position of 5 bony landmarks. # @return[matrix] The left GH-Joint estimate. def _GHEstimateLRegressionMethod(self, pc, ac, aa, ts, ai): pcb = pc.copy() acb = ac.copy() aab = aa.copy() tsb = ts.copy() aib = ai.copy() pcb[1,:] = -pcb[1,:] acb[1,:] = -acb[1,:] aab[1,:] = -aab[1,:] tsb[1,:] = -tsb[1,:] aib[1,:] = -aib[1,:] GHl = self.__GHEstimateRegressionMethod(pcb*10, acb*10, aab*10, tsb*10, aib*10)/10 GHl[1,:] = -GHl[1,:] return GHl ## Calculates GH from regression equations according to Meskers et al 1997. juli 1996. C. Meskers. # @param[in] (pc, ac, aa, ts, ai) The relative position of 5 bony landmarks. # @return[matrix] The GH-Joint estimate. def __GHEstimateRegressionMethod(self, pc, ac, aa, ts, ai): Rsca = self.__AsScap96RegressionMethod(ac, ts, ai) Osca = ac pc = transpose(Rsca) * (pc - Osca) ac = transpose(Rsca) * (ac - Osca) aa = transpose(Rsca) * (aa - Osca) ts = transpose(Rsca) * (ts - Osca) ai = transpose(Rsca) * (ai - Osca) lacaa = norm(ac - aa) ltspc = norm(ts - pc) laiaa = norm(ai - aa) lacpc = norm(ac - pc) scx = vstack((1, pc[0,0], ai[0,0], laiaa, pc[1,0])) scy = vstack((1, lacpc, pc[1,0], lacaa, ai[0,0])) scz = vstack((1, pc[1,0], pc[2,0], ltspc)) thx = matrix("[18.9743 0.2434 0.2341 0.1590 0.0558]") thy = matrix("[-3.8791 -0.1002 0.1732 -0.3940 0.1205]") thz = matrix("[9.2629 -0.2403 1.0255 0.1720]") GHx = thx * scx GHy = thy * scy GHz = thz * scz gh = vstack((GHx, GHy, GHz)) return (Rsca * gh) + Osca ## Calculation of local coordinate system of the scapula S. # @param[in] (AC, TS, AI) The column vectors. # @return[matrix] The local coordinate system. def __AsScap96RegressionMethod(self, AC, TS, AI): xs = (AC-TS) / norm(AC-TS) zhulp = cross(transpose(xs), transpose((AC-AI))) zhulp = zhulp / norm(zhulp) ys = cross(zhulp, transpose(xs)) zs = cross(transpose(xs),ys) return hstack((xs, transpose(ys), transpose(zs))) ## Method calculating the GH-Joints using the movement method. def CalcMovementMethod(self): pass
Python
## SensorState contains the functionality behind the SensorPanel. class SensorState: ## The constructor of SensorState. # @param[in] main Main wx.App derived instance. def __init__(self, main): ## Main wx.App derived instance. self.main = main ## The sensor rulebase. main.config is an instantiation of the ConfigfileReader class. self.sensorRB = self.main.config.ReadSensorRulebase() ## Get dictionary mapping from GSI to position string. # This is derived from the currently instantiated list of sensors, # so as to give feedback what was actually done with the information in the config file. # @return[dictionary] A (key,value) mapping from sensor name to position, e.g. {'fob0_3', 'Thorax'}. def get_sensor_positions(self): gp_dict = {} for sensor in self.main.sensors: gp_dict[sensor.ID] = sensor.name return gp_dict ## Checks the sensors and their positions compared to eachother using the rulebase. # @return[boolean] True if all the rules are true, else False. def CheckSensors(self): # Update the positions of all the sensors. # self.main.driver is an instantiation of the FoBDriver class. self.main.driver.SampleSensors() # Create a dictionary of sensors to pass it to the rules. sensors_dict = {} for sensor in self.main.sensors: sensors_dict[sensor.ID] = sensor.position # Check each rule in the rulebase. for rule in self.sensorRB: if not rule.IsTrue(sensors_dict): return False return True
Python
## Python does not offer real interfaces in its library, this implementation is a construction with behaviour similair to that of an interface. # Each method raises a NotImplementedError when the inheriting class does not implemented one of the methods listed in DriverInterface. # Methods in this class have default implementations, but these can be overwritten by inheriting classes. class DriverInterface: ## The constructor of DriverInterface. # @param[in] main Main wx.App derived instance. def __init__(self, main): raise NotImplementedError("DriverInterface.__init__ has not been implemented.") ## Puts the system to sleep. def sleep(self): raise NotImplementedError("DriverInterface.sleep has not been implemented.") ## Runs the system. def run(self): raise NotImplementedError("DriverInterface.run has not been implemented.") ## Closes communication. def close(self): raise NotImplementedError("DriverInterface.close has not been implemented.") ## Returns raw data. # @param[in] id The sensor ID from which we are requesting data. def get_sample(self,id): raise NotImplementedError("DriverInterface.get_sample has not been implemented.") ## Applies the calibration procedure on the raw FoB data. # Used by the CalibrateSingleSensor method. # @param[in] rawData The data that needs to be calibrated. def __CalibrateRawData(self, rawData): raise NotImplementedError("DriverInterface.__CalibrateRawData has not been implemented.") ## Calculates the rotations x, y, and z resp. around the x-, y-, and z-axis. # @param[in] R The matrix of which we are calculating the rotations. def __RotXYZ(self, R): raise NotImplementedError("DriverInterface.__RotXYZ has not been implemented.") ## Calculate position vector of bony landmark relative to its sensors. # @param[in] stylusSensor The sensor representing the stylus. # @param[in] sampleSensor The sensor corresponding to the bony landmark. def GetBLRelativePosition(self, stylusSensor, sampleSensor): raise NotImplementedError("DriverInterface.GetBLRelativePosition has not been implemented.") ## Calculates the endpoint of the stylus. # @param[in] sensorPosition The position of the stylus. # @param[in] sensorRotation The rotation of the stylus. def __StylusCompensation(self, sensorPosition, sensorRotation): raise NotImplementedError("DriverInterface.__StylusCompensation has not been implemented.") ## Calculates the relative vector of the bony landmark w.r.t. the sensor. # @param[in] bonyLandmarkPosition The position of the bony landmark. # @param[in] sensorPosition The position of the sensor. # @param[in] sensorRotation The rotation of the sensor. def __CalcBLVec(self, bonyLandmarkPosition, sensorPosition, sensorRotation): raise NotImplementedError("DriverInterface.__CalcBLVec has not been implemented.") ## Calculates the global vector of the bony landmark w.r.t. the transmitter coordinate system. # @param[in] relativePosition The relative position of the sensor. # @param[in] sensorPosition The position of the sensor. # @param[in] sensorRotation The rotation of the sensor. def RelativeToGlobal(self, relativePosition, sensorPosition, sensorRotation): raise NotImplementedError("DriverInterface.RelativeToGlobal has not been implemented.") ## Gets position and rotation data for all sensors. def SampleSensors(self): raise NotImplementedError("DriverInterface.SampleSensors has not been implemented.") ## Append a new 'OnPedal transform' to the "bony landmark - sensor mapping": imSensor. # @param[in] blIndex The index of the bony landmark. # @param[in] sensorID The ID of the sensor. def FetchBL_SensorPositionRotation(self, blIndex, sensorID): raise NotImplementedError("DriverInterface.FetchBL_SensorPositionRotation has not been implemented.") ## Calibrate a single sensor. # @param[in] singleSensor A sensor object. def CalibrateSingleSensor(self, singleSensor): raise NotImplementedError("DriverInterface.CalibrateSingleSensor has not been implemented.")
Python
import wx from vtk.wx.wxVTKRenderWindowInteractor import wxVTKRenderWindowInteractor from vtk import vtkInteractorStyleTrackballCamera from Sensor import Sensor import os ## Subpanel of VisualizationPanel which shows the real time movement using the VTK window. New recordings can also be made in this panel. class RecordingPanel(wx.Panel): ## The constructor of RecordingPanel. GUI elements of the panel are setup here. # @param[in] parent The wx window parent (VisualizationState) of this panel. # @param[in] state RecordingState instance attached to this panel. def __init__(self, parent, state): wx.Panel.__init__(self, parent) ## The name of this notebook panel. self.name = "Recording" ## RecordingState instance attached to this panel. self.state = state self.state.panel = self self.lastpath = "" ## wxVTKRenderWindowInteractor used to show the 3D model. self.widget = wxVTKRenderWindowInteractor(self, -1) self.widget.SetInteractorStyle(vtkInteractorStyleTrackballCamera()) self.widget.GetRenderWindow().AddRenderer(self.state.ren) if self.state.main.Smooth3DModel: self.widget.GetRenderWindow().SetAAFrames(3) ## Starts a recording. self.recordButton = wx.BitmapButton(self, -1, wx.Bitmap("Images/Record.png", wx.BITMAP_TYPE_PNG)) ## Label indicating whether you are recording or not. self.recordLabel = wx.StaticText(self, -1, "") ## Reset Camera button. self.resetCamButton = wx.Button(self, -1, "Reset Camera") # Set properties. self.widget.SetSize(self.widget.GetBestSize()) self.recordButton.SetMinSize((75, 25)) # Set sizers. realTimeSizer = wx.BoxSizer(wx.HORIZONTAL) realTimeGrid = wx.FlexGridSizer(2, 1, 10, 0) buttonSizer = wx.FlexGridSizer(2, 2, 0, 5) buttonSizer.Add(self.resetCamButton, 0, wx.RIGHT|wx.BOTTOM|wx.ALIGN_RIGHT, 10) buttonSizer.Add(self.recordButton, 0, wx.RIGHT|wx.BOTTOM|wx.ALIGN_RIGHT, 10) buttonSizer.Add(wx.StaticText(self, -1, ""),0, wx.RIGHT|wx.BOTTOM|wx.ALIGN_RIGHT, 10) buttonSizer.Add(self.recordLabel, 0, wx.ALIGN_CENTER_VERTICAL, 0) realTimeGrid.Add(self.widget, 0, wx.ALL|wx.EXPAND, 10) realTimeGrid.Add(buttonSizer, 1, wx.ALIGN_RIGHT, 0) realTimeGrid.AddGrowableRow(0) realTimeGrid.AddGrowableCol(0) realTimeSizer.Add(realTimeGrid, 1, wx.EXPAND, 0) self.SetSizer(realTimeSizer) self.Bind(wx.EVT_BUTTON, self.OnRecord, self.recordButton) self.Bind(wx.EVT_BUTTON, self.OnResetCam, self.resetCamButton) self.Layout() ## Event handler for the timer, stops timer. def OnTimer(self, event): self.recordLabel.SetLabel("") ## Event handler for the Record button, toggles the recording on and off in visualizationState. def OnRecord(self, event): if self.state.RECORDING: self.recordButton.SetBitmapLabel(wx.Bitmap(self.state.main.config.root+"\\Images\\Record.png", wx.BITMAP_TYPE_PNG)) self.recordLabel.SetLabel("Recording Completed") else: self.recordButton.SetBitmapLabel(wx.Bitmap(self.state.main.config.root+"\\Images\\Stop.png", wx.BITMAP_TYPE_PNG)) self.recordLabel.SetLabel("Recording...") self.Layout() self.OnToggleRecord() ## Toggles the recording of movement on and off. def OnToggleRecord(self): if self.state.RECORDING: #~ self.state.main.driver.fileWriter.close() self.state.RECORDING = False dlg = wx.FileDialog(self.state.main.gui, message="Save as FoB file", defaultDir=os.getcwd(), defaultFile="", wildcard="FoB file (*.fob)|*.fob", style=wx.SAVE | wx.CHANGE_DIR | wx.OVERWRITE_PROMPT) if dlg.ShowModal() == wx.ID_OK: self.state.recordingSession.filename = dlg.GetPath() self.state.parent.recordingsProcessor.SaveRecording(dlg.GetPath(), self.state.recordingSession) self.state.parent.playbackState.addRecording(self.state.recordingSession) dlg.Destroy() fobfilepath = dlg.GetPath() matfilepath = fobfilepath.rstrip('.fob') + '.txt' fileWriter = open(matfilepath, 'w') for i in self.state.main.driver.rawoutputlist: fileWriter.write(i) fileWriter.close() self.state.main.driver.rawoutputlist = [] else: #~ dlg = wx.FileDialog(self.state.main.gui, message="Save as Raw Output file", defaultDir=os.getcwd(), defaultFile="", #~ wildcard="Txt-file (*.txt)|*.txt", style=wx.SAVE | wx.CHANGE_DIR | wx.OVERWRITE_PROMPT) #~ if dlg.ShowModal() == wx.ID_OK: #~ txtpath = dlg.GetPath() #~ self.lastpath = txtpath #~ self.state.main.driver.fileWriter = open(txtpath, 'w') #~ dlg.Destroy() self.state.newRecordingSession() self.state.RECORDING = True ## Resets the camera. def OnResetCam(self, event): self.state.parent.ResetCamera(self.state)
Python
from Sensor import Sensor from BonyLandmark import BonyLandmark from Rule import Rule from ConfigParser import ConfigParser import wx import sys, os ## Parses the configuration file. class ConfigfileReader: ## The constructor of ConfigfileReader. Opens the config file config.ini and reads the entire content. # @param[in] gui GUI instance. # @param[in] configString The path to the config.ini file. def __init__(self, gui, configString): ## Instantiation of Python's ConfigParser. self.config = ConfigParser() ## The path to the config.ini file. self.configFile = configString ## GUI instance. self.gui = gui ## The root directory of the application. self.root = self.ReadRootDirectory() try: self.config.read(self.configFile) except: msg = "Could not read the configuration file %s." % self.configFile self.DisplayErrorDialog(msg) ## Reads the GH-Joints data. # @param[in] allGHJoints a Boolean value, true to return all GHJoints, whether they are active or not # @return[dict] A dictionary containing the number and names of GH-Joints. def ReadGHJoints(self, allGHJoints): try: ghJoints = self.config.items("GH-Joints") except: msg = "An error ocurred while reading GH-Joints data. Please check the configuration file %s for inconsistencies." % self.configFile self.DisplayErrorDialog(msg) # Make list of active bony landmarks. activeBLCheck = [] for blList in self.ReadActiveBonyLandmarks(): activeBLCheck += blList[1 :] gh_dict = {} for ghJointNumber, ghj in ghJoints: # If all the GHJoints are included or # If the gh-joint is an active bl, then it is added to the list. if allGHJoints or int(ghJointNumber) in activeBLCheck: gh_dict[int(ghJointNumber)] = ghj return gh_dict ## Calculates the connection between the GH-Joints and bony landmarks. # @return[dict] A dictionary containing each GH-Joint and their corresponding bony landmark connections. def ReadGHJointsRegressionConnection(self): try: regCon = self.config.items("GH-Joints Regression Connection") except: msg = "An error ocurred while reading GH-Joints Regression Connection data. Please check the configuration file %s for inconsistencies." % self.configFile self.DisplayErrorDialog(msg) blActiveList = self.ReadActiveBonyLandmarks() activeCheck = [] # Make list of active bony landmarks. for blList in blActiveList: activeCheck += blList[1 :] reCon_dict = {} for key, connections in regCon: conActive = True conStrings = connections.split(" ") # Convert the indices to integers. for i in range(0,len(conStrings)): conStrings[i] = int(conStrings[i]) # Check if the bony landmark is active. conActive = conActive and conStrings[i] in activeCheck # Make a new entry in the dictionary if both the GH-Joint and it's bl connections are active. if conActive and int(key)in activeCheck: reCon_dict[int(key)] = conStrings return reCon_dict ## The GSI mapping from fob0_x to COM[port]_[address] as read from the config.ini file. # @return[dict] A dictionary containing a mapping between GSI ID's and COM ports. def ReadComports(self): try: comports = self.config.items("FobDevice") except: msg = "An error ocurred while reading FobDevice data. Please check the configuration file %s for inconsistencies." % self.configFile self.DisplayErrorDialog(msg) com_dict = {} for gsi, com in comports: com_dict[gsi.split('_')[1]] = com return com_dict ## Reads the positions of the sensors to be displayed on the body in SensorPanel. # @return[dict] A dictionary containing the sensor and corresponding coordinates on the body. def ReadSensorPictPos(self): try: sensorcoord = self.config.items("SensorPictPos") except: msg = "An error ocurred while reading SensorPictPos data. Please check the configuration file %s for inconsistencies." % self.configFile self.DisplayErrorDialog(msg) spp_dict = {} for sensor, coord in sensorcoord: if coord[0] + coord[-1] != "()": raise ValueError("Badly formatted string (missing brackets).") items = coord[1:-1] pos = [int(i.strip()) for i in items.split(',')] spp_dict[sensor] = tuple(pos) return spp_dict ## Creates a list of sensors, read from the [ActiveSensors] section in the config.ini file. # @return[array] The list of active sensors. def ReadActiveSensors(self): try: ass = self.config.get("ActiveSensors", "active_sensors") except: msg = "An error ocurred while reading ActiveSensors data. Please check the configuration file %s for inconsistencies." % self.configFile self.DisplayErrorDialog(msg) asl = [i.strip() for i in ass.split(',')] return asl ## Read the default positions of the sensors. This only returns positions that are associated with active sensors! # @return[dictionary] A (key,value) mapping from sensor name to position, e.g. {'fob0_3', 'Thorax'}. def ReadDefaultPositions(self): try: positions = self.config.items("DefaultPositions") except: msg = "An error ocurred while reading DefaultPositions data. Please check the configuration file %s for inconsistencies." % self.configFile self.DisplayErrorDialog(msg) asl = self.ReadActiveSensors() dp_dict = {} for gsi, position in positions: if gsi in asl: dp_dict[gsi] = position return dp_dict ## Creates an array containing all the bony landmarks of the default protocol. # @return[array] The list of all the bony landmarks of the default protocol. def ReadBonyLandmarks(self): try: names = self.config.items("BonyLandmarks") except: msg = "An error ocurred while reading BonyLandmarks data. Please check the configuration file %s for inconsistencies." % self.configFile self.DisplayErrorDialog(msg) for i in range(0,len(names)): names[i] = (int(names[i][0]), names[i][1]) names.sort() bonyLandmarks = [] activeSensors = self.ReadActiveSensors() for name in names: bonyLandmarks.append(BonyLandmark(name[0], name[1])) # Add GH-joint BLs. for ghBlNumber, ghBlName in self.ReadGHJoints(True).items(): bonyLandmarks.append(BonyLandmark(ghBlNumber, ghBlName)) # Sets the sensorID For each bony landmark connected to an active sensor. for blList in self.ReadActiveBonyLandmarks(): # Set the sensorID of each BL (defaults to -1). for i in range(1,len(blList)): bonyLandmarks[blList[i]].sensorID = blList[0] # Remove the bony landmarks that don't have any active sensor connections. updatedBonyLandmarks = list(bonyLandmarks) for bonyLandmark in bonyLandmarks: if bonyLandmark.sensorID == -1: updatedBonyLandmarks.remove(bonyLandmark) return updatedBonyLandmarks ## Creates an array containing all the names of the bony landmarks of the default protocol. # @return[array] The list of all the names of the bony landmarks of the default protocol. def ReadBonyLandmarkNames(self): try: names = self.config.items("BonyLandmarks") except: msg = "An error ocurred while reading BonyLandmarks data. Please check the configuration file %s for inconsistencies." % self.configFile self.DisplayErrorDialog(msg) for i in range(0,len(names)): names[i] = (int(names[i][0]), names[i][1]) names.sort() return names; ## Returns a list of bony landmarks indices arrays with the sensorID of the active sensor they are coupled to. # @return[array] Lists of bony landmark indices and the coupled active sensors ID's. def ReadActiveBonyLandmarks(self): # Read BL relative sensors. try: sensor_bl_connection_list = self.config.items("Sensor-BL-Connection") except: msg = "An error ocurred while reading Sensor-BL-Connection data. Please check the configuration file %s for inconsistencies." % self.configFile self.DisplayErrorDialog(msg) try: active_sensors = self.config.items("ActiveSensors") except: msg = "An error ocurred while reading ActiveSensors data. Please check the configuration file %s for inconsistencies." % self.configFile self.DisplayErrorDialog(msg) sensor_bl_connection_list.sort() bls = [] for sensor_bl_connection in sensor_bl_connection_list: # Set the Sensors of the bony landmarks using the active sensor ID's. if sensor_bl_connection[0] in active_sensors[0][1]: sensorID = sensor_bl_connection[0] bonyLandmarkList = [int(blID) for blID in (sensor_bl_connection[1].split())] bonyLandmarkList.insert(0,sensorID) bls.append(bonyLandmarkList) #list of BL ids # The first entry will always be emptpy or contain fob0_2. return bls[1 :] ## Read all the bony landmark descriptions. # @return[array] An array of strings containing the bony landmark descriptions. def ReadDescriptions(self): try: descriptions = self.config.items("BL Descriptions") except: msg = "An error ocurred while reading BL Descriptions data. Please check the configuration file %s for inconsistencies." % self.configFile self.DisplayErrorDialog(msg) for i in range(0,len(descriptions)): descriptions[i] = (int(descriptions[i][0]), descriptions[i][1]) descriptions.sort() for i in range(0,len(descriptions)): descriptions[i] = descriptions[i][1] return descriptions ## Read the rulebase for bony landmarks. # @return[array] All the rules for bony landmarks. def ReadBLRulebase(self): return self.__ReadRulebase("BLRulebase", "BonyLandmark") ## Read the rulebase for sensors. # @return[array] All the rules for sensors. def ReadSensorRulebase(self): return self.__ReadRulebase("SensorRulebase", "Sensor") ## Returns a rulebase (a list of Rule objects) from the given string. # @param[in] rulebase The rulebase to be loaded, BLRulebase or SensorRulebase. # @param[in] ruleType The type of rule, Sensor or BonyLandmark. # @return[array] The rulebase corresponding to ruleType. def __ReadRulebase(self, rulebase, ruleType): try: rules = self.config.items(rulebase) except: msg = "An error ocurred while reading %s data. Please check the configuration file %s for inconsistencies." % rulebase, self.configFile self.DisplayErrorDialog(msg) rules.sort() rulebase = [] activeCheck = [] if ruleType == "BonyLandmark": blActiveList = self.ReadActiveBonyLandmarks() # Make list of active bony landmarks. for blList in blActiveList: activeCheck += blList[1 :] # Convert all the items from integers to strings. for i in range(0,len(activeCheck)): activeCheck[i] = '%s' % activeCheck[i] else: activeCheck = self.config.items("ActiveSensors")[0][1] for rule in rules: components = rule[1].split() if components[1] in activeCheck and components[3] in activeCheck: if ruleType == "BonyLandmark": rulebase.append(Rule(components[0], int(components[1]), int(components[3]), ruleType)) else: rulebase.append(Rule(components[0], components[1], components[3], ruleType)) return rulebase ## Returns a list containing the 3D model numbers and their connected bony landmarks. # @return[array] Array containing 3d model numbers and their bony landmarks. def Read3DModelConnection(self): try: modelConnection = self.config.items("3DModelConnection") except: msg = "An error ocurred while reading 3DModelConnection data. Please check the configuration file %s for inconsistencies." % self.configFile self.DisplayErrorDialog(msg) validConnections = [] activeBonyLandmarks = [] # Make a list containing the active bony landmarks. for blList in self.ReadActiveBonyLandmarks(): activeBonyLandmarks += blList[1 :] # Process each line from the config file for i in range(0, len(modelConnection)): validConnection = True bonyLandmarkList = [] modelList = [] # Make a list of the 3d model numbers. modelnumbers = modelConnection[i][0].split() if len(modelnumbers) == 3 and modelnumbers[1] == '-': modelList = range(int(modelnumbers[0]),int(modelnumbers[2])+1) else: for j in range(0,len(modelnumbers)): modelList.append(int(modelnumbers[j])) # Make a list of the bony landmarks numbers. Sets the validConnection bool to false if # one of the bony landmarks in the 3D Model - Bonylandmark connection is not in the active bonylandmarks. for bC in modelConnection[i][1].split(): validConnection = int(bC) in activeBonyLandmarks and validConnection bonyLandmarkList.append(int(bC)) # If it is a valid connection, add the model numbers and bony landmark numbers to the list. if validConnection: validConnections.append([modelList, bonyLandmarkList]) return validConnections ## Returns the number of parts of the 3d Model. # @return[int] The number of elements in the 3D Model. def Read3DModelParts(self): try: parts = int(self.config.items("3DModelParts")[0][1]) except: msg = "An error ocurred while reading 3DModelParts data. Please check the configuration file %s for inconsistencies." % self.configFile self.DisplayErrorDialog(msg) return parts ## Returns a string containing the path and the format of the 3D model VTK files. # @return[string] Path and format of the 3D model VTK files. def Read3DFileName(self): try: filename = os.path.join(self.root, self.config.items("3DFileName")[0][1]) except: msg = "An error ocurred while reading 3DFileName data. Please check the configuration file %s for inconsistencies." % self.configFile self.DisplayErrorDialog(msg) return filename ## Determines whether 3D smoothing is on or off. # @return[Boolean] Boolean representing the 3D smoothing of the model. def Read3DSmoothing(self): try: smoothing = self.config.items("3DSmoothing")[0][1] == "True" except: msg = "An error ocurred while reading 3DSmooth data. Please check the configuration file %s for inconsistencies." % self.configFile self.DisplayErrorDialog(msg) return smoothing ## Reads the framerate of the application. # @return[float] The framerate. def ReadFramerate(self): try: framerate = self.config.items("Framerate")[0][1] except: msg = "An error ocurred while reading Framerate data. Please check the configuration file %s for inconsistencies." % self.configFile self.DisplayErrorDialog(msg) return float(framerate) ## Returns a string containing the root directory path of the FoB installation. # @return[string] The root directory path. def ReadRootDirectory(self): if hasattr(sys, 'frozen') and sys.frozen: root, exe = os.path.split(sys.executable) else: dirname = os.path.dirname(sys.argv[0]) if dirname and dirname != os.curdir: root = dirname else: root = os.getcwd() return root ## Displays an error dialog. # @param[in] msg The message to be displayed in the dialog. def DisplayErrorDialog(self, msg): dlg = wx.MessageDialog(self.gui, msg, 'Warning', wx.OK | wx.NO_DEFAULT | wx.ICON_EXCLAMATION) dlg.ShowModal()
Python
#!/usr/bin/python # -*- coding: utf-8 -*- ## # (C) Copyright 2011 Jose Carrasco <jose.carrasco[a]vikuit.com> # (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com> # # This file is part of "vikuit". # # "vikuit" is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # "vikuit" 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with "vikuit". If not, see <http://www.gnu.org/licenses/>. ## import os import sha import time import Cookie COOKIE_NAME = 'vikuit' class Session(object): def __init__(self, seed): self.time = None self.user = None self.auth = None self.seed = seed def load(self): string_cookie = os.environ.get('HTTP_COOKIE', '') string_cookie = string_cookie.replace(';', ':') # for old sessions self.cookie = Cookie.SimpleCookie() self.cookie.load(string_cookie) if self.cookie.get(COOKIE_NAME): value = self.cookie[COOKIE_NAME].value tokens = value.split(':') if len(tokens) != 3: return False else: h = tokens[2] tokens = tokens[:-1] tokens.append(self.seed) if h == self.hash(tokens): self.time = tokens[0] self.user = tokens[1] self.auth = h try: t = int(self.time) except: return False if t > int(time.time()): return True return False def store(self, user, expire): self.time = str(int(time.time())+expire) self.user = user params = [self.time, self.user, self.seed] self.auth = self.hash(params) params = [self.time, self.user, self.auth] self.cookie[COOKIE_NAME] = ':'.join(params) self.cookie[COOKIE_NAME]['expires'] = expire self.cookie[COOKIE_NAME]['path'] = '/' print 'Set-Cookie: %s; HttpOnly' % (self.cookie.output().split(':', 1)[1].strip()) def hash(self, params): return sha.new(';'.join(params)).hexdigest() """ def __str__(self): params = [self.time, self.user, self.auth] self.cookie[COOKIE_NAME] = ':'.join(params) self.cookie[COOKIE_NAME]['path'] = '/' return self.cookie.output() s = Session('1234') s.load() if s.load(): print s.auth print s.user s.store('anabel', 3200) """
Python
#!/usr/bin/python # -*- coding: utf-8 -*- # # (C) Copyright 2008 Ignacio Andreu <plunchete at gmail dot com> # # This file is part of "debug_mode_on". # # "debug_mode_on" is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # "debug_mode_on" 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with "debug_mode_on". If not, see <http://www.gnu.org/licenses/>. # import simplejson import model from google.appengine.api import memcache from google.appengine.ext import webapp class BaseRest(webapp.RequestHandler): def render_json(self, data): self.response.headers['Content-Type'] = 'application/json;charset=UTF-8' self.response.headers['Pragma'] = 'no-cache' self.response.headers['Cache-Control'] = 'no-cache' self.response.headers['Expires'] = 'Wed, 27 Aug 2008 18:00:00 GMT' self.response.out.write(simplejson.dumps(data))
Python
#!/usr/bin/python # -*- coding: utf-8 -*- # # (C) Copyright 2008 Ignacio Andreu <plunchete at gmail dot com> # # This file is part of "debug_mode_on". # # "debug_mode_on" is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # "debug_mode_on" 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with "debug_mode_on". If not, see <http://www.gnu.org/licenses/>. # from handlers.BaseHandler import * class SearchResult(BaseHandler): def execute(self): self.render('templates/search-result.html')
Python
#!/usr/bin/python # -*- coding: utf-8 -*- # # (C) Copyright 2008 Alberto Gimeno <gimenete at gmail dot com> # # This file is part of "debug_mode_on". # # "debug_mode_on" is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # "debug_mode_on" 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with "debug_mode_on". If not, see <http://www.gnu.org/licenses/>. # from handlers.BaseHandler import * class Static(BaseHandler): def execute(self): template = self.request.path.split('/', 2)[2] self.render('templates/static/%s' % template)
Python
#!/usr/bin/python # -*- coding: utf-8 -*- ## # (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com> # # This file is part of "vikuit". # # "vikuit" is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # "vikuit" 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with "vikuit". If not, see <http://www.gnu.org/licenses/>. ## from handlers.BaseHandler import BaseHandler class NotFound(BaseHandler): def execute(self): self.not_found()
Python
#!/usr/bin/python # -*- coding: utf-8 -*- ## # (C) Copyright 2011 Jose Carrasco <jose.carrasco[a]vikuit.com> # # This file is part of "vikuit". # # "vikuit" is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # "vikuit" 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with "vikuit". If not, see <http://www.gnu.org/licenses/>. ## from google.appengine.ext import db from google.appengine.ext import webapp from google.appengine.api import memcache from google.appengine.ext.webapp import template from handlers.BaseHandler import * from utilities.AppProperties import AppProperties # Params UPDATER_VERSION = "0.8" def update(): app = model.Application.all().get() if app is None: initializeDb() #self.response.out.write('App installed. Created user administrator. nickname="admin", password="1234". Please change the password.') return elif not app.session_seed: import sha, random app.session_seed = sha.new(str(random.random())).hexdigest() app.put() #self.response.out.write('Seed installed') version = app.version if version is None or version != UPDATER_VERSION: update07to08() #self.response.out.write ('updated to version 0.8') # elif app.version == '0.8': # update08to09() # elif app.version == '0.9': # update09to10() return def initializeDb(): app = model.Application.all().get() if app is None: app = model.Application() app.name = 'vikuit-example' app.subject = 'Social portal: lightweight and easy to install' app.recaptcha_public_key = '6LdORAMAAAAAAL42zaVvAyYeoOowf4V85ETg0_h-' app.recaptcha_private_key = '6LdORAMAAAAAAGS9WvIBg5d7kwOBNaNpqwKXllMQ' app.theme = 'blackbook' app.users = 0 app.communities = 0 app.articles = 0 app.threads = 0 app.url = "http://localhost:8080" app.mail_subject_prefix = "[Vikuit]" app.mail_sender = "admin.example@vikuit.com" app.mail_footer = "" app.max_results = 20 app.max_results_sublist = 20 import sha, random app.session_seed = sha.new(str(random.random())).hexdigest() app.version = UPDATER_VERSION app.put() user = model.UserData(nickname='admin', email='admin.example@vikuit.com', password='1:c07cbf8821d47575a471c1606a56b79e5f6e6a68', language='en', articles=0, draft_articles=0, messages=0, draft_messages=0, comments=0, rating_count=0, rating_total=0, rating_average=0, threads=0, responses=0, communities=0, favourites=0, public=False, contacts=0, rol='admin') user.put() parent_category = model.Category(title='General', description='General category description', articles = 0, communities = 0) parent_category.put() category = model.Category(title='News', description='News description', articles = 0, communities = 0) category.parent_category = parent_category category.put() post = model.Mblog(author=user, author_nickname=user.nickname, content='Welcome to Vikuit!!', responses=0) post.put() # update from 0.7 to 0.8 release def update07to08(): app = model.Application.all().get() app.theme = 'blackbook' app.version = '0.8' app.put() memcache.delete('app') AppProperties().updateJinjaEnv() return # update from 0.8 to 0.9 release def update08to09(): app = model.Application.all().get() app.version = '0.9' app.put() # update from 0.9 to 01 release def update09to10(): app = model.Application.all().get() app.version = '1.0' app.put()
Python
#!/usr/bin/python # -*- coding: utf-8 -*- ## # (C) Copyright 2011 Jose Carrasco <jose.carrasco[a]vikuit.com> # (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com> # # This file is part of "vikuit". # # "vikuit" is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # "vikuit" 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with "vikuit". If not, see <http://www.gnu.org/licenses/>. ## from google.appengine.ext import db from google.appengine.ext import webapp from google.appengine.ext.webapp import template from handlers.BaseHandler import * class Initialization(BaseHandler): def get(self): self.response.headers['Content-Type'] = 'text/plain' app = model.Application.all().get() if app is None: populateDB() self.response.out.write('App installed. Created user administrator. nickname="admin", password="1234". Please change the password.') return elif not app.session_seed: import sha, random app.session_seed = sha.new(str(random.random())).hexdigest() app.put() self.response.out.write('Seed installed') return p = int(self.request.get('p')) key = self.request.get('key') action = self.request.get('action') if key: community = model.Community.get(key) if not community: self.response.out.write('community not found') return offset = (p-1)*10 if action == 'gi': i = self.community_articles(community, offset) elif action == 'gu': i = self.community_users(community, offset) elif action == 'th': i = self.threads(offset) elif action == 'cc': i = self.contacts(offset) elif action == 'fv': i = self.favourites(offset) elif action == 'sg': i = self.show_communities(offset) return elif action == 'ut': i = self.update_threads(offset) elif action == 'uis': i = self.update_article_subscription(p-1) self.response.out.write('Processed from %d to %d. %d updated. Action %s' % (p-1, i[0], i[1], action)) return elif action == 'ugs': i = self.update_community_subscription(community, offset) elif action == 'uts': i = self.update_thread_subscription(p-1) self.response.out.write('Processed from %d to %d. %d updated. Action %s' % (p-1, i[0], i[1], action)) return elif action == 'ugc': i = self.update_community_counters(p-1) self.response.out.write('Processed from %d to %d. %d updated. Action %s' % (p-1, i[0], i[1], action)) return elif action == 'adus': i = self.add_date_user_subscription(offset) elif action == 'afg': i = self.add_follower_community(offset) elif action == 'afu': i = self.add_follower_user(offset) elif action == 'afi': i = self.add_follower_article(offset) elif action == 'aft': i = self.add_follower_thread(offset) else: self.response.out.write('unknown action -%s-' % action) return self.response.out.write('Processed from %d to %d. %d updated. Action %s' % (offset, i[0], i[1], action)) def community_articles(self, community, offset): i = offset p = 0 for gi in model.CommunityArticle.all().filter('community', community).order('-creation_date').fetch(10, offset): if not gi.community_title: article = gi.article community = gi.community gi.article_author_nickname = article.author_nickname gi.article_title = article.title gi.article_url_path = article.url_path gi.community_title = community.title gi.community_url_path = community.url_path gi.put() p += 1 i+=1 return (i, p) def community_users(self, community, offset): i = offset p = 0 for gu in model.CommunityUser.all().filter('community', community).order('-creation_date').fetch(10, offset): if not gu.community_title: user = gu.user community = gu.community gu.user_nickname = gu.user.nickname gu.community_title = community.title gu.community_url_path = community.url_path gu.put() p += 1 i+=1 return (i, p) def threads(self, offset): i = offset p = 0 for th in model.Thread.all().order('-creation_date').fetch(10, offset): if not th.community_title: community = th.community th.community_title = community.title th.community_url_path = community.url_path if not th.url_path: th.url_path = th.parent_thread.url_path th.put() p += 1 i+=1 return (i, p) def contacts(self, offset): i = offset p = 0 for cc in model.Contact.all().order('-creation_date').fetch(10, offset): if not cc.user_from_nickname: cc.user_from_nickname = cc.user_from.nickname cc.user_to_nickname = cc.user_to.nickname cc.put() p += 1 i+=1 return (i, p) def favourites(self, offset): i = offset p = 0 for fv in model.Favourite.all().order('-creation_date').fetch(10, offset): if not fv.user_nickname: article = fv.article fv.article_author_nickname = article.author_nickname fv.article_title = article.title fv.article_url_path = article.url_path fv.user_nickname = fv.user.nickname fv.put() p += 1 i+=1 return (i, p) def show_communities(self, offset): for g in model.Community.all().order('-creation_date').fetch(10, offset): self.response.out.write("('%s', '%s', %d),\n" % (g.title, str(g.key()), g.members)) def update_threads(self, offset): i = offset p = 0 for th in model.Thread.all().filter('parent_thread', None).order('-creation_date').fetch(10, offset): if th.views is None: th.views = 0 th.put() p += 1 i+=1 return (i, p) def update_article_subscription(self, offset): i = offset p = 0 for article in model.Article.all().order('-creation_date').fetch(1, offset): if article.subscribers: for subscriber in article.subscribers: user = model.UserData.all().filter('email', subscriber).get() if not model.UserSubscription.all().filter('user', user).filter('subscription_type', 'article').filter('subscription_id', article.key().id()).get(): self.add_user_subscription(user, 'article', article.key().id()) p += 1 i+=1 return (i, p) def update_community_subscription(self, community, offset): i = offset p = 0 for community_user in model.CommunityUser.all().filter('community', community).order('-creation_date').fetch(10, offset): if not model.UserSubscription.all().filter('user', community_user.user).filter('subscription_type', 'community').filter('subscription_id', community.key().id()).get(): self.add_user_subscription(community_user.user, 'community', community.key().id()) p += 1 i += 1 return (i, p) def update_thread_subscription(self, offset): i = offset p = 0 for thread in model.Thread.all().filter('parent_thread', None).order('-creation_date').fetch(1, offset): if thread.subscribers: for subscriber in thread.subscribers: user = model.UserData.all().filter('email', subscriber).get() if not model.UserSubscription.all().filter('user', user).filter('subscription_type', 'thread').filter('subscription_id', thread.key().id()).get(): self.add_user_subscription(user, 'thread', thread.key().id()) p += 1 i+=1 return (i, p) def update_community_counters(self, offset): i = offset p = 0 for community in model.Community.all().order('-creation_date').fetch(1, offset): users = model.CommunityUser.all().filter('community', community).count() articles = model.CommunityArticle.all().filter('community', community).count() community_threads = model.Thread.all().filter('community', community).filter('parent_thread', None) threads = community_threads.count() comments = 0 for thread in community_threads: comments += model.Thread.all().filter('community', community).filter('parent_thread', thread).count() if community.members != users or community.articles != articles or community.threads != threads or community.responses != comments: community.members = users community.articles = articles community.threads = threads community.responses = comments p += 1 if not community.activity: community.activity = 0 community.activity = (community.members * 1) + (community.threads * 5) + (community.articles * 15) + (community.responses * 2) community.put() i += 1 return (i, p) def add_date_user_subscription(self, offset): i = offset p = 0 for user_subscription in model.UserSubscription.all().fetch(10, offset): if user_subscription.creation_date is None: user_subscription.creation_date = datetime.datetime.now() user_subscription.put() p += 1 i += 1 return (i, p) def add_follower_community(self, offset): i = offset p = 0 for community_user in model.CommunityUser.all().fetch(10, offset): if community_user.user_nickname is None: self.desnormalizate_community_user(community_user) self.add_follower(community=community_user, nickname=community_user.user_nickname) p +=1 i += 1 return(i,p) def add_follower_user(self, offset): i = offset p = 0 for cc in model.Contact.all().fetch(10, offset): if cc.user_from_nickname is None: self.desnormalizate_user_contact(cc) self.add_follower(user=cc.user_to, nickname=cc.user_from_nickname) p += 1 i += 1 return(i,p) def add_follower_article(self, offset): i = offset p = 0 for article in model.Article.all().filter('deletion_date', None).filter('draft', False).fetch(10, offset): self.add_follower(article=article, nickname=article.author_nickname) p += 1 i += 1 return(i,p) def add_follower_thread(self, offset): i = offset p = 0 for t in model.Thread.all().filter('parent_thread', None).fetch(10, offset): self.add_follower(thread=t, nickname=t.author_nickname) p += 1 i += 1 return(i, p) def desnormalizate_community_user(self, gu): user = gu.user community = gu.community gu.user_nickname = gu.user.nickname gu.community_title = community.title gu.community_url_path = community.url_path gu.put() def desnormalizate_user_contact(self, cc): cc.user_from_nickname = cc.user_from.nickname cc.user_to_nickname = cc.user_to.nickname cc.put() def populateDB(): app = model.Application.all().get() if app is None: app = model.Application() app.name = 'vikuit-example' app.subject = 'Social portal: lightweight and easy to install' app.recaptcha_public_key = '6LdORAMAAAAAAL42zaVvAyYeoOowf4V85ETg0_h-' app.recaptcha_private_key = '6LdORAMAAAAAAGS9WvIBg5d7kwOBNaNpqwKXllMQ' app.theme = 'blackbook' app.users = 0 app.communities = 0 app.articles = 0 app.threads = 0 app.url = "http://localhost:8080" app.mail_subject_prefix = "[Vikuit]" app.mail_sender = "admin.example@vikuit.com" app.mail_footer = "" app.max_results = 20 app.max_results_sublist = 20 import sha, random app.session_seed = sha.new(str(random.random())).hexdigest() app.put() user = model.UserData(nickname='admin', email='admin.example@vikuit.com', password='1:c07cbf8821d47575a471c1606a56b79e5f6e6a68', language='en', articles=0, draft_articles=0, messages=0, draft_messages=0, comments=0, rating_count=0, rating_total=0, rating_average=0, threads=0, responses=0, communities=0, favourites=0, public=False, contacts=0, rol='admin') user.put() parent_category = model.Category(title='General', description='General category description', articles = 0, communities = 0) parent_category.put() category = model.Category(title='News', description='News description', articles = 0, communities = 0) category.parent_category = parent_category category.put() post = model.Mblog(author=user, author_nickname=user.nickname, content='Welcome to Vikuit!!', responses=0) post.put()
Python
#!/usr/bin/python # -*- coding: utf-8 -*- # # (C) Copyright 2008 Alberto Gimeno <gimenete at gmail dot com> # # This file is part of "debug_mode_on". # # "debug_mode_on" is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # "debug_mode_on" 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with "debug_mode_on". If not, see <http://www.gnu.org/licenses/>. # from handlers.BaseHandler import * class Tag(BaseHandler): def execute(self): tag = self.request.path.split('/', 2)[2] query = model.Article.all().filter('tags =', tag).filter('draft', False).filter('deletion_date', None).order('-creation_date') self.values['articles'] = self.paging(query, 10) self.add_tag_cloud() self.values['tag'] = tag self.render('templates/tag.html')
Python
#!/usr/bin/python # -*- coding: utf-8 -*- ## # (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com> # # This file is part of "vikuit". # # "vikuit" is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # "vikuit" 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with "vikuit". If not, see <http://www.gnu.org/licenses/>. ## from handlers.BaseHandler import * class AuthenticatedHandler(BaseHandler): def pre_execute(self): user = self.get_current_user() #user = self.values['user'] if not user: self.redirect(self.values['login']) return self.execute()
Python
#!/usr/bin/python # -*- coding: utf-8 -*- # # (C) Copyright 2008 Alberto Gimeno <gimenete at gmail dot com> # # This file is part of "debug_mode_on". # # "debug_mode_on" is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # "debug_mode_on" 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with "debug_mode_on". If not, see <http://www.gnu.org/licenses/>. # from handlers.BaseHandler import * class ForumList(BaseHandler): def execute(self): self.values['tab'] = '/forum.list' query = model.Thread.all().filter('parent_thread', None) app = self.get_application() key = '%s?%s' % (self.request.path, self.request.query) results = 10 if app.max_results: results = app.max_results threads = self.paging(query, results, '-last_response_date', app.threads, ['-last_response_date'], key) # migration for t in threads: if not t.last_response_date: last_response = model.Thread.all().filter('parent_thread', t).order('-creation_date').get() if last_response: t.last_response_date = last_response.creation_date else: t.last_response_date = t.creation_date t.put() # end migration self.values['threads'] = threads self.add_tag_cloud() self.render('templates/forum-list.html')
Python
#!/usr/bin/python # -*- coding: utf-8 -*- ## # (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com> # (C) Copyright 2011 Jose Carrasco <jose.carrasco[a]vikuit.com> # This file is part of "vikuit". # # "vikuit" is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # "vikuit" 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with "vikuit". If not, see <http://www.gnu.org/licenses/>. ## import model import logging from google.appengine.api import memcache from google.appengine.ext import webapp class ImageDisplayer(webapp.RequestHandler): def get(self): cached = memcache.get(self.request.path) params = self.request.path.split('/') if params[2] == 'user': user = model.UserData.gql('WHERE nickname=:1', params[4]).get() self.display_image(user, params, cached, 'user128_1.png', 'user48_1.png') elif params[2] == 'community': community = model.Community.get_by_id(int(params[4])) self.display_image(community, params, cached, 'community128.png', 'community48.png') elif params[2] == 'gallery': query = model.Image.gql('WHERE url_path=:1', '%s/%s' % (params[4], params[5]) ) image = query.get() self.display_image(image, params, cached, 'unknown128.png', 'unknown48.png', False) elif params[2] == 'application': app = model.Application.all().get() image = app.logo self.display_image(image, params, cached, 'logo.gif', 'logo.gif', False) else: self.error(404) return def display_image(self, obj, params, cached, default_avatar, default_thumbnail, not_gallery=True): if obj is None: if not_gallery: self.error(404) else: self.redirect('/static/images/%s' % default_thumbnail) return image = None if cached: image = self.write_image(cached) else: if params[3] == 'avatar': image = obj.avatar if not image: self.redirect('/static/images/%s' % default_avatar) return elif params[3] == 'thumbnail': image = obj.thumbnail if not image: self.redirect('/static/images/%s' % default_thumbnail) return elif params[3] == 'logo': image = obj if not image: self.redirect('/static/images/%s' % default_thumbnail) return if not_gallery and (len(params) == 5 or not obj.image_version or int(params[5]) != obj.image_version): if not obj.image_version: obj.image_version = 1 obj.put() newparams = params[:5] newparams.append(str(obj.image_version)) self.redirect('/'.join(newparams)) return # self.response.headers['Content-Type'] = 'text/plain' # self.response.out.write('/'.join(params)) else: if not cached: memcache.add(self.request.path, image) self.write_image(image) def write_image(self, image): self.response.headers['Content-Type'] = 'image/jpg' self.response.headers['Cache-Control'] = 'public, max-age=31536000' self.response.out.write(image) def showImage(self, image, default): if image: self.write_image(image) memcache.add(self.request.path, image) else: self.redirect('/static/images/%s' % default)
Python
#!/usr/bin/python # -*- coding: utf-8 -*- ## # (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com> # # This file is part of "vikuit". # # "vikuit" is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # "vikuit" 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with "vikuit". If not, see <http://www.gnu.org/licenses/>. ## import model import logging from google.appengine.api import memcache from google.appengine.ext import webapp from handlers.BaseHandler import BaseHandler class ImageBrowser(BaseHandler): def execute(self): user = self.values['user'] #TODO PAGINATE if user: list = "" if user.rol == 'admin': images = model.Image.all() else: images = model.Image.gql('WHERE author_nickname=:1', user.nickname) self.values['images'] = images self.render('templates/editor/browse.html') return
Python
#!/usr/bin/python # -*- coding: utf-8 -*- ## # (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com> # # This file is part of "vikuit". # # "vikuit" is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # "vikuit" 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with "vikuit". If not, see <http://www.gnu.org/licenses/>. ## import datetime import os import model import logging from google.appengine.api import memcache from google.appengine.ext import webapp from handlers.AuthenticatedHandler import AuthenticatedHandler class ImageUploader(AuthenticatedHandler): def execute(self): method = self.request.method user = self.values['user'] if method == 'GET':#Request identifies actions action = self.get_param('act') url_path = self.get_param('url') query = model.Image.gql('WHERE url_path=:1', url_path ) image = query.get() if not image: self.render_json({ 'saved': False, 'msg': self.getLocale('Not found') }) elif user.nickname != image.author_nickname and user.rol != 'admin': self.render_json({ 'saved': False, 'msg': self.getLocale('Not allowed') }) elif action == 'del': #delete image image.delete() self.render_json({ 'saved': True }) else: self.render_json({ 'saved': False }) else:#File upload # Get the uploaded file from request. upload = self.request.get("upload") nick = user.nickname dt = datetime.datetime.now() prnt = dt.strftime("%Y%m%d%H%M%S") url_path = nick +"/"+ prnt try: query = model.Image.all(keys_only=True).filter('url_path', url_path) entity = query.get() if entity: raise Exception('unique_property must have a unique value!') image = model.Image(author=user, author_nickname=nick, thumbnail=upload, url_path=url_path) image.put() self.values["label"] = self.getLocale("Uploaded as: %s") % url_path except: self.values["label"] = self.getLocale('Error saving image') self.render("/translator-util.html") return
Python
#!/usr/bin/python # -*- coding: utf-8 -*- ## # (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com> # # This file is part of "vikuit". # # "vikuit" is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # "vikuit" 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with "vikuit". If not, see <http://www.gnu.org/licenses/>. ## import time import model import datetime import markdown from google.appengine.api import memcache from google.appengine.ext import webapp from google.appengine.ext.webapp import template from time import strftime, gmtime, time from utilities.AppProperties import AppProperties class Feed(webapp.RequestHandler): def get(self): data = memcache.get(self.request.path) if not data: time = 600 params = self.request.path.split('/', 4) if not params[2]: latest = model.Article.gql('WHERE draft=:1 AND deletion_date=:2 ORDER BY creation_date DESC LIMIT 20', False, None) data = self.to_rss(self.get_application().name, latest) elif params[2] == 'mblog': query = model.Mblog.all().filter('deletion_date', None).order('-creation_date') latest = [o for o in query.fetch(25)] data = self.posts_to_rss(self.getLocale("Microbblogging"), latest) time = 200 elif params[2] == 'tag': query = model.Article.all().filter('deletion_date', None).filter('tags =', params[3]).order('-creation_date') latest = [o for o in query.fetch(10)] data = self.to_rss(self.getLocale("Articles labeled with %s") % params[3], latest) elif params[3] == 'community.forum': community = model.Community.gql('WHERE url_path=:1',params[4]).get() if not community: community = model.Community.gql('WHERE old_url_path=:1',params[4]).get() threads = model.Thread.gql('WHERE community=:1 ORDER BY creation_date DESC LIMIT 20', community) data = self.threads_to_rss(self.getLocale("Forum %s") % community.title, threads) elif params[3] == 'community': community = model.Community.gql('WHERE url_path=:1',params[4]).get() if not community: community = model.Community.gql('WHERE old_url_path=:1',params[4]).get() community_articles = model.CommunityArticle.gql('WHERE community=:1 ORDER BY creation_date DESC LIMIT 20', community) latest = [gi.article for gi in community_articles] data = self.to_rss(self.getLocale("Articles by community %s") % community.title, latest) elif params[3] == 'user': latest = model.Article.gql('WHERE author_nickname=:1 AND draft=:2 AND deletion_date=:3 ORDER BY creation_date DESC LIMIT 20', params[4], False, None) data = self.to_rss(self.getLocale("Articles by %s") % params[3], latest) else: data = self.not_found() memcache.add(self.request.path, data, time) self.response.headers['Content-Type'] = 'application/rss+xml' self.response.out.write(template.render('templates/feed.xml', data)) def threads_to_rss(self, title, threads): articles = [] url = self.get_application().url md = markdown.Markdown() for i in threads: article = { 'title': i.title, 'link': "%s/module/community.forum/%s" % (url, i.url_path), 'description': md.convert(i.content), 'pubDate': self.to_rfc822(i.creation_date), 'guid':"%s/module/community.forum/%s" % (url,i.url_path), 'author': i.author_nickname # guid como link para mantener compatibilidad con feed.xml } articles.append(article) values = { 'title': title, 'self': url+self.request.path, 'link': url, 'description': '', 'articles': articles } return values def posts_to_rss(self, title, list): posts = [] url = self.get_application().url for i in list: post = { 'title': "%s" % i.content, 'link': "%s/module/mblog.edit/%s" % (url, i.key().id()), 'description': "%s" % i.content, 'pubDate': self.to_rfc822(i.creation_date), 'guid':"%s/module/mblog.edit/%s" % (url,i.key().id()), 'author': i.author_nickname } posts.append(post) values = { 'title': title, 'self': url+self.request.path, 'link': url, 'description': '%s Microbblogging' % self.get_application().name, 'articles': posts } return values def to_rss(self, title, latest): import MediaContentFilters as contents articles = [] url = self.get_application().url md = markdown.Markdown() for i in latest: if i.author.not_full_rss: content = md.convert(i.description) else: content = md.convert(i.content) content = contents.media_content(content) article = { 'title': i.title, 'link': "%s/module/article/%s" % (url, i.url_path), 'description': content, 'pubDate': self.to_rfc822(i.creation_date), 'guid':"%s/module/article/%d/" % (url, i.key().id()), 'author': i.author_nickname } articles.append(article) values = { 'title': title, 'self': url+self.request.path, 'link': url, 'description': '', 'articles': articles } return values def to_rfc822(self, date): return date.strftime("%a, %d %b %Y %H:%M:%S GMT") def get_application(self): app = memcache.get('app') import logging if not app: app = model.Application.all().get() memcache.add('app', app, 0) return app def not_found(self): url = self.get_application().url values = { 'title': self.get_application().name, 'self': url, 'link': url, 'description': '', 'articles': '' } return values ### i18n def getLocale(self, label): env = AppProperties().getJinjaEnv() t = env.get_template("/translator-util.html") return t.render({"label": label})
Python
#!/usr/bin/python # -*- coding: utf-8 -*- ## # (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com> # # This file is part of "vikuit". # # "vikuit" is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # "vikuit" 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with "vikuit". If not, see <http://www.gnu.org/licenses/>. ## from google.appengine.api import mail from google.appengine.ext import db from handlers.BaseHandler import * import re class Invite(BaseHandler): def execute(self): user = self.values['user'] method = self.request.method app = self.get_application() if not user: self.redirect('/module/user.login') if method == 'GET': #u"""Te invito a visitar %s, %s.\n %s self.values['personalmessage'] = self.getLocale("Let me invite you to visit %s, %s. %s") % (app.name, app.subject, app.url) self.render('templates/invite-friends.html') return elif self.auth(): contacts = self.get_param('contacts').replace(' ','') contacts = contacts.rsplit(',',19) if contacts[0]=='' or not contacts: self.values['failed']=True self.render('templates/invite-friends.html') return self.values['_users'] = [] invitations = [] for contact in contacts: #FIXME inform the user about bad formed mails if re.match('\S+@\S+\.\S+', contact): u = model.UserData.gql('WHERE email=:1', contact).get() if u: self.values['_users'].append(u) else: invitations.append(contact) personalmessage = self.get_param('personalmessage') subject = self.getLocale("%s invites you to participate in %s") % (user.nickname, app.name) body = self.getLocale("Let me invite you to visit %s, %s. %s") % (app.name, app.subject, app.url) if personalmessage: body = u"%s \n\n\n\n\t %s" % (self.clean_ascii(personalmessage), self.get_application().url) self.mail(subject=subject, body=body, bcc=invitations) self.values['sent'] = True self.values['invitations'] = invitations self.render('templates/invite-friends.html')
Python
#!/usr/bin/python # -*- coding: utf-8 -*- # # (C) Copyright 2008 Néstor Salceda <nestor.salceda at gmail dot com> # (C) Copyright 2008 Alberto Gimeno <gimenete at gmail dot com> # # This file is part of "debug_mode_on". # # "debug_mode_on" is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # "debug_mode_on" 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with "debug_mode_on". If not, see <http://www.gnu.org/licenses/>. # import model from google.appengine.api import mail from google.appengine.runtime import apiproxy_errors from google.appengine.ext import webapp class MailQueue(webapp.RequestHandler): def get(self): self.response.headers['Content-Type'] = 'text/plain' n = 10 next = model.MailQueue.all().get() sent = None if not next: self.response.out.write('No pending mail') return if not next.bcc and not next.to: self.response.out.write('email without recipients') next.delete() return if next.bcc: bcc = next.bcc[:n] del next.bcc[:n] sent = self.send_mail(next, bcc=bcc) elif next.to: to = next.to[:n] del next.to[:n] sent = self.send_mail(next, to=to) if not sent: self.response.out.write('error. Mail was not sent') return if next.bcc or next.to: next.put() self.response.out.write('mail sent, something pending') else: next.delete() self.response.out.write('mail sent, mail queue deleted') def send_mail(self, queue, bcc=[], to=[]): app = model.Application.all().get() message = mail.EmailMessage(sender=app.mail_sender, subject=queue.subject, body=queue.body) if not to: to = app.mail_sender message.to = to if bcc: message.bcc = bcc try: message.send() except apiproxy_errors.OverQuotaError, message: return False return True
Python
#!/usr/bin/python # -*- coding: utf-8 -*- # # (C) Copyright 2008 Alberto Gimeno <gimenete at gmail dot com> # # This file is part of "debug_mode_on". # # "debug_mode_on" is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # "debug_mode_on" 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with "debug_mode_on". If not, see <http://www.gnu.org/licenses/>. # import model import simplejson from google.appengine.ext import webapp class TaskQueue(webapp.RequestHandler): def get(self): self.response.headers['Content-Type'] = 'text/plain;charset=utf-8' task = model.Task.all().order('-priority').get() if not task: self.response.out.write('No pending tasks') return data = simplejson.loads(task.data) data = self.__class__.__dict__[task.task_type].__call__(self, data) if data is None: self.response.out.write('Task finished %s %s' % (task.task_type, task.data)) task.delete() else: task.data = simplejson.dumps(data) task.put() self.response.out.write('Task executed but not finished %s %s' % (task.task_type, task.data)) def delete_recommendations(self, data): offset = data['offset'] recs = model.Recommendation.all().fetch(1, offset) if len(recs) == 0: return None next = recs[0] article_to = next.article_to article_from = next.article_from if article_from.draft or article_to.draft or article_from.deletion_date is not None or article_to.deletion_date is not None: next.delete() else: data['offset'] += 1 return data def update_recommendations(self, data): offset = data['offset'] recs = model.Recommendation.all().fetch(1, offset) if len(recs) == 0: return None next = recs[0] article_to = next.article_to article_from = next.article_from self.calculate_recommendation(article_from, article_to) data['offset'] += 1 return data def begin_recommendations(self, data): offset = data['offset'] articles = model.Article.all().filter('draft', False).filter('deletion_date', None).order('creation_date').fetch(1, offset) print 'articles: %d' % len(articles) if len(articles) == 0: return None next = articles[0] data['offset'] += 1 t = model.Task(task_type='article_recommendation', priority=0, data=simplejson.dumps({'article': next.key().id(), 'offset': 0})) t.put() return data def article_recommendation(self, data): article = model.Article.get_by_id(data['article']) if article.draft or article.deletion_date is not None: return None offset = data['offset'] articles = model.Article.all().filter('draft', False).filter('deletion_date', None).order('creation_date').fetch(1, offset) if not articles: return None next = articles[0] data['offset'] += 1 self.calculate_recommendation(next, article) return data def calculate_recommendation(self, next, article): def distance(v1, v2): all = [] all.extend(v1) all.extend(v2) return float(len(all) - len(set(all))) def create_recommendation(article_from, article_to, value): return model.Recommendation(article_from=article_from, article_to=article_to, value=value, article_from_title=article_from.title, article_to_title=article_to.title, article_from_author_nickname=article_from.author_nickname, article_to_author_nickname=article_to.author_nickname, article_from_url_path=article_from.url_path, article_to_url_path=article_to.url_path) if next.key().id() == article.key().id(): return r1 = model.Recommendation.all().filter('article_from', article).filter('article_to', next).get() r2 = model.Recommendation.all().filter('article_from', next).filter('article_to', article).get() diff = distance(article.tags, next.tags) if diff > 0: if not r1: r1 = create_recommendation(article, next, diff) else: r1.value = diff if not r2: r2 = create_recommendation(next, article, diff) else: r2.value = diff r1.put() r2.put() else: if r1: r1.delete() if r2: r2.delete()
Python
#!/usr/bin/python # -*- coding: utf-8 -*- ## # (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com> # # This file is part of "vikuit". # # "vikuit" is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # "vikuit" 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with "vikuit". If not, see <http://www.gnu.org/licenses/>. ## from handlers.BaseHandler import * from google.appengine.api import users class UserView(BaseHandler): def execute(self): self.values['tab'] = '/module/user.list' nickname = self.request.path.split('/')[3] this_user = model.UserData.gql('WHERE nickname=:1', nickname).get() if not this_user: self.not_found() return # TODO: not show if the user profile is not public user = self.values['user'] contact = False if user and user.nickname != this_user.nickname: self.values['canadd'] = True contact = self.is_contact(this_user) self.values['is_contact'] = contact if (user is not None and this_user.nickname == user.nickname) or contact: self.values['im_addresses'] = [(link.split('##', 2)[1], link.split('##', 2)[0]) for link in this_user.im_addresses] else: self.values['im_addresses'] = [] self.values['this_user'] = this_user linksChanged = False counter = 0 for link in this_user.list_urls: if not link.startswith('http'): linksChanged = True link = 'http://' + link this_user.list_urls[counter] = link if link.startswith('http://https://'): linksChanged = True link = link[7:len(link)] this_user.list_urls[counter] = link counter += 1 if linksChanged: this_user.put() links = [(link.split('##', 2)[1], link.split('##', 2)[0]) for link in this_user.list_urls] self.values['links'] = links self.values['personal_message'] = this_user.personal_message self.values['articles'] = model.Article.all().filter('author =', this_user).filter('draft =', False).filter('deletion_date', None).order('-creation_date').fetch(5) self.values['communities'] = model.CommunityUser.all().filter('user =', this_user).order('-creation_date').fetch(18) self.values['contacts'] = model.Contact.all().filter('user_from', this_user).order('-creation_date').fetch(18) self.render('templates/module/user/user-view.html')
Python
#!/usr/bin/python # -*- coding: utf-8 -*- ## # (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com> # # This file is part of "vikuit". # # "vikuit" is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # "vikuit" 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with "vikuit". If not, see <http://www.gnu.org/licenses/>. ## from google.appengine.api import mail from handlers.AuthenticatedHandler import * class UserContact(AuthenticatedHandler): def execute(self): user = self.values['user'] user_to = model.UserData.all().filter('nickname', self.get_param('user_to')).get() if not user_to: self.not_found() return if not self.auth(): return contact = model.Contact.all().filter('user_from', user).filter('user_to', user_to).get() if not contact: contact = model.Contact(user_from=user, user_to=user_to, user_from_nickname=user.nickname, user_to_nickname=user_to.nickname) contact.put() user.contacts += 1 user.put() self.add_follower(user=user_to, nickname=user.nickname) followers = list(self.get_followers(user=user)) followers.append(user.nickname) if not user_to.nickname in followers: followers.append(user_to.nickname) self.create_event(event_type='contact.add', followers=followers, user=user, user_to=user_to) app = self.get_application() subject = self.getLocale("%s has added you as contact") % user.nickname # "%s te ha agregado como contacto" # %s te ha agregado como contacto en %s\nPuedes visitar su perfil en: %s/module/user/%s\n body = self.getLocale("%s has added you as contact in %s\nVisit profile page: %s/module/user/%s\n") % (user.nickname, app.url, app.url, user.nickname) self.mail(subject=subject, body=body, to=[user_to.email]) if self.get_param('x'): self.render_json({ 'action': 'added' }) else: self.redirect('/module/user/%s' % user_to.nickname) else: contact.delete() user.contacts -= 1 user.put() self.remove_follower(user=user_to, nickname=user.nickname) if self.get_param('x'): self.render_json({ 'action': 'deleted' }) else: self.redirect('/module/user/%s' % user_to.nickname)
Python
#!/usr/bin/python # -*- coding: utf-8 -*- ## # (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com> # # This file is part of "vikuit". # # "vikuit" is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # "vikuit" 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with "vikuit". If not, see <http://www.gnu.org/licenses/>. ## from handlers.BaseHandler import * from google.appengine.api import users class UserArticles(BaseHandler): def execute(self): self.values['tab'] = '/module/user.list' nickname = self.request.path.split('/')[3] this_user = model.UserData.gql('WHERE nickname=:1', nickname).get() if not this_user: self.not_found() return # TODO: not show if the user profile is not public self.values['this_user'] = this_user query = model.Article.all().filter('author =', this_user).filter('draft =', False).filter('deletion_date', None) self.values['articles'] = self.paging(query, 10, '-creation_date', this_user.articles, ['-creation_date']) self.render('templates/module/user/user-articles.html')
Python