From 00e836cfa4e2652d724972585d661143142af002 Mon Sep 17 00:00:00 2001 From: eugue Date: Mon, 24 Jan 2011 14:41:38 -0500 Subject: merge with biginstall --- behaviors/Accelerate.xml | 2 +- behaviors/AddPixelEvent.py | 26 ++++++++++++++++++++++++-- behaviors/BehaviorChain.py | 9 +++++++-- behaviors/ColorChangerBehavior.py | 2 +- behaviors/DebugBehavior.py | 2 +- behaviors/EchoBehavior.py | 2 +- behaviors/ModifyParam.py | 8 +++----- behaviors/MoveBehavior.py | 29 +++++++++++++++++++++++++++++ behaviors/PixelDecay.xml | 4 ++-- behaviors/RandomWalk.py | 14 ++++++++++++++ behaviors/RecursiveDecay.py | 3 ++- behaviors/RedShift.xml | 9 +++++++++ behaviors/ResponseMover.py | 15 +++++++++++++++ behaviors/RestrictLocation.py | 36 ++++++++++++++++++++++++++++++++++++ behaviors/RunningBehavior.py | 1 + behaviors/Square.py | 11 +++++++++++ 16 files changed, 157 insertions(+), 16 deletions(-) create mode 100644 behaviors/MoveBehavior.py create mode 100644 behaviors/RedShift.xml create mode 100644 behaviors/ResponseMover.py create mode 100644 behaviors/RestrictLocation.py create mode 100644 behaviors/Square.py (limited to 'behaviors') diff --git a/behaviors/Accelerate.xml b/behaviors/Accelerate.xml index c78195b..f9de077 100644 --- a/behaviors/Accelerate.xml +++ b/behaviors/Accelerate.xml @@ -3,6 +3,6 @@ Sensor StepSize - {val}*1.01 + {val}*1.1 diff --git a/behaviors/AddPixelEvent.py b/behaviors/AddPixelEvent.py index bf3cfff..7f134e1 100644 --- a/behaviors/AddPixelEvent.py +++ b/behaviors/AddPixelEvent.py @@ -1,4 +1,26 @@ from operationscore.Behavior import * +import util.Strings as Strings +from logger import main_log class AddPixelEvent(Behavior): - def initBehavior(self): - className = self['Class'] + def behaviorInit(self): + [module, className] = self['Class'].split('.') + try: + exec('from ' + module+'.'+className + ' import *', globals()) + except Exception as inst: + main_log.error('Error importing ' + module+'.'+className+ '. Component not\ + initialized.') + main_log.error(str(inst)) + self.eventGenerator = eval('lambda args:'+className+'(args)') + + #^lambda function to do generate new event (takes args) + + def processResponse(self, sensors, recurses): + ret = [] + for sensory in sensors: + outDict = {} + outDict[Strings.LOCATION] = sensory[Strings.LOCATION] + settingsDict = dict(self.argDict) + settingsDict['Color'] = sensory['Color'] + outDict['PixelEvent'] = self.eventGenerator(settingsDict) + ret.append(outDict) + return (ret, recurses) diff --git a/behaviors/BehaviorChain.py b/behaviors/BehaviorChain.py index 0170fa8..39f4402 100644 --- a/behaviors/BehaviorChain.py +++ b/behaviors/BehaviorChain.py @@ -29,6 +29,11 @@ class BehaviorChain(Behavior): if hookRecurrence != []: main_log.warn('Hook recurrences are not currently supported. Implement it\ yourself or bug russell') - self.feedback[behaviorId] = recurrence - return response + self.feedback[behaviorId] = recurrence + return (response, []) + + def appendBehavior(behavior): + bid = compReg.registerComponent(behavior) #register behavior (will make + #a new id if there isn't one) + self['ChainedBehaviors'].append(bid) diff --git a/behaviors/ColorChangerBehavior.py b/behaviors/ColorChangerBehavior.py index e1827eb..2a8d974 100644 --- a/behaviors/ColorChangerBehavior.py +++ b/behaviors/ColorChangerBehavior.py @@ -11,4 +11,4 @@ class ColorChangerBehavior(Behavior): else: newDict['Color'] = color.randomColor() ret.append(newDict) - return (ret, recursiveInputs) + return (ret, []) diff --git a/behaviors/DebugBehavior.py b/behaviors/DebugBehavior.py index 9bf3ea8..34f4106 100644 --- a/behaviors/DebugBehavior.py +++ b/behaviors/DebugBehavior.py @@ -5,4 +5,4 @@ class DebugBehavior(Behavior): def processResponse(self, sensorInputs, recursiveInputs): if sensorInputs != []: main_log.debug('Sensor Inputs: ' + str(sensorInputs)) - return [] + return ([], []) diff --git a/behaviors/EchoBehavior.py b/behaviors/EchoBehavior.py index be0ed14..589c42b 100644 --- a/behaviors/EchoBehavior.py +++ b/behaviors/EchoBehavior.py @@ -9,4 +9,4 @@ class EchoBehavior(Behavior): outDict[Strings.LOCATION] = sensory[Strings.LOCATION] outDict['Color'] = (255,0,0) ret.append(outDict) - return ret + return (ret, []) diff --git a/behaviors/ModifyParam.py b/behaviors/ModifyParam.py index 3701013..f589e05 100644 --- a/behaviors/ModifyParam.py +++ b/behaviors/ModifyParam.py @@ -5,7 +5,7 @@ class ModifyParam(Behavior): def processResponse(self, sensorInputs, recursiveInputs): paramType = self['ParamType'] paramName = self['ParamName'] - paramOp = self['ParamOp'] + paramOp = str(self['ParamOp']) if paramType == 'Sensor': searchSet = sensorInputs elif paramType == 'Recurse': @@ -13,12 +13,10 @@ class ModifyParam(Behavior): else: raise Exception('Unknown Param Type') for behaviorInput in searchSet: - if paramName in behaviorInput: - try: + if paramName in behaviorInput: #TODO: copy -> modify instead of just + #copying paramOp = paramOp.replace('{val}', 'behaviorInput[paramName]') #convert the {val} marker to something we can execute behaviorInput[paramName] = eval(paramOp) - except: - raise Exception('Bad operation. Use things like \'{val}*5\', \'{val}+5\', exp({val}) etc.') if paramType == 'Sensor': #return accordingly return (searchSet, recursiveInputs) if paramType == 'Recurse': diff --git a/behaviors/MoveBehavior.py b/behaviors/MoveBehavior.py new file mode 100644 index 0000000..9ae98b9 --- /dev/null +++ b/behaviors/MoveBehavior.py @@ -0,0 +1,29 @@ +from operationscore.Behavior import * +import util.ComponentRegistry as compReg +import util.Geo as Geo +import util.Strings as Strings + +class MoveBehavior(Behavior): + def processResponse(self, sensorInputs, recursiveInputs): + print 'processing' + print sensorInputs + if recursiveInputs: + currRecLocs = recursiveInputs + else: + currRecLocs = [{'Location' : (5, 5)), 'Color' : [255, 255, 255]}] + + if sensorInputs: # if input exists, change location + ret = [] + for currRecLoc in currRecLocs: + currDict = dict(currRecLoc) + for sensorInput in sensorInputs: + currDict['Location'][0] += sensorInput['x'] * self['XStep'] + currDict['Location'][1] += sensorInput['y'] * self['YStep'] + #currDict['Color'] = sensorInput['color'] + ret.append(currDict) + #print ret + return (ret, ret) + + else: # if not, return current recursive location. + #print currRecLocs + return (currRecLocs, currRecLocs) diff --git a/behaviors/PixelDecay.xml b/behaviors/PixelDecay.xml index f9eee0d..c19a1a8 100644 --- a/behaviors/PixelDecay.xml +++ b/behaviors/PixelDecay.xml @@ -1,9 +1,9 @@ - behaviors.DecayBehavior + behaviors.AddPixelEvent + pixelevents.DecayEvent Exponential .01 0 - False diff --git a/behaviors/RandomWalk.py b/behaviors/RandomWalk.py index 8254430..fd6c2c8 100644 --- a/behaviors/RandomWalk.py +++ b/behaviors/RandomWalk.py @@ -1,5 +1,19 @@ from operationscore.Behavior import * import util.ComponentRegistry as compReg +import util.Geo as Geo +import util.Strings as Strings +import random +import pdb class RandomWalk(Behavior): def processResponse(self, sensors, recursives): + ret = [] + s = self['StepSize'] + for sensory in sensors: + step = [random.randint(-s,s), random.randint(-s,s)] + outdict = dict(sensory) + outdict[Strings.LOCATION] = Geo.addLocations(step, outdict[Strings.LOCATION]) + ret.append(outdict) + return (ret,recursives) + + diff --git a/behaviors/RecursiveDecay.py b/behaviors/RecursiveDecay.py index ee38bc4..218813d 100644 --- a/behaviors/RecursiveDecay.py +++ b/behaviors/RecursiveDecay.py @@ -1,4 +1,5 @@ from operationscore.Behavior import * +import pdb class RecursiveDecay(Behavior): def processResponse(self, sensorInputs, recursiveInputs): ret = [] @@ -9,4 +10,4 @@ class RecursiveDecay(Behavior): response['ResponsesLeft'] -= 1 if response['ResponsesLeft'] > 0: ret.append(response) - return (ret, recursiveInputs) #no direct ouput + return (ret, []) #no direct ouput diff --git a/behaviors/RedShift.xml b/behaviors/RedShift.xml new file mode 100644 index 0000000..a99e2ba --- /dev/null +++ b/behaviors/RedShift.xml @@ -0,0 +1,9 @@ + + behaviors.RestrictLocation + + (255,0,255) + Color + {x}>100 + + + diff --git a/behaviors/ResponseMover.py b/behaviors/ResponseMover.py new file mode 100644 index 0000000..e1faccb --- /dev/null +++ b/behaviors/ResponseMover.py @@ -0,0 +1,15 @@ +import pdb +from operationscore.Behavior import * +import util.ComponentRegistry as compReg +#ResponseMover is a scaffold for behaviors that spawn 'walkers' which act autonomously on input. +#Add a recursive hook to control the movement. +class ResponseMover(Behavior): + def processResponse(self, sensorInputs, recursiveInputs): + newResponses = sensorInputs + ret = [] + for recurInput in recursiveInputs: + outDict = dict(recurInput) + ret.append(outDict) + ret += newResponses + return (ret, ret) + diff --git a/behaviors/RestrictLocation.py b/behaviors/RestrictLocation.py new file mode 100644 index 0000000..febc9ed --- /dev/null +++ b/behaviors/RestrictLocation.py @@ -0,0 +1,36 @@ +from operationscore.Behavior import * +import util.ComponentRegistry as compReg +from behaviors.ModifyParam import * +import util.Geo as Geo +import util.Strings as Strings +import random +import pdb +class RestrictLocation(Behavior): + def behaviorInit(self): + action = self['Action'] + modifyParamArgs = {'ParamType': 'Sensor', + 'ParamName':self['ParamName'],'ParamOp':self['Action']} + self.locBounds = self['LocationRestriction'] + self.paramModifier = ModifyParam(modifyParamArgs) + if isinstance(self.locBounds, str): + self.locBounds = self.locBounds.replace('{x}', 'l[0]') + self.locBounds = self.locBounds.replace('{y}', 'l[1]') + self.locEval = eval('lambda l:'+self.locBounds) + elif isinstance(self.locBounds, tuple): + if len(self.locBounds) != 4: + raise Exception('Must be in form (xmin,yin,xmax,ymax)') + else: + self.locEval = lambda l:Geo.pointWithinBoundingBox(l,\ + self.LocBounds) + def processResponse(self, sensorInputs, recursiveInputs): + ret = [] + for data in sensorInputs: + if not self.locEval(data['Location']): + (dataOut, recur) = self.paramModifier.immediateProcessInput([data], []) + #behaviors expect lists ^[] + ret += dataOut + else: + ret.append(data) + return (ret, []) + + diff --git a/behaviors/RunningBehavior.py b/behaviors/RunningBehavior.py index 92db69b..5eb33f7 100644 --- a/behaviors/RunningBehavior.py +++ b/behaviors/RunningBehavior.py @@ -15,6 +15,7 @@ class RunningBehavior(Behavior): outDict['StepSize'] = self['StepSize'] outDict['Location']= Geo.addLocations(outDict['Location'], (outDict['StepSize']*outDict['Dir'],0)) + if not Geo.pointWithinBoundingBox(outDict['Location'], \ compReg.getComponent('Screen').getSize()): outDict['Dir'] *= -1 diff --git a/behaviors/Square.py b/behaviors/Square.py new file mode 100644 index 0000000..a6e9401 --- /dev/null +++ b/behaviors/Square.py @@ -0,0 +1,11 @@ +from operationscore.Behavior import * +class Square(Behavior): + def processResponse(self, sensorInputs, recursiveInputs): + for sensory in sensorInputs:#TODO: consider replicating the dict + xLoc = sensory['Location'][0] + yLoc = sensory['Location'][1] + width = self['Width'] + sensory['Location'] =\ + '{x}<'+str(xLoc+width)+',{x}>'+str(xLoc-width)+\ + ',{y}<'+str(yLoc+width)+',{y}>'+str(yLoc-width) + return (sensorInputs, recursiveInputs) -- cgit v1.2.3 From ad8ad25072f55413ecfd696eff1e07c1cd08984e Mon Sep 17 00:00:00 2001 From: rcoh Date: Tue, 25 Jan 2011 14:07:05 -0500 Subject: Fancy param modification --- behaviors/ModifyParam.py | 4 ++++ behaviors/XYMove.py | 1 + config/6thFloor.xml | 16 +++++++++++++--- 3 files changed, 18 insertions(+), 3 deletions(-) (limited to 'behaviors') diff --git a/behaviors/ModifyParam.py b/behaviors/ModifyParam.py index f589e05..6e76d05 100644 --- a/behaviors/ModifyParam.py +++ b/behaviors/ModifyParam.py @@ -1,4 +1,5 @@ from operationscore.Behavior import * +import math import pdb #Class to perform a given operation on some element of an argDict. Designed to be used a recursive hook, but can serve sensor-based functions as well. Specify ParamType (Sensor or Recurse), ParamName, and ParamOp, (a valid python statement with the old value represented as {val}) class ModifyParam(Behavior): @@ -16,6 +17,9 @@ class ModifyParam(Behavior): if paramName in behaviorInput: #TODO: copy -> modify instead of just #copying paramOp = paramOp.replace('{val}', 'behaviorInput[paramName]') #convert the {val} marker to something we can execute + #TODO: move elsewhere + paramOp = paramOp.replace('{y}', "behaviorInput['Location'][1]") + paramOp = paramOp.replace('{x}', "behaviorInput['Location'][0]") behaviorInput[paramName] = eval(paramOp) if paramType == 'Sensor': #return accordingly return (searchSet, recursiveInputs) diff --git a/behaviors/XYMove.py b/behaviors/XYMove.py index 8acbba8..1b99ee1 100644 --- a/behaviors/XYMove.py +++ b/behaviors/XYMove.py @@ -6,6 +6,7 @@ class XYMove(Behavior): for loc in sensor: oploc = dict(loc) self.insertStepIfMissing(oploc) + print oploc['YStep'] oploc['Location'] = Geo.addLocations((oploc['XStep'], oploc['YStep']), oploc['Location']) ret.append(oploc) return (ret, []) diff --git a/config/6thFloor.xml b/config/6thFloor.xml index 3f734d9..9f3904a 100644 --- a/config/6thFloor.xml +++ b/config/6thFloor.xml @@ -121,11 +121,21 @@ movebounce xymove - ybounce + xbounce + ysin + + behaviors.ModifyParam + + ysin + YStep + Sensor + 4*math.sin({x}/float(40)) + + behaviors.BehaviorChain @@ -182,9 +192,9 @@ behaviors.BehaviorChain runcolordecay - + colorchange running -- cgit v1.2.3 From 82f99fc4583ca3cc9861a9fe30990a4a9ef162c4 Mon Sep 17 00:00:00 2001 From: eugue Date: Tue, 25 Jan 2011 15:22:24 -0500 Subject: working version of IconMover --- behaviors/MoveBehavior.py | 10 ++-- config/MobileTest.xml | 119 ++++++++++++++++++++++++++++++++++++------- inputs/TCPInput.py | 25 +++++---- operationscore/PixelEvent.py | 1 + 4 files changed, 118 insertions(+), 37 deletions(-) (limited to 'behaviors') diff --git a/behaviors/MoveBehavior.py b/behaviors/MoveBehavior.py index 9ae98b9..590f0e4 100644 --- a/behaviors/MoveBehavior.py +++ b/behaviors/MoveBehavior.py @@ -5,21 +5,19 @@ import util.Strings as Strings class MoveBehavior(Behavior): def processResponse(self, sensorInputs, recursiveInputs): - print 'processing' - print sensorInputs if recursiveInputs: currRecLocs = recursiveInputs else: - currRecLocs = [{'Location' : (5, 5)), 'Color' : [255, 255, 255]}] + currRecLocs = [{'Location' : (5, 5), 'Color' : [255, 255, 255]}] if sensorInputs: # if input exists, change location ret = [] for currRecLoc in currRecLocs: currDict = dict(currRecLoc) for sensorInput in sensorInputs: - currDict['Location'][0] += sensorInput['x'] * self['XStep'] - currDict['Location'][1] += sensorInput['y'] * self['YStep'] - #currDict['Color'] = sensorInput['color'] + currDict['Location'] = (currDict['Location'][0] - sensorInput['x'] * self['XStep'], \ + currDict['Location'][1] + sensorInput['y'] * self['YStep']) + currDict['Color'] = [sensorInput['r'], sensorInput['g'], sensorInput['b']] ret.append(currDict) #print ret return (ret, ret) diff --git a/config/MobileTest.xml b/config/MobileTest.xml index 2f736ea..a318069 100644 --- a/config/MobileTest.xml +++ b/config/MobileTest.xml @@ -6,7 +6,7 @@ - layouts/BasicSixStrip.xml + layouts/60StripLayout.xml @@ -29,7 +29,7 @@ - renderers/SixStripUDP.xml + renderers/60StripSeq.xml renderers/Pygame.xml @@ -40,7 +40,15 @@ inputs.PygameInput pygame - 100 + 10 + + + + inputs.TCPInput + + tcp + 20120 + 50 @@ -52,14 +60,6 @@ randomLoc - - inputs.TCPInput - - TCP - 20120 - 100 - - @@ -70,12 +70,21 @@ False + + behaviors/RedShift.xml + behaviors/RandomColor.xml behaviors/PixelDecay.xml + + behaviors/PixelDecay.xml + + .01 + + behaviors.DebugBehavior @@ -92,10 +101,17 @@ pixelsleft + + behaviors.Square + + square + 20 + + behaviors/LoopAndDie.xml - 200 + 50 @@ -115,6 +131,46 @@ gaussmap + + behaviors.BehaviorChain + + randomwalk + + pygame + + + colorchange + mover + decay + + {'mover':'redwalk'} + True + gaussmap + + + + behaviors.ResponseMover + + mover + + + + behaviors.BehaviorChain + + redwalk + + randmovement + redshift + + + + + behaviors.RandomWalk + + randmovement + 2 + + behaviors/Accelerate.xml @@ -128,6 +184,22 @@ + + behaviors.BehaviorChain + + mousechaser + + followmouse + + + echo + redshift + square + slowdecay + + True + + behaviors/RunningBehavior.xml @@ -135,12 +207,23 @@ behaviors.MoveBehavior move - - TCP - - 1 - 1 - True + 5 + 5 + + + + behaviors.BehaviorChain + + moveanddecay + + tcp + + + move + decay + + True + gaussmap diff --git a/inputs/TCPInput.py b/inputs/TCPInput.py index e5475c1..513b853 100644 --- a/inputs/TCPInput.py +++ b/inputs/TCPInput.py @@ -21,28 +21,27 @@ class TCPInput(Input): def sensingLoop(self): data = self.conn.recv(self.BUFFER_SIZE) main_log.debug('Incoming data', data) - if not data or 'end' in data or data == '': # data end, close socket + if not data or 'end' in data: # data end, close socket main_log.debug('End in data') print 'end of stream' self.IS_RESPONDING = 0 self.conn.close() self.sock.close() - - if self.IS_RESPONDING == 1: # if 'responding', respond to the received data - dataDict = json.loads(data) - self.respond(dataDict) - #try: - # for datagroup in data.split('\n'): - # if datagroup != None and datagroup != '': - # dataDict = json.loads(datagroup) - # self.respond(dataDict) - # socketDict = {'data':dataDict, 'address':self.address} + if self.IS_RESPONDING == 1: # if 'responding', respond to the received data + #dataDict = json.loads(data) + try: + for datagroup in data.split('\n'): + if datagroup != None and datagroup != '': + dataDict = json.loads(datagroup) + #print dataDict + self.respond(dataDict) + #socketDict = {'data':dataDict, 'address':self.address} #socketDict = {Strings.LOCATION: (dataDict['x'], dataDict['y'])} # like PygameInput #print 'input' #self.respond(socketDict) - #except Exception as exp: - # print str(exp) + except Exception as exp: + print str(exp) else: # if not 'responding', don't respond to data and restart socket # * an incomplete hack for now. will be changed if same-type-multi-Input is implemented. diff --git a/operationscore/PixelEvent.py b/operationscore/PixelEvent.py index 80d3b9e..c41df17 100644 --- a/operationscore/PixelEvent.py +++ b/operationscore/PixelEvent.py @@ -26,5 +26,6 @@ class PixelEvent(SmootCoreObject): color = responseDict['Color'] else: raise Exception('Need Color. Probably') + pdb.set_trace() responseDict['PixelEvent'] = StepEvent.generate(300, color) -- cgit v1.2.3 From 328464219a02c014caf1608a27a898900cad8456 Mon Sep 17 00:00:00 2001 From: eugue Date: Thu, 27 Jan 2011 14:28:20 -0500 Subject: mobile shake behavior added. --- behaviors/MobileShakeBehavior.py | 17 +++++++++++++++++ behaviors/MoveBehavior.py | 16 ++++++++++------ config/MobileTest.xml | 28 +++++++++++++++++++++++++--- 3 files changed, 52 insertions(+), 9 deletions(-) create mode 100644 behaviors/MobileShakeBehavior.py (limited to 'behaviors') diff --git a/behaviors/MobileShakeBehavior.py b/behaviors/MobileShakeBehavior.py new file mode 100644 index 0000000..e25e929 --- /dev/null +++ b/behaviors/MobileShakeBehavior.py @@ -0,0 +1,17 @@ +from operationscore.Behavior import * +import util.Strings as Strings + +class MobileShakeBehavior(Behavior): + def processResponse(self, sensorInputs, recursiveInputs): + #print sensorInputs + ret = [] + for sInput in sensorInputs: + outDict = dict(sInput) + if 'type' in sInput and sInput['type'] == 2: + outDict['Location'] = '{x}>' + str(0) + ',{y}>' + str(0) + outDict['Color'] = [sInput['r'], sInput['g'], sInput['b']] + else: # dumb invisible pixel + outDict['Location'] = (-1, -1) + outDict['Color'] = [0, 0, 0] + ret.append(outDict) + return (ret, recursiveInputs) diff --git a/behaviors/MoveBehavior.py b/behaviors/MoveBehavior.py index 590f0e4..be41b52 100644 --- a/behaviors/MoveBehavior.py +++ b/behaviors/MoveBehavior.py @@ -1,7 +1,7 @@ from operationscore.Behavior import * -import util.ComponentRegistry as compReg -import util.Geo as Geo -import util.Strings as Strings +#import util.ComponentRegistry as compReg +#import util.Geo as Geo +#import util.Strings as Strings class MoveBehavior(Behavior): def processResponse(self, sensorInputs, recursiveInputs): @@ -15,9 +15,13 @@ class MoveBehavior(Behavior): for currRecLoc in currRecLocs: currDict = dict(currRecLoc) for sensorInput in sensorInputs: - currDict['Location'] = (currDict['Location'][0] - sensorInput['x'] * self['XStep'], \ - currDict['Location'][1] + sensorInput['y'] * self['YStep']) - currDict['Color'] = [sensorInput['r'], sensorInput['g'], sensorInput['b']] + if 'type' in sensorInput and sensorInput['type'] == 1: + currDict['Location'] = (currDict['Location'][0] - sensorInput['x'] * self['XStep'], \ + currDict['Location'][1] + sensorInput['y'] * self['YStep']) + currDict['Color'] = [sensorInput['r'], sensorInput['g'], sensorInput['b']] + #elif sensorInput['type'] == 2: + # currDict['Shake'] = 1 + # currDict['Force'] = sensorInput['force'] ret.append(currDict) #print ret return (ret, ret) diff --git a/config/MobileTest.xml b/config/MobileTest.xml index a318069..af94c25 100644 --- a/config/MobileTest.xml +++ b/config/MobileTest.xml @@ -207,10 +207,17 @@ behaviors.MoveBehavior move - 5 - 5 + 3 + 3 + + behaviors.MobileShakeBehavior + + mobileshake + 3 + + behaviors.BehaviorChain @@ -222,9 +229,24 @@ move decay - True + True gaussmap + + behaviors.BehaviorChain + + shakeanddecay + + tcp + + + mobileshake + slowdecay + + True + simplemap + + -- cgit v1.2.3 From 5fb3ea060025241105dc8e9a174513c112f9a133 Mon Sep 17 00:00:00 2001 From: rcoh Date: Thu, 27 Jan 2011 16:50:59 -0500 Subject: A metric $#%$-ton of changes. Added doc-strings to EVERYTHING. Phew. Fixed a massive bug that increases performance in by up to a factor of 60. A bunch of new behaviors for the class. --- LightInstallation.py | 44 ++++++---------- behaviors/AddPixelEvent.py | 5 ++ behaviors/AllPixels.py | 11 ++-- behaviors/AllPixelsLeft.py | 1 + behaviors/BehaviorChain.py | 23 +++++++-- behaviors/ColorChangerBehavior.py | 18 ++++++- behaviors/DebugBehavior.py | 3 ++ behaviors/DecayBehavior.py | 1 + behaviors/DimColor.xml | 2 +- behaviors/DoorBehavior.py | 4 -- behaviors/EchoBehavior.py | 2 + behaviors/Expand.py | 4 ++ behaviors/MITDoors.py | 20 ++++++++ behaviors/ModifyParam.py | 9 ++++ behaviors/MoveBehavior.py | 3 ++ behaviors/RandomWalk.py | 3 ++ behaviors/RecursiveDecay.py | 5 ++ behaviors/ResponseMover.py | 6 ++- behaviors/RestrictLocation.py | 10 ++++ behaviors/RiseFall.py | 40 +++++++++++++++ behaviors/RiseFall.xml | 7 +++ behaviors/RunningBehavior.py | 5 ++ behaviors/Square.py | 25 +++++---- behaviors/TimedDie.py | 15 ++++++ behaviors/Timeout.py | 16 ++++++ behaviors/XYMove.py | 7 +++ config/6thFloor.xml | 85 ++++++++++++++++--------------- inputs/PygameInput.py | 35 ++++++++----- inputs/RandomLocs.py | 3 ++ inputs/TCPInput.py | 9 ++-- inputs/UDPInput.py | 4 ++ layouts/LineLayout.py | 2 +- layouts/ZigzagLayout.py | 9 ++++ operationscore/Behavior.py | 18 ++++--- operationscore/Input.py | 14 +++-- operationscore/PixelEvent.py | 7 ++- operationscore/PixelMapper.py | 8 ++- operationscore/Renderer.py | 8 +-- operationscore/SmootCoreObject.py | 9 ++-- operationscore/ThreadedSmootCoreObject.py | 2 + pixelcore/Pixel.py | 32 +++++------- pixelcore/PixelEventManager.py | 2 - pixelcore/PixelStrip.py | 29 +++-------- pixelcore/Screen.py | 13 +++-- pixelevents/DecayEvent.py | 4 ++ pixelevents/SingleFrameEvent.py | 3 ++ pixelmappers/GaussianMapper.py | 10 +++- pixelmappers/SimpleMapper.py | 5 +- renderers/IndoorRenderer.py | 6 +-- renderers/PygameRenderer.py | 7 ++- tests/TestComponentRegistry.py | 3 ++ tests/TestConfigLoaders.py | 3 ++ util/ColorOps.py | 5 ++ util/Config.py | 26 ++++++---- util/Geo.py | 9 +++- util/NetworkOps.py | 1 - util/PacketComposition.py | 9 +++- util/Search.py | 6 +-- util/TimeOps.py | 1 + 59 files changed, 459 insertions(+), 217 deletions(-) delete mode 100644 behaviors/DoorBehavior.py create mode 100644 behaviors/MITDoors.py create mode 100644 behaviors/RiseFall.py create mode 100644 behaviors/RiseFall.xml create mode 100644 behaviors/TimedDie.py create mode 100644 behaviors/Timeout.py delete mode 100644 pixelcore/PixelEventManager.py (limited to 'behaviors') diff --git a/LightInstallation.py b/LightInstallation.py index b582bd2..ad1e38d 100644 --- a/LightInstallation.py +++ b/LightInstallation.py @@ -89,8 +89,8 @@ class LightInstallation(object): self.inputs = inputs for inputClass in inputs: inputClass.start() - self.inputBehaviorRegistry[inputClass['Id']] = [] - #empty list is list of bound behaviors + self.inputBehaviorRegistry[inputClass['Id']] = [] #Bound behaviors will be added to this + #list def initializeRenderers(self, rendererConfig): self.renderers = self.initializeComponent(rendererConfig) @@ -98,13 +98,9 @@ class LightInstallation(object): def registerComponents(self, components): for component in components: cid = compReg.registerComponent(component) - main_log.debug(cid + ' registered') - cid = component['Id'] - if cid == None: #TODO: determine if componenent is critical, and if so, die - main_log.error('Components must be registered with Ids. Component not registered') - else: - compReg.registerComponent(component) - main_log.debug(cid + ' registered') + main_log.info(cid + ' registered') + compReg.registerComponent(component) + main_log.info(cid + ' registered') def initializeComponent(self, config): components = [] @@ -114,7 +110,6 @@ class LightInstallation(object): [module,className] = configItem.find('Class').text.split('.') except: main_log.error('Module must have Class element') - main_log.warn('Module without class element. Module not initialized') continue try: exec('from ' + module+'.'+className + ' import *') @@ -125,16 +120,13 @@ class LightInstallation(object): main_log.error(str(inst)) continue args = configGetter.pullArgsFromItem(configItem) - args['parentScope'] = self #TODO: we shouldn't give away scope - #like this, find another way. + args['parentScope'] = self try: new_component = eval(className+'(args)') new_component.addDieListener(self) - components.append(new_component) #TODO: doesn't error - main_log.debug(className + 'initialized with args ' + str(args)) - #right + components.append(new_component) + main_log.info(className + 'initialized with args ' + str(args)) except Exception as inst: - pdb.set_trace() main_log.error('Failure while initializing ' + className + ' with ' + str(args)) main_log.error(str(inst)) @@ -146,10 +138,9 @@ class LightInstallation(object): def mainLoop(self): lastLoopTime = clock.time() refreshInterval = 30 - while not self.dieNow: + while not self.dieNow: #dieNow is set if one of its constituents sends a die request. loopStart = clock.time() - responses = self.evaluateBehaviors() #inputs are all queued when they - #happen, so we only need to run the behaviors + responses = self.evaluateBehaviors() self.timer.start() [self.screen.respond(response) for response in responses if response != []] @@ -160,19 +151,17 @@ class LightInstallation(object): main_log.debug('Loop complete in ' + str(loopElapsed) + 'ms. Sleeping for ' +\ str(sleepTime)) self.timer.stop() - #print self.timer.elapsed() if sleepTime > 0: time.sleep(sleepTime/1000) - #evaluates all the behaviors (including inter-dependencies) and returns a - #list of responses to go to the screen. def evaluateBehaviors(self): + """Evaluates all the behaviors (including inter-dependencies) and returns a list of responses to + go to the screen""" responses = {} responses['Screen'] = [] #responses to the screen for behavior in self.behaviors: responses[behavior['Id']] = behavior.timeStep() - if behavior['RenderToScreen'] == True: #TODO: this uses extra space, - #we can use less in the future if needbe. + if behavior['RenderToScreen'] == True: responses['Screen'] += responses[behavior['Id']] return responses['Screen'] @@ -181,9 +170,9 @@ class LightInstallation(object): for behavior in self.behaviors: self.addBehavior(behavior) - #Does work needed to add a behavior: currently -- maps behavior inputs into - #the input behavior registry. def addBehavior(self, behavior): + """Does work needed to add a behavior: currently -- maps behavior inputs into the input behavior + registry""" for inputId in behavior.argDict['Inputs']: if inputId in self.inputBehaviorRegistry: #it could be a behavior self.inputBehaviorRegistry[inputId].append(behavior['Id']) @@ -191,12 +180,11 @@ class LightInstallation(object): def processResponse(self,inputDict, responseDict): inputId = inputDict['Id'] boundBehaviorIds = self.inputBehaviorRegistry[inputId] - #TODO: fix this, it crashes because inputs get run before beahviors exist try: [compReg.getComponent(b).addInput(responseDict) for b in boundBehaviorIds] except: pass - #print 'Behaviors not initialized yet. WAIT!' + #Behavior run before loading. Not a big deal. def handleDie(self, caller): self.dieNow = True diff --git a/behaviors/AddPixelEvent.py b/behaviors/AddPixelEvent.py index 7f134e1..821f432 100644 --- a/behaviors/AddPixelEvent.py +++ b/behaviors/AddPixelEvent.py @@ -2,6 +2,9 @@ from operationscore.Behavior import * import util.Strings as Strings from logger import main_log class AddPixelEvent(Behavior): + """AddPixelEvent is a behavior to append an arbitrary PixelEvent to a behavior response. The + classname of the PixelEvent should be specified in the Class field of Args. All arguments normally + passed to the PixelEvent should also be specified in Args.""" def behaviorInit(self): [module, className] = self['Class'].split('.') try: @@ -18,6 +21,8 @@ class AddPixelEvent(Behavior): ret = [] for sensory in sensors: outDict = {} + if not 'Location' in sensory: + pdb.set_trace() outDict[Strings.LOCATION] = sensory[Strings.LOCATION] settingsDict = dict(self.argDict) settingsDict['Color'] = sensory['Color'] diff --git a/behaviors/AllPixels.py b/behaviors/AllPixels.py index e155e55..7f66ad6 100644 --- a/behaviors/AllPixels.py +++ b/behaviors/AllPixels.py @@ -1,6 +1,9 @@ from operationscore.Behavior import * class AllPixels(Behavior): - def processResponse(self, sensorInputs, recursiveInputs): - for sensory in sensorInputs:#TODO: consider replicating the dict - sensory['Location'] = 'True' - return (sensorInputs, recursiveInputs) + """Turns on all Pixels in the installation. Must use SimpleMapper, or other Mapper supporting + conditional pixel locations.""" + + def processResponse(self, sensorInputs, recursiveInputs): + for sensory in sensorInputs:#TODO: consider replicating the dict + sensory['Location'] = 'True' + return (sensorInputs, recursiveInputs) diff --git a/behaviors/AllPixelsLeft.py b/behaviors/AllPixelsLeft.py index b48bfc1..b223156 100644 --- a/behaviors/AllPixelsLeft.py +++ b/behaviors/AllPixelsLeft.py @@ -2,6 +2,7 @@ from operationscore.Behavior import * import util.ComponentRegistry as compReg import pdb class AllPixelsLeft(Behavior): + """Behavior which returns all points left of its input. No Args.""" def processResponse(self, sensorInputs, recursiveInputs): for sensory in sensorInputs: xLoc = sensory['Location'][0] diff --git a/behaviors/BehaviorChain.py b/behaviors/BehaviorChain.py index 39f4402..631ad98 100644 --- a/behaviors/BehaviorChain.py +++ b/behaviors/BehaviorChain.py @@ -3,6 +3,24 @@ import util.ComponentRegistry as compReg from logger import main_log import pdb class BehaviorChain(Behavior): + """BehaviorChain is a class which chains together multiple behavior. BehaviorChain is in itself a + behavior, and behaves and can be used accordingly. BehaviorChain also supports recursive hooks to + be set on its constituent behaviors. ChainedBehaviors should be specified in as follows: + + + behavior1Id + behavior2Id + + + Behaviors may also be appended programmatically via the appendBehavior method. + + Recursive hooks should be specified with Python dict syntax as follows: + + {'behavior1Id':'hookid'} + + Behavior Chain manages all recurrences that its constituents propogate. At this point, it does not + support recurrences in its hooks.""" + def behaviorInit(self): self.feedback = {} #dictionary to allow feedback of recursives self.hooks = self['RecursiveHooks'] @@ -27,11 +45,10 @@ class BehaviorChain(Behavior): hookBehavior.immediateProcessInput(recurrence, \ []) if hookRecurrence != []: - main_log.warn('Hook recurrences are not currently supported. Implement it\ -yourself or bug russell') + main_log.warn('Hook recurrences are not currently supported.') self.feedback[behaviorId] = recurrence return (response, []) - + def appendBehavior(behavior): bid = compReg.registerComponent(behavior) #register behavior (will make #a new id if there isn't one) diff --git a/behaviors/ColorChangerBehavior.py b/behaviors/ColorChangerBehavior.py index 2a8d974..e2f8bd3 100644 --- a/behaviors/ColorChangerBehavior.py +++ b/behaviors/ColorChangerBehavior.py @@ -2,12 +2,26 @@ from operationscore.Behavior import * import util.ColorOps as color import pdb class ColorChangerBehavior(Behavior): + """ColorChangerBehavior is a behavior for adding colors to responses. If given no arguments, it + will generate a random color. If it is given a list of colors [as below] it will pick randomly + from them. + + + (255,0,0) + (30,79,200) + + + ColorList also supports specification of a single color.""" + def processResponse(self, sensorInputs, recursiveInputs): ret = [] for sensory in sensorInputs: - newDict = dict(sensory) #don't run into shallow copy issues + newDict = dict(sensory) if self['ColorList'] != None: - newDict['Color'] = color.chooseRandomColor(self['ColorList']) #TODO: this doesn't work. + if isinstance(self['ColorList'], list): + newDict['Color'] = color.chooseRandomColor(self['ColorList']) #Pick randomly + else: + newDict['Color'] = self['ColorList'] #Unless there is only one else: newDict['Color'] = color.randomColor() ret.append(newDict) diff --git a/behaviors/DebugBehavior.py b/behaviors/DebugBehavior.py index 17383db..8f81954 100644 --- a/behaviors/DebugBehavior.py +++ b/behaviors/DebugBehavior.py @@ -2,6 +2,9 @@ from operationscore.Behavior import * from logger import main_log import pdb class DebugBehavior(Behavior): + """DebugBehavior simply writes all of its inputs to the logs, currently at the ERROR level for + easy visibility. Will be changed to DEBUG or INFO in the future""" + def processResponse(self, sensorInputs, recursiveInputs): if sensorInputs != []: main_log.error('Sensor Inputs: ' + str(sensorInputs)) diff --git a/behaviors/DecayBehavior.py b/behaviors/DecayBehavior.py index c1f6f92..f19ffc8 100644 --- a/behaviors/DecayBehavior.py +++ b/behaviors/DecayBehavior.py @@ -3,6 +3,7 @@ from pixelevents.DecayEvent import * import util.Strings as Strings import pdb class DecayBehavior(Behavior): + """DecayBehavior is obsolete. Use AddPixelEvent instead""" def processResponse(self, sensorInputs, recursiveInputs): ret = [] for sensory in sensorInputs: diff --git a/behaviors/DimColor.xml b/behaviors/DimColor.xml index b01908e..58b0673 100644 --- a/behaviors/DimColor.xml +++ b/behaviors/DimColor.xml @@ -3,6 +3,6 @@ Sensor Color - [chan*.99 for chan in {val}] + [chan*.95 for chan in {val}] diff --git a/behaviors/DoorBehavior.py b/behaviors/DoorBehavior.py deleted file mode 100644 index 5058f69..0000000 --- a/behaviors/DoorBehavior.py +++ /dev/null @@ -1,4 +0,0 @@ -from operationscore.behavior import * -class DoorBehavior.py(Behavior): - def behaviorInit(self): - pyt diff --git a/behaviors/EchoBehavior.py b/behaviors/EchoBehavior.py index 589c42b..6ef4fcb 100644 --- a/behaviors/EchoBehavior.py +++ b/behaviors/EchoBehavior.py @@ -2,6 +2,8 @@ from operationscore.Behavior import * import util.Strings as Strings import pdb class EchoBehavior(Behavior): + """EchoBehavior generates a RED response at all locations specified in sensorInputs. Useful for + debugging""" def processResponse(self, sensorInputs, recursiveInputs): ret = [] for sensory in sensorInputs: diff --git a/behaviors/Expand.py b/behaviors/Expand.py index 3415966..323e71f 100644 --- a/behaviors/Expand.py +++ b/behaviors/Expand.py @@ -1,5 +1,9 @@ from operationscore.Behavior import * class Expand(Behavior): + """Expand is a behavior that generates a response that grows horizontally starting a location + specifed in input. Required Args: + 123 which is the expandrate in units/response""" + def processResponse(self, sensorInputs, recurs): ret = [] for data in sensorInputs: diff --git a/behaviors/MITDoors.py b/behaviors/MITDoors.py new file mode 100644 index 0000000..d602a55 --- /dev/null +++ b/behaviors/MITDoors.py @@ -0,0 +1,20 @@ +from operationscore.Behavior import * +class MITDoors(Behavior): + """MITDoors is a case-specific behavior to map keypresses to specific locations. Written for + Kuan 1/26/11 by RCOH""" + + def behaviorInit(self): + self.keymapping = {'q':[2,19], 'w':[22,36], 'e':[37,49], 'r':[52,69], 't':[76,91], 'y':[94,105], + 'u':[106,117], 'i':[123,154], 'o':[158,161], 'p':[164,167], '[':[172,184]} + def processResponse(self, sensorInputs, recursiveInputs): + ret = [] + for data in sensorInputs: + key = chr(data['Key']) + if key in self.keymapping: + bounds = self.keymapping[key] + data = dict(data) + data['Left'], data['Right'] = bounds + data['Bottom'] = self['Bottom'] + data['Location'] = (sum(bounds) / 2., self['Bottom']) + ret.append(data) + return (ret, []) diff --git a/behaviors/ModifyParam.py b/behaviors/ModifyParam.py index f589e05..4f45be0 100644 --- a/behaviors/ModifyParam.py +++ b/behaviors/ModifyParam.py @@ -2,8 +2,17 @@ from operationscore.Behavior import * import pdb #Class to perform a given operation on some element of an argDict. Designed to be used a recursive hook, but can serve sensor-based functions as well. Specify ParamType (Sensor or Recurse), ParamName, and ParamOp, (a valid python statement with the old value represented as {val}) class ModifyParam(Behavior): + """ModifyParam is a powerful class to perform an action on a specified key in the Argument + Dictionary of a response. Specify: + -- Sensor or Recurse + -- The name of the parameter you wish to modify + -- The modification you wish to do. Use {val} to specify the current value of the + parameter in question. Special hooks for {x} and {y} exist in some versions""" + def processResponse(self, sensorInputs, recursiveInputs): paramType = self['ParamType'] + if paramType == None: + paramType = 'Sensor' paramName = self['ParamName'] paramOp = str(self['ParamOp']) if paramType == 'Sensor': diff --git a/behaviors/MoveBehavior.py b/behaviors/MoveBehavior.py index 590f0e4..d2f60a0 100644 --- a/behaviors/MoveBehavior.py +++ b/behaviors/MoveBehavior.py @@ -4,6 +4,9 @@ import util.Geo as Geo import util.Strings as Strings class MoveBehavior(Behavior): + """Moves current location by the x and y components of sensorInput. Uses recurrences to track + current input. @Author: Euguene""" + def processResponse(self, sensorInputs, recursiveInputs): if recursiveInputs: currRecLocs = recursiveInputs diff --git a/behaviors/RandomWalk.py b/behaviors/RandomWalk.py index fd6c2c8..c9049af 100644 --- a/behaviors/RandomWalk.py +++ b/behaviors/RandomWalk.py @@ -5,6 +5,9 @@ import util.Strings as Strings import random import pdb class RandomWalk(Behavior): + """Behavior to move the curent location by a random distance specified by + -- StepSize in units/response""" + def processResponse(self, sensors, recursives): ret = [] s = self['StepSize'] diff --git a/behaviors/RecursiveDecay.py b/behaviors/RecursiveDecay.py index 218813d..0ae21ea 100644 --- a/behaviors/RecursiveDecay.py +++ b/behaviors/RecursiveDecay.py @@ -1,6 +1,11 @@ from operationscore.Behavior import * import pdb class RecursiveDecay(Behavior): + """RecursiveDecay is an event to allow recursive hooks to stop recursing after a certain number + of iterations specified in + -- Int, number of total responses. + Designed to be used as part of a recursive hook. + """ def processResponse(self, sensorInputs, recursiveInputs): ret = [] for response in sensorInputs: diff --git a/behaviors/ResponseMover.py b/behaviors/ResponseMover.py index e1faccb..59e353a 100644 --- a/behaviors/ResponseMover.py +++ b/behaviors/ResponseMover.py @@ -1,9 +1,11 @@ import pdb from operationscore.Behavior import * import util.ComponentRegistry as compReg -#ResponseMover is a scaffold for behaviors that spawn 'walkers' which act autonomously on input. -#Add a recursive hook to control the movement. class ResponseMover(Behavior): + """ResponseMover is a scaffold for behaviors that spawn 'walkers' which act autonomously on input. + To control the movment, use the behavior as part of a BehaviorChain and add a recursive hook which + modulates the location.""" + def processResponse(self, sensorInputs, recursiveInputs): newResponses = sensorInputs ret = [] diff --git a/behaviors/RestrictLocation.py b/behaviors/RestrictLocation.py index f6c26ff..5e12440 100644 --- a/behaviors/RestrictLocation.py +++ b/behaviors/RestrictLocation.py @@ -6,6 +6,16 @@ import util.Strings as Strings import random import pdb class RestrictLocation(Behavior): + """RestrictLocation is a Behavior which does an action -- A ModifyParam, actually, when a certain + location based condition is met. It takes arguments as follows: + + -- Operation to perform, using ModifyParam syntax. Use {val} to reference the variable + specified by ParamName. + -- the name of the parameter to modify. + -- either a tuple of (xmin,ymin,xmax,ymax) or a python-correct conditional. Use {x} and + {y} to reference x and y. Use < and > to get < and > in XML. EG: + {x}<0 or {x}>800""" + def behaviorInit(self): action = self['Action'] modifyParamArgs = {'ParamType': 'Sensor', diff --git a/behaviors/RiseFall.py b/behaviors/RiseFall.py new file mode 100644 index 0000000..109cd10 --- /dev/null +++ b/behaviors/RiseFall.py @@ -0,0 +1,40 @@ +from operationscore.Behavior import * +import math +import util.TimeOps as timeOps +#Required Args: +#Period (ms), MaxHeight, Width +class RiseFall(Behavior): + """RiseFall is a behavior that creates a rising and falling column of light. Specify: + -- the maximum height that it rises to. + -- the width of the column OR and + -- the period of oscillation in ms + + Designed to be used as part of a recursive hook. + """ + + def processResponse(self, sensorInputs, recurInputs): + ret = [] + for data in sensorInputs: + #first time with behavior: + data = dict(data) + if not 'StartTime' in data: + data['StartTime'] = timeOps.time() + data['Period'] = self['Period'] + data['MaxHeight'] = self['MaxHeight'] #Consider just using += + if not 'Bottom' in data: + data['Bottom'] = data['Location'][1] + if 'Width' in self: #TODO: improve + data['Width'] = self['Width'] + data['Left'] = data['Location'][0]-data['Width']/2. + data['Right'] = data['Location'][0]+data['Width']/2. + currentTime = timeOps.time() + deltaTime = currentTime-data['StartTime'] + data['Height'] = data['MaxHeight']*math.sin(deltaTime/data['Period']*(math.pi*2)) + data['Location'] = "{x}>"+str(data['Left']) + ", " +\ + "{x}<"+str(data['Right'])+", {y}<" + str(data['Bottom']) + ",\ + {y}>"+str(data['Bottom']-data['Height']) + + ret.append(data) + return (ret, []) + + diff --git a/behaviors/RiseFall.xml b/behaviors/RiseFall.xml new file mode 100644 index 0000000..eaadd7b --- /dev/null +++ b/behaviors/RiseFall.xml @@ -0,0 +1,7 @@ + + behaviors.RiseFall + + 2000 + 50 + + diff --git a/behaviors/RunningBehavior.py b/behaviors/RunningBehavior.py index 5eb33f7..ab3dc80 100644 --- a/behaviors/RunningBehavior.py +++ b/behaviors/RunningBehavior.py @@ -3,6 +3,11 @@ import util.ComponentRegistry as compReg import util.Geo as Geo import pdb class RunningBehavior(Behavior): + """RunningBehavior is a straightforward behavior that makes a Location run back and forth across + a screen. Specify: + -- the length of movment in units when the response moves. + """ + def processResponse(self, sensorInputs, recursiveInputs): newResponses = sensorInputs ret = [] diff --git a/behaviors/Square.py b/behaviors/Square.py index aef3622..9d3223a 100644 --- a/behaviors/Square.py +++ b/behaviors/Square.py @@ -1,12 +1,17 @@ from operationscore.Behavior import * class Square(Behavior): - def processResponse(self, sensorInputs, recursiveInputs): - for sensory in sensorInputs:#TODO: consider replicating the dict - xLoc = sensory['Location'][0] - yLoc = sensory['Location'][1] - width = self['Width'] - #sensory['Location'] = 'True' - sensory['Location'] =\ - '{x}<'+str(xLoc+width)+',{x}>'+str(xLoc-width)+\ - ',{y}<'+str(yLoc+width)+',{y}>'+str(yLoc-width) - return (sensorInputs, recursiveInputs) + """Square is a simple behavior that makes a square with side lengths Width*2 around locations in + the sensor input. Specify: + -- the sidelength/2 + """ + + def processResponse(self, sensorInputs, recursiveInputs): + for sensory in sensorInputs:#TODO: consider replicating the dict + xLoc = sensory['Location'][0] + yLoc = sensory['Location'][1] + width = self['Width'] + #sensory['Location'] = 'True' + sensory['Location'] =\ + '{x}<'+str(xLoc+width)+',{x}>'+str(xLoc-width)+\ + ',{y}<'+str(yLoc+width)+',{y}>'+str(yLoc-width) + return (sensorInputs, recursiveInputs) diff --git a/behaviors/TimedDie.py b/behaviors/TimedDie.py new file mode 100644 index 0000000..e75e9dd --- /dev/null +++ b/behaviors/TimedDie.py @@ -0,0 +1,15 @@ +from operationscore.Behavior import * +class Timeout(Behavior): + """Timeout is a behavior designed to be used in recursive hooks to stop responses after a certain + amount of time. It is the Time-version of RecursiveDecay. Specify: + -- the time in ms that the response will run. + """ + + def processResponse(self, sensorInputs, recur): + ret = [] + for data in sensorInputs: + if not 'StartTime' in data: + data['StartTime'] = timeops.time() + if timeops.time()-data['StartTime'] < self['Timeout']: + ret.append(data) + return (ret, []) diff --git a/behaviors/Timeout.py b/behaviors/Timeout.py new file mode 100644 index 0000000..14d4873 --- /dev/null +++ b/behaviors/Timeout.py @@ -0,0 +1,16 @@ +from operationscore.Behavior import * +import util.TimeOps as timeops +class Timeout(Behavior): + """Timeout is a behavior designed to be used in recursive hooks to stop responses after a certain + amount of time. It is the Time-version of RecursiveDecay. Specify: + -- the time in ms that the response will run. + """ + + def processResponse(self,sensorInputs, recur): + ret = [] + for data in sensorInputs: + if not 'StartTime' in data: + data['StartTime'] = timeops.time() + if timeops.time()-data['StartTime'] < self['Timeout']: + ret.append(data) + return (ret,[]) diff --git a/behaviors/XYMove.py b/behaviors/XYMove.py index 8acbba8..11cee96 100644 --- a/behaviors/XYMove.py +++ b/behaviors/XYMove.py @@ -1,6 +1,13 @@ from operationscore.Behavior import * import util.Geo as Geo class XYMove(Behavior): + """XYMove is a behavior designed to be used as a recursive hook to ResponseMover to move pixels by + XStep and YStep. As XStep and YStep are maintained in the responses itself, they can be + modulated to facilitate, acceleration, modulation, bouncing, etc. Specify: + -- the starting XStep + -- the starting YStep + """ + def processResponse(self, sensor, recurs): ret = [] for loc in sensor: diff --git a/config/6thFloor.xml b/config/6thFloor.xml index c98486a..b58ff57 100644 --- a/config/6thFloor.xml +++ b/config/6thFloor.xml @@ -39,8 +39,17 @@ inputs.PygameInput - pygame + pygameclick 10 + True + + + + inputs.PygameInput + + pygamekey + 10 + True @@ -62,14 +71,11 @@ inputs/MouseFollower.xml - - inputs.RandomLocs - - randomLoc - - + + behaviors/RiseFall.xml + behaviors.EchoBehavior @@ -88,9 +94,6 @@ 1 - - behaviors/RedShift.xml - behaviors/RandomColor.xml @@ -159,21 +162,32 @@ + + behaviors.BehaviorChain + + risefalldie + + risefall + 2sec + dim + + + behaviors.BehaviorChain inpexpanddim - pygame + pygamekey + mitdoors colorchange mover decay - {'mover':'movebounce'} + {'mover':'risefalldie'} True - gaussmap @@ -182,11 +196,25 @@ debug 0 - pygame + pygamekey udp + + behaviors.Timeout + + 2sec + 2000 + + + + behaviors.MITDoors + + mitdoors + 50 + + behaviors.AllPixelsLeft @@ -211,7 +239,7 @@ runcolordecay - pygame + pygameclick colorchange @@ -223,39 +251,12 @@ gaussmap - - behaviors.BehaviorChain - - randomwalk - - pygame - - - colorchange - mover - decay - - {'mover':'redwalk'} - False - gaussmap - - behaviors.ResponseMover mover - - behaviors.BehaviorChain - - redwalk - - randmovement - redshift - - - behaviors.RandomWalk diff --git a/inputs/PygameInput.py b/inputs/PygameInput.py index 27b82b0..399a77e 100644 --- a/inputs/PygameInput.py +++ b/inputs/PygameInput.py @@ -6,18 +6,27 @@ from pygame.locals import * #This class processes input from an already running pygame instance and passes #it to the parent. This class requires an already running pygame instance. class PygameInput(Input): + """PygameInput is an input tied to the PygameDisplay. Specify: + True to receive an input every frame specifying the current mouse + position. + True to grab keystrokes + True to grab clicks. + + NB: If follow mouse is enabled, PygameInput will not return mouse and keypresses. You can, however, + instantiate other PygameInputs in the XML that will capture mouse and keypresses.""" def sensingLoop(self): - #try: - if self['FollowMouse']: - self.respond({Strings.LOCATION: pygame.mouse.get_pos()}) - return - for event in pygame.event.get(): - if event.type is KEYDOWN: - if event.key == 27: - self.die() - self.respond({Strings.LOCATION: (5,5),'Key': event.key}) - if event.type is MOUSEBUTTONDOWN: + if self['FollowMouse']: + self.respond({Strings.LOCATION: pygame.mouse.get_pos()}) + return + for event in pygame.event.get(): + if event.type is KEYDOWN: + if event.key == 27: + self.die() + if self['Keyboard']: + self.respond({'Key': event.key}) + return + else: + pygame.event.post(event) + if event.type is MOUSEBUTTONDOWN: + if self['Clicks']: self.respond({Strings.LOCATION: pygame.mouse.get_pos()}) - #except: - #raise Exception('Pygame not initialized. Pygame must be \ - #initialized.') diff --git a/inputs/RandomLocs.py b/inputs/RandomLocs.py index d1ce1c7..2719981 100644 --- a/inputs/RandomLocs.py +++ b/inputs/RandomLocs.py @@ -4,6 +4,9 @@ import util.Geo as Geo import util.Strings as Strings from operationscore.Input import * class RandomLocs(Input): + """RandomLocs is an Input that generates RandomLocations at a preset time interval. Just a + prototype, some assembly required.""" + def inputInit(self): self['LastEvent'] = clock.time() def sensingLoop(self): #TODO: move to params diff --git a/inputs/TCPInput.py b/inputs/TCPInput.py index 2bc69ef..17ea7e6 100644 --- a/inputs/TCPInput.py +++ b/inputs/TCPInput.py @@ -6,6 +6,10 @@ import logging as main_log import string class TCPInput(Input): + """TCPInput is a input to receive input on a TCP port. In its current incarnation, it parses + json data into python dicts. Warning: contains a bug where init will hang until it receives a + connection. Specify: + -- Port number to listen on.""" def inputInit(self): self.HOST = '' # Symbolic name meaning all available interfaces self.PORT = self.argDict['Port'] # Arbitrary non-privileged port @@ -34,12 +38,7 @@ class TCPInput(Input): for datagroup in data.split('\n'): if datagroup != None and datagroup != '': dataDict = json.loads(datagroup) - #print dataDict self.respond(dataDict) - #socketDict = {'data':dataDict, 'address':self.address} - #socketDict = {Strings.LOCATION: (dataDict['x'], dataDict['y'])} # like PygameInput - #print 'input' - #self.respond(socketDict) except Exception as exp: print str(exp) else: diff --git a/inputs/UDPInput.py b/inputs/UDPInput.py index e95bd33..83e2f77 100644 --- a/inputs/UDPInput.py +++ b/inputs/UDPInput.py @@ -1,6 +1,10 @@ from operationscore.Input import * import socket class UDPInput(Input): + """UDPInput is a barebones UDP Input class. It takes any data it receives and adds it to the + 'data' element of the response dict. It also notes the 'address'. Specify: + -- the Port to listen on.""" + def inputInit(self): HOST = '' # Symbolic name meaning all available interfaces PORT = self.argDict['Port'] # Arbitrary non-privileged port diff --git a/layouts/LineLayout.py b/layouts/LineLayout.py index 34f5e36..1d40105 100644 --- a/layouts/LineLayout.py +++ b/layouts/LineLayout.py @@ -1,5 +1,5 @@ from operationscore.PixelAssembler import * -#Simple layout class that simply makes a line of LEDs class LineLayout(PixelAssembler): + """LineLayout is a layout class that makes a line of LEDs""" def layoutFunc(self, lastLocation): return (lastLocation[0]+self.argDict['spacing'], lastLocation[1]) diff --git a/layouts/ZigzagLayout.py b/layouts/ZigzagLayout.py index 221571c..3fc2ea1 100644 --- a/layouts/ZigzagLayout.py +++ b/layouts/ZigzagLayout.py @@ -10,6 +10,15 @@ import pdb # | # X-X-X-X etc. class ZigzagLayout(PixelAssembler): + """ZigZagLayout is a slightly more complex layout class that makes a zig-Zag Led Pattern + Inheriting classes must specify zigLength, the length in lights of a of a zig + and zig Axis, the direction of the long X axis (X or Y). + EG: zig length = 4, zig Axis = X would give: + X-X-X-X + | + X-X-X-X + | + X-X-X-X etc. def initLayout(self): if not 'zigLength' in self.argDict: raise Exception('zigLength must be defined in argDict') diff --git a/operationscore/Behavior.py b/operationscore/Behavior.py index b3f7342..6424842 100644 --- a/operationscore/Behavior.py +++ b/operationscore/Behavior.py @@ -1,11 +1,3 @@ -#Abstract class for a behavior. On every time step, the behavior is passed the -#inputs from all sensors it is bound to as well as any recursive inputs that it -#spawned during the last time step. Inheriting classes MUST define -#processResponse. processResponse should return a list of dictionaries which -#define the properties of the light response, (outputs, recursions). They must give a location and -#color. They may define a PixelEvent to more closely control the outgoing -#data, however, this is normally handled by routing the event to a behavior -#specifically designed to do this (like DecayBehavior). import pdb from operationscore.SmootCoreObject import * @@ -13,6 +5,16 @@ from logger import main_log #timeStep is called on every iteration of the LightInstallation #addInput is called on each individual input received, and the inputs queue class Behavior(SmootCoreObject): + """Abstract class for a behavior. On every time step, the behavior is passed the + inputs from all sensors it is bound to as well as any recursive inputs that it + spawned during the last time step. Inheriting classes MUST define + processResponse. processResponse should return a list of dictionaries which + define the properties of the light response, (outputs, recursions). They must give a location and + color. They may define a PixelEvent to more closely control the outgoing + data, however, this is normally handled by routing the event to a behavior + specifically designed to do this (like AddPixelEvent). + timeStep is called on every iteration of the LightInstallation + addInput is called on each individual input received, and the inputs queue""" def init(self): self.validateArgs('Behavior.params') if type(self['Inputs']) != type([]): diff --git a/operationscore/Input.py b/operationscore/Input.py index 69375d3..d3d5644 100644 --- a/operationscore/Input.py +++ b/operationscore/Input.py @@ -1,16 +1,14 @@ import threading,time from logger import main_log, exception_log from operationscore.ThreadedSmootCoreObject import ThreadedSmootCoreObject -#Abstract class for inputs. Inheriting classes should call "respond" to raise -#their event. Inheriting classes MUST define sensingLoop. Called at the -#interval specified in RefreshInterval while the input is active. For example, if you are writing -#webserver, this is where the loop should go. -#Inheriting classes MAY define inputInit. This is called before the loop -#begins. import pdb class Input(ThreadedSmootCoreObject): - #Event scope is a function pointer the function that will get called when - #an Parent is raised. + """Abstract class for inputs. Inheriting classes should call "respond" to raise + their event. Inheriting classes MUST define sensingLoop. Called at the + interval specified in RefreshInterval while the input is active. For example, if you are writing + webserver, this is where the loop should go. + Inheriting classes MAY define inputInit. This is called before the loop + begins.""" def init(self): self.eventQueue = [] if not 'RefreshInterval' in self.argDict: diff --git a/operationscore/PixelEvent.py b/operationscore/PixelEvent.py index c41df17..5ed6163 100644 --- a/operationscore/PixelEvent.py +++ b/operationscore/PixelEvent.py @@ -1,6 +1,6 @@ -#Class defining a light response. Inheriting classes should define lightState, -#which should return a color, or None if the response is complete. Consider -#requiring a generate event. +"""PixelEvent is a class defining a light response. Inheriting classes should define state, +which should return a color, or None if the response is complete. Consider +requiring a generate event.""" from operationscore.SmootCoreObject import * from pixelevents.StepEvent import * import util.ColorOps as color @@ -26,6 +26,5 @@ class PixelEvent(SmootCoreObject): color = responseDict['Color'] else: raise Exception('Need Color. Probably') - pdb.set_trace() responseDict['PixelEvent'] = StepEvent.generate(300, color) diff --git a/operationscore/PixelMapper.py b/operationscore/PixelMapper.py index 7e2b0af..3937973 100644 --- a/operationscore/PixelMapper.py +++ b/operationscore/PixelMapper.py @@ -2,6 +2,9 @@ from operationscore.SmootCoreObject import * from logger import main_log import pdb class PixelMapper(SmootCoreObject): + """PixelMapper is the parent class for PixelMappers. Inheriting classes should define + mappingFunction which takes an eventLocation and a screen and returns a list of (weight, pixels). PixelMapper + handles caching automatically.""" def init(self): self.mem = {} #Dictionary of all seen events self.totalCalls = 0 @@ -19,6 +22,7 @@ class PixelMapper(SmootCoreObject): return self.mem[eventLocation] #Takes a Screen and returns a list of tuples #(pixel, weight), with the sum of weights = 1 - #TODO: consider abstracting away from pixels def mappingFunction(self,eventLocation, screen): - pass + """Takes a Screen and event location and returns a list of tuples (pixel,weight) with + sum(weights)=1""" + raise Exception('Mapping function not defined!') diff --git a/operationscore/Renderer.py b/operationscore/Renderer.py index b422304..0861c44 100644 --- a/operationscore/Renderer.py +++ b/operationscore/Renderer.py @@ -1,10 +1,10 @@ -#Renderer abstract class. Doesn't do much now, but might do more later. -#Inheriting classes MUST define render which takes a light system and renders it. -#Inheriting classes may define initRenderer which is called after the dictionary -#is pulled from config. #TODO: multithreaded-rendering from operationscore.SmootCoreObject import * class Renderer(SmootCoreObject): + """Renderer abstract class. Doesn't do much now, but might do more later. + Inheriting classes MUST define render which takes a light system and renders it. + Inheriting classes may define initRenderer which is called after the dictionary + is pulled from config.""" def init(self): self.initRenderer() def render(lightSystem): diff --git a/operationscore/SmootCoreObject.py b/operationscore/SmootCoreObject.py index 8b36f4d..0d32773 100644 --- a/operationscore/SmootCoreObject.py +++ b/operationscore/SmootCoreObject.py @@ -4,6 +4,10 @@ import thread import util.Config as configGetter class SmootCoreObject(object): + """SmootCoreObject is essentially a super-object class which grants us some niceties. It allows + us to use objects as if they are dictionaries -- we use this to store their arguments + convienently -- note that querying for a parameter that does not exist will return None. It + also offers some basic ThreadSafety.""" def __init__(self, argDict, skipValidation = False): self.dieListeners = [] self.argDict = argDict @@ -13,8 +17,6 @@ class SmootCoreObject(object): for key in argDict: setattr(self, key, argDict[key]) self.init() #call init of inheriting class - # self.__setitem__ = self.argDict.__setitem__ - # self.__getitem__ = self.argDict.__getitem__ def init(self): pass @@ -37,7 +39,8 @@ class SmootCoreObject(object): return self.argDict[item] else: return None - + def __contains__(self, item): + return item in self.argDict def __getiter__(self): return self.argDict.__getiter__() diff --git a/operationscore/ThreadedSmootCoreObject.py b/operationscore/ThreadedSmootCoreObject.py index 967ee35..4b5d513 100644 --- a/operationscore/ThreadedSmootCoreObject.py +++ b/operationscore/ThreadedSmootCoreObject.py @@ -4,6 +4,8 @@ import thread import util.Config as configGetter from operationscore.SmootCoreObject import SmootCoreObject class ThreadedSmootCoreObject(SmootCoreObject, threading.Thread): + """ThreadedSmootCoreObject is a version of SmootCoreObject for objects that want to run on their + own thread""" def __init__(self, argDict, skipValidation = False): SmootCoreObject.__init__(self, argDict, skipValidation) threading.Thread.__init__(self) diff --git a/pixelcore/Pixel.py b/pixelcore/Pixel.py index 2f21fd8..6ff2e67 100644 --- a/pixelcore/Pixel.py +++ b/pixelcore/Pixel.py @@ -2,12 +2,13 @@ import util.ColorOps as color import pdb from pixelevents.StepEvent import * import util.TimeOps as timeops -#Pixel keeps a queue of events (PixelEvent objects) (actually a dictionary -#keyed by event time). Every time is state is -#requested, it processes all the members of its queue. If a member returns none, -#it is removed from the queue. Otherwise, its value added to the Pixels color -#weighted by z-index. class Pixel: + """Pixel keeps a queue of events (PixelEvent objects) (actually a dictionary + keyed by event time). Every time is state is + requested, it processes all the members of its queue. If a member returns none, + it is removed from the queue. Otherwise, its value added to the Pixels color + weighted by z-index.""" + radius = 2 timeOff = -1 @@ -24,26 +25,22 @@ class Pixel: #processInput instead. Also, you shouldn't use this anyway. You should be #using the input method on the screen! def turnOnFor(self, time): - event = StepEvent.generate(time, (255,255,255)) #TODO: Move color to + event = StepEvent.generate(time, (255,255,255)) self.processInput(event, 0) - #arg #Add a pixelEvent to the list of active events def processInput(self,pixelEvent,zindex, scale=1,currentTime=None): #consider migrating arg to dict - #TODO: fix for multiple pixel events if currentTime == None: currentTime = timeops.time() - #if not currentTime in self.events: - # self.events[currentTime] = [] - #self.events[currentTime].append((zindex,scale, pixelEvent)) - self.events.append((currentTime, zindex, scale, pixelEvent)) #TODO: this is kindof - #gross + self.events.append((currentTime, zindex, scale, pixelEvent)) #TODO: clean this up, maybe? def clearAllEvents(self): self.events = [] - #Combines all PixelEvents currently active and computes the current color of - #the pixel. - def state(self, currentTime=timeops.time()): #TODO: this only evaluates at import time, I think + def state(self, currentTime=None): + """Combines all PixelEvents currently active and computes the current color of + the pixel.""" + if currentTime == None: + currentTime = timeops.time() if currentTime-self.lastRenderTime < 5: return self.lastRender if self.events == []: @@ -54,8 +51,7 @@ class Pixel: colors = [] for eventObj in self.events: #TODO: right color weighting code if len(self.events) > 50: - pdb.set_trace() - #TODO: this sucks. fix it + main_log.error('High pixel event count! Investigate!') eventTime, zindex, scale, pixelEvent = eventObj eventResult = pixelEvent.state(currentTime-eventTime) if eventResult != None: diff --git a/pixelcore/PixelEventManager.py b/pixelcore/PixelEventManager.py deleted file mode 100644 index 779a0ce..0000000 --- a/pixelcore/PixelEventManager.py +++ /dev/null @@ -1,2 +0,0 @@ -class PixelEventManager(object): - def init(self) diff --git a/pixelcore/PixelStrip.py b/pixelcore/PixelStrip.py index 662b8fe..595ce72 100644 --- a/pixelcore/PixelStrip.py +++ b/pixelcore/PixelStrip.py @@ -4,36 +4,21 @@ import util.Geo as Geo from pixelevents.StepEvent import * import math import pdb -#Python class representing a single Pixel strip (usually 50 Pixels) class PixelStrip: + """Python class representing a single Pixel strip (usually 50 Pixels)""" + def __init__(self, layoutEngine): self.initStrip(layoutEngine) self.argDict = layoutEngine.getStripArgs() + def initStrip(self, layoutEngine): pixelLocations = layoutEngine.getPixelLocations() self.pixels = [Pixel(l) for l in pixelLocations] + def __iter__(self): return self.pixels.__iter__() - def render(self, surface): - [l.render(surface) for l in self.pixels] - #step - def allOn(self, time): - [l.turnOnFor(time) for l in self.pixels] #TODO: add test-on method to - #pixels - def respond(self, responseInfo): - location = responseInfo[Strings.LOCATION] - if not 'PixelEvent' in responseInfo: - if 'Color' in responseInfo: - color = responseInfo['Color'] - else: - raise Exception('Need Color. Probably') - responseInfo['PixelEvent'] = StepEvent.generate(300, color) - (dist, pixel) = self.getPixelNearest(location) - pixel.processInput(responseInfo['PixelEvent'], 0) #TODO: z-index + + + - def getPixelNearest(self, location): - dists = [(Geo.dist(location, pixel.location), pixel) for pixel in self.pixels] - dists.sort() - return dists[0] - #just for now. diff --git a/pixelcore/Screen.py b/pixelcore/Screen.py index b595847..9a81df7 100644 --- a/pixelcore/Screen.py +++ b/pixelcore/Screen.py @@ -10,9 +10,10 @@ import itertools import sys import pdb from logger import main_log -#Class representing a collection of Pixels grouped into PixelStrips. Needs a -#PixelMapper, currently set via setMapper by may be migrated into the argDict. class Screen: + """Class representing a collection of Pixels grouped into PixelStrips. Needs a + PixelMapper, currently set via setMapper by may be migrated into the argDict.""" + def __init__(self): self.responseQueue = [] self.pixelStrips = [] @@ -20,14 +21,15 @@ class Screen: self.xPixelLocs = [] sizeValid = False self.pixelsSorted = False + def addStrip(self, lS): self.pixelStrips.append(lS) self.sizeValid = False #keep track of whether or not our screen size has self.pixelsSorted = False #been invalidated by adding more pixels - #Returns (pixelIndex, pixel). Does a binary search. def pixelsInRange(self, minX, maxX): + """Returns (pixelIndex, pixel). Does a binary search.""" if not self.pixelsSorted: self.computeXSortedPixels() minIndex = Search.find_ge(self.xPixelLocs, minX) @@ -41,10 +43,7 @@ class Screen: self.xSortedPixels.sort() self.xPixelLocs = [p[0] for p in self.xSortedPixels] self.pixelsSorted = True - #For debug only - def allOn(self): - [lS.allOn(-1) for lS in self.pixelStrips] - + def __iter__(self): #the iterator of all our pixel strips chained togther return itertools.chain(*[strip.__iter__() for strip in \ self.pixelStrips]) #the * operator breaks the list into args diff --git a/pixelevents/DecayEvent.py b/pixelevents/DecayEvent.py index f8d5ef0..8ff423c 100644 --- a/pixelevents/DecayEvent.py +++ b/pixelevents/DecayEvent.py @@ -3,6 +3,10 @@ import math from util.ColorOps import * import util.Geo as Geo class DecayEvent(PixelEvent): + """DecayEvent is a pixel event that can decay either Exponentially or Proportionally. Specify: + -- Exponential or Proportional + -- Controls the speed of decay.""" + def initEvent(self): self.coefficient = float(abs(self.Coefficient)) if self.DecayType == 'Exponential': diff --git a/pixelevents/SingleFrameEvent.py b/pixelevents/SingleFrameEvent.py index 767f403..252e31b 100644 --- a/pixelevents/SingleFrameEvent.py +++ b/pixelevents/SingleFrameEvent.py @@ -1,5 +1,8 @@ from operationscore.PixelEvent import * class SingleFrameEvent(PixelEvent): + """SingleFrameEvent is a PixelEvent that will only render for the first frame on which it is + queried""" + def initEvent(self): self.timeState = -1 def state(self, timeDelay): diff --git a/pixelmappers/GaussianMapper.py b/pixelmappers/GaussianMapper.py index c82f243..883a95d 100644 --- a/pixelmappers/GaussianMapper.py +++ b/pixelmappers/GaussianMapper.py @@ -1,8 +1,16 @@ from operationscore.PixelMapper import * import util.Geo as Geo class GaussianMapper(PixelMapper): + """GaussianMapper is a PixelMapper which weights pixels around an event proportional to a + gaussian surface. Specify: + -- The height of the gaussian surface + -- The width of the gaussian surface + -- the minimum weight event that can be returned + -- the maximum radius considered + """ + def mappingFunction(self, eventLocation, screen): - returnPixels = [] #TODO: consider preallocation and trimming + returnPixels = [] [x,y] = eventLocation potentialPixels = screen.pixelsInRange(x-self.CutoffDist, \ x+self.CutoffDist) diff --git a/pixelmappers/SimpleMapper.py b/pixelmappers/SimpleMapper.py index 19d44c4..1568de3 100644 --- a/pixelmappers/SimpleMapper.py +++ b/pixelmappers/SimpleMapper.py @@ -2,6 +2,10 @@ from operationscore.PixelMapper import * import util.Geo as Geo import sys class SimpleMapper(PixelMapper): + """SimpleMapper is a PixelMapper which maps events to the nearest Pixel. It also supports + strings of the form: + {x}>5, {y}<10, {x}*{y}<{x}, etc. (Conditons, separated by commas. and and or may also be + used).""" def mappingFunction(self, eventLocation, screen): if type(eventLocation) == type(tuple()): bestDist = sys.maxint @@ -19,7 +23,6 @@ class SimpleMapper(PixelMapper): return [] else: #{x}>5,{y}1) for i in range(4)]) == 4 + def addLocations(l1,l2): return tuple([l1[i]+l2[i] for i in range(len(l1))]) + def gaussian(x,height,center,width): a=height b=center c=width return a*math.exp(-((x-b)**2)/(2*c**2)) + def dist(l1, l2): - return math.sqrt((l1[0]-l2[0])**2+(l1[1]-l2[1])**2) - #return math.sqrt(sum([(l1[i]-l2[i])**2 for i in range(len(l1))])) + return math.sqrt((l1[0]-l2[0])**2+(l1[1]-l2[1])**2) #For speed + def randomLoc(boundingBox): #TODO: make less shitty loc = [] loc.append(random.randint(0, boundingBox[0])) loc.append(random.randint(0, boundingBox[1])) return tuple(loc) + def approxexp(x): + """Approximates exp with a 3 term Taylor Series.""" return 1+x+x**2/2+x**3/6 diff --git a/util/NetworkOps.py b/util/NetworkOps.py index 6c50c6d..8894b78 100644 --- a/util/NetworkOps.py +++ b/util/NetworkOps.py @@ -8,4 +8,3 @@ def getConnectedSocket(ip,port): except Exception as inst: main_log.error('Network down. All network based renderers and sensors will not function.', inst) - print (ip, port) diff --git a/util/PacketComposition.py b/util/PacketComposition.py index c4fcdc3..7b4fe95 100644 --- a/util/PacketComposition.py +++ b/util/PacketComposition.py @@ -6,6 +6,7 @@ UNI = 0 import pdb import util.TimeOps as timeops argDict = {'flags': 0, 'startcode': 0, 'pad':0} + def composePixelStripData(pixelStrip,currentTime=timeops.time()): packet = bytearray() for light in pixelStrip: @@ -19,6 +20,7 @@ def composePixelStripData(pixelStrip,currentTime=timeops.time()): #color = pixelStrip.pixels[i].state() #packet[i:i+2] = color # return bytearray(packet) + cache = {} def memoize(f): def helper(x): @@ -26,6 +28,7 @@ def memoize(f): cache[x] = f(x) return cache[x] return helper + @memoize def cachePacketHeader(port): packet = bytearray() @@ -35,11 +38,13 @@ def cachePacketHeader(port): packet.extend(portOutPacket(subDict)) packet.append(0x0) return packet + def composePixelStripPacket(pixelStrip,port, currentTime): packet = bytearray(cachePacketHeader(port)) data = composePixelStripData(pixelStrip, currentTime) packet.extend(data) return packet + def packheader(): header = bytearray() header.extend(struct.pack('L', MAGIC)) @@ -47,18 +52,20 @@ def packheader(): header.extend(struct.pack('H', PORTOUT)) header.extend(struct.pack('L', 0)) return header + def portOut(): header = packheader() header.extend(struct.pack('L', UNI)) return header + def portOutPayload(argDict): payload = bytearray() payload.extend(struct.pack('B', argDict['port'])) payload.extend(struct.pack('H', argDict['flags'])) - #payload.append(0x00) #somepadding? lolwtf. payload.extend(struct.pack('H', argDict['len'])) payload.extend(struct.pack('H', argDict['startcode'])) return payload + def portOutPacket(payloadArgs): packet = bytearray() packet.extend(portOut()) diff --git a/util/Search.py b/util/Search.py index f7e4b81..1499e23 100644 --- a/util/Search.py +++ b/util/Search.py @@ -1,13 +1,13 @@ from bisect import * def find_le(a, x): - 'Find rightmost value less than or equal to x' + """Find rightmost value less than or equal to x""" return bisect_right(a, x)-1 def find_ge(a, x): - 'Find leftmost value greater than x' + """Find leftmost value greater than x""" return bisect_left(a, x) -#returns parents of nodes that meed a given condition def parental_tree_search(root, childrenstr, conditionstr): + """Returns parents of nodes that meed a given condition""" ret = [] queue = [root] while queue: diff --git a/util/TimeOps.py b/util/TimeOps.py index dcd5038..841efab 100644 --- a/util/TimeOps.py +++ b/util/TimeOps.py @@ -1,6 +1,7 @@ import time as clock def time(): return clock.time()*1000 #all times in MS + class Stopwatch: def __init__(self): self.running = False -- cgit v1.2.3 From f103e47da5d563d1b8448bc021676ed7db0f529d Mon Sep 17 00:00:00 2001 From: rcoh Date: Thu, 27 Jan 2011 17:25:15 -0500 Subject: Doc change. Merge experimental. --- behaviors/ModifyParam.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'behaviors') diff --git a/behaviors/ModifyParam.py b/behaviors/ModifyParam.py index 2c8f12d..0ef3a60 100644 --- a/behaviors/ModifyParam.py +++ b/behaviors/ModifyParam.py @@ -8,7 +8,8 @@ class ModifyParam(Behavior): -- Sensor or Recurse -- The name of the parameter you wish to modify -- The modification you wish to do. Use {val} to specify the current value of the - parameter in question. Special hooks for {x} and {y} exist in some versions""" + parameter in question. Special hooks for {x} and {y} also exist to access the x and y + locations.""" def processResponse(self, sensorInputs, recursiveInputs): paramType = self['ParamType'] -- cgit v1.2.3 From 3319a58ecc391f9aac092ade45f9f50dc2af5aa6 Mon Sep 17 00:00:00 2001 From: rcoh Date: Fri, 28 Jan 2011 09:50:38 -0500 Subject: Finishing up for the demo --- behaviors/Accelerate.xml | 2 +- behaviors/DimColor.xml | 2 +- behaviors/Expand.py | 3 ++- behaviors/MITDoors.py | 7 +++++++ behaviors/ResponseMover.py | 8 +------- behaviors/XYMove.py | 1 - config/6thFloor.xml | 2 +- inputs/PygameInput.py | 2 +- pixelcore/Screen.py | 19 +++++++------------ 9 files changed, 21 insertions(+), 25 deletions(-) (limited to 'behaviors') diff --git a/behaviors/Accelerate.xml b/behaviors/Accelerate.xml index f9de077..c78195b 100644 --- a/behaviors/Accelerate.xml +++ b/behaviors/Accelerate.xml @@ -3,6 +3,6 @@ Sensor StepSize - {val}*1.1 + {val}*1.01 diff --git a/behaviors/DimColor.xml b/behaviors/DimColor.xml index 58b0673..ef98fee 100644 --- a/behaviors/DimColor.xml +++ b/behaviors/DimColor.xml @@ -3,6 +3,6 @@ Sensor Color - [chan*.95 for chan in {val}] + [chan*.98 for chan in {val}] diff --git a/behaviors/Expand.py b/behaviors/Expand.py index 323e71f..f017c16 100644 --- a/behaviors/Expand.py +++ b/behaviors/Expand.py @@ -15,7 +15,8 @@ class Expand(Behavior): data = dict(data) data['Left'] -= data['ExpandRate'] data['Right'] += data['ExpandRate'] - data['Location'] = "{x}>" + str(data['Left']) + ", {x}<" + str(data['Right']) + data['Location'] = "{x}>" + str(data['Left']) + ", {x}<" +\ + str(data['Right'])+", {y}<50" ret.append(data) return (ret, []) diff --git a/behaviors/MITDoors.py b/behaviors/MITDoors.py index d602a55..03bef6d 100644 --- a/behaviors/MITDoors.py +++ b/behaviors/MITDoors.py @@ -1,4 +1,6 @@ from operationscore.Behavior import * +import math +import util.ComponentRegistry as compReg class MITDoors(Behavior): """MITDoors is a case-specific behavior to map keypresses to specific locations. Written for Kuan 1/26/11 by RCOH""" @@ -6,6 +8,11 @@ class MITDoors(Behavior): def behaviorInit(self): self.keymapping = {'q':[2,19], 'w':[22,36], 'e':[37,49], 'r':[52,69], 't':[76,91], 'y':[94,105], 'u':[106,117], 'i':[123,154], 'o':[158,161], 'p':[164,167], '[':[172,184]} + screenWidth = compReg.getComponent('Screen').getSize()[2] #(minx, miny,maxx, maxy) + maxKey = max([max(self.keymapping[v]) for v in self.keymapping]) + mult = screenWidth / float(maxKey) + for k in self.keymapping: + self.keymapping[k] = [int(val*mult) for val in self.keymapping[k]] def processResponse(self, sensorInputs, recursiveInputs): ret = [] for data in sensorInputs: diff --git a/behaviors/ResponseMover.py b/behaviors/ResponseMover.py index 59e353a..3d559df 100644 --- a/behaviors/ResponseMover.py +++ b/behaviors/ResponseMover.py @@ -7,11 +7,5 @@ class ResponseMover(Behavior): modulates the location.""" def processResponse(self, sensorInputs, recursiveInputs): - newResponses = sensorInputs - ret = [] - for recurInput in recursiveInputs: - outDict = dict(recurInput) - ret.append(outDict) - ret += newResponses - return (ret, ret) + return (recursiveInputs, recursiveInputs+sensorInputs) diff --git a/behaviors/XYMove.py b/behaviors/XYMove.py index 0ba3baf..11cee96 100644 --- a/behaviors/XYMove.py +++ b/behaviors/XYMove.py @@ -13,7 +13,6 @@ class XYMove(Behavior): for loc in sensor: oploc = dict(loc) self.insertStepIfMissing(oploc) - print oploc['YStep'] oploc['Location'] = Geo.addLocations((oploc['XStep'], oploc['YStep']), oploc['Location']) ret.append(oploc) return (ret, []) diff --git a/config/6thFloor.xml b/config/6thFloor.xml index 81f0c9f..ef195ec 100644 --- a/config/6thFloor.xml +++ b/config/6thFloor.xml @@ -186,7 +186,7 @@ behaviors.BehaviorChain - inpexpanddim + doors pygamekey diff --git a/inputs/PygameInput.py b/inputs/PygameInput.py index 399a77e..18f463d 100644 --- a/inputs/PygameInput.py +++ b/inputs/PygameInput.py @@ -23,7 +23,7 @@ class PygameInput(Input): if event.key == 27: self.die() if self['Keyboard']: - self.respond({'Key': event.key}) + self.respond({'Key': event.key, 'KeyChar': chr(event.key)}) return else: pygame.event.post(event) diff --git a/pixelcore/Screen.py b/pixelcore/Screen.py index 9a81df7..ada8d4a 100644 --- a/pixelcore/Screen.py +++ b/pixelcore/Screen.py @@ -22,14 +22,14 @@ class Screen: sizeValid = False self.pixelsSorted = False - def addStrip(self, lS): - self.pixelStrips.append(lS) + def addStrip(self, strip): + self.pixelStrips.append(strip) self.sizeValid = False #keep track of whether or not our screen size has self.pixelsSorted = False #been invalidated by adding more pixels def pixelsInRange(self, minX, maxX): - """Returns (pixelIndex, pixel). Does a binary search.""" + """Returns (pixelIndex, pixel). Does a binary search. Sorts first if neccesary.""" if not self.pixelsSorted: self.computeXSortedPixels() minIndex = Search.find_ge(self.xPixelLocs, minX) @@ -48,12 +48,11 @@ class Screen: return itertools.chain(*[strip.__iter__() for strip in \ self.pixelStrips]) #the * operator breaks the list into args - #increment time -- This processes all queued responses. Responses generated - #during this period are added to the queue that will be processed on the next - #time step. #SUBVERTING DESIGN FOR EFFICIENCY 1/24/11, RCOH -- It would be cleaner to store the time on the responses #themselves, however, it is faster to just pass it in. def timeStep(self, currentTime=None): + """Increments time -- This processes all queued responses, adding that to a queue that will + be processed on the next time step.""" if currentTime == None: currentTime = timeops.time() tempQueue = list(self.responseQueue) @@ -66,6 +65,7 @@ class Screen: self.responseQueue.append(responseInfo) def getSize(self): + """Returns the size of the screen in the form: (minx, miny, maxx, maxy)""" if self.sizeValid: return self.size (minX, minY, maxX, maxY) = (sys.maxint,sys.maxint,-sys.maxint,-sys.maxint) @@ -79,24 +79,19 @@ class Screen: maxY = max(y, maxY) self.size = (0,0, maxX, maxY) self.sizeValid = True - print self.size - return (0, 0, maxX+100, maxY+100) #TODO: cleaner + return (0, 0, maxX, maxY) #private def processResponse(self, responseInfo, currentTime=None): #we need to make a new dict for #each to prevent interference - #[strip.respond(dict(responseInfo)) for strip in self.pixelStrips] if currentTime == None: currentTime = timeops.time() - print 'cachetime fail' if type(responseInfo) != type(dict()): pass if 'Mapper' in responseInfo: mapper = compReg.getComponent(responseInfo['Mapper']) else: mapper = compReg.getComponent(Strings.DEFAULT_MAPPER) - #if type(mapper) != type(PixelMapper): - # raise Exception('No default mapper specified.') pixelWeightList = mapper.mapEvent(responseInfo['Location'], self) main_log.debug('Screen processing response. ' + str(len(pixelWeightList)) + ' events\ generated') -- cgit v1.2.3