def main(): from time import time from direct.showbase.ShowBase import ShowBase from panda3d.core import loadPrcFileData from panda3d.core import PStatClient from .selection import BoxSel from .util.util import ui_text, console, exit_cleanup from .ui import CameraControl, Axis3d, Grid3d from test_objects import makeSimpleGeom import sys sys.modules['core'] = sys.modules['panda3d.core'] PStatClient.connect() #run pstats in console loadPrcFileData('', 'view-frustum-cull 0') base = ShowBase() uiRoot = render.attachNewNode("uiRoot") level2Root = render.attachNewNode('collideRoot') base.setBackgroundColor(0, 0, 0) ut = ui_text() grid = Grid3d() axis = Axis3d() cc = CameraControl() base.disableMouse() con = console() exit_cleanup() #profileOctit() #counts = [1,250,510,511,512,513,1000,2000,10000] #counts = [1000,1000] counts = [999 for _ in range(99)] for i in range(len(counts)): nnodes = counts[i] #positions = np.random.uniform(-nnodes/10,nnodes/10,size=(nnodes,3)) positions = np.cumsum(np.random.randint(-1, 2, (nnodes, 3)), axis=0) #positions = [] #for j in np.linspace(-10,10,512): #positions += [[0,v+j,0] for v in np.arange(-1000,1000,100)] #positions = np.array(positions) #nnodes = len(positions) #uuids = np.arange(0,nnodes) * (i + 1) uuids = np.array(["%s" % uuid4() for _ in range(nnodes)]) geomCollide = np.ones(nnodes) * .5 out = treeMe(level2Root, positions, uuids, geomCollide) #print(out) render.attachNewNode(makeSimpleGeom(positions, np.random.rand(4))) #uiRoot = render.find('uiRoot') #uiRoot.detach() bs = BoxSel( False ) # TODO make it so that all the "root" nodes for the secen are initialized in their own space, probably in with defaults or something globalValues.py? #base.camLens.setFov(150) base.run()
def __init__(self): DirectObject.__init__(self) self.close=lambda:None #create main window base=ShowBase() __builtin__.base=base props = WindowProperties() #props.setTitle(ConfigVariableString('win-title').getValue()) props.setFullscreen(ConfigVariableBool('fullscreen').getValue()) props.setSize(ConfigVariableInt('win-width').getValue(),ConfigVariableInt('win-height').getValue()) base.win.requestProperties(props) self.width=base.win.getXSize() self.height=base.win.getYSize() print 'size=',self.width,'x',self.height self.accept('window-event',self.on_resize) base.disableMouse() #set fps limit globalClock=ClockObject.getGlobalClock() globalClock.setMode(ClockObject.MLimited) globalClock.setFrameRate(ConfigVariableDouble('clock-frame-rate').getValue()) __builtin__.screen=self __builtin__.gui=pixel2d.attachNewNode('Screen.gui') #gui is the node for 2d rendering, scaled to the screen resolution, #with origin at bottom-left, and max at top-right gui.setZ(gui,-self.height) __builtin__.console=Console(print_messenger_events=False) __builtin__.out=console.out console.request('Open') __builtin__.mouse=base.pointerWatcherNodes[0] #is used as a stack. stores frames showed to the user (top at the front of the screen) self.frames=[]
def main(): from direct.showbase.ShowBase import ShowBase from .util.util import startup_data, exit_cleanup, ui_text, console, frame_rate base = ShowBase() base.disableMouse() base.setBackgroundColor(0, 0, 0) startup_data() frame_rate() ec = exit_cleanup() uit = ui_text() con = console() cc = CameraControl() ax = Axis3d() gd = Grid3d() items = [('testing%s' % i, lambda self, index: self.__del_item__(index)) for i in range(8)] frames = [ #GuiFrame('MegaTyj', x=-.5, y=.5, height=.25, width=-.25), #GuiFrame('MegaTyj', x=-.3, y=-.3, height=.25, width=-.25, text_h=.2), #GuiFrame('testing', x=0, y=0, height=.25, width=.25, items = items), #GuiFrame('cookies', x=1, y=1, height=-.25, width=-.25, items = items), #GuiFrame('neg x', x=-.25, y=0, height=.1, width=-.25, items = items), #GuiFrame('text', x=.5, y=.5, height=.25, width=-.25, items = items), #GuiFrame('text', x=.5, y=.5, height=-.25, width=-.25, items = items), #GuiFrame('text', x=.5, y=.25, height=.25, width=.25, items = items), ] frames = [ GuiFrame('%s' % i, x=-.1, y=.1, height=.25, width=-.25, items=items) for i in range(10) ] # FIXME calling add_item after this causes weird behvaior base.run()
def main(): from direct.showbase.ShowBase import ShowBase from .util.util import startup_data, exit_cleanup, ui_text, console, frame_rate base = ShowBase() base.disableMouse() base.setBackgroundColor(0,0,0) startup_data() frame_rate() ec = exit_cleanup() uit = ui_text() con = console() cc = CameraControl() ax = Axis3d() gd = Grid3d() items = [('testing%s'%i, lambda self, index: self.__del_item__(index) ) for i in range(8)] frames = [ #GuiFrame('MegaTyj', x=-.5, y=.5, height=.25, width=-.25), #GuiFrame('MegaTyj', x=-.3, y=-.3, height=.25, width=-.25, text_h=.2), #GuiFrame('testing', x=0, y=0, height=.25, width=.25, items = items), #GuiFrame('cookies', x=1, y=1, height=-.25, width=-.25, items = items), #GuiFrame('neg x', x=-.25, y=0, height=.1, width=-.25, items = items), #GuiFrame('text', x=.5, y=.5, height=.25, width=-.25, items = items), #GuiFrame('text', x=.5, y=.5, height=-.25, width=-.25, items = items), #GuiFrame('text', x=.5, y=.25, height=.25, width=.25, items = items), ] frames = [GuiFrame('%s'%i, x=-.1, y=.1, height=.25, width=-.25, items=items) for i in range(10)] # FIXME calling add_item after this causes weird behvaior base.run()
def start(): """ start a local renderManager with all the stuff needed for viewing """ from direct.showbase.ShowBase import ShowBase from .render_manager import renderManager from .util.util import startup_data, exit_cleanup, ui_text, console, frame_rate from .ui import CameraControl, Axis3d, Grid3d, GuiFrame from .selection import BoxSel from .keys import AcceptKeys, callbacks # FIXME this needs to be pulled in automatically if exit_cleanup is imported base = ShowBase() base.disableMouse() base.setBackgroundColor(0,0,0) startup_data() frame_rate() ec = exit_cleanup() uit = ui_text() con = console() cc = CameraControl() ax = Axis3d() gd = Grid3d() rendman = renderManager() frames = { 'data':GuiFrame('Data view','f') } frames['data'].toggle_vis() bs = BoxSel(frames) # FIXME must be loaded AFTER render manager or collRoot won't exist ak = AcceptKeys() return rendman, base
def main(): from time import time from direct.showbase.ShowBase import ShowBase from panda3d.core import loadPrcFileData from panda3d.core import PStatClient from .selection import BoxSel from .util.util import ui_text, console, exit_cleanup from .ui import CameraControl, Axis3d, Grid3d from test_objects import makeSimpleGeom import sys sys.modules['core'] = sys.modules['panda3d.core'] PStatClient.connect() #run pstats in console loadPrcFileData('','view-frustum-cull 0') base = ShowBase() uiRoot = render.attachNewNode("uiRoot") level2Root = render.attachNewNode('collideRoot') base.setBackgroundColor(0,0,0) ut = ui_text() grid = Grid3d() axis = Axis3d() cc = CameraControl() base.disableMouse() con = console() exit_cleanup() #profileOctit() #counts = [1,250,510,511,512,513,1000,2000,10000] #counts = [1000,1000] counts = [999 for _ in range(99)] for i in range(len(counts)): nnodes = counts[i] #positions = np.random.uniform(-nnodes/10,nnodes/10,size=(nnodes,3)) positions = np.cumsum(np.random.randint(-1,2,(nnodes,3)), axis=0) #positions = [] #for j in np.linspace(-10,10,512): #positions += [[0,v+j,0] for v in np.arange(-1000,1000,100)] #positions = np.array(positions) #nnodes = len(positions) #uuids = np.arange(0,nnodes) * (i + 1) uuids = np.array(["%s"%uuid4() for _ in range(nnodes)]) geomCollide = np.ones(nnodes) * .5 out = treeMe(level2Root, positions, uuids, geomCollide) #print(out) render.attachNewNode(makeSimpleGeom(positions,np.random.rand(4))) #uiRoot = render.find('uiRoot') #uiRoot.detach() bs = BoxSel(False) # TODO make it so that all the "root" nodes for the secen are initialized in their own space, probably in with defaults or something globalValues.py? #base.camLens.setFov(150) base.run()
def __init__(self, mesh, pm_filebuf): scene_members = getSceneMembers(mesh) base = ShowBase() if len(scene_members) > 1: print('There is more than one geometry in the scene, so I think this is not a progressive base mesh.') sys.exit(1) rotateNode = GeomNode("rotater") rotatePath = render.attachNewNode(rotateNode) matrix = numpy.identity(4) if mesh.assetInfo.upaxis == collada.asset.UP_AXIS.X_UP: r = collada.scene.RotateTransform(0,1,0,90) matrix = r.matrix elif mesh.assetInfo.upaxis == collada.asset.UP_AXIS.Y_UP: r = collada.scene.RotateTransform(1,0,0,90) matrix = r.matrix rotatePath.setMat(Mat4(*matrix.T.flatten().tolist())) geom, renderstate, mat4 = scene_members[0] node = GeomNode("primitive") node.addGeom(geom) if renderstate is not None: node.setGeomState(0, renderstate) self.geomPath = rotatePath.attachNewNode(node) self.geomPath.setMat(mat4) wrappedNode = ensureCameraAt(self.geomPath, base.camera) base.disableMouse() attachLights(render) render.setShaderAuto() render.setTransparency(TransparencyAttrib.MDual, 1) base.render.analyze() KeyboardMovement() MouseDrag(wrappedNode) MouseScaleZoom(wrappedNode) ButtonUtils(wrappedNode) MouseCamera() print('Loading pm into memory... ', end=' ') sys.stdout.flush() self.pm_refinements = readPDAE(pm_filebuf) self.pm_index = 0 print('Done') self.slider = DirectSlider(range=(0,len(self.pm_refinements)), value=0, pageSize=len(self.pm_refinements)/20, command=self.sliderMoved, pos=(0, 0, -.9), scale=1) for key, val in uiArgs.items(): self.slider.thumb[key] = val self.triText = OnscreenText(text="", pos=(-1,0.85), scale = 0.15, fg=(1, 0.5, 0.5, 1), align=TextNode.ALeft, mayChange=1) base.run()
def main(): import pickle from .util.util import ui_text, console, exit_cleanup, frame_rate, startup_data from .keys import AcceptKeys from .render_manager import renderManager from .ui import CameraControl, Axis3d, Grid3d base = ShowBase() base.setBackgroundColor(0,0,0) base.disableMouse() startup_data() console() exit_cleanup() frame_rate() CameraControl() Axis3d() Grid3d() r = renderManager() from .test_objects import makeSimpleGeom import numpy as np from .trees import treeMe from uuid import uuid4 from panda3d.core import GeomLinestrips n = 1000 #positions = np.array([i for i in zip(np.linspace(-1000,1000,n),np.linspace(-1000,1000,n),np.linspace(-1000,1000,n))]) # wat 1 #positions = np.array([i for i in zip(np.linspace(-1000,1000,n),np.linspace(-1000,1000,n),np.zeros(n))]) # wat 2 positions = np.array([i for i in zip(np.linspace(-1000,1000,n),np.zeros(n),np.zeros(n))]) #positions = np.random.randint(-1000,1000,(n,3)) # so it turns out that the collision nodes don't render properly on this, the tree constructed with math is correct, the rendering is not r.geomRoot.attachNewNode(makeSimpleGeom(positions,(1,1,1,1))) uuids = np.array(['%s'%uuid4() for _ in range(n)]) bounds = np.ones(n) * .5 treeMe(r.collRoot, positions, uuids, bounds) base.camLens.setFov(90) n = 1E4 # apparently 1e8 is a bit too big and 1e7 is slowwww... definitely need downsampling positions = np.array([i for i in zip(10*np.sin(np.arange(0,n)),np.arange(0,n),10*np.cos(np.arange(0,n)))]) # fukken saved r.geomRoot.attachNewNode(makeSimpleGeom(positions,(1,1,1,1), geomType=GeomLinestrips)) #with open('edge_case_data_tuple.pickle','rb') as f: #data_tuple = pickle.load(f) #r.cache['edgecase'] = False #r.set_nodes('edgecase',data_tuple) sgn = GeomNode('srct') sgn.addGeom(makeSelectRect()) sn = render.attachNewNode(sgn) sn.setSx(10) sn.setSy(10) sn.setColor(.5,.5,.5,.5) ut = ui_text() dt = BoxSel(visualize = BoxSel.VIS_ALL) ac = AcceptKeys() base.run()
class ColorSquare(object): def __init__(self): self.base = ShowBase() self.base.disableMouse() self.base.camera.setPos(0, -10, 0) color_vertices = [(0.2, 0.2, 0.1, 1), (0.2, 0.7, 0.1, 1), (0.7, 0.7, 0.1, 1), (0.7, 0.2, 0.1, 1)] square = make_square(color_vertices) sq_node = GeomNode('square') sq_node.addGeom(square) self.base.render.attachNewNode(sq_node)
def main(): from direct.showbase.ShowBase import ShowBase from test_objects import Grid3d,Axis3d from .util.util import ui_text base = ShowBase() base.setBackgroundColor(0,0,0) ut = ui_text() cc = CameraControl() grid = Grid3d() axis = Axis3d() base.disableMouse() base.run()
def _gen_viewer(queue, max_points=17776, massage_que=None): base = ShowBase() base.setBackgroundColor(0, 0, 0) base.disableMouse() base.camera.setPos(0, -50, 20) base.camera.setHpr(0, -22, 0) base.mouseWatcherNode.set_modifier_buttons(ModifierButtons()) base.buttonThrowers[0].node().set_modifier_buttons(ModifierButtons()) base.setFrameRateMeter(True) pc_viewer = _PointCloudFrameViewer(point_cloud_size=max_points, queue=queue) base.run()
def main(): from panda3d.core import PStatClient from panda3d.core import loadPrcFileData from .ui import CameraControl, Axis3d, Grid3d #loadPrcFileData('','threading-model Cull/Draw') #XXX wow, not good for this use case... base = ShowBase() base.disableMouse() base.setBackgroundColor(0, 0, 0) cc = CameraControl() ax = Axis3d() gd = Grid3d() #nt = emptyTest(2000) gt = geomTest(2000) PStatClient.connect() base.run()
def main(): from panda3d.core import PStatClient from panda3d.core import loadPrcFileData from .ui import CameraControl, Axis3d, Grid3d #loadPrcFileData('','threading-model Cull/Draw') #XXX wow, not good for this use case... base = ShowBase() base.disableMouse() base.setBackgroundColor(0,0,0) cc = CameraControl() ax = Axis3d() gd = Grid3d() #nt = emptyTest(2000) gt = geomTest(2000) PStatClient.connect() base.run()
def __init__(self): ShowBase.__init__(self) ShowBase.disableMouse(self) self.nodes = [] self.ways = [] self.meter = 200.0 / 2200.0 #2200 meters - diameter of rendered area self.setBackgroundColor(135.0 / 256.0, 206.0 / 256.0, 235.0 / 256.0) self.prepareFloor() self.downloadOSMData() self.loadLines() self.camera.setPos(0, 0, 3.0 * self.meter) # Add the spinCameraTask procedure to the task manager. self.taskMgr.add(self.spinCameraTask, "SpinCameraTask")
def __init__(self): ShowBase.__init__(self) ShowBase.disableMouse(self) self.nodes = [] self.ways = [] self.meter = 200.0 / 2200.0 #2200 meters - diameter of rendered area self.setBackgroundColor(135.0/256.0,206.0/256.0,235.0/256.0) self.prepareFloor() self.downloadOSMData() self.loadLines() self.camera.setPos(0,0,3.0*self.meter) # Add the spinCameraTask procedure to the task manager. self.taskMgr.add(self.spinCameraTask, "SpinCameraTask")
def _main(): from .util.util import ui_text from .ui import CameraControl, Axis3d, Grid3d #from panda3d.core import ConfigVariableBool #ConfigVariableString('view-frustum-cull',False) from panda3d.core import loadPrcFileData from time import time from panda3d.core import PStatClient from dragsel import BoxSel PStatClient.connect() loadPrcFileData('', 'view-frustum-cull 0') #loadPrcFileData('','threading-model Cull/Draw') #bad for lots of nodes base = ShowBase() base.setBackgroundColor(0, 0, 0) ut = ui_text() grid = Grid3d() axis = Axis3d() cc = CameraControl() base.disableMouse() #pt = PointsTest(999,99999) #pt = PointsTest(1,9999999) #pt = PointsTest(1,999999) #SLOW AS BALLS: IDEA: render faraway nodes as static meshes and transform them to live as we get closer! #pt = PointsTest(9999999,1) #pt = PointsTest(99999,100) #runs fine when there is only 1 node >_< #pt = PointsTest(999,10) #runs fine when there is only 1 node >_< #pt = PointsTest(1,99999) #still slow :/ #pt = PointsTest(1,9999) #still slow :/ #deep trees segfault! #pt = PointsTest(1,4000) #still slow :/ #this one is ok #pt = PointsTest(1,999) #still slow #pt = PointsTest(1,499) #still slow 15 fps with 0,0,0 positioned geom points #pt = PointsTest(1,249) #about 45fps :/ bins = 1 #999=.057, below 200 ~.044 so hard to tell (for n = 99) #FIXME low numbers of points causes major problems! #nt = NodeTest(999999,bins) #the inscreased time is more pronounced with larger numbers of nodes... is it the serialization? #ct = CollTest(9999,bins) #the inscreased time is more pronounced with larger numbers of nodes... is it the serialization? #nt = NodeTest(999,5) #base.camLens.setFar(9E12) #view-frustum-cull 0 bs = BoxSel() #some stuff ft = FullTest(999, bins) base.run( ) #looks like this is the slow case... probably should look into non blocking model loading?
def run_the_world(cmd_args): global MY_BASE, MY_WORLD, PAUSE_MENU, BLOCK_MENU, SUB_TERRAIN, BLOCK_SCALE if cmd_args.level: level_ground = True print(f"\nBuilding world with level ground, block-type = [{cmd_args.block}]") else: level_ground = False print(f"\nBuilding world with noisy ground, block-type = [{cmd_args.block}]") if cmd_args.mini: BLOCK_SCALE = 0.9 MY_BASE = ShowBase() MY_BASE.disableMouse() # Dumping in a sample Model for testing - it actually looks pretty funny there. # GROUND_MODEL = "gfx/environment.egg" # environ = MY_BASE.loader.loadModel(GROUND_MODEL) # environ.reparentTo(MY_BASE.render) # environ.setPos(0, 0, 0) # environ.setScale(0.01) # SUB_TERRAIN = environ cur_block = cmd_args.block BLOCK_MENU = BlockMenu(MY_BASE, cur_block) MY_WORLD = write_ground_blocks(MY_BASE, cur_block, level_ground, BLOCK_SCALE) PAUSE_MENU = PauseScreen(MY_BASE, MY_WORLD, BLOCK_SCALE) setup_lighting(MY_BASE) setup_fog(MY_BASE, cur_block) setup_camera(MY_BASE, MY_WORLD, CAMERA_START_COORDS) setup_base_keys(MY_BASE, call_pause_screen, handle_click, toggle_mouse, call_toggle_blocks, reset_stuff) if cmd_args.skybox: setup_skybox(MY_BASE) setup_tasks(MY_BASE) MY_BASE.run()
def main(): base = ShowBase() base.disableMouse() base.setBackgroundColor(0, 0, 0) # WARNING: testing with 3 states will melt your brain pt = PointsTest(num_states=3) # XXX comment out when testing 2 #pt = PointsTest(num_states=2) # XXX uncomment to test with 2 states m = pt.load_point(-1.5, 5, 0, (1, 0, 1, 1), 'magenta') r = pt.load_point(-.5, 5, 0, (1, 0, 0, 1), 'red') g = pt.load_point(.5, 5, 0, (0, 1, 0, 1), 'green') b = pt.load_point(1.5, 5, 0, (0, 0, 1, 1), 'blue') b.reparentTo(render) m.reparentTo(r) render.setRenderModeThickness(1) print([n for n in render.findAllMatches('*')]) base.run()
def _main(): from .util.util import ui_text from .ui import CameraControl, Axis3d, Grid3d #from panda3d.core import ConfigVariableBool #ConfigVariableString('view-frustum-cull',False) from panda3d.core import loadPrcFileData from time import time from panda3d.core import PStatClient from dragsel import BoxSel PStatClient.connect() loadPrcFileData('','view-frustum-cull 0') #loadPrcFileData('','threading-model Cull/Draw') #bad for lots of nodes base = ShowBase() base.setBackgroundColor(0,0,0) ut = ui_text() grid = Grid3d() axis = Axis3d() cc = CameraControl() base.disableMouse() #pt = PointsTest(999,99999) #pt = PointsTest(1,9999999) #pt = PointsTest(1,999999) #SLOW AS BALLS: IDEA: render faraway nodes as static meshes and transform them to live as we get closer! #pt = PointsTest(9999999,1) #pt = PointsTest(99999,100) #runs fine when there is only 1 node >_< #pt = PointsTest(999,10) #runs fine when there is only 1 node >_< #pt = PointsTest(1,99999) #still slow :/ #pt = PointsTest(1,9999) #still slow :/ #deep trees segfault! #pt = PointsTest(1,4000) #still slow :/ #this one is ok #pt = PointsTest(1,999) #still slow #pt = PointsTest(1,499) #still slow 15 fps with 0,0,0 positioned geom points #pt = PointsTest(1,249) #about 45fps :/ bins = 1 #999=.057, below 200 ~.044 so hard to tell (for n = 99) #FIXME low numbers of points causes major problems! #nt = NodeTest(999999,bins) #the inscreased time is more pronounced with larger numbers of nodes... is it the serialization? #ct = CollTest(9999,bins) #the inscreased time is more pronounced with larger numbers of nodes... is it the serialization? #nt = NodeTest(999,5) #base.camLens.setFar(9E12) #view-frustum-cull 0 bs = BoxSel() #some stuff ft = FullTest(999,bins) base.run() #looks like this is the slow case... probably should look into non blocking model loading?
def main(): from .util.util import ui_text, frame_rate, exit_cleanup, startup_data from .ui import CameraControl, Axis3d, Grid3d from panda3d.core import loadPrcFileData from time import time from panda3d.core import PStatClient from .selection import BoxSel from .render_manager import renderManager PStatClient.connect() loadPrcFileData('','view-frustum-cull 0') base = ShowBase() base.setBackgroundColor(0,0,0) ut = ui_text() grid = Grid3d() axis = Axis3d() cc = CameraControl() base.disableMouse() frame_rate() startup_data() #render something #ct = CollTest(2000) #ft = FullTest(99,1) renderManager() frames = {'data':GuiFrame('data','f')} bs = BoxSel(frames) # FIXME must be started after renderManager >_< dnd = dond() #d4d = do4d() ec = exit_cleanup() ac = AcceptKeys() base.run() # we don't need threading for this since panda has a builtin events interface
def main(): from .util.util import ui_text, frame_rate, exit_cleanup, startup_data from .ui import CameraControl, Axis3d, Grid3d from panda3d.core import loadPrcFileData from time import time from panda3d.core import PStatClient from .selection import BoxSel from .render_manager import renderManager PStatClient.connect() loadPrcFileData('', 'view-frustum-cull 0') base = ShowBase() base.setBackgroundColor(0, 0, 0) ut = ui_text() grid = Grid3d() axis = Axis3d() cc = CameraControl() base.disableMouse() frame_rate() startup_data() #render something #ct = CollTest(2000) #ft = FullTest(99,1) renderManager() frames = {'data': GuiFrame('data', 'f')} bs = BoxSel(frames) # FIXME must be started after renderManager >_< #dnd = dond() d4d = do4d() ec = exit_cleanup() ac = AcceptKeys() base.run( ) # we don't need threading for this since panda has a builtin events interface
def main(): from direct.showbase.ShowBase import ShowBase from .util.util import startup_data, exit_cleanup, ui_text, console, frame_rate from .ui import CameraControl, Axis3d, Grid3d from .keys import AcceptKeys, callbacks base = ShowBase() base.disableMouse() base.setBackgroundColor(0,0,0) startup_data() frame_rate() uit = ui_text() con = console({}) ec = exit_cleanup() cc = CameraControl() ax = Axis3d() gd = Grid3d() ac = AcceptKeys() ### # XXX REAL CODE HERE ### size = 256 shift = .001 # .001 works with scale .499 and size 2 scale = 1/size - (1/ (size * 100)) #scale = 1 #shift = -size * .125 array = np.random.randint(0,255,(size,size,size)) #array = np.linspace(0,255,size**3).reshape(size,size,size) tex, memarray = make_texture3d(array) tex2 = Texture() tex2.setup2dTexture() # TODO how to read the matrix in?! geomNode = GeomNode('shader_test') geomNode.addGeom(make_cube(size,size,size)) nodePath = render.attachNewNode(geomNode) #embed() nodePath.setTexGen(TextureStage.getDefault(), TexGenAttrib.MWorldPosition) nodePath.setTexProjector(TextureStage.getDefault(), render, nodePath) nodePath.setTexPos(TextureStage.getDefault(), shift, shift, shift) nodePath.setTexScale(TextureStage.getDefault(), scale) nodePath.setTexture(tex) #embed() #nodePath.setTexGen(TextureStage.getDefault(), 0, 0, 0) #bug? #""" #myShader = Shader.load(Shader.SL_GLSL, "my_vert.glsl", "my_frag.glsl")#, "my_geom.glsl") # wow, this actually... turns the box black or something, probably shound't attach the texture to the nodepath if we do it this way #nodePath.set_shader_input("my_param",(1,1,1)) #nodePath.set_shader_input('color.bgra', 10) # bad #myvec = Vec4(.2, 1.0, 1.0, .4) #embed() myShader = Shader.load(Shader.SL_GLSL, "simple_vert.glsl", "simple_frag.glsl") nodePath.set_shader(myShader) nodePath.set_shader_input('camera', camera) con.locals_['myShader'] = myShader con.locals_['nodePath'] = nodePath #nodePath.set_shader_input('textcoord', (1.0, .5)) #nodePath.set_shader_input("tex", tex2) #nodePath.set_shader_input("volume_tex", tex) #nodePath.set_shader_input("stepsize", .5) #""" base.run()
class Fountain(object): def __init__(self): self.base = ShowBase() self.thrust = 0.5 self.wind = 0.2 self.UP = Vec3(0, 0, 1) # might as well just make this a variable # set up camera self.base.disableMouse() self.base.camera.setPos(20, -20, 5) self.base.camera.lookAt(0, 0, 5) # Set up the collision traverser. If we bind it to base.cTrav, then Panda will handle # management of this traverser (for example, by calling traverse() automatically for us once per frame) self.base.cTrav = CollisionTraverser() # Now let's set up some collision bits for our masks self.ground_bit = 1 self.ball_bit = 2 self.base.setBackgroundColor(0.64, 0, 0) # First, we build a card to represent the ground cm = CardMaker('ground-card') cm.setFrame(-60, 60, -60, 60) card = self.base.render.attachNewNode(cm.generate()) card.lookAt(0, 0, -1) # align upright #tex = loader.loadTexture('maps/envir-ground.jpg') tex = loader.loadTexture('models/textures/rock12.bmp') card.setTexture(tex) # Then we build a collisionNode which has a plane solid which will be the ground's collision # representation groundColNode = card.attachNewNode(CollisionNode('ground-cnode')) groundColPlane = CollisionPlane(Plane(Vec3(0, -1, 0), Point3(0, 0, 0))) groundColNode.node().addSolid(groundColPlane) # Now, set the ground to the ground mask groundColNode.setCollideMask(BitMask32().bit(self.ground_bit)) # Why aren't we adding a collider? There is no need to tell the collision traverser about this # collisionNode, as it will automatically be an Into object during traversal. # enable forces self.base.enableParticles() node = NodePath("PhysicsNode") node.reparentTo(self.base.render) # may want to have force dependent on mass eventually, # but at the moment assume all balls same weight self.force_mag = 200 # gravity gravity_fn = ForceNode('world-forces') gravity_fnp = self.base.render.attachNewNode(gravity_fn) gravity_force = LinearVectorForce(0.0, 0.0, -9.81) gravity_fn.addForce(gravity_force) self.base.physicsMgr.addLinearForce(gravity_force) # wind wind_fn = ForceNode('world-forces') wind_fnp = self.base.render.attachNewNode(wind_fn) wind_force = LinearVectorForce(1.0, 0.5, 0.0) wind_fn.addForce(wind_force) self.base.physicsMgr.addLinearForce(wind_force) # spurt out of fountain, bounce self.spurt = ForceNode("spurt") spurt_np = self.base.render.attachNewNode(self.spurt) # create a list for our ball actors, not sure if I need this, but seems likely self.ball_actors = [] # make a teapot teapot = loader.loadModel('teapot.egg') tex = loader.loadTexture('maps/color-grid.rgb') #teapot.setTexGen(TextureStage.getDefault(), TexGenAttrib.MWorldPosition) teapot.setTexture(tex) teapot.reparentTo(self.base.render) teapot.setPos(-5, 10, 10) # create the first ball: #ball = self.create_a_ball() #self.enliven_ball(ball) smiley = loader.loadModel('smiley.egg') lerper = NodePath('lerper') smiley.setTexProjector(TextureStage.getDefault(), NodePath(), lerper) smiley.reparentTo(self.base.render) smiley.setPos(5, 10, 10) i = lerper.posInterval(5, VBase3(0, 1, 0)) i.loop() # Tell the messenger system we're listening for smiley-into-ground messages and invoke our callback self.base.accept('ball_cnode-into-ground-cnode', self.ground_callback) ball_fountain = taskMgr.doMethodLater(.5, self.spurt_balls, 'tickTask') # tasks #self.frameTask = self.base.taskMgr.add(self.frame_loop, "frame_loop") #self.frameTask.last = 0 def frame_loop(self, task): # Make more balls! dt = task.time - task.last task.last = task.time # self.move_ball(dt) return task.cont # This task increments itself so that the delay between task executions # gradually increases over time. If you do not change task.delayTime # the task will simply repeat itself every 2 seconds def spurt_balls(self, task): print "Delay:", task.delayTime print "Frame:", task.frame # task.delayTime += 1 # for i in range(5): ball = self.create_a_ball() self.enliven_ball(ball) return task.again def move_ball(self, dt): pass #x, y, z = self.ball.getPos() #print x, y, z #print self.actor_node.getPhysicsObject().getPosition() # rotate ball #prevRot = LRotationf(self.ball.getQuat()) #axis = self.UP.cross(self.ballV) #newRot = LRotationf(axis, 45, 5 * dt) #self.ball.setQuat(prevRot + newRot) #print x, y, z #z += dt * self.thrust #x += dt * self.wind #y += dt * self.wind #self.ball.setPos(x, y, z) def remove_force(self, actor, force, task): print('remove force', force) actor.getPhysical(0).removeLinearForce(force) self.spurt.removeForce(force) return task.done def apply_spurt(self, actor_node, force=None): print 'spurt' print('force', force) #print actor_node # really want this to remember its previous state with that # particular ball, and reduce the force from then by some amount. if force is None: # force = LinearVectorForce(0.0, 0.0, self.force_mag) force = LinearVectorForce(0.0, 0.0, self.force_mag) self.spurt.addForce(force) print('new', force) #self.force_mag -= 15 else: force.getAmplitude() # apply the spurt actor_node.getPhysical(0).addLinearForce(force) print('added force', self.spurt.getForce(0).getVector(actor_node.getPhysicsObject())[2]) #print force, actor_node #for child in self.base.render.getChildren(): # print child # set a task that will clear this force a short moment later self.base.taskMgr.doMethodLater(0.01, self.remove_force, 'removeForceTask', extraArgs=[actor_node, force], appendTask=True) print 'set do method later' def ground_callback(self, entry): '''This is our ground collision message handler. It is called whenever a collision message is triggered''' print 'callback' # Get our parent actor_node ball_actor_node = entry.getFromNodePath().getParent().node() # Why do we call getParent? Because we are passed the CollisionNode during the event and the # ActorNode is one level up from there. Our node graph looks like so: # - ActorNode # + ModelNode # + CollisionNode # add bounce! self.apply_spurt(ball_actor_node) def create_a_ball(self): print 'new ball' ball = self.base.loader.loadModel('smiley') texture = self.base.loader.loadTexture('models/textures/rock12.bmp') #ball.setTexture(texture) #tex = loader.loadTexture('maps/noise.rgb') ball.setPos(0, 0, 0) ball.reparentTo(self.base.render) ball.setTexture(texture, 1) return ball def enliven_ball(self, ball): # create an actor node for the balls ball_actor = self.base.render.attachNewNode(ActorNode("ball_actor_node")) # choose a random color #ball_actor.setColor(random.random(), random.random(), random.random(), random.random()) self.create_ball_coll(ball_actor) # apply forces to it self.base.physicsMgr.attachPhysicalNode(ball_actor.node()) #spurt_force = LinearVectorForce(0.0, 0.0, self.force_mag) #spurt_force.setMassDependent(True) #self.spurt.addForce(spurt_force) #self.spurt.addForce() self.apply_spurt(ball_actor.node()) ball.reparentTo(ball_actor) self.ball_actors.append(ball_actor) def create_ball_coll(self, ball_actor): # Build a collisionNode for this smiley which is a sphere of the same diameter as the model ball_coll_node = ball_actor.attachNewNode(CollisionNode('ball_cnode')) ball_coll_sphere = CollisionSphere(0, 0, 0, 1) ball_coll_node.node().addSolid(ball_coll_sphere) # Watch for collisions with our brothers, so we'll push out of each other ball_coll_node.node().setIntoCollideMask(BitMask32().bit(self.ball_bit)) # we're only interested in colliding with the ground and other smileys cMask = BitMask32() cMask.setBit(self.ground_bit) cMask.setBit(self.ball_bit) ball_coll_node.node().setFromCollideMask(cMask) # Now, to keep the spheres out of the ground plane and each other, let's attach a physics handler to them ball_handler = PhysicsCollisionHandler() # Set the physics handler to manipulate the smiley actor's transform. ball_handler.addCollider(ball_coll_node, ball_actor) # This call adds the physics handler to the traverser list # (not related to last call to addCollider!) self.base.cTrav.addCollider(ball_coll_node, ball_handler) # Now, let's set the collision handler so that it will also do a CollisionHandlerEvent callback # But...wait? Aren't we using a PhysicsCollisionHandler? # The reason why we can get away with this is that all CollisionHandlerXs are inherited from # CollisionHandlerEvent, # so all the pattern-matching event handling works, too ball_handler.addInPattern('%fn-into-%in') return ball_coll_node
class PandaController(object): DEFAULT_FULLSCREEN = False DEFAULT_WIDTH = 800 DEFAULT_HEIGHT = 600 DEFAULT_FPS = 60 DEFAULT_FRAME_METER = False DEFAULT_MUSIC_VOLUME = .3 DEFAULT_SOUND_VOLUME = .1 DEFAULT_MAX_DELTA = 1. / 20. DEFAULT_SHADERS = True def __init__(self): super(PandaController, self).__init__() self._timer = Timer() self._timer.max_delta = self.DEFAULT_MAX_DELTA self._tasks = task.TaskGroup() self._tasks.add(self._panda_task) self._music = None self._mouse_task = None self._relative_mouse = False @property def timer(self): return self._timer @property def tasks(self): return self._tasks def start(self, title): cfg = GlobalConf().child('panda') self.set_defaults(cfg) self.base = ShowBase() self.base.disableMouse() self.audio = self.base.sfxManagerList[0] self.audio3d = Audio3DManager(self.audio, camera) self.audio3d.setListenerVelocityAuto() self.audio3d.setDropOffFactor(0.1) # HACK self.create_properties(title) self.update_properties(cfg) self.listen_conf(cfg) loadPrcFileData("", "interpolate-frames 1") loadPrcFileData("", "support-threads #f") path = getModelPath() path.prependPath('./data') self.base.enableParticles() def loop(self): self._timer.reset() self._timer.loop(self._loop_fn) def _loop_fn(self, timer): task_count = 1 # _panda_task if self._relative_mouse: task_count += 1 # _mouse_task if self._tasks.count > task_count: return self._tasks.update(timer) return False def set_defaults(self, cfg): cfg.child('fps').default(self.DEFAULT_FPS) cfg.child('width').default(self.DEFAULT_WIDTH) cfg.child('height').default(self.DEFAULT_HEIGHT) cfg.child('fullscreen').default(self.DEFAULT_FULLSCREEN) cfg.child('frame-meter').default(self.DEFAULT_FRAME_METER) cfg.child('music-volume').default(self.DEFAULT_MUSIC_VOLUME) cfg.child('sound-volume').default(self.DEFAULT_SOUND_VOLUME) def listen_conf(self, cfg): cfg.on_conf_nudge += self.update_properties cfg.child('fps').on_conf_change += self.update_fps cfg.child('frame-meter').on_conf_change += self.update_frame_meter cfg.child('music-volume').on_conf_change += self.update_music_volume cfg.child('sound-volume').on_conf_change += self.update_sound_volume self.audio.setVolume(cfg.child('sound-volume').value) def create_properties(self, title): self._prop = WindowProperties() self._prop.setTitle(title) def relative_mouse(self): if not self._relative_mouse: self._prop.setCursorHidden(True) self._prop.setMouseMode(WindowProperties.MRelative) self.base.win.requestProperties(self._prop) self._mouse_task = self._tasks.add(MouseTask()) self._mouse_task.on_mouse_move += lambda x, y: \ messenger.send ('mouse-move', [(x, y)]) self._relative_mouse = True def absolute_mouse(self): if self._relative_mouse: self._relative_mouse = False if self._mouse_task: self._mouse_task.kill() self._prop.setCursorHidden(False) self._prop.setMouseMode(WindowProperties.MAbsolute) self.base.win.requestProperties(self._prop) def has_shaders(self): return self.base.win.getGsg().getSupportsBasicShaders() == 0 def update_properties(self, cfg): self._prop.setSize(cfg.child('width').value, cfg.child('height').value) self._prop.setFullscreen(cfg.child('fullscreen').value) self.base.win.requestProperties(self._prop) self._timer.fps = cfg.child('fps').value self.base.setFrameRateMeter(cfg.child('frame-meter').value) def update_frame_meter(self, cfg): self.base.setFrameRateMeter(cfg.value) def update_fps(self, cfg): self._timer.fps = cfg.value def update_music_volume(self, cfg): if self._music: self._music.setVolume(cfg.value) def update_sound_volume(self, cfg): if self.audio: self.audio.setVolume(cfg.value) def _panda_task(self, timer): taskMgr.step() return task.running def set_background_color(self, *color): base.setBackgroundColor(*color) def loop_music(self, file): if self._music: self._music.setLoop(False) self.tasks.add( task.sequence( task.linear(self._music.setVolume, self._music.getVolume(), 0.0))) volume = GlobalConf().path('panda.music-volume').value self._music = loader.loadSfx(file) self._music.setLoop(True) self.tasks.add( task.sequence( task.linear(self._music.setVolume, 0.0, volume, init=True))) self._music.play()
class ServerInst(): def __init__(self): # Initialise Window self.showbase=ShowBase() # Disable Mouse Control for camera self.showbase.disableMouse() # Start our server up self.server = Server(9099, compress=True) self.users={} for i in range(num_users): new_user={} new_user['name']='cake' new_user['connection']='cake' new_user['ready']=True new_user['new_dest']=False new_user['new_spell']=False self.users[len(self.users)]=new_user camera.setPos(0,0,45*num_users) camera.lookAt(0,0,0) #taskMgr.doMethodLater(0.5, self.pregame_loop, 'Lobby Loop') taskMgr.doMethodLater(0.5, self.lobby_loop, 'Lobby Loop') # handles new joining clients and updates all clients of chats and readystatus of players def lobby_loop(self,task): # if in lobby state temp=self.server.getData() if temp!=[]: for i in range(len(temp)): valid_packet=False package=temp[i] if len(package)==2: print "Received: " + str(package) +" "+ str(package[1].getAddress()) if len(package[0])==2: # if username is sent, assign to client if package[0][0]=='username': user_found=False valid_packet=True for u in range(len(self.users)): if self.users[u]['name']==package[0][1]: print "User already exists" user_found=True data = {} data[0] = "error" data[1] = "User already exists" self.server.sendData(data,package[1]) # send something back to the client saying to change username if not user_found: new_user={} new_user['name']=package[0][1] new_user['connection']=package[1] new_user['ready']=False new_user['new_dest']=False new_user['new_spell']=False self.users[len(self.users)]=new_user data = {} data[0] = "which" data[1] = len(self.users)-1 self.server.sendData(data,package[1]) # else check to make sure connection has username for u in range(len(self.users)): if self.users[u]['connection']==package[1]: print "Packet from "+self.users[u]['name'] # process packet update_warlocks=False # if chat packet if package[0][0]=='chat': print "Chat: "+package[0][1] valid_packet=True # Broadcast data to all clients ("username: message") data = {} data[0]='chat' data[1]=self.users[u]['name']+": "+package[0][1] self.server.broadcastData(data) # else if ready packet elif package[0][0]=='ready': print self.users[u]['name']+" is ready!" self.users[u]['ready']=True valid_packet=True update_warlocks=True # else if unready packet elif package[0][0]=='unready': print self.users[u]['name']+" is not ready!" self.users[u]['ready']=False valid_packet=True update_warlocks=True if update_warlocks: data = {} data[0]='warlocks' data[1]=len(self.users) self.server.broadcastData(data) # break out of for loop break #else: # print str(self.users[u]['connection'])+" "+str(package[1]) if not valid_packet: data = {} data[0] = "error" data[1] = "Please Login" self.server.sendData(data,package[1]) print "User not logged in" else: print "Data in packet wrong size" else: print "Packet wrong size" # if all players are ready and there is X of them game_ready=True # if there is any clients connected if not self.server.getClients(): game_ready=False for u in range(len(self.users)): if self.users[u]['ready']==False: game_ready=False if game_ready: data = {} data[0]='state' data[1]='game' self.server.broadcastData(data) taskMgr.doMethodLater(0.5, self.pregame_loop, 'Pregame Loop') return task.done return task.again def pregame_loop(self,task): print "Pregame State" self.game_time=0 self.tick=0 self.game=Game(len(self.users),game_tick,self.showbase) for u in range(len(self.users)): self.users[u]['warlock']=self.game.warlock[u] taskMgr.doMethodLater(0.5, self.game_loop, 'Game Loop') return task.done #return task.again def game_loop(self,task): # if there is any clients connected if self.server.getClients(): # process incoming packages temp=self.server.getData() if temp!=[]: for i in range(len(temp)): valid_packet=False package=temp[i] if len(package)==2: print "Received: " + str(package) +" "+str(package[1]) if len(package[0])==2: #print "packet right size" # else check to make sure connection has username for u in range(len(self.users)): if self.users[u]['connection']==package[1]: #print "Packet from "+self.users[u]['name'] # process packet # if chat packet if package[0][0]=='destination': print "Destination: "+str(package[0][1]) valid_packet=True # Update warlock data for client self.users[u]['warlock'].set_destination(Vec3(package[0][1][0],package[0][1][1],0)) self.users[u]['new_dest']=True elif package[0][0]=='spell': print "Spell: "+str(package[0][1]) valid_packet=True # Update warlock data for client self.users[u]['warlock'].set_spell(package[0][1][0],package[0][1][1]) self.users[u]['new_spell']=True break #else: # print "couldnt find connection"+str(self.users[u]['connection'])+" "+str(package[1]) # get frame delta time dt=globalClock.getDt() self.game_time+=dt # if time is less than 3 secs (countdown for determining pings of clients) # tick out for clients if (self.game_time>game_tick): # update all clients with new info before saying tick for u in range(len(self.users)): # new warlock destinations if self.users[u]['new_dest']: data = {} data[0]='update_dest' data[1]=u data[2]={} data[2][0]=self.users[u]['warlock'].destination.getX() data[2][1]=self.users[u]['warlock'].destination.getY() self.users[u]['new_dest']=False self.server.broadcastData(data) # new warlock spell elif self.users[u]['new_spell']: data = {} data[0]='update_spell' data[1]=u data[2]=self.users[u]['warlock'].get_spell() data[3]=self.users[u]['warlock'].get_target() self.users[u]['new_spell']=False self.server.broadcastData(data) data = {} data[0]='tick' data[1]=self.tick self.server.broadcastData(data) self.game_time-=game_tick self.tick+=1 # run simulation self.game.run_tick() return task.cont else: taskMgr.doMethodLater(0.5, self.lobby_loop, 'Lobby Loop') return task.done
from panda3d.core import TransformState, CullFaceAttrib from panda3d.core import Light, AmbientLight, Spotlight from panda3d.core import NodePath from panda3d.core import LVector3, LMatrix4 from direct.task.Task import Task from direct.gui.OnscreenText import OnscreenText from direct.showbase.DirectObject import DirectObject import math import random import time import sys import os random.seed() base = ShowBase() base.disableMouse() base.camera.setPos(0, -180, 30) numPrimitives = 0 title = OnscreenText(text="Panda3D: Tutorial - Procedurally Making a Tree", style=1, fg=(1, 1, 1, 1), parent=base.a2dBottomCenter, pos=(0, 0.1), scale=.08) qEvent = OnscreenText( text="Q: Start Scene Over", parent=base.a2dTopLeft, align=TextNode.ALeft, style=1, fg=(1, 1, 1, 1), pos=(0.06, -0.10), scale=.05) wEvent = OnscreenText( text="W: Add Another Tree", parent=base.a2dTopLeft, align=TextNode.ALeft, style=1, fg=(1, 1, 1, 1), pos=(0.06, -0.16),
class PlayWorld(object): def __init__(self, config=None): if config is None: self.config = {} execfile('play_config.py', self.config) else: self.config = config self.reward = None print self.config['pydaq'] if pydaq and self.config.setdefault('pydaq', True) is not None: self.reward = pydaq.GiveReward() self.reward_count = 0 # adjustment to speed so corresponds to gobananas task # 7 seconds to cross original environment # speed needs to be adjusted to both speed in original # environment and c_range of colors # self.speed = 0.05 * (self.c_range[1] - self.c_range[0]) # speed is own variable, so can be changed during training. self.speed = self.config['speed'] # need a multiplier to the joystick output to tolerable speed self.vel_base = 4 self.max_vel = [500, 500, 0] self.base = ShowBase() self.base.disableMouse() # self.base.setFrameRateMeter(True) # assume we are showing windows unless proven otherwise if self.config.get('win', True): # only need inputs if we have a window self.inputs = Inputs(self.base) props = WindowProperties() props.setCursorHidden(True) props.setForeground(True) print self.config.get('resolution') if self.config.get('resolution'): # main window props.set_size(int(self.config['resolution'][0]), int(self.config['resolution'][1])) # props.set_origin(1920, 0) props.set_origin(500, 0) else: props.set_size(600, 600) props.set_origin(400, 50) self.base.win.requestProperties(props) # print 'background color', self.base.getBackgroundColor() # field = self.base.loader.loadModel("../goBananas/models/play_space/field.bam") field = self.base.loader.loadModel( "../goBananas/models/play_space/round_courtyard.bam") field.setPos(0, 0, 0) field.reparent_to(self.base.render) field_node_path = field.find('**/+CollisionNode') field_node_path.node().setIntoCollideMask(0) sky = self.base.loader.loadModel( "../goBananas/models/sky/sky_kahana2.bam") sky.setPos(0, 0, 0) sky.setScale(1.6) sky.reparentTo(self.base.render) windmill = self.base.loader.loadModel( "../goBananas/models/windmill/windmill.bam") windmill.setPos(-10, 30, -1) windmill.setScale(0.03) windmill.reparentTo(self.base.render) # mountain = self.base.loader.loadModel("../goBananas/models/mountain/mountain.bam") # mountain.setScale(0.0005) # mountain.setPos(10, 30, -0.5) # create the avatar self.avatar = NodePath(ActorNode("avatar")) self.avatar.reparentTo(self.base.render) self.avatar.setPos(0, 0, 1) self.avatar.setScale(0.5) pl = self.base.cam.node().getLens() pl.setFov(60) self.base.cam.node().setLens(pl) self.base.camera.reparentTo(self.avatar) # initialize task variables self.frame_task = None self.started_game = None self.showed_match = None self.gave_reward = None # initialize and start the game self.set_next_trial() # print 'end init' def start_loop(self): # need to get new match self.start_play() def start_play(self): print 'start play' # log this # print self.base.render.ls() self.frame_task = self.base.taskMgr.add(self.game_loop, "game_loop") self.frame_task.last = 0 # initiate task time of the last frame def game_loop(self, task): dt = task.time - task.last task.last = task.time velocity = self.inputs.poll_inputs(LVector3(0)) self.move_avatar(dt, velocity) return task.cont def reward_loop(self, task): self.reward_count += 1 if self.reward_count <= self.config['num_beeps']: if self.reward: # log this print 'give a bloody reward already' self.reward.pumpOut() print 'give reward' return task.again else: self.end_loop() return task.done def move_avatar(self, dt, velocity): # print 'velocity', self.velocity self.avatar.setH(self.avatar.getH() - velocity[0] * 1.1) move = LVector3(0, velocity[1], 0) self.avatar.setPos(self.avatar, move * dt * self.vel_base) def give_reward(self): # clear the background self.base.setBackgroundColor(0.41, 0.41, 0.41) print 'give first reward' self.reward_count = 1 if self.reward: # log this self.reward.pumpOut() self.gave_reward = self.base.taskMgr.doMethodLater( self.config['pump_delay'], self.reward_loop, 'reward_loop') def end_loop(self): print 'end loop' # clear avatar map # if there is a match set, return to center of color gradient, # set new match, if applicable self.set_next_trial() def set_next_trial(self): print 'set next trial' # move avatar back to beginning position, only matters for # showing card for next color match # self.avatar.set_pos(-10, -10, 2) # start the game self.start_loop() def check_key_map(self): if self.config['colors'][0]: if self.inputs.key_map['r']: self.config['match_direction'] = ['right'] elif self.inputs.key_map['r'] is not None: self.config['match_direction'] = ['left'] elif self.config['colors'][1]: if self.inputs.key_map['f']: self.config['match_direction'] = ['front'] elif self.inputs.key_map['f'] is not None: self.config['match_direction'] = ['back'] def setup_display2(self, display_node): print 'setup display2' props = WindowProperties() props.set_cursor_hidden(True) props.set_foreground(False) if self.config.get('resolution'): props.setSize(700, 700) props.setOrigin(-int(self.config['resolution'][0] - 5), 5) else: props.setSize(300, 300) props.setOrigin(10, 10) window2 = self.base.openWindow(props=props, aspectRatio=1) lens = OrthographicLens() lens.set_film_size(2, 2) lens.setNearFar(-100, 100) self.render2d = NodePath('render2d') self.render2d.attach_new_node(display_node) camera2d = self.base.makeCamera(window2) camera2d.setPos(0, -10, 0) camera2d.node().setLens(lens) camera2d.reparentTo(self.render2d)
def getPmPerceptualError(mesh, pm_filebuf, mipmap_tarfilebuf): perceptualdiff = which('perceptualdiff') if perceptualdiff is None: raise Exception("perceptualdiff exectuable not found on path") pm_chunks = [] if pm_filebuf is not None: data = pm_filebuf.read(PM_CHUNK_SIZE) refinements_read = 0 num_refinements = None while len(data) > 0: (refinements_read, num_refinements, pm_refinements, data_left) = pdae_utils.readPDAEPartial(data, refinements_read, num_refinements) pm_chunks.append(pm_refinements) data = data_left + pm_filebuf.read(PM_CHUNK_SIZE) tar = tarfile.TarFile(fileobj=mipmap_tarfilebuf) texsizes = [] largest_tarinfo = (0, None) for tarinfo in tar: tarinfo.xsize = int(tarinfo.name.split('x')[0]) if tarinfo.xsize > largest_tarinfo[0]: largest_tarinfo = (tarinfo.xsize, tarinfo) if tarinfo.xsize >= 128: texsizes.append(tarinfo) if len(texsizes) == 0: texsizes.append(largest_tarinfo[1]) texsizes = sorted(texsizes, key=lambda t: t.xsize) texims = [] first_image_data = None for tarinfo in texsizes: f = tar.extractfile(tarinfo) texdata = f.read() if first_image_data is None: first_image_data = texdata texpnm = PNMImage() texpnm.read(StringStream(texdata), 'something.jpg') newtex = Texture() newtex.load(texpnm) texims.append(newtex) mesh.images[0].setData(first_image_data) scene_members = getSceneMembers(mesh) # turn off panda3d printing to stdout nout = MultiplexStream() Notify.ptr().setOstreamPtr(nout, 0) nout.addFile(Filename(os.devnull)) base = ShowBase() rotateNode = GeomNode("rotater") rotatePath = base.render.attachNewNode(rotateNode) matrix = numpy.identity(4) if mesh.assetInfo.upaxis == collada.asset.UP_AXIS.X_UP: r = collada.scene.RotateTransform(0, 1, 0, 90) matrix = r.matrix elif mesh.assetInfo.upaxis == collada.asset.UP_AXIS.Y_UP: r = collada.scene.RotateTransform(1, 0, 0, 90) matrix = r.matrix rotatePath.setMat(Mat4(*matrix.T.flatten().tolist())) geom, renderstate, mat4 = scene_members[0] node = GeomNode("primitive") node.addGeom(geom) if renderstate is not None: node.setGeomState(0, renderstate) geomPath = rotatePath.attachNewNode(node) geomPath.setMat(mat4) wrappedNode = ensureCameraAt(geomPath, base.camera) base.disableMouse() attachLights(base.render) base.render.setShaderAuto() base.render.setTransparency(TransparencyAttrib.MNone) base.render.setColorScaleOff(9999) controls.KeyboardMovement() controls.MouseDrag(wrappedNode) controls.MouseScaleZoom(wrappedNode) controls.ButtonUtils(wrappedNode) controls.MouseCamera() error_data = [] try: tempdir = tempfile.mkdtemp(prefix='meshtool-print-pm-perceptual-error') triangleCounts = [] hprs = [(0, 0, 0), (0, 90, 0), (0, 180, 0), (0, 270, 0), (90, 0, 0), (-90, 0, 0)] for texim in texims: np = base.render.find("**/rotater/collada") np.setTextureOff(1) np.setTexture(texim, 1) for angle, hpr in enumerate(hprs): wrappedNode.setHpr(*hpr) takeScreenshot(tempdir, base, geomPath, texim, angle) triangleCounts.append(getNumTriangles(geomPath)) for pm_chunk in pm_chunks: pdae_panda.add_refinements(geomPath, pm_chunk) for texim in texims: np = base.render.find("**/rotater/collada") np.setTextureOff(1) np.setTexture(texim, 1) for angle, hpr in enumerate(hprs): wrappedNode.setHpr(*hpr) takeScreenshot(tempdir, base, geomPath, texim, angle) triangleCounts.append(getNumTriangles(geomPath)) full_tris = triangleCounts[-1] full_tex = texims[-1] for numtris in triangleCounts: for texim in texims: pixel_diff = 0 for angle, hpr in enumerate(hprs): curFile = '%d_%d_%d_%d.png' % (numtris, texim.getXSize(), texim.getYSize(), angle) curFile = os.path.join(tempdir, curFile) fullFile = '%d_%d_%d_%d.png' % (full_tris, full_tex.getXSize(), full_tex.getYSize(), angle) fullFile = os.path.join(tempdir, fullFile) try: output = subprocess.check_output([ perceptualdiff, '-threshold', '1', fullFile, curFile ]) except subprocess.CalledProcessError as ex: output = ex.output output = output.strip() if len(output) > 0: pixel_diff = max(pixel_diff, int(output.split('\n')[1].split()[0])) error_data.append({ 'triangles': numtris, 'width': texim.getXSize(), 'height': texim.getYSize(), 'pixel_error': pixel_diff }) finally: shutil.rmtree(tempdir, ignore_errors=True) return error_data
def main(): PStatClient.connect() #run pstats in console loadPrcFileData('', 'view-frustum-cull 0') base = ShowBase() print('welp') base.setBackgroundColor(0, 0, 0) base.disableMouse() # TODO init all these into a dict or summat? startup_data() frame_rate() ut = ui_text() grid = Grid3d() axis = Axis3d() cc = CameraControl() # TODO make it so that all the "root" nodes for the secen are initialized in their own space, probably in with defaults or something globalValues.py? # roots # frames XXX FIXME TODO this is a terrible way to pass this around... frames = {'data': GuiFrame('Data view', 'f')} frames['data'].toggle_vis() #asyncio and network setup clientLoop = get_event_loop() #ppe = ProcessPoolExecutor(4) # not sure if 4 is better... ppe = False # serilization is currently broken so we can't use pipes for this #clientLoop.set_default_executor(ppe) rendMan = renderManager(clientLoop, ppe) bs = BoxSel(frames) #, BoxSel.VIS_ALL) # TODO ssl contexts conContext = ssl.create_default_context( purpose=ssl.Purpose.SERVER_AUTH, cadata=None ) # TODO cadata should allow ONLY our self signed, severly annoying to develop... dataContext = ssl.create_default_context(purpose=ssl.Purpose.CLIENT_AUTH) #datCli_base = type('dataClientProtocol',(dataClientProtocol,), #{'set_nodes':rendMan.set_nodes, # FIXME this needs to go through make_nodes #'render_set_send_request':rendMan.set_send_request, #'cache':rendMan.cache, #'event_loop':clientLoop }) # FIXME we could move event_loop to __new__? datCli_base = dataClientProtocol(rendMan.render_callback, rendMan.set_send_request, rendMan.cache, clientLoop) datCli = datCli_base() datCli.connection_lost('START') #rendMan.fake_request() load_points = rendMan.load_points asyncThread = Thread(target=clientLoop.run_forever) asyncThread.start() #make sure we can exit el = exit_cleanup( clientLoop, ppe, datCli.transport) #use this to call stop() on run_forever con = console(locals(), True) ak = AcceptKeys() # this needs to go last after all the classes init base.run( ) # this MUST be called last because we use sys.exit() to terminate print('I AM THE GREATEST')
class MyApp: """The main class.""" def __init__(self): """Start the app.""" self.base = ShowBase() self.base.disableMouse() filters = CommonFilters(self.base.win, self.base.cam) filters.setBloom(blend=(0, 0, 0, 1)) self.base.render.setShaderAuto( BitMask32.allOn() & ~BitMask32.bit(Shader.BitAutoShaderGlow)) ts = TextureStage('ts') ts.setMode(TextureStage.MGlow) tex = self.base.loader.loadTexture('models/black.png') self.base.render.setTexture(ts, tex) self.terrain = Terrain(self.base.render, self.base.loader) minimap_size = 200 self.minimap = Minimap( self.base.win.makeDisplayRegion( 1 - minimap_size / self.base.win.getProperties().getXSize(), 1, 1 - minimap_size / self.base.win.getProperties().getYSize(), 1)) self.minimap.node_path.reparentTo(self.base.render) # self.light_nodes = self.set_lights() self.set_fog() self.key_state = dict.fromkeys(Object.values(config.key_map.character), False) self.set_key_state_handler() self.game_state = "pause" self.toggle_pause() self.selection = Selection(self.base.loader, self.terrain.geom_node) self.selection_text = OnscreenText( mayChange=True, scale=0.07, align=TextNode.ALeft, pos=(0.02 - self.base.getAspectRatio(), 1 - 0.07)) self.timer_text = OnscreenText(mayChange=True, scale=0.07, align=TextNode.ALeft, pos=(0.02 - self.base.getAspectRatio(), -1 + 0.02 + 0.07)) self.enemies = set() self.base.accept(config.key_map.utility.pause, self.toggle_pause) self.base.accept( "q", lambda: self.selection.advance_tower(self.base.loader)) self.base.accept("mouse1", self.player_click) self.base.cam.node().setCameraMask(BitMask32.bit(0)) self.base.setBackgroundColor(*config.map_params.colors.sky) self.player = Player() self.base.taskMgr.add(lambda task: self.terrain.start_up(), "start up") self.mouse_pos = (0.0, 0.0) self.base.taskMgr.add(self.move_player_task, "move_player_task") self.base.taskMgr.add(self.move_enemies_task, "move_enemies_task") self.base.taskMgr.add(self.player_select_task, "player_select_task") self.base.taskMgr.add(self.tower_task, "tower_task") self.base.taskMgr.add(self.check_end_game, "check_end_game_task") rand = Random() rand.seed(config.map_params.seed) self.base.taskMgr.doMethodLater(1, self.clock_task, 'clock_task', extraArgs=[rand]) self.rounds = 0 self.coin = 40 # self.base.setFrameRateMeter(True) def set_fog(self): """Set render distance of camera.""" fog = Fog("Scene fog") fog.setColor(0.7, 0.7, 0.7) fog.setExpDensity(0.01) # self.terrain.geom_node.setFog(fog) self.base.camLens.setFar(4000.0) return fog def set_lights(self): """Set up the lights.""" light_nodes = [None] * 9 for i, dirs in zip(range(9), [0] + Object.values(directions) * 2): dlight = DirectionalLight(f"directional light {i}") if i <= 4: dlight.setColor((0.5, 0.5, 0.5, 0.8)) else: dlight.setColor((2, 2, 2, 2)) light_nodes[i] = self.base.render.attachNewNode(dlight) if i == 0: light_nodes[i].setPos(0, 0, 1) else: light_nodes[i].setPos(*dirs, 0) light_nodes[i].lookAt(0, 0, 0) if i <= 4: self.base.render.setLight(light_nodes[i]) self.terrain.terrain_node.clearLight(light_nodes[i]) else: # self.terrain.terrain_node.setLight(light_nodes[i]) pass alight = AmbientLight('ambient light') alight.setColor((0.3, 0.3, 0.3, 1)) ambient_light_node = self.base.render.attachNewNode(alight) self.base.render.setLight(ambient_light_node) return light_nodes, ambient_light_node def set_key_state_handler(self): """Accept key and records to key_state.""" def set_key_state(key, state): self.key_state[key] = state for key in self.key_state: self.base.accept(key, set_key_state, [key, True]) self.base.accept(key + "-up", set_key_state, [key, False]) def toggle_pause(self): """Toggle pause.""" if self.game_state == "ended": return if self.game_state == "pause": self.game_state = "active" props = WindowProperties() props.setCursorHidden(True) props.setMouseMode(WindowProperties.M_confined) self.base.win.requestProperties(props) else: self.game_state = "pause" props = WindowProperties() props.setCursorHidden(False) props.setMouseMode(WindowProperties.M_absolute) self.base.win.requestProperties(props) print("toggled pause") def move_player_task(self, task): # pylint: disable=unused-argument """The task that handles player movement.""" if self.game_state != "active": return Task.cont if not self.base.mouseWatcherNode.hasMouse(): self.toggle_pause() return Task.cont self.player.update_pos(self.key_state, ClockObject.getGlobalClock().getDt(), lambda pos: self.terrain.get_tile(pos).walkable) self.mouse_pos = ( self.mouse_pos[0] + self.base.mouseWatcherNode.getMouseX(), self.mouse_pos[1] + self.base.mouseWatcherNode.getMouseY(), ) self.player.update_hpr(self.mouse_pos) self.base.win.movePointer(0, self.base.win.getXSize() // 2, self.base.win.getYSize() // 2) self.base.camera.setPos(self.player.pos) self.minimap.set_pos(self.player.pos, self.player.hpr) self.base.camera.setHpr(self.player.hpr) self.terrain.update_player_pos(tuple(self.player.pos)) return Task.cont def move_enemies_task(self, task): # pylint: disable=unused-argument """The task that handles enemy movement.""" if self.game_state != "active": return Task.cont for enemy in set(self.enemies): if not enemy.generated: enemy.generate(self.terrain.path_finder, self.base.loader, self.terrain.geom_node, self.terrain.get_tile) if not enemy.check_active(): self.enemies.remove(enemy) continue # enemy.model.setPos(self.player.pos) enemy.move(ClockObject.getGlobalClock().getDt()) return Task.cont def tower_task(self, task): if self.game_state != "active": return Task.cont for tower in set(self.terrain.towers): if not tower.generated: tower.generate(self.base.loader, self.terrain.geom_node, self.terrain.get_tile) if not tower.check_active(): self.terrain.towers.remove(tower) self.terrain[tower.grid_pos] = Floor() continue tower.move(ClockObject.getGlobalClock().getDt(), self.enemies) tower.generate_bullet(self.base.loader, self.terrain.geom_node, self.terrain.get_tile) return Task.cont def player_select_task(self, task): self.selection.set_selection( self.player.view(self.terrain.get_tile, self.enemies)) self.selection_text.setText(self.selection.get_text()) if self.selection.tower_class != Empty: self.selection.set_disable( self.coin < self.selection.tower_class.cost) return Task.cont def player_click(self): if isinstance(self.selection.select, Floor) and \ issubclass(self.selection.tower_class, Tower) and \ self.selection.tower_class.cost <= self.coin: self.coin -= self.selection.tower_class.cost pos = self.selection.model.getPos() coord_pos = (int(pos[0] // config.map_params.unit_size), int(pos[1] // config.map_params.unit_size)) self.terrain[coord_pos] = self.selection.tower_class(coord_pos) def spawn_enemies(self, rand): if self.game_state != "active": return Task.cont dsts = [tower.model.getPos().length() for tower in self.terrain.towers] radius = max(dsts + [0]) + 100 num = (self.rounds + config.game.sep // 2) // config.game.sep for _ in range(num): theta = rand.uniform(0, 2 * pi) enemy = Kikiboss if _ % 5 or num % 5 else Dabi self.enemies.add(enemy(Vec3(cos(theta), sin(theta), 0) * radius)) return Task.again def clock_task(self, rand): if self.game_state != "active": return Task.cont self.rounds += 1 self.coin += 1 ending = "y" if self.coin <= 1 else "ies" self.timer_text.setText( f"You have {self.coin} cherr{ending}\n" + f"{config.game.sep - self.rounds % config.game.sep}s " + f"until wave {self.rounds // config.game.sep + 1}.") if self.rounds % config.game.sep == 0: return self.spawn_enemies(rand) return Task.again def check_end_game(self, task): if self.terrain[(0, 0)].hp <= 0: if self.game_state == "active": self.toggle_pause() self.game_state = "ended" self.terrain.geom_node.setColorScale(0.2, 0.2, 0.2, 1) OnscreenText(text="GAME OVER", scale=0.2, fg=(1, 0, 0, 1), align=TextNode.ACenter, pos=(0, 0)) OnscreenText(text=f"score: {self.rounds}", scale=0.07, align=TextNode.ACenter, pos=(0, -.15)) return task.done return task.cont def run(self): """Run.""" self.base.run()
def main(): PStatClient.connect() #run pstats in console loadPrcFileData('','view-frustum-cull 0') base = ShowBase() print('welp') base.setBackgroundColor(0,0,0) base.disableMouse() # TODO init all these into a dict or summat? startup_data() frame_rate() ut = ui_text() grid = Grid3d() axis = Axis3d() cc = CameraControl() # TODO make it so that all the "root" nodes for the secen are initialized in their own space, probably in with defaults or something globalValues.py? # roots # frames XXX FIXME TODO this is a terrible way to pass this around... frames = { 'data':GuiFrame('Data view','f') } frames['data'].toggle_vis() #asyncio and network setup clientLoop = get_event_loop() #ppe = ProcessPoolExecutor(4) # not sure if 4 is better... ppe = False # serilization is currently broken so we can't use pipes for this #clientLoop.set_default_executor(ppe) rendMan = renderManager(clientLoop, ppe) bs = BoxSel(frames)#, BoxSel.VIS_ALL) # TODO ssl contexts conContext = ssl.create_default_context(purpose=ssl.Purpose.SERVER_AUTH, cadata=None) # TODO cadata should allow ONLY our self signed, severly annoying to develop... dataContext = ssl.create_default_context(purpose=ssl.Purpose.CLIENT_AUTH) #datCli_base = type('dataClientProtocol',(dataClientProtocol,), #{'set_nodes':rendMan.set_nodes, # FIXME this needs to go through make_nodes #'render_set_send_request':rendMan.set_send_request, #'cache':rendMan.cache, #'event_loop':clientLoop }) # FIXME we could move event_loop to __new__? datCli_base = dataClientProtocol(rendMan.render_callback, rendMan.set_send_request, rendMan.cache, clientLoop) datCli = datCli_base() datCli.connection_lost('START') #rendMan.fake_request() load_points = rendMan.load_points asyncThread = Thread(target=clientLoop.run_forever) asyncThread.start() #make sure we can exit el = exit_cleanup(clientLoop, ppe, datCli.transport) #use this to call stop() on run_forever con = console(locals(), True) ak = AcceptKeys() # this needs to go last after all the classes init base.run() # this MUST be called last because we use sys.exit() to terminate print('I AM THE GREATEST')
def runViewer(mesh): scene_members = getSceneMembers(mesh) loadPrcFileData('', 'win-size 300 300') base = ShowBase() globNode = GeomNode("collada") nodePath = base.render.attachNewNode(globNode) rotateNode = GeomNode("rotater") rotatePath = nodePath.attachNewNode(rotateNode) matrix = numpy.identity(4) if mesh.assetInfo.upaxis == collada.asset.UP_AXIS.X_UP: r = collada.scene.RotateTransform(0, 1, 0, 90) matrix = r.matrix elif mesh.assetInfo.upaxis == collada.asset.UP_AXIS.Y_UP: r = collada.scene.RotateTransform(1, 0, 0, 90) matrix = r.matrix rotatePath.setMat(Mat4(*matrix.T.flatten().tolist())) basecollada = GeomNode("basecollada") basecolladaNP = rotatePath.attachNewNode(basecollada) for geom, renderstate, mat4 in scene_members: node = GeomNode("primitive") node.addGeom(geom) if renderstate is not None: node.setGeomState(0, renderstate) geomPath = basecolladaNP.attachNewNode(node) geomPath.setMat(mat4) for boundlight in mesh.scene.objects('light'): if len(boundlight.color) == 3: color = (boundlight.color[0], boundlight.color[1], boundlight.color[2], 1) else: color = boundlight.color if isinstance(boundlight, collada.light.BoundDirectionalLight): dl = DirectionalLight('dirLight') dl.setColor(Vec4(color[0], color[1], color[2], color[3])) lightNP = rotatePath.attachNewNode(dl) lightNP.lookAt( Point3(boundlight.direction[0], boundlight.direction[1], boundlight.direction[2])) elif isinstance(boundlight, collada.light.BoundAmbientLight): ambientLight = AmbientLight('ambientLight') ambientLight.setColor(Vec4(color[0], color[1], color[2], color[3])) lightNP = rotatePath.attachNewNode(ambientLight) elif isinstance(boundlight, collada.light.BoundPointLight): pointLight = PointLight('pointLight') pointLight.setColor(Vec4(color[0], color[1], color[2], color[3])) pointLight.setAttenuation( Vec3(boundlight.constant_att, boundlight.linear_att, boundlight.quad_att)) lightNP = rotatePath.attachNewNode(pointLight) lightNP.setPos( Vec3(boundlight.position[0], boundlight.position[1], boundlight.position[2])) elif isinstance(boundlight, collada.light.BoundSpotLight): spotLight = Spotlight('spotLight') spotLight.setColor(Vec4(color[0], color[1], color[2], color[3])) spotLight.setAttenuation( Vec3(boundlight.constant_att, boundlight.linear_att, boundlight.quad_att)) spotLight.setExponent(boundlight.falloff_exp) lightNP = rotatePath.attachNewNode(spotLight) lightNP.setPos( Vec3(boundlight.position[0], boundlight.position[1], boundlight.position[2])) lightNP.lookAt( Point3(boundlight.direction[0], boundlight.direction[1], boundlight.direction[2]), Vec3(boundlight.up[0], boundlight.up[1], boundlight.up[2])) else: print 'Unknown light type', boundlight continue base.render.setLight(lightNP) for boundcam in mesh.scene.objects('camera'): if isinstance(boundcam, collada.camera.BoundPerspectiveCamera): base.camera.reparentTo(rotatePath) base.camLens.setNear(boundcam.znear) base.camLens.setFar(boundcam.zfar) if boundcam.xfov is not None and boundcam.yfov is not None: #xfov + yfov base.camLens.setFov(boundcam.xfov, boundcam.yfov) elif boundcam.xfov is not None and boundcam.aspect_ratio is not None: #xfov + aspect_ratio base.camLens.setFov(boundcam.xfov) base.camLens.setAspectRatio(boundcam.aspect_ratio) elif boundcam.yfov is not None and boundcam.aspect_ratio is not None: #yfov + aspect_ratio #aspect_ratio = tan(0.5*xfov) / tan(0.5*yfov) xfov = math.degrees( 2.0 * math.atan(boundcam.aspect_ratio * math.tan(math.radians(0.5 * boundcam.yfov)))) base.camLens.setFov(xfov, boundcam.yfov) elif boundcam.yfov is not None: #yfov only #aspect_ratio = tan(0.5*xfov) / tan(0.5*yfov) xfov = math.degrees( 2.0 * math.atan(base.camLens.getAspectRatio() * math.tan(math.radians(0.5 * boundcam.yfov)))) base.camLens.setFov(xfov, boundcam.yfov) elif boundcam.xfov is not None: base.camLens.setFov(boundcam.xfov) base.camera.setPos( Vec3(boundcam.position[0], boundcam.position[1], boundcam.position[2])) base.camera.lookAt( Point3(boundcam.direction[0], boundcam.direction[1], boundcam.direction[2]), Vec3(boundcam.up[0], boundcam.up[1], boundcam.up[2])) elif isinstance(boundcam, collada.camera.BoundOrthographicCamera): lens = OrthographicLens() base.cam.node().setLens(lens) base.camLens = lens base.camera.reparentTo(rotatePath) base.camLens.setNear(boundcam.znear) base.camLens.setFar(boundcam.zfar) if boundcam.xmag is not None and boundcam.ymag is not None: #xmag + ymag base.camLens.setFilmSize(boundcam.xmag, boundcam.ymag) elif boundcam.xmag is not None and boundcam.aspect_ratio is not None: #xmag + aspect_ratio base.camLens.setFilmSize(boundcam.xmag) base.camLens.setAspectRatio(boundcam.aspect_ratio) elif boundcam.ymag is not None and boundcam.aspect_ratio is not None: #ymag + aspect_ratio xmag = boundcam.aspect_ratio * boundcam.ymag base.camLens.setFilmSize(xmag, boundcam.ymag) elif boundcam.ymag is not None: #ymag only xmag = base.camLens.getAspectRatio() * boundcam.ymag base.camLens.setFilmSize(xmag, boundcam.ymag) elif boundcam.xmag is not None: base.camLens.setFilmSize(boundcam.xmag) base.camera.setPos( Vec3(boundcam.position[0], boundcam.position[1], boundcam.position[2])) base.camera.lookAt( Point3(boundcam.direction[0], boundcam.direction[1], boundcam.direction[2]), Vec3(boundcam.up[0], boundcam.up[1], boundcam.up[2])) else: print 'Unknown camera type', boundcam continue base.disableMouse() base.render.setShaderAuto() base.render.setTransparency(TransparencyAttrib.MDual, 1) KeyboardMovement() MouseDrag(basecolladaNP) MouseScaleZoom(basecolladaNP) base.run()
def main(): import pickle from .util.util import ui_text, console, exit_cleanup, frame_rate, startup_data from .keys import AcceptKeys from .render_manager import renderManager from .ui import CameraControl, Axis3d, Grid3d base = ShowBase() base.setBackgroundColor(0, 0, 0) base.disableMouse() startup_data() console() exit_cleanup() frame_rate() CameraControl() Axis3d() Grid3d() r = renderManager() from .test_objects import makeSimpleGeom import numpy as np from .trees import treeMe from uuid import uuid4 from panda3d.core import GeomLinestrips n = 1000 #positions = np.array([i for i in zip(np.linspace(-1000,1000,n),np.linspace(-1000,1000,n),np.linspace(-1000,1000,n))]) # wat 1 #positions = np.array([i for i in zip(np.linspace(-1000,1000,n),np.linspace(-1000,1000,n),np.zeros(n))]) # wat 2 positions = np.array([ i for i in zip(np.linspace(-1000, 1000, n), np.zeros(n), np.zeros(n)) ]) #positions = np.random.randint(-1000,1000,(n,3)) # so it turns out that the collision nodes don't render properly on this, the tree constructed with math is correct, the rendering is not r.geomRoot.attachNewNode(makeSimpleGeom(positions, (1, 1, 1, 1))) uuids = np.array(['%s' % uuid4() for _ in range(n)]) bounds = np.ones(n) * .5 treeMe(r.collRoot, positions, uuids, bounds) base.camLens.setFov(90) n = 1E4 # apparently 1e8 is a bit too big and 1e7 is slowwww... definitely need downsampling positions = np.array([ i for i in zip(10 * np.sin(np.arange(0, n)), np.arange(0, n), 10 * np.cos(np.arange(0, n))) ]) # fukken saved r.geomRoot.attachNewNode( makeSimpleGeom(positions, (1, 1, 1, 1), geomType=GeomLinestrips)) #with open('edge_case_data_tuple.pickle','rb') as f: #data_tuple = pickle.load(f) #r.cache['edgecase'] = False #r.set_nodes('edgecase',data_tuple) sgn = GeomNode('srct') sgn.addGeom(makeSelectRect()) sn = render.attachNewNode(sgn) sn.setSx(10) sn.setSy(10) sn.setColor(.5, .5, .5, .5) ut = ui_text() dt = BoxSel(visualize=BoxSel.VIS_ALL) ac = AcceptKeys() base.run()
class CrossTraining(JoystickHandler): def __init__(self): self.base = ShowBase() config = {} execfile('cross_config.py', config) if not unittest: JoystickHandler.__init__(self) self.base.disableMouse() print('Subject is', config['subject']) # set up reward system if config['reward'] and PYDAQ_LOADED: self.reward = pydaq.GiveReward() print 'pydaq' else: self.reward = None self.frameTask = self.base.taskMgr.add(self.frame_loop, "frame_loop") if not unittest: wp = WindowProperties() wp.setSize(1280, 800) wp.setOrigin(0, 0) base.win.requestProperties(wp) self.crosshair = TextNode('crosshair') self.crosshair.setText('+') textNodePath = aspect2d.attachNewNode(self.crosshair) textNodePath.setScale(0.2) self.setup_inputs() # starting variables. "suppose" to be initiated here, which makes it silly # to then have them again, but kind of necessary to test. Making PyCharm happy ;-) self.x_mag = 0 self.y_mag = 0 # variables for counting how long to hold joystick self.js_count = 0 # how much to push joystick before reward self.js_goal = config['goal'] # (count increases before checking for goal match) # default is to reward for backward movement. May want # to make this a configuration option instead. # zero, all backward allowed # one, straight backward not rewarded # two, no backward rewarded self.backward = config['backward'] self.forward = True self.right = True self.left = True # all kinds of start defaults self.delay_start = False self.reward_delay = False self.reward_time = config['pulseInterval'] # 200 ms self.reward_override = False self.reward_on = True self.current_dir = None self.frameTask.delay = 0 print 'initialized' def frame_loop(self, task): # delay_start means we just gave reward and need to set wait time if self.delay_start: task.delay = task.time + self.reward_time #print('time now', task.time) #print('delay until', task.delay) self.delay_start = False #self.reward_delay = True return task.cont if task.time > task.delay: self.reward_on = True if self.backward > 0 or not self.forward: #print 'check y axis' # if we are not allowing a y dir, also need to check y dir. x_test = -0.1 < self.x_mag < 0.1 #print x_test #print self.y_mag if self.backward == 1 and self.y_mag > 0 and x_test: # don't allow straight back (within x tolerance) self.reward_on = False #print 'backward' #print self.y_mag if self.backward == 2 and self.y_mag > 0.1: print self.y_mag, self.x_mag # don't allow any backward, but make the threshold higher # this way movements to left or right that happen to be slightly # backward still get rewarded, back small amount still nor rewarded, # since we are under the threshold self.reward_on = False if self.forward == 1 and self.y_mag < 0.1 and x_test: # if going straight forward (within x tolerance) self.reward_on = False if not self.left or not self.right: #print 'check x axis' # if we are not allowing an x dir, also need to check y dir. y_test = -0.1 < self.y_mag < 0.1 #print y_test #print self.x_mag if not self.right and self.x_mag > 0 and y_test: # don't allow straight right (within y tolerance) self.reward_on = False #print 'backward' #print self.y_mag if not self.left and self.x_mag < 0.1 and y_test: # if going straight left (within y tolerance) self.reward_on = False #print dist if self.reward_on: dist = sqrt(self.x_mag**2 + self.y_mag**2) #print dist if dist > 0.1: # eligible for reward. if not getting reward, # need to turn on reward_delay so wait proper amount #print 'ok for reward' self.js_count += 1 if self.js_count != self.js_goal: self.delay_start = True self.reward_on = False #print 'counts for reward' else: #print 'no reward' self.reward_on = False self.js_count = 0 # actual reward condition if self.reward_on or self.reward_override: #print 'reward' #print self.y_mag self.crosshair.setTextColor(1, 0, 0, 1) self.give_reward() self.js_count = 0 else: self.crosshair.setTextColor(1, 1, 1, 1) return task.cont def give_reward(self): if self.reward: self.reward.pumpOut() print('beep') # must now wait for pump delay. self.delay_start = True def move(self, js_dir, js_input): print('move') print(js_dir, js_input) if js_dir == 'x': self.x_mag = js_input else: self.y_mag = js_input def start_reward(self): self.reward_override = True def stop_reward(self): self.reward_override = False def inc_js_goal(self): self.js_goal += 1 print('new goal', self.js_goal) def dec_js_goal(self): self.js_goal -= 1 if self.js_goal < 1: self.js_goal = 1 print('new goal', self.js_goal) def allow_backward(self): self.backward += 1 if self.backward > 2: self.backward = 0 print('backward allowed:', self.backward) def allow_forward(self): self.forward = not self.forward print('forward allowed:', self.forward) def allow_left(self): self.left = not self.left print('left allowed:') def allow_right(self): self.right = not self.right print('right allowed:') def setup_inputs(self): self.accept('x_axis', self.move, ['x']) self.accept('y_axis', self.move, ['y']) self.accept('q', self.close) self.accept('e', self.inc_js_goal) self.accept('d', self.dec_js_goal) self.accept('b', self.allow_backward) self.accept('f', self.allow_forward) self.accept('r', self.allow_right) self.accept('l', self.allow_left) self.accept('space', self.start_reward) self.accept('space-up', self.stop_reward) def reset_variables(self): print('reset') # reset everything except stuff from config file self.x_mag = 0 self.y_mag = 0 # variables for counting how long to hold joystick self.js_count = 0 # eventually may want start goal in config file # (count increases before checking for goal match) self.js_goal = 1 # start out just have to hit joystick # all kinds of start defaults self.delay_start = False self.reward_delay = False self.reward_override = False self.reward_on = True self.current_dir = None self.frameTask.delay = 0 def close(self): sys.exit()
def getPmPerceptualError(mesh, pm_filebuf, mipmap_tarfilebuf): perceptualdiff = which('perceptualdiff') if perceptualdiff is None: raise Exception("perceptualdiff exectuable not found on path") pm_chunks = [] if pm_filebuf is not None: data = pm_filebuf.read(PM_CHUNK_SIZE) refinements_read = 0 num_refinements = None while len(data) > 0: (refinements_read, num_refinements, pm_refinements, data_left) = pdae_utils.readPDAEPartial(data, refinements_read, num_refinements) pm_chunks.append(pm_refinements) data = data_left + pm_filebuf.read(PM_CHUNK_SIZE) tar = tarfile.TarFile(fileobj=mipmap_tarfilebuf) texsizes = [] largest_tarinfo = (0, None) for tarinfo in tar: tarinfo.xsize = int(tarinfo.name.split('x')[0]) if tarinfo.xsize > largest_tarinfo[0]: largest_tarinfo = (tarinfo.xsize, tarinfo) if tarinfo.xsize >= 128: texsizes.append(tarinfo) if len(texsizes) == 0: texsizes.append(largest_tarinfo[1]) texsizes = sorted(texsizes, key=lambda t: t.xsize) texims = [] first_image_data = None for tarinfo in texsizes: f = tar.extractfile(tarinfo) texdata = f.read() if first_image_data is None: first_image_data = texdata texpnm = PNMImage() texpnm.read(StringStream(texdata), 'something.jpg') newtex = Texture() newtex.load(texpnm) texims.append(newtex) mesh.images[0].setData(first_image_data) scene_members = getSceneMembers(mesh) # turn off panda3d printing to stdout nout = MultiplexStream() Notify.ptr().setOstreamPtr(nout, 0) nout.addFile(Filename(os.devnull)) base = ShowBase() rotateNode = GeomNode("rotater") rotatePath = base.render.attachNewNode(rotateNode) matrix = numpy.identity(4) if mesh.assetInfo.upaxis == collada.asset.UP_AXIS.X_UP: r = collada.scene.RotateTransform(0,1,0,90) matrix = r.matrix elif mesh.assetInfo.upaxis == collada.asset.UP_AXIS.Y_UP: r = collada.scene.RotateTransform(1,0,0,90) matrix = r.matrix rotatePath.setMat(Mat4(*matrix.T.flatten().tolist())) geom, renderstate, mat4 = scene_members[0] node = GeomNode("primitive") node.addGeom(geom) if renderstate is not None: node.setGeomState(0, renderstate) geomPath = rotatePath.attachNewNode(node) geomPath.setMat(mat4) wrappedNode = ensureCameraAt(geomPath, base.camera) base.disableMouse() attachLights(base.render) base.render.setShaderAuto() base.render.setTransparency(TransparencyAttrib.MNone) base.render.setColorScaleOff(9999) controls.KeyboardMovement() controls.MouseDrag(wrappedNode) controls.MouseScaleZoom(wrappedNode) controls.ButtonUtils(wrappedNode) controls.MouseCamera() error_data = [] try: tempdir = tempfile.mkdtemp(prefix='meshtool-print-pm-perceptual-error') triangleCounts = [] hprs = [(0, 0, 0), (0, 90, 0), (0, 180, 0), (0, 270, 0), (90, 0, 0), (-90, 0, 0)] for texim in texims: np = base.render.find("**/rotater/collada") np.setTextureOff(1) np.setTexture(texim, 1) for angle, hpr in enumerate(hprs): wrappedNode.setHpr(*hpr) takeScreenshot(tempdir, base, geomPath, texim, angle) triangleCounts.append(getNumTriangles(geomPath)) for pm_chunk in pm_chunks: pdae_panda.add_refinements(geomPath, pm_chunk) for texim in texims: np = base.render.find("**/rotater/collada") np.setTextureOff(1) np.setTexture(texim, 1) for angle, hpr in enumerate(hprs): wrappedNode.setHpr(*hpr) takeScreenshot(tempdir, base, geomPath, texim, angle) triangleCounts.append(getNumTriangles(geomPath)) full_tris = triangleCounts[-1] full_tex = texims[-1] for numtris in triangleCounts: for texim in texims: pixel_diff = 0 for angle, hpr in enumerate(hprs): curFile = '%d_%d_%d_%d.png' % (numtris, texim.getXSize(), texim.getYSize(), angle) curFile = os.path.join(tempdir, curFile) fullFile = '%d_%d_%d_%d.png' % (full_tris, full_tex.getXSize(), full_tex.getYSize(), angle) fullFile = os.path.join(tempdir, fullFile) try: output = subprocess.check_output([perceptualdiff, '-threshold', '1', fullFile, curFile]) except subprocess.CalledProcessError as ex: output = ex.output output = output.strip() if len(output) > 0: pixel_diff = max(pixel_diff, int(output.split('\n')[1].split()[0])) error_data.append({'triangles': numtris, 'width': texim.getXSize(), 'height': texim.getYSize(), 'pixel_error': pixel_diff}) finally: shutil.rmtree(tempdir, ignore_errors=True) return error_data
class TrainingBananas(JoystickHandler): def __init__(self): """ Initialize the experiment """ pydaq_loaded = PYDAQ_LOADED self.base = ShowBase() config = {} execfile('train_config.py', config) if not unittest: JoystickHandler.__init__(self) self.base.disableMouse() sys.stdout.write('Subject is ' + str(config['subject']) + '\n') self.subject = config['subject'] self.levels_available = [[2, 2.1, 2.2, 2.3, 2.4, 2.5, 2.6], [3, 3.1], [4, 4.1, 4.2]] # set up reward system # if unit-testing, pretend like we couldn't # load the module if unittest: pydaq_loaded = False if config['reward'] and pydaq_loaded: self.reward = pydaq.GiveReward() else: self.reward = None sys.stdout.write('Warning: reward system not on \n') # setup windows if not unittest: # if doing unittests, there is no window wp = WindowProperties() # wp.setSize(1280, 800) wp.setSize(1024, 768) wp.setOrigin(0, 0) wp.setCursorHidden(True) self.base.win.requestProperties(wp) # base.setFrameRateMeter(True) # initialize training file name self.data_file_name = '' self.data_file = None self.open_data_file(config) # Get initial direction, only matters for manual, random will override later # for bananas, changing the angle from avatar to banana, so left is negative # right is positive. if config['trainingDirection'] == 'Right': self.multiplier = 1 elif config['trainingDirection'] == 'Left': self.multiplier = -1 # print config['trainingDirection'] self.last_multiplier = self.multiplier # get more variables from configuration self.side_bias = config['random_bias'] # bring some configuration parameters into memory, so we don't need to # reload the config file multiple times, also allows us to change these # variables dynamically self.num_beeps = config['numBeeps'] # not changing now, but may eventually... self.x_alpha = config['xHairAlpha'] self.reward_time = config['pulseInterval'] # usually 200ms # amount need to hold crosshair on banana to get reward (2.3) # must be more than zero. At 1.5 distance, must be greater than # 0.5 to require stopping self.hold_aim = config['hold_aim'] self.initial_speed = config['initial_turn_speed'] self.initial_forward_speed = config['initial_forward_speed'] self.forward_limit = config['forward_limit'] self.training = config['training'] if not unittest: sys.stdout.write('training level: ' + str(self.training) + '\n') if self.training < 2.2: sys.stdout.write('starting direction: ' + str(config['trainingDirection']) + '\n') # random selection used for training 2.3 and above self.all_random_selections = config['random_lists'] self.current_choice = config['random_selection'] - 1 self.random_choices = self.all_random_selections[self.current_choice] # Setup Graphics # bitmasks for collisions ray_mask = BitMask32(0x1) sphere_mask = BitMask32(0x2) self.mask_list = [ray_mask, sphere_mask, ray_mask | sphere_mask] if config['background']: field = self.base.loader.loadModel("models/play_space/field.bam") field.setPos(Point3(0, 0, 0)) field.reparentTo(self.base.render) field_node_path = field.find('**/+CollisionNode') field_node_path.node().setIntoCollideMask(0) sky = self.base.loader.loadModel("models/sky/sky.bam") sky.setPos(Point3(0, 0, 0)) sky.reparentTo(self.base.render) # set up banana self.banana = None self.banana_mask = None self.banana_node_path = None self.banana_coll_node = None self.load_fruit(config.get('fruit', 'banana')) # set up collision system and collision ray to camera self.base.cTrav = CollisionTraverser() self.collHandler = CollisionHandlerQueue() ray_node = self.base.camera.attachNewNode(CollisionNode('CrossHairRay')) # ray that comes straight out from the camera ray_solid = CollisionRay(0, 0, 0, 0, 1, 0) self.ray_node_path = self.make_coll_node_path(ray_node, ray_solid) self.ray_node_path.node().setIntoCollideMask(0) self.ray_node_path.node().setFromCollideMask(ray_mask) # add collision sphere to camera sphere_node = self.base.camera.attachNewNode(CollisionNode('CollisionSphere')) # camera_sphere = CollisionSphere(0, 0, 0, 1.3) # avatar_radius = 0.3 avatar_radius = 1 camera_sphere = CollisionSphere(0, 0, 0, avatar_radius) self.sphere_node_path = self.make_coll_node_path(sphere_node, camera_sphere) self.sphere_node_path.node().setIntoCollideMask(0) self.sphere_node_path.node().setFromCollideMask(sphere_mask) # into collide masks are set with level variables, since we change # whether between using the sphere or the ray for detecting collisions, # depending on which level we are on. self.base.cTrav.addCollider(self.ray_node_path, self.collHandler) self.base.cTrav.addCollider(self.sphere_node_path, self.collHandler) # self.base.cTrav.showCollisions(self.base.render) # self.ray_node_path.show() # self.sphere_node_path.show() # self.banana_node_path.show() # self.base.render.find('**/+CollisionNode').show() # Camera self.base.camLens.setFov(60) # set avatar position/heading # Default positions self.avatar_pos = Point3(0, -1.5, 1) self.avatar_h = 0 self.screen_edge = 30 self.config_avatar_d = -config['avatar_start_d'] self.config_avatar_h = config['avatar_start_h'] # Cross hair # color changes for crosshair self.x_start_c = Point4(1, 1, 1, self.x_alpha) self.x_stop_c = Point4(1, 0, 0, self.x_alpha) self.crosshair = TextNode('crosshair') self.crosshair.setText('+') text_node_path = self.base.aspect2d.attachNewNode(self.crosshair) text_node_path.setScale(0.2) # crosshair is always in center, but # need it to be in same place as collisionRay is, but it appears that center is # at the bottom left of the collisionRay, and the top right of the text, so they # don't have center in the same place. Makes more sense to move text than ray. # These numbers were scientifically determined. JK, moved around until the cross looked # centered on the ray # crosshair_pos = Point3(0, 0, 0) # crosshair_pos = Point3(-0.07, 0, -0.05) crosshair_pos = Point3(-0.055, 0, -0.03) # print text_node_path.getPos() text_node_path.setPos(crosshair_pos) # set level # setup variables related to training levels # initialize training variables # will be set to proper levels in set_level_variables method self.free_move = 0 self.must_release = False self.random_banana = False self.require_aim = False self.go_forward = False #self.set_level_variables(self.training) # setup keyboard/joystick inputs self.setup_inputs() # Initialize more variables # These variables are set to their initial states in reset_variables, so # does not matter what they are set to here. # DO NOT SET VARIABLES HERE, GO TO RESET_VARIABLES!!! # variable used to notify when changing direction of new target self.new_dir = None # and variable to notify when changing levels self.change_level = False self.max_angle = None self.min_angle = None self.delay_start = False self.yay_reward = False self.reward_delay = False self.reward_on = True self.reward_count = 0 self.x_mag = 0 self.y_mag = 0 self.speed = self.initial_speed # factor to slow down movement of joystick and control acceleration # speed for going in the wrong direction, when same speed as initial speed, then no change self.forward_speed = self.initial_forward_speed self.wrong_speed = 0.005 self.slow_speed = self.wrong_speed # toggle for whether moving is allowed or not self.moving = True # toggle for making sure stays on banana for min time for 2.3 self.set_zone_time = False # keeps track of how long we have held self.hold_time = 0 self.check_zone = False # self.check_time = 0 # toggle for when trial begins self.start_trial = True # print self.avatar_h # print self.base.camera.getH() # print self.avatar_pos # print self.base.camera.getPos() # print self.base.camLens.getFov() # print self.base.camLens.getNear() # print self.base.camLens.getFar() # print self.base.camLens.getAspectRatio() self.base.camLens.setNear(avatar_radius/3.0) # print self.banana.getPos() # set variables to their actual starting values self.reset_variables() self.set_level_variables(self.training) # print 'set level' self.set_camera() # print 'set camera' # start stuff happening! self.start_task() def frame_loop(self, task): # print self.training # print 'loop' dt = task.time - task.last task.last = task.time # print('dt', dt) # delay_start means we just gave reward and need to set wait # until reward pump is done to do anything if self.delay_start: task.delay = task.time + self.reward_time # print('time now', task.time) # print('delay until', task.delay) self.delay_start = False # self.reward_delay = True return task.cont # set_zone_time means we have the crosshair over the banana, # and have to set how long to leave it there if self.set_zone_time: # print 'reset zone time' self.hold_time = task.time + self.hold_aim self.set_zone_time = False self.check_zone = True # reward delay is over, on to regularly scheduled program if task.time > task.delay: # print 'past delay' # check for reward # print('beeps so far', self.reward_count) # print self.yay_reward if self.yay_reward == 'partial': # print 'giving partial reward' self.give_reward() self.yay_reward = None self.go_forward = True # since none, don't need to return, won't give more reward, but # will go on to let move elif self.yay_reward and self.reward_count < self.num_beeps: # print 'gave reward' self.reward_count += 1 self.give_reward() return task.cont elif self.yay_reward and self.reward_count == self.num_beeps: # print 'gave final reward' # done giving reward, time to start over, maybe # hide the banana self.banana.stash() # change the color of the crosshair self.x_change_color(self.x_start_c) # before we can proceed, subject may need to let go of the joystick if self.must_release: # print 'checking for release' # print self.x_mag if abs(self.x_mag) > 0 or abs(self.y_mag) > 0: # print('let go!') return task.cont # and now we can start things over again # print('start over') self.restart_bananas() # check_time is used to see how long it takes subject # to get banana from time plotted # self.check_time = task.time return task.cont # check to see if we are moving if self.moving: # moving, forward first, only bother checking if possible to go forward if self.go_forward: # forward needs a little speed boost compared to turning if self.start_trial or self.y_mag == 0: self.forward_speed = self.initial_forward_speed self.start_trial = False else: # self.y_mag (how much you push the joystick) affects # acceleration as well as speed self.forward_speed += self.initial_forward_speed * abs(self.y_mag) position = self.base.camera.getPos() # print(position) # print('y_mag', self.y_mag) # print('speed', self.speed) # print('dt', dt) # print('change in position', self.y_mag * self.speed * dt) position[1] += self.y_mag * self.forward_speed * dt # if this puts us past center, stay at center if position[1] > 0: position[1] = 0 self.base.camera.setPos(position) # Now check for rotation. Don't need to check this if going forward if not self.go_forward: # print 'rotating' heading = self.base.camera.getH() delta_heading = self.get_new_heading(heading, dt) self.base.camera.setH(heading + delta_heading) # print('camera heading', self.base.camera.getH()) # check for collision: collide_banana = self.check_banana() # print('collide', collide_banana) # if we need to be stopping and leaving (holding) crosshair over banana, # make sure still in target zone. if self.check_zone: # print('check hold') # not sure if I will use a zone for going forward yet # The 'zone' is whenever the ray is colliding with the banana. # use zone for both left-right training and for forward training, # whenever self.require_aim is true. # with forward training, use to see if we went off course, and then # lined up the crosshair and banana again. # print collide_banana if collide_banana: # print('still in the zone') if task.time > self.hold_time: # print('hold aim', self.hold_aim) # print('ok, get reward') # print self.free_move # print('hold time', task.time > self.hold_time) # stop moving and get reward if self.free_move == 4: # partial reward for lining up banana in level 4.x # print 'partial reward' self.yay_reward = 'partial' self.check_zone = False elif self.yay_reward is not None: self.x_change_color(self.x_stop_c) self.moving = False self.yay_reward = True self.check_zone = False else: pass # print('keep holding') # print('time', task.time) # print('hold until', self.hold_time) else: # print('left zone, wait for another collision') self.x_change_color(self.x_start_c) # print('require aim', self.require_aim) if self.require_aim == 'slow': # print 'aim slow' self.check_zone = None else: # print "don't slow down" self.check_zone = False else: # not currently checking zone, so either collide_banana means reward immediately # or start timer to check if leaving zone # print('camera heading before collision', self.base.camera.getH()) if collide_banana: # print('time took: ', task.time - self.check_time) # print 'collision' # print 'change xhair color to red' self.x_change_color(self.x_stop_c) # if we require aim, we start timer when we have a collision, # but if self.go_forward, than we have already aimed. if self.require_aim and not self.go_forward: self.set_zone_time = True else: # print 'yes' # reward time! # stop moving self.moving = False # move to center if self.base.camera.getH != 0: pass # print 'moved camera' # self.base.camera.setH(0) self.yay_reward = True elif collide_banana is None: # partial reward for lining up banana in level 4.x # print 'partial reward' self.yay_reward = 'partial' # self.yay_reward = True # self.reward_count = self.num_beeps - 1 return task.cont def give_reward(self): # print('beep') if self.reward: self.reward.pumpOut() if not unittest: self.data_file.write(str(self.frameTask.time) + ', ' + 'reward' + '\n') self.delay_start = True def check_banana(self): # print 'check banana' collide_banana = False # print self.base.camera.getPos() # if we are doing only forward, or only side, only need to check for entries, # but if doing both movement, have to check for whichever we are currently # interested in. if self.free_move == 4: # why doesn't the camera show that we see the banana, ever? wrong camera? # print self.base.camNode.isInView(self.banana.getPos()) for i in range(self.collHandler.getNumEntries()): entry = self.collHandler.getEntry(i) # in_view = self.base.camNode.isInView(entry.getIntoNodePath().getPos()) # print in_view # print entry.getIntoNodePath().getPos() if entry.getFromNodePath() == self.sphere_node_path: # print 'ran into banana going forward' collide_banana = True self.moving = False elif entry.getFromNodePath() == self.ray_node_path: # print 'collide ray' # print self.yay_reward # if we are requiring aim, than use collide_banana = True, # since this will automatically get diverted before full reward if self.yay_reward is not None and not self.require_aim: # print 'lined up banana from side' collide_banana = None elif self.yay_reward is not None and self.require_aim: # print 'lined up banana from side, need to aim' collide_banana = True # print entry.getFromNodePath() elif self.collHandler.getNumEntries() > 0: # print 'collided' # the only object we can be running into is the banana, so there you go... collide_banana = True # print self.collHandler.getEntries() # print self.base.camera.getH() # print self.base.camera.getPos() # print self.banana.getPos() return collide_banana def restart_bananas(self): # print 'restarted' # print('training', self.training) # reset a couple of variables self.yay_reward = False self.reward_count = 0 # self.check_time = 0 # used to reset speed self.start_trial = True # print self.multiplier # check to see if we are switching the banana to the other side if self.new_dir is not None: self.multiplier = self.new_dir self.new_dir = None # for some versions, subject could still be holding joystick at this point. # (for example, was going to the right, but now is suppose to be going to the left, # but since we only detect when the joystick position has changed, and it has # not, may not realize that that we are now going what is considered a 'wrong' direction # so we are essentially re-checking the the joystick position, given the other updated # parameters). # send the current joystick position through the move method to correct that. # the original signal had its sign changed, so switch the sign here as well. # print 'move' self.move('x', -self.x_mag) #print('change direction', -self.x_mag) if self.change_level: # print 'actually change level now' self.set_level_variables(self.change_level) print('angle', self.base.camera.getH()) self.change_level = False # check to see if banana is on random if self.random_banana: # print 'random' # make side not entirely random. Don't want too many in a row on one side # for MP, because he is a bit of an idiot. # First check if we care about the next direction if self.side_bias and abs(self.last_multiplier) > 1: # if there have been two in a row in the same direction, pick the opposite # direction, otherwise choose randomly # print 'change, self.last_multiplier is zero' self.multiplier = - self.multiplier else: # print 'random' self.multiplier = random.choice([1, -1]) # print('next up', self.multiplier) # multiplier should never be zero when doing this comparison # last_multiplier is the only one that can be zero, and only # very briefly # if this gives you a negative 1, than we are switching sides, # if we don't care about side_bias, we don't look at last_multiplier, # and this doesn't matter if self.last_multiplier/self.multiplier != 1: # print 'reset' self.last_multiplier = 0 self.last_multiplier += self.multiplier # print('last currently', self.last_multiplier) self.avatar_h = random.choice(self.random_choices) # for some versions, subject could still be holding joystick at this point. # this means we x_mag is at a position that might no longer be # allowed, so we are going to send the current joystick position # through the move method to correct that. move switches the sign, so switch # the sign here as well. # print 'move' self.move('x', -self.x_mag) self.set_camera() if not unittest: self.data_file.write(str(self.frameTask.time) + ', ' + 'banana position, ' + str(self.multiplier * self.avatar_h) + '\n') # print('min time to reward:', sqrt(2 * self.avatar_h / 0.05 * 0.01)) # for training 4, switch from going forward to left/right if self.free_move == 4: self.go_forward = False # un-hide banana self.banana.unstash() # print 'avatar can move again, new trial starting' self.moving = True # print('yay', self.yay_reward) def start_task(self): self.frameTask = self.base.taskMgr.add(self.frame_loop, "frame_loop") self.frameTask.delay = -0.1 # want initial delay less than zero self.frameTask.last = 0 # task time of the last frame #print 'set task' if not unittest: self.data_file.write(str(self.frameTask.time) + ', ' + 'banana position, ' + str(self.multiplier * self.avatar_h) + '\n') def set_camera(self): self.base.camera.setH(self.multiplier * abs(self.avatar_h)) self.base.camera.setPos(self.avatar_pos) #print self.base.camera.getPos() #print self.banana.getPos() # print self.base.camera.getH() sys.stdout.write('current angle: ' + str(self.base.camera.getH()) + '\n') def x_change_color(self, color): # print self.crosshair.getColor() self.crosshair.setTextColor(color) # self.cross.setColor(Point4(1, 0, 0, 1)) def move(self, js_dir, js_input): # most restrictions on movement handled in frame_loop, # both due to levels and due to environment if not unittest: self.data_file.write(str(self.frameTask.time) + ', ' + str(js_dir) + ', ' + str(-js_input) + '\n') # print(js_dir, js_input) # Threshold. If too low, noise will create movement. if abs(js_input) < 0.1: js_input = 0 # we are moving the camera in the opposite direction of the joystick, # x and y inputs will both be inverted if js_dir == 'x' or js_dir == 'x_key': # print js_input # x direction is reversed self.x_mag = -js_input # print('x_mag', self.x_mag) # hack for Mr. Peepers... # barely touch joystick and goes super speedy. speed not dependent # on how hard he touches joystick (always 2) # if self.subject == 'MP' and js_input != 0: # # print 'yes' # # need it to be the same direction as negative of js_input # self.x_mag = js_input/abs(js_input) * -2 # new hack for Mr. Peepers... # joystick pressure has more of an effect than acceleration # (0 to 2 instead of 0 to 1, trying to get him to push harder on # on the joystick) if self.subject == 'MP' and js_input != 0: self.x_mag = js_input * -2 # print('x', self.x_mag) else: # y direction is also reversed, # not allowed to go backward, ever if js_input < 0: self.y_mag = -js_input else: self.y_mag = 0 def restrict_forward(self): """ :return: As self.forward_limit increases, we require the subject to 'go straighter', iow, the subject should not be pushing the joystick to the side, only forward When forward_limit hits one, can only go forward (any side movement means don't go anywhere) """ self.go_forward = True if self.x_mag > self.forward_limit: self.go_forward = False def get_new_heading(self, heading, dt): # print 'get new heading' # set new turning speed. # if new trial or subject stopped moving, reverts to initial speed if self.start_trial or self.x_mag == 0: self.speed = self.initial_speed self.slow_speed = self.wrong_speed self.start_trial = False else: # the larger the push on the joystick, # the more the speed increases. self.slow_speed += self.wrong_speed * abs(self.x_mag) # self.speed += 0.05 * abs(self.x_mag) self.speed += self.initial_speed * abs(self.x_mag) # determine if moving towards the banana to_banana = False # first make sure we don't divide by zero, if self.x_mag != 0 and heading != 0: if self.x_mag/abs(self.x_mag) * heading/abs(heading) < 0: to_banana = True # unless there is a reason to stop movement, this is the heading delta_heading = self.x_mag * self.speed * dt # if not allowed to go past banana, stop directly at center # if self.free_move == 1: # if heading + delta_heading switches it from + to - # if heading away from banana, many opportunities to slow or # stop movement... if not to_banana: if abs(heading) >= self.screen_edge: # block off edge of screen # print 'hit a wall' delta_heading = 0 elif self.check_zone is None: # if check_zone is None, than went past banana target zone, # and we want to go slow # print 'went past zone' delta_heading = self.x_mag * self.slow_speed * dt # delta_heading = self.x_mag * self.initial_speed * dt elif self.free_move == 1: # print 'free move is 1' # self.free_move is one, only allowed to go towards banana delta_heading = 0 elif self.free_move == 2: # print 'free move is 2' # self.free_move is two, both directions allowed, but go # in direction away from banana more slowly. # print 'slow' # self.x_mag /= self.wrong_speed delta_heading = self.x_mag * self.slow_speed * dt # print self.slow_speed # delta_heading = self.x_mag * self.speed * dt # print('delta heading', delta_heading) return delta_heading def inc_angle(self): # print('old pos', self.avatar_h) # self.avatar_h[0] = self.avatar_h[0] * 1.5 # self.avatar_h *= 1.5 self.avatar_h *= 1.1 # print('would be', self.avatar_h) if abs(self.avatar_h) > self.max_angle: self.avatar_h = self.multiplier * self.max_angle # y is always going to be positive # self.avatar_h[1] = sqrt(25 - self.avatar_h[0] ** 2) sys.stdout.write('increase angle, new angle: ' + str(self.avatar_h) + '\n') if not unittest: self.data_file.write(str(self.frameTask.time) + ', ' + 'keypress, increase angle ' + str(self.multiplier * self.avatar_h) + '\n') # print('min time to reward:', sqrt(2 * self.avatar_h / 0.05 * 0.01)) def dec_angle(self): # print('old pos', self.avatar_h) # self.avatar_h /= 1.5 self.avatar_h /= 1.1 if abs(self.avatar_h) < self.min_angle: self.avatar_h = self.multiplier * self.min_angle # self.banana_pos[0] = x_sign * (abs(self.banana_pos[0]) - 1) # self.banana_pos[1] = sqrt(25 - self.banana_pos[0] ** 2) sys.stdout.write('decrease angle, new angle: ' + str(self.avatar_h) + '\n') if not unittest: self.data_file.write(str(self.frameTask.time) + ', ' + 'keypress, decrease angle ' + str(self.multiplier * self.avatar_h) + '\n') # print('min time to reward:', sqrt(2 * self.avatar_h / 0.05 * 0.01)) def inc_reward(self): self.num_beeps += 1 sys.stdout.write('increase reward, new reward: ' + str(self.num_beeps) + '\n') if not unittest: self.data_file.write(str(self.frameTask.time) + ', ' + 'keypress, increase reward ' + str(self.num_beeps) + '\n') def dec_reward(self): self.num_beeps -= 1 sys.stdout.write('decrease reward, new reward: ' + str(self.num_beeps) + '\n') if not unittest: self.data_file.write(str(self.frameTask.time) + ', ' + 'keypress, decrease reward ' + str(self.num_beeps) + '\n') def inc_level(self): # increase the level, if we are jumping multiple levels, # at once, self.training will not have increased yet, so # check to see what self.change_level is first (don't want # to change levels in the middle of a trial) training = self.training if self.change_level: training = self.change_level # print('old level', training) # get current position in sequence: seq_num = self.get_seq_num(training) if training == self.levels_available[-1][-1]: sys.stdout.write('already at most difficult level \n') self.change_level = training elif training == self.levels_available[seq_num][-1]: sys.stdout.write('switching to new sequence \n') self.change_level = self.levels_available[seq_num + 1][0] else: self.change_level = round(training + 0.1, 2) sys.stdout.write('increase level, new level: ' + str(self.change_level) + '\n') # print('new level', self.change_level) if not unittest: self.data_file.write(str(self.frameTask.time) + ', ' + 'keypress, increase level ' + str(self.change_level) + '\n') def dec_level(self): # decrease the level, if we are jumping multiple levels, # at once, self.training will not have increased yet, so # check to see what self.change_level is first (don't want # to change levels in the middle of a trial) training = self.training if self.change_level: training = self.change_level # print('old level', training) # get current position in sequence: seq_num = self.get_seq_num(training) if training == self.levels_available[0][0]: sys.stdout.write('already at easiest level \n') self.change_level = training elif training == self.levels_available[seq_num][0]: sys.stdout.write('switching to new sequence \n') self.change_level = self.levels_available[seq_num - 1][-1] else: self.change_level = round(training - 0.1, 2) sys.stdout.write('increase level, new level: ' + str(self.change_level) + '\n') if not unittest: self.data_file.write(str(self.frameTask.time) + ', ' + 'keypress, decrease level ' + str(self.change_level) + '\n') def get_seq_num(self, training): seq_num = 0 for seq_num, sequence in enumerate(self.levels_available): if sequence.count(training) > 0: if sequence.index(training) is not None: break return seq_num def inc_wrong_speed(self): if self.wrong_speed >= self.initial_speed: self.wrong_speed = self.initial_speed sys.stdout.write('now same speed as towards the banana \n') else: self.wrong_speed += 0.01 sys.stdout.write('increase speed in wrong direction, new: ' + str(self.wrong_speed) + '\n') if not unittest: self.data_file.write(str(self.frameTask.time) + ', ' + 'keypress, increase wrong speed ' + str(self.wrong_speed) + '\n') def dec_wrong_speed(self): self.wrong_speed -= 0.01 sys.stdout.write('decrease speed in wrong direction, new: ' + str(self.wrong_speed) + '\n') if not unittest: self.data_file.write(str(self.frameTask.time) + ', ' + 'keypress, decrease wrong speed ' + str(self.wrong_speed) + '\n') def inc_random(self): if self.current_choice == len(self.all_random_selections) - 1: sys.stdout.write('already at max \n') else: # current is the current length, which conveniently # enough is the next number to use, because of zero indexing self.current_choice += 1 self.random_choices = self.all_random_selections[self.current_choice] sys.stdout.write('increase selection of random bananas, new: ' + str(self.random_choices) + '\n') if not unittest: self.data_file.write(str(self.frameTask.time) + ', ' + 'keypress, increase random selection ' + str(self.random_choices) + '\n') def dec_random(self): if self.current_choice == 0: sys.stdout.write('already at min \n') else: # current is the current length, so we need to subtract # by two, because of zero indexing self.current_choice -= 1 self.random_choices = self.all_random_selections[self.current_choice] sys.stdout.write('decrease selection of random bananas, new: ' + str(self.random_choices) + '\n') if not unittest: self.data_file.write(str(self.frameTask.time) + ', ' + 'keypress, decrease random selection ' + str(self.random_choices) + '\n') def inc_forward_speed(self): self.initial_forward_speed += 0.01 sys.stdout.write('increase forward speed, new: ' + str(self.initial_forward_speed) + '\n') if not unittest: self.data_file.write(str(self.frameTask.time) + ', ' + 'keypress, increase forward speed ' + str(self.initial_forward_speed) + '\n') def dec_forward_speed(self): self.initial_forward_speed -= 0.01 sys.stdout.write('decrease forward speed, new: ' + str(self.initial_forward_speed) + '\n') if not unittest: self.data_file.write(str(self.frameTask.time) + ', ' + 'keypress, decrease forward speed ' + str(self.initial_forward_speed) + '\n') def change_left(self): self.new_dir = -1 sys.stdout.write('new dir: left \n') print('new direction', self.new_dir) if not unittest: self.data_file.write(str(self.frameTask.time) + ', ' + 'keypress, new dir left' + '\n') def change_right(self): self.new_dir = 1 sys.stdout.write('new dir: right \n') print('new direction', self.new_dir) if not unittest: self.data_file.write(str(self.frameTask.time) + ', ' + 'keypress, new dir right' + '\n') def extra_reward(self): sys.stdout.write('beep \n') if self.reward: self.reward.pumpOut() def reset_variables(self): # this is only called once, from init self.base.taskMgr.remove("frame_loop") # set/reset to the original state of variables # self.max_angle = 26 self.max_angle = 40 self.min_angle = 1.5 self.delay_start = False self.yay_reward = False self.reward_delay = False self.reward_on = True self.reward_count = 0 self.x_mag = 0 self.y_mag = 0 self.speed = self.initial_speed # factor to change speed of joystick and control acceleration self.forward_speed = self.initial_forward_speed # speed for going in the wrong direction, when same speed as initial speed, then no change self.wrong_speed = 0.005 self.slow_speed = self.wrong_speed # toggle for whether moving is allowed or not self.moving = True # toggle for making sure stays on banana for min time for 2.3 self.set_zone_time = False # amount need to hold crosshair on banana to get reward (2.3) # must be more than zero. At 1.5 distance, must be greater than # 0.5 to require stopping self.hold_aim = 0.6 if unittest: self.hold_aim = 0.1 # keeps track of how long we have held self.hold_time = 0 # check_zone is a toggle that happens when lined up crosshair with banana # if check_zone is False, not currently in the zone, if true checking to # see if we have left the zone. if none, left the zone and in mode where # slows down after leaving the zone. self.check_zone = False # self.check_time = 0 # speed for going in the wrong direction, 1 is no change, higher numbers slower self.wrong_speed = 0.005 self.slow_speed = self.wrong_speed # toggle for when trial begins self.start_trial = True def set_level_variables(self, training): #print 'really setting level variables' # default is lowest training level self.training = training self.free_move = 1 self.must_release = False self.random_banana = False self.require_aim = False self.go_forward = False self.banana_coll_node.setIntoCollideMask(self.mask_list[0]) self.avatar_h = self.config_avatar_h self.avatar_pos = Point3(0, -1.5, 1) self.banana_node_path.setScale(0.1) if training > self.levels_available[0][0]: # print '2.1' self.must_release = True if training > self.levels_available[0][1]: # print '2.2' self.random_banana = True if training > self.levels_available[0][2]: # print '2.3' self.free_move = 2 if training > self.levels_available[0][3]: # print '2.4' self.free_move = 3 if training > self.levels_available[0][4]: # print '2.5' self.require_aim = 'slow' if training > self.levels_available[0][5]: # print '2.6' self.require_aim = True # print self.levels_available[0][-1] # level 3 training if training > self.levels_available[0][-1]: # print '3.0' self.avatar_pos = Point3(0.01, self.config_avatar_d, 1) self.banana_coll_node.setIntoCollideMask(self.mask_list[1]) # defaults for level 3 training self.go_forward = True self.free_move = 0 self.must_release = False self.random_banana = False self.require_aim = True if training > self.levels_available[1][0]: # print '3.1' self.must_release = True # level 4 training if training > self.levels_available[1][-1]: #self.banana_node_path.setScale(0.2) # print '4.0' self.banana_coll_node.setIntoCollideMask(self.mask_list[2]) self.go_forward = False self.free_move = 4 self.must_release = False self.random_banana = False self.require_aim = False if training > self.levels_available[2][0]: # print '4.1' self.random_banana = True if training > self.levels_available[2][1]: # print '4.2' self.require_aim = 'slow' if training > self.levels_available[2][2]: # print '4.3' self.require_aim = True #print('what sequence?', self.get_seq_num(training)) # In case random_bananas changed: if self.random_banana: self.random_choices = self.all_random_selections[self.current_choice] self.avatar_h = random.choice(self.random_choices) sys.stdout.write('current angles available ' + str(self.random_choices) + '\n') elif self.get_seq_num(training) == 1: # really should have started out with training zero, # then numbering would be better... # print 'sequence 3?' self.avatar_h = 0 else: self.avatar_h = self.config_avatar_h # print self.banana.getH() # print self.avatar_pos # print self.avatar_h sys.stdout.write('forward: ' + str(self.go_forward) + '\n') sys.stdout.write('free move: ' + str(self.free_move) + '\n') sys.stdout.write('random: ' + str(self.random_banana) + '\n') sys.stdout.write('require aim: ' + str(self.require_aim) + '\n') def load_fruit(self, fruit): if fruit == 'banana': self.banana = self.base.loader.loadModel("models/bananas/banana.bam") self.banana.setH(280) # self.banana.setH(0) self.banana.setScale(0.5) # banana always in the same position, just move avatar. self.banana.setPos(Point3(0, 0, 1)) self.banana_node_path = self.banana.find('**/+CollisionNode') self.banana.reparentTo(self.base.render) elif fruit == 'cherry': # or cherry as banana? self.banana = self.base.render.attachNewNode('root') # banana center is off, re-center with new node new_node_path = self.base.loader.loadModel("models/fruit/cherries_no_cn.egg") new_node_path.reparentTo(self.banana) new_node_path.setPos(0, 0, 0) #new_node_path.setScale(0.08) self.banana.setScale(0.08) # cherry # move the center of the cherries self.banana.setPos(Point3(0.08, 0, 1)) # can't get built in cherry collision node to work properly... cs = CollisionSphere(-10, 0, 0, 11) self.banana_node_path = new_node_path.attachNewNode(CollisionNode('c_node')) self.banana_node_path.node().addSolid(cs) # usually 0.1 for banana # self.banana_node_path = self.banana.find('**/+CollisionNode') # self.banana_node_path.setScale(1) self.banana_mask = BitMask32(0x1) # banana intoCollideMask will change depending on which level we # are training on. self.banana_coll_node = self.banana_node_path.node() self.banana_coll_node.setIntoCollideMask(self.mask_list[0]) def open_data_file(self, config): # open file for recording eye data data_dir = 'data/' + config['subject'] if not os.path.exists(data_dir): os.makedirs(data_dir) self.data_file_name = data_dir + '/' + config['subject'] + '_TR_' + \ datetime.datetime.now().strftime("%y_%m_%d_%H_%M") sys.stdout.write('data file: ' + str(self.data_file_name) + '\n') # open file for recording eye positions self.data_file = open(self.data_file_name, 'w') self.data_file.write('timestamp, joystick input, for subject: ' + config['subject'] + '\n') # Closing methods def close_files(self): self.data_file.close() def close(self): if not unittest: self.close_files() sys.exit() def setup_inputs(self): self.accept('x_axis', self.move, ['x']) self.accept('y_axis', self.move, ['y']) self.accept('arrow_right', self.move, ['x_key', 0.5]) self.accept('arrow_left', self.move, ['x_key', -0.5]) self.accept('arrow_right-up', self.move, ['x_key', 0]) self.accept('arrow_left-up', self.move, ['x_key', 0]) self.accept('arrow_right-repeat', self.move, ['x_key', 0.5]) self.accept('arrow_left-repeat', self.move, ['x_key', -0.5]) self.accept('arrow_up', self.move, ['y_key', -0.5]) self.accept('arrow_up-up', self.move, ['y_key', 0]) self.accept('arrow_up-repeat', self.move, ['y_key', -0.5]) self.accept('q', self.close) self.accept('w', self.inc_reward) self.accept('s', self.dec_reward) self.accept('e', self.inc_angle) self.accept('d', self.dec_angle) self.accept('t', self.inc_level) self.accept('g', self.dec_level) self.accept('y', self.inc_wrong_speed) self.accept('h', self.dec_wrong_speed) self.accept('u', self.inc_random) self.accept('j', self.dec_random) self.accept('i', self.inc_forward_speed) self.accept('k', self.dec_forward_speed) self.accept('r', self.change_right) self.accept('l', self.change_left) self.accept('space', self.extra_reward) @staticmethod def make_coll_node_path(node_path, solid): # Creates a collision node and attaches the collision solid to the # supplied NodePath. Returns the nodepath of the collision node. # Creates a collision node named after the name of the NodePath. coll_node = CollisionNode("%s c_node" % node_path.getName()) coll_node.addSolid(solid) collision_node_path = node_path.attachNewNode(coll_node) # Show the collision node, which makes the solids show up. # actually, it appears to do nothing... # collision_node_path.show() return collision_node_path
class ServerInst(): def __init__(self): # Initialise Window self.showbase=ShowBase() # Disable Mouse Control for camera self.showbase.disableMouse() # Start our server up self.server = Server(9099, compress=True) self.db = DataBase() self.users={} # We should send the clients from the lobby to here somehow? or just get it from somewhere... for i in range(num_users): new_user={} new_user['name']='cake' new_user['connection']='cake' new_user['ready']=True new_user['new_dest']=False new_user['new_spell']=False self.users[len(self.users)]=new_user camera.setPos(0,0,45*num_users) camera.lookAt(0,0,0) taskMgr.doMethodLater(0.5, self.pregame_loop, 'Lobby Loop') #taskMgr.doMethodLater(0.5, self.lobby_loop, 'Lobby Loop') #if newGame == True: # Lets make something that instances the gameServer class for everything game thats hosted? #taskMgr.doMethodLater(0.5, self.login_loop, 'Login Loop') # Probly start the game then # FROM HERE WILL GO TO GAME SERVER>>> def pregame_loop(self,task): """# Guess all of this should move after the if. #print "Pregame State" if self.server.getClients(): self.game_time=0 self.tick=0 self.game=Game(len(self.users),game_tick,self.showbase) temp=self.server.getData() print temp if temp!=[]: for i in range(len(temp)): valid_packet=False package=temp[i] if len(package)==2: print "Received: "+str(package)+" "+str(package[1]) if len(package[0])==2: print "Packet right size" for u in range(len(self.users)): self.users[u]['warlock']=self.game.warlock[u] if self.users[u]['connection']==package[1]: print "Packet from "+self.users[u]['name'] if package[0][0]=='ready': print "So i got the ready and im in game state" taskMgr.doMethodLater(0.5, self.game_loop, 'Game Loop') return task.done else: print "well i didnt get shit" return task.again """ # if in pregame state temp=self.server.getData() if temp!=[]: for i in range(len(temp)): valid_packet=False package=temp[i] if len(package)==2: print "Received: " + str(package) +" "+ str(package[1].getAddress()) if len(package[0])==2: # if username is sent, assign to client if package[0][0]=='username': user_found=False valid_packet=True for u in range(len(self.users)): if self.users[u]['name']==package[0][1]: print "User already exists" user_found=True data = {} data[0] = "error" data[1] = "User already exists" self.server.sendData(data,package[1]) # send something back to the client saying to change username if not user_found: new_user={} new_user['name']=package[0][1] new_user['connection']=package[1] new_user['ready']=False new_user['new_dest']=False new_user['new_spell']=False self.users[len(self.users)]=new_user data = {} data[0] = "which" data[1] = len(self.users)-1 self.server.sendData(data,package[1]) # else check to make sure connection has username for u in range(len(self.users)): if self.users[u]['connection']==package[1]: print "Packet from "+self.users[u]['name'] # process packet update_warlocks=False # if chat packet if package[0][0]=='chat': print "Chat: "+package[0][1] valid_packet=True # Broadcast data to all clients ("username: message") data = {} data[0]='chat' data[1]=self.users[u]['name']+": "+package[0][1] self.server.broadcastData(data) # else if ready packet elif package[0][0]=='ready': print self.users[u]['name']+" is ready!" self.users[u]['ready']=True valid_packet=True update_warlocks=True # else if unready packet elif package[0][0]=='unready': print self.users[u]['name']+" is not ready!" self.users[u]['ready']=False valid_packet=True update_warlocks=True if update_warlocks: data = {} data[0]='warlocks' data[1]=len(self.users) self.server.broadcastData(data) # break out of for loop break #else: # print str(self.users[u]['connection'])+" "+str(package[1]) if not valid_packet: data = {} data[0] = "error" data[1] = "Please Login" self.server.sendData(data,package[1]) print "User not logged in" else: print "Data in packet wrong size" else: print "Packet wrong size" # if all players are ready and there is X of them game_ready=True # if there is any clients connected if not self.server.getClients(): game_ready=False for u in range(len(self.users)): if self.users[u]['ready']==False: game_ready=False if game_ready: data = {} data[0]='state' data[1]='game' self.server.broadcastData(data) taskMgr.doMethodLater(0.5, self.preround_loop, 'Preround Loop') return task.done return task.again def preround_loop(self,task): print "Preround State" self.game_time=0 self.tick=0 self.showbase.num_warlocks=len(self.users) # i guess this shit should be in the pregame part, so people can choose their spells based of these # also it will need to be created in there from data passed from the server (where it will be procedurally generated) # spell0 spell0=Spell() spell0.damage=10 spell0.target_knockback=20 spell0.self_knockback=0 spell0.range=25 spell0.speed=15 spell0.aoe=False spell0.aoe_range=0 spell0.targeting=False spell0.casting_time=0 spell0.interruptable=False spell0.model="media/spells/blockyball" # spell1 spell1=Spell() spell1.damage=25 spell1.target_knockback=10 spell1.self_knockback=0 spell1.range=50 spell1.speed=25 spell1.aoe=False spell1.aoe_range=0 spell1.targeting=False spell1.casting_time=0 spell1.interruptable=False spell1.model="media/spells/pointyball" # spell2 spell2=Spell() spell2.damage=50 spell2.target_knockback=10 spell2.self_knockback=30 spell2.range=50 spell2.speed=15 spell2.aoe=False spell2.aoe_range=0 spell2.targeting=False spell2.casting_time=0 spell2.interruptable=False spell2.model="media/spells/blockyball" # spell3 spell3=Spell() spell3.model="media/spells/pointyball" # maybe this shit too, or this can stay here and just pass in an array of spells self.showbase.spell_man=SpellManager(self.showbase.num_warlocks) # until the Game() class is created in here which i think it should self.showbase.spell_man.add_spell(spell0) self.showbase.spell_man.add_spell(spell1) self.showbase.spell_man.add_spell(spell2) self.showbase.spell_man.add_spell(spell3) self.game=Game(self.showbase,game_tick) for u in range(self.showbase.num_warlocks): self.users[u]['warlock']=self.game.warlock[u] taskMgr.doMethodLater(0.5, self.game_loop, 'Game Loop') return task.done #return task.again def game_loop(self,task): #print "Game State" # if there is any clients connected if self.server.getClients(): # process incoming packages temp=self.server.getData() if temp!=[]: for i in range(len(temp)): valid_packet=False package=temp[i] if len(package)==2: print "Received: " + str(package) +" "+str(package[1]) if len(package[0])==2: #print "packet right size" # else check to make sure connection has username for u in range(len(self.users)): if self.users[u]['connection']==package[1]: print "Packet from "+self.users[u]['name'] # process packet # if chat packet if package[0][0]=='destination': print "Destination: "+str(package[0][1]) valid_packet=True # Update warlock data for client self.users[u]['warlock'].set_destination(Vec3(package[0][1][0],package[0][1][1],0)) self.users[u]['new_dest']=True elif package[0][0]=='spell': print "Spell: "+str(package[0][1]) valid_packet=True # Update warlock data for client self.users[u]['warlock'].set_spell(package[0][1][0],package[0][1][1]) self.users[u]['new_spell']=True break #else: # print "couldnt find connection"+str(self.users[u]['connection'])+" "+str(package[1]) # get frame delta time dt=globalClock.getDt() self.game_time+=dt # if time is less than 3 secs (countdown for determining pings of clients) # tick out for clients if (self.game_time>game_tick): # update all clients with new info before saying tick for u in range(self.showbase.num_warlocks): # new warlock destinations if self.users[u]['new_dest']: data = {} data[0]='update_dest' data[1]=u data[2]={} data[2][0]=self.users[u]['warlock'].destination.getX() data[2][1]=self.users[u]['warlock'].destination.getY() self.users[u]['new_dest']=False self.server.broadcastData(data) # new warlock spell elif self.users[u]['new_spell']: data = {} data[0]='update_spell' data[1]=u data[2]=self.users[u]['warlock'].get_spell() data[3]=self.users[u]['warlock'].get_target() self.users[u]['new_spell']=False self.server.broadcastData(data) data = {} data[0]='tick' data[1]=self.tick self.server.broadcastData(data) self.game_time-=game_tick self.tick+=1 # run simulation if not self.game.run_tick(): print 'Game Over' return task.cont else: #taskMgr.doMethodLater(0.5, self.lobby_loop, 'Lobby Loop') return task.done
def __init__(self, mesh, pm_filebuf): scene_members = getSceneMembers(mesh) base = ShowBase() if len(scene_members) > 1: print 'There is more than one geometry in the scene, so I think this is not a progressive base mesh.' sys.exit(1) rotateNode = GeomNode("rotater") rotatePath = render.attachNewNode(rotateNode) matrix = numpy.identity(4) if mesh.assetInfo.upaxis == collada.asset.UP_AXIS.X_UP: r = collada.scene.RotateTransform(0, 1, 0, 90) matrix = r.matrix elif mesh.assetInfo.upaxis == collada.asset.UP_AXIS.Y_UP: r = collada.scene.RotateTransform(1, 0, 0, 90) matrix = r.matrix rotatePath.setMat(Mat4(*matrix.T.flatten().tolist())) geom, renderstate, mat4 = scene_members[0] node = GeomNode("primitive") node.addGeom(geom) if renderstate is not None: node.setGeomState(0, renderstate) self.geomPath = rotatePath.attachNewNode(node) self.geomPath.setMat(mat4) wrappedNode = ensureCameraAt(self.geomPath, base.camera) base.disableMouse() attachLights(render) render.setShaderAuto() render.setTransparency(TransparencyAttrib.MDual, 1) base.render.analyze() KeyboardMovement() MouseDrag(wrappedNode) MouseScaleZoom(wrappedNode) ButtonUtils(wrappedNode) MouseCamera() print 'Loading pm into memory... ', sys.stdout.flush() self.pm_refinements = readPDAE(pm_filebuf) self.pm_index = 0 print 'Done' self.slider = DirectSlider(range=(0, len(self.pm_refinements)), value=0, pageSize=len(self.pm_refinements) / 20, command=self.sliderMoved, pos=(0, 0, -.9), scale=1) for key, val in uiArgs.iteritems(): self.slider.thumb[key] = val self.triText = OnscreenText(text="", pos=(-1, 0.85), scale=0.15, fg=(1, 0.5, 0.5, 1), align=TextNode.ALeft, mayChange=1) base.run()
class ServerInst(): def __init__(self): # Initialise Window self.showbase = ShowBase() # Disable Mouse Control for camera self.showbase.disableMouse() # Start our server up self.server = Server(9099, compress=True) self.db = DataBase() self.users = { } # We should send the clients from the lobby to here somehow? or just get it from somewhere... for i in range(num_users): new_user = {} new_user['name'] = 'cake' new_user['connection'] = 'cake' new_user['ready'] = True new_user['new_dest'] = False new_user['new_spell'] = False self.users[len(self.users)] = new_user camera.setPos(0, 0, 45 * num_users) camera.lookAt(0, 0, 0) taskMgr.doMethodLater(0.5, self.pregame_loop, 'Lobby Loop') #taskMgr.doMethodLater(0.5, self.lobby_loop, 'Lobby Loop') #if newGame == True: # Lets make something that instances the gameServer class for everything game thats hosted? #taskMgr.doMethodLater(0.5, self.login_loop, 'Login Loop') # Probly start the game then # FROM HERE WILL GO TO GAME SERVER>>> def pregame_loop(self, task): """# Guess all of this should move after the if. #print "Pregame State" if self.server.getClients(): self.game_time=0 self.tick=0 self.game=Game(len(self.users),game_tick,self.showbase) temp=self.server.getData() print temp if temp!=[]: for i in range(len(temp)): valid_packet=False package=temp[i] if len(package)==2: print "Received: "+str(package)+" "+str(package[1]) if len(package[0])==2: print "Packet right size" for u in range(len(self.users)): self.users[u]['warlock']=self.game.warlock[u] if self.users[u]['connection']==package[1]: print "Packet from "+self.users[u]['name'] if package[0][0]=='ready': print "So i got the ready and im in game state" taskMgr.doMethodLater(0.5, self.game_loop, 'Game Loop') return task.done else: print "well i didnt get shit" return task.again """ # if in pregame state temp = self.server.getData() if temp != []: for i in range(len(temp)): valid_packet = False package = temp[i] if len(package) == 2: print "Received: " + str(package) + " " + str( package[1].getAddress()) if len(package[0]) == 2: # if username is sent, assign to client if package[0][0] == 'username': user_found = False valid_packet = True for u in range(len(self.users)): if self.users[u]['name'] == package[0][1]: print "User already exists" user_found = True data = {} data[0] = "error" data[1] = "User already exists" self.server.sendData(data, package[1]) # send something back to the client saying to change username if not user_found: new_user = {} new_user['name'] = package[0][1] new_user['connection'] = package[1] new_user['ready'] = False new_user['new_dest'] = False new_user['new_spell'] = False self.users[len(self.users)] = new_user data = {} data[0] = "which" data[1] = len(self.users) - 1 self.server.sendData(data, package[1]) # else check to make sure connection has username for u in range(len(self.users)): if self.users[u]['connection'] == package[1]: print "Packet from " + self.users[u]['name'] # process packet update_warlocks = False # if chat packet if package[0][0] == 'chat': print "Chat: " + package[0][1] valid_packet = True # Broadcast data to all clients ("username: message") data = {} data[0] = 'chat' data[1] = self.users[u][ 'name'] + ": " + package[0][1] self.server.broadcastData(data) # else if ready packet elif package[0][0] == 'ready': print self.users[u]['name'] + " is ready!" self.users[u]['ready'] = True valid_packet = True update_warlocks = True # else if unready packet elif package[0][0] == 'unready': print self.users[u][ 'name'] + " is not ready!" self.users[u]['ready'] = False valid_packet = True update_warlocks = True if update_warlocks: data = {} data[0] = 'warlocks' data[1] = len(self.users) self.server.broadcastData(data) # break out of for loop break #else: # print str(self.users[u]['connection'])+" "+str(package[1]) if not valid_packet: data = {} data[0] = "error" data[1] = "Please Login" self.server.sendData(data, package[1]) print "User not logged in" else: print "Data in packet wrong size" else: print "Packet wrong size" # if all players are ready and there is X of them game_ready = True # if there is any clients connected if not self.server.getClients(): game_ready = False for u in range(len(self.users)): if self.users[u]['ready'] == False: game_ready = False if game_ready: data = {} data[0] = 'state' data[1] = 'game' self.server.broadcastData(data) taskMgr.doMethodLater(0.5, self.preround_loop, 'Preround Loop') return task.done return task.again def preround_loop(self, task): print "Preround State" self.game_time = 0 self.tick = 0 self.showbase.num_warlocks = len(self.users) # i guess this shit should be in the pregame part, so people can choose their spells based of these # also it will need to be created in there from data passed from the server (where it will be procedurally generated) # spell0 spell0 = Spell() spell0.damage = 10 spell0.target_knockback = 20 spell0.self_knockback = 0 spell0.range = 25 spell0.speed = 15 spell0.aoe = False spell0.aoe_range = 0 spell0.targeting = False spell0.casting_time = 0 spell0.interruptable = False spell0.model = "media/spells/blockyball" # spell1 spell1 = Spell() spell1.damage = 25 spell1.target_knockback = 10 spell1.self_knockback = 0 spell1.range = 50 spell1.speed = 25 spell1.aoe = False spell1.aoe_range = 0 spell1.targeting = False spell1.casting_time = 0 spell1.interruptable = False spell1.model = "media/spells/pointyball" # spell2 spell2 = Spell() spell2.damage = 50 spell2.target_knockback = 10 spell2.self_knockback = 30 spell2.range = 50 spell2.speed = 15 spell2.aoe = False spell2.aoe_range = 0 spell2.targeting = False spell2.casting_time = 0 spell2.interruptable = False spell2.model = "media/spells/blockyball" # spell3 spell3 = Spell() spell3.model = "media/spells/pointyball" # maybe this shit too, or this can stay here and just pass in an array of spells self.showbase.spell_man = SpellManager( self.showbase.num_warlocks ) # until the Game() class is created in here which i think it should self.showbase.spell_man.add_spell(spell0) self.showbase.spell_man.add_spell(spell1) self.showbase.spell_man.add_spell(spell2) self.showbase.spell_man.add_spell(spell3) self.game = Game(self.showbase, game_tick) for u in range(self.showbase.num_warlocks): self.users[u]['warlock'] = self.game.warlock[u] taskMgr.doMethodLater(0.5, self.game_loop, 'Game Loop') return task.done #return task.again def game_loop(self, task): #print "Game State" # if there is any clients connected if self.server.getClients(): # process incoming packages temp = self.server.getData() if temp != []: for i in range(len(temp)): valid_packet = False package = temp[i] if len(package) == 2: print "Received: " + str(package) + " " + str( package[1]) if len(package[0]) == 2: #print "packet right size" # else check to make sure connection has username for u in range(len(self.users)): if self.users[u]['connection'] == package[1]: print "Packet from " + self.users[u]['name'] # process packet # if chat packet if package[0][0] == 'destination': print "Destination: " + str( package[0][1]) valid_packet = True # Update warlock data for client self.users[u][ 'warlock'].set_destination( Vec3(package[0][1][0], package[0][1][1], 0)) self.users[u]['new_dest'] = True elif package[0][0] == 'spell': print "Spell: " + str(package[0][1]) valid_packet = True # Update warlock data for client self.users[u]['warlock'].set_spell( package[0][1][0], package[0][1][1]) self.users[u]['new_spell'] = True break #else: # print "couldnt find connection"+str(self.users[u]['connection'])+" "+str(package[1]) # get frame delta time dt = globalClock.getDt() self.game_time += dt # if time is less than 3 secs (countdown for determining pings of clients) # tick out for clients if (self.game_time > game_tick): # update all clients with new info before saying tick for u in range(self.showbase.num_warlocks): # new warlock destinations if self.users[u]['new_dest']: data = {} data[0] = 'update_dest' data[1] = u data[2] = {} data[2][0] = self.users[u]['warlock'].destination.getX( ) data[2][1] = self.users[u]['warlock'].destination.getY( ) self.users[u]['new_dest'] = False self.server.broadcastData(data) # new warlock spell elif self.users[u]['new_spell']: data = {} data[0] = 'update_spell' data[1] = u data[2] = self.users[u]['warlock'].get_spell() data[3] = self.users[u]['warlock'].get_target() self.users[u]['new_spell'] = False self.server.broadcastData(data) data = {} data[0] = 'tick' data[1] = self.tick self.server.broadcastData(data) self.game_time -= game_tick self.tick += 1 # run simulation if not self.game.run_tick(): print 'Game Over' return task.cont else: #taskMgr.doMethodLater(0.5, self.lobby_loop, 'Lobby Loop') return task.done
class JoystickWorld(DirectObject): # a bit of a strange example of joystick use, because there is no acceleration, and movement # is literal (forward forward, left is left, etc), iow no turning, no looking around. this is # due to the strange game this code eventually went into, but still a useful example of using # joystick and/or keyboard for movement. Eventually I would like to use this to show different # examples of movement, but at least we see basic implementation, as is. def __init__(self, config=None): DirectObject.__init__(self) # joystick js_count = 0 self.joystick = None if pygame: pygame.init() js_count = pygame.joystick.get_count() if js_count > 1: raise NotImplementedError("More than one Joystick is connected") elif js_count == 1: self.joystick = pygame.joystick.Joystick(0) print 'Using joystick' self.joystick.init() # print self.joystick.get_numaxes() # threshold for joystick self.threshold = 0.1 else: print 'No joystick found' # print('joystick', self.joystick) self.last_avt = [0, 0] self.map_avt_node = [] # need a multiplier to the joystick output to make tolerable speed self.vel_base = 5 self.max_vel = [500, 500, 0] self.base = ShowBase() self.base.disableMouse() self.velocity = LVector3(0) # environment self.environ = self.base.loader.loadModel("models/environment") self.environ.reparent_to(self.base.render) # create the avatar self.avatar = NodePath(ActorNode("avatar")) self.avatar.reparentTo(self.base.render) self.avatar.setH(self.base.camera.getH()) self.base.camera.reparentTo(self.avatar) self.base.camera.setPos(0, 0, 0) self.avatar.setPos(-10, -10, 2) self.setup_inputs() self.frameTask = self.base.taskMgr.add(self.frame_loop, "frame_loop") self.frameTask.last = 0 # task time of the last frame # print 'end init' def frame_loop(self, task): dt = task.time - task.last task.last = task.time self.poll_joystick() self.poll_keyboard() self.move_avatar(dt) return task.cont def poll_joystick(self): if not self.joystick: return # joystick input -1 to 1, # if I get the event, it only has a signal when # there is movement, so loop through the events, # to collect events into axis call, but call # axis after, since it will stay at whatever the # last signal was, instead of zeroing out whenever # no movement. Much more convenient that way. for event in pygame.event.get(): pass x = self.joystick.get_axis(0) y = self.joystick.get_axis(1) # if both are under threshold, assume noise # if one is deliberate, noise in the other won't affect much if -self.threshold < x < self.threshold and -self.threshold < y < self.threshold: # print 'threshold' # print 'x', x, 'y', y self.velocity.x = 0 self.velocity.y = 0 else: self.velocity.x = x self.velocity.y = -y def poll_keyboard(self): # under normal circumstances, use median of joytick output x_speed = 0.5 y_speed = 0.5 # checks keyboard, not mouse, in this case is_down = self.base.mouseWatcherNode.is_button_down if not self.joystick: self.velocity.x = 0 self.velocity.y = 0 if is_down(KeyboardButton.up()): self.velocity.y += y_speed if is_down(KeyboardButton.down()): self.velocity.y -= y_speed if is_down(KeyboardButton.left()): self.velocity.x -= x_speed # print 'keyboard' if is_down(KeyboardButton.right()): self.velocity.x += x_speed def move_avatar(self, dt): # print 'velocity', self.velocity # this makes for smooth (correct speed) diagonal movement # print 'velocity', self.velocity magnitude = max(abs(self.velocity[0]), abs(self.velocity[1])) if self.velocity.normalize(): # go left in increasing amount # print 'dt', dt # print 'normalized' # print 'velocity', self.velocity # print 'magnitude', magnitude self.velocity *= magnitude # print 'velocity', self.velocity # this makes for smooth movement move = self.velocity * self.vel_base * dt # print move self.avatar.setFluidPos(self.avatar, move) def setup_inputs(self): self.accept('q', self.close) def close(self): pygame.quit() sys.exit()
class ColorWorld(object): def __init__(self, config=None): # keep track of velocity, this allows me to counteract joystick with keyboard self.velocity = LVector3(0) if config is None: self.config = {} execfile('config.py', self.config) else: self.config = config self.reward = None if pydaq: self.reward = pydaq.GiveReward() self.reward_count = 0 # self.color_map always corresponds to (r, g, b) # does not change during game, each game uses a particular color space self.color_dict = square.make_color_map(self.config['colors']) # sets the range of colors for this map self.c_range = self.config['c_range'] # color variables (make dictionary?) # color_list is set in beginning, and then after that this is only # called again for non-random (training) self.color_list = square.set_start_position_colors(self.config) self.color_match = [0, 0, 0] self.color_tolerance = [] self.last_avt, self.avt_factor = square.translate_color_map(self.config, self.color_dict, self.color_list) print 'starting avt position', self.last_avt print 'map avatar factor', self.avt_factor self.random = True if self.config.get('match_direction'): self.random = False # adjustment to speed so corresponds to gobananas task # 7 seconds to cross original environment # speed needs to be adjusted to both speed in original # environment and c_range of colors # self.speed = 0.05 * (self.c_range[1] - self.c_range[0]) # speed is own variable, so can be changed during training. self.speed = self.config['speed'] # map avatar variables self.render2d = None self.match_square = None self.map_avt_node = [] # need a multiplier to the joystick output to tolerable speed self.vel_base = 3 self.max_vel = [500, 500, 0] self.card = None self.base = ShowBase() self.base.disableMouse() # assume we are showing windows unless proven otherwise if self.config.get('win', True): # only need inputs if we have a window self.inputs = Inputs(self.base) props = WindowProperties() props.setCursorHidden(True) props.setForeground(True) print self.config.get('resolution') if self.config.get('resolution'): props.set_size(int(self.config['resolution'][0]), int(self.config['resolution'][1])) props.set_origin(0, 0) else: props.set_size(600, 600) props.set_origin(400, 50) self.base.win.requestProperties(props) # print self.base.win.get_size() # setup color map on second window sq_node = square.setup_square(self.config) self.setup_display2(sq_node) # print 'background color', self.base.getBackgroundColor() # create the avatar self.avatar = NodePath(ActorNode("avatar")) self.avatar.reparentTo(self.base.render) self.avatar.setH(self.base.camera.getH()) self.base.camera.reparentTo(self.avatar) self.base.camera.setPos(0, 0, 0) # initialize task variables self.frame_task = None self.started_game = None self.showed_match = None self.gave_reward = None # initialize and start the game self.set_next_trial() # print 'end init' def start_loop(self): # need to get new match print 'start loop' self.started_game = self.base.taskMgr.doMethodLater(5, self.start_play, 'start_play') self.showed_match = self.base.taskMgr.add(self.show_match_sample, 'match_image') # Task methods def show_match_sample(self, task): print 'show match sample' print self.color_match[:] # match_image.fill(*self.color_match[:]) card = CardMaker('card') color_match = self.color_match[:] # add alpha channel color_match.append(1) print color_match card.set_color(*color_match[:]) card.set_frame(-12, -8, 0, 4) # log this self.card = self.base.render.attach_new_node(card.generate()) return task.done def start_play(self, task): print 'start play' # log this self.base.taskMgr.remove('match_image') self.card.removeNode() # print self.base.render.ls() self.frame_task = self.base.taskMgr.add(self.game_loop, "game_loop") self.frame_task.last = 0 # initiate task time of the last frame # log this self.base.setBackgroundColor(self.color_list[:]) return task.done def game_loop(self, task): dt = task.time - task.last task.last = task.time self.velocity = self.inputs.poll_inputs(self.velocity) move = self.move_avatar(dt) stop = self.change_background(move) self.move_map_avatar(move, stop) match = self.check_color_match() if match: self.give_reward() return task.done return task.cont def reward_loop(self, task): self.reward_count += 1 if self.reward_count <= self.config['num_beeps']: if self.reward: # log this print 'give a bloody reward already' self.reward.pumpOut() print 'give reward' return task.again else: self.end_loop() return task.done def move_avatar(self, dt): # print 'velocity', self.velocity # this makes for smooth (correct speed) diagonal movement # print 'velocity', self.velocity magnitude = max(abs(self.velocity[0]), abs(self.velocity[1])) move = None if self.velocity.normalize(): # go left in increasing amount # print 'dt', dt # print 'normalized' # print 'velocity', self.velocity # print 'magnitude', magnitude self.velocity *= magnitude # print 'velocity', self.velocity # this makes for smooth movement move = self.velocity * self.vel_base * dt # print move self.avatar.setFluidPos(self.avatar, move) return move def change_background(self, move): stop = [True, True, True] if move: # print move move *= self.speed for i in range(3): value = self.color_dict[i] if value is not None: stop[i] = False # keys correspond to x,y,z # values correspond to r,g,b if i == 2: # z axis is treated differently # need to work on this. z should # be at min when both x and y are at max # taking the average is not quite right... z_move = (move[0] + move[1])/2 # print z_move self.color_list[value] -= z_move else: self.color_list[value] += move[i] if self.color_list[value] < self.c_range[0]: self.color_list[value] = self.c_range[0] stop[i] = True elif self.color_list[value] > self.c_range[1]: self.color_list[value] = self.c_range[1] stop[i] = True # log this self.base.setBackgroundColor(self.color_list[:]) # print self.base.getBackgroundColor() return stop def move_map_avatar(self, move, stop): # print move # avatar is mapped assuming c_range of 0.5. What do I need to # change to use a different c_range? c_range of one is twice # the if move: avt = LineSegs() avt.setThickness(1) avt.setColor(1, 1, 1) # print 'last', self.last_avt avt.move_to(self.last_avt[0], -5, self.last_avt[1]) # print 'move', move new_move = [i + (j * self.avt_factor) for i, j in zip(self.last_avt, move)] # new_move = [i + j for i, j in zip(self.last_avt, move)] # would it be better to have a local stop condition? if stop[0]: new_move[0] = self.last_avt[0] # print 'stop x', self.last_avt[0] if stop[1]: new_move[1] = self.last_avt[1] # print 'stop y', self.last_avt[1] # print 'new', new_move self.last_avt = [new_move[0], new_move[1]] avt.draw_to(new_move[0], -5, new_move[1]) self.map_avt_node.append(self.render2d.attach_new_node(avt.create())) # print self.map_avt_node[-1] # can't let too many nodes pile up if len(self.map_avt_node) > 299: # removing the node does not remove the object from the list for i, j in enumerate(self.map_avt_node): j.removeNode() if i > 49: break del self.map_avt_node[0:50] def check_color_match(self): # print 'match this', self.color_tolerance # print self.color_list check_color = [j[0] < self.color_list[i] < j[1] for i, j in enumerate(self.color_tolerance)] # print check_color if all(check_color): return True else: return False def give_reward(self): # clear the background self.base.setBackgroundColor(0.41, 0.41, 0.41) print 'give first reward' self.reward_count = 1 if self.reward: # log this self.reward.pumpOut() self.gave_reward = self.base.taskMgr.doMethodLater(self.config['pump_delay'], self.reward_loop, 'reward_loop') def end_loop(self): print 'end loop' # clear avatar map self.clear_avatar_map() # if there is a match set, return to center of color gradient, # set new match, if applicable self.set_next_trial() def clear_avatar_map(self): for i, j in enumerate(self.map_avt_node): j.removeNode() self.map_avt_node = [] def plot_match_square(self, corners): print 'plot match square' print corners match = LineSegs() match.setThickness(1.5) match.setColor(0, 0, 0) match.move_to(corners[0][0], -5, corners[1][0]) match.draw_to(corners[0][1], -5, corners[1][0]) match.draw_to(corners[0][1], -5, corners[1][1]) match.draw_to(corners[0][0], -5, corners[1][1]) match.draw_to(corners[0][0], -5, corners[1][0]) # print self.render2d self.match_square = self.render2d.attach_new_node(match.create()) def create_avatar_map_match_square(self, config=None): print 'make new square for map' if config is not None: config_dict = config else: config_dict = self.config # create square on avatar map for new color match map_color_match, factor = square.translate_color_map(config_dict, self.color_dict, self.color_match) tolerance = config_dict['tolerance'] * factor map_color_tolerance = [(i - tolerance, i + tolerance) for i in map_color_match] print map_color_tolerance if self.render2d: if self.match_square: self.match_square.removeNode() self.plot_match_square(map_color_tolerance) def set_next_trial(self): print 'set next trial' # move avatar back to beginning position, only matters for # showing card for next color match self.avatar.set_pos(-10, -10, 2) # set color_list with starting color # if random, won't use this again, but for manual, will # return to center # need to update self.config to new direction, if there is one if self.config.get('match_direction'): self.check_key_map() # return to center, otherwise random will start where you left off self.color_list = square.set_start_position_colors(self.config) # starting position for map avatar, just translate new color_list self.last_avt, self.avt_factor = square.translate_color_map(self.config, self.color_dict, self.color_list) print 'start color', self.color_list print self.color_dict # again need to update self.config for match if using keys self.color_match = square.set_match_colors(self.config, self.color_dict) # sets the tolerance for how close to a color for reward self.color_tolerance = [(i - self.config['tolerance'], i + self.config['tolerance']) for i in self.color_match] print 'color match', self.color_match print 'color tolerance', self.color_tolerance self.create_avatar_map_match_square(self.config) # start the game self.start_loop() def check_key_map(self): if self.config['colors'][0]: if self.inputs.key_map['r']: self.config['match_direction'] = ['right'] elif self.inputs.key_map['r'] is not None: self.config['match_direction'] = ['left'] elif self.config['colors'][1]: if self.inputs.key_map['f']: self.config['match_direction'] = ['front'] elif self.inputs.key_map['f'] is not None: self.config['match_direction'] = ['back'] def setup_display2(self, display_node): print 'setup display2' props = WindowProperties() props.set_cursor_hidden(True) props.set_foreground(False) if self.config.get('resolution'): props.setSize(700, 700) props.setOrigin(-int(self.config['resolution'][0] - 5), 5) else: props.setSize(300, 300) props.setOrigin(10, 10) window2 = self.base.openWindow(props=props, aspectRatio=1) lens = OrthographicLens() lens.set_film_size(2, 2) lens.setNearFar(-100, 100) self.render2d = NodePath('render2d') self.render2d.attach_new_node(display_node) camera2d = self.base.makeCamera(window2) camera2d.setPos(0, -10, 0) camera2d.node().setLens(lens) camera2d.reparentTo(self.render2d)
class ColorWorld(object): def __init__(self, config=None): # keep track of velocity, this allows me to counteract joystick with keyboard self.velocity = LVector3(0) if config is None: self.config = {} execfile('config.py', self.config) else: self.config = config self.reward = None if pydaq: self.reward = pydaq.GiveReward() self.reward_count = 0 # self.color_map always corresponds to (r, g, b) # does not change during game, each game uses a particular color space self.color_dict = square.make_color_map(self.config['colors']) # sets the range of colors for this map self.c_range = self.config['c_range'] # color variables (make dictionary?) # color_list is set in beginning, and then after that this is only # called again for non-random (training) self.color_list = square.set_start_position_colors(self.config) self.color_match = [0, 0, 0] self.color_tolerance = [] self.last_avt, self.avt_factor = square.translate_color_map( self.config, self.color_dict, self.color_list) print 'starting avt position', self.last_avt print 'map avatar factor', self.avt_factor self.random = True if self.config.get('match_direction'): self.random = False # adjustment to speed so corresponds to gobananas task # 7 seconds to cross original environment # speed needs to be adjusted to both speed in original # environment and c_range of colors # self.speed = 0.05 * (self.c_range[1] - self.c_range[0]) # speed is own variable, so can be changed during training. self.speed = self.config['speed'] # map avatar variables self.render2d = None self.match_square = None self.map_avt_node = [] # need a multiplier to the joystick output to tolerable speed self.vel_base = 3 self.max_vel = [500, 500, 0] self.card = None self.base = ShowBase() self.base.disableMouse() # assume we are showing windows unless proven otherwise if self.config.get('win', True): # only need inputs if we have a window self.inputs = Inputs(self.base) props = WindowProperties() props.setCursorHidden(True) props.setForeground(True) print self.config.get('resolution') if self.config.get('resolution'): props.set_size(int(self.config['resolution'][0]), int(self.config['resolution'][1])) props.set_origin(0, 0) else: props.set_size(600, 600) props.set_origin(400, 50) self.base.win.requestProperties(props) # print self.base.win.get_size() # setup color map on second window sq_node = square.setup_square(self.config) self.setup_display2(sq_node) # print 'background color', self.base.getBackgroundColor() # create the avatar self.avatar = NodePath(ActorNode("avatar")) self.avatar.reparentTo(self.base.render) self.avatar.setH(self.base.camera.getH()) self.base.camera.reparentTo(self.avatar) self.base.camera.setPos(0, 0, 0) # initialize task variables self.frame_task = None self.started_game = None self.showed_match = None self.gave_reward = None # initialize and start the game self.set_next_trial() # print 'end init' def start_loop(self): # need to get new match print 'start loop' self.started_game = self.base.taskMgr.doMethodLater( 5, self.start_play, 'start_play') self.showed_match = self.base.taskMgr.add(self.show_match_sample, 'match_image') # Task methods def show_match_sample(self, task): print 'show match sample' print self.color_match[:] # match_image.fill(*self.color_match[:]) card = CardMaker('card') color_match = self.color_match[:] # add alpha channel color_match.append(1) print color_match card.set_color(*color_match[:]) card.set_frame(-12, -8, 0, 4) # log this self.card = self.base.render.attach_new_node(card.generate()) return task.done def start_play(self, task): print 'start play' # log this self.base.taskMgr.remove('match_image') self.card.removeNode() # print self.base.render.ls() self.frame_task = self.base.taskMgr.add(self.game_loop, "game_loop") self.frame_task.last = 0 # initiate task time of the last frame # log this self.base.setBackgroundColor(self.color_list[:]) return task.done def game_loop(self, task): dt = task.time - task.last task.last = task.time self.velocity = self.inputs.poll_inputs(self.velocity) move = self.move_avatar(dt) stop = self.change_background(move) self.move_map_avatar(move, stop) match = self.check_color_match() if match: self.give_reward() return task.done return task.cont def reward_loop(self, task): self.reward_count += 1 if self.reward_count <= self.config['num_beeps']: if self.reward: # log this print 'give a bloody reward already' self.reward.pumpOut() print 'give reward' return task.again else: self.end_loop() return task.done def move_avatar(self, dt): # print 'velocity', self.velocity # this makes for smooth (correct speed) diagonal movement # print 'velocity', self.velocity magnitude = max(abs(self.velocity[0]), abs(self.velocity[1])) move = None if self.velocity.normalize(): # go left in increasing amount # print 'dt', dt # print 'normalized' # print 'velocity', self.velocity # print 'magnitude', magnitude self.velocity *= magnitude # print 'velocity', self.velocity # this makes for smooth movement move = self.velocity * self.vel_base * dt # print move self.avatar.setFluidPos(self.avatar, move) return move def change_background(self, move): stop = [True, True, True] if move: # print move move *= self.speed for i in range(3): value = self.color_dict[i] if value is not None: stop[i] = False # keys correspond to x,y,z # values correspond to r,g,b if i == 2: # z axis is treated differently # need to work on this. z should # be at min when both x and y are at max # taking the average is not quite right... z_move = (move[0] + move[1]) / 2 # print z_move self.color_list[value] -= z_move else: self.color_list[value] += move[i] if self.color_list[value] < self.c_range[0]: self.color_list[value] = self.c_range[0] stop[i] = True elif self.color_list[value] > self.c_range[1]: self.color_list[value] = self.c_range[1] stop[i] = True # log this self.base.setBackgroundColor(self.color_list[:]) # print self.base.getBackgroundColor() return stop def move_map_avatar(self, move, stop): # print move # avatar is mapped assuming c_range of 0.5. What do I need to # change to use a different c_range? c_range of one is twice # the if move: avt = LineSegs() avt.setThickness(1) avt.setColor(1, 1, 1) # print 'last', self.last_avt avt.move_to(self.last_avt[0], -5, self.last_avt[1]) # print 'move', move new_move = [ i + (j * self.avt_factor) for i, j in zip(self.last_avt, move) ] # new_move = [i + j for i, j in zip(self.last_avt, move)] # would it be better to have a local stop condition? if stop[0]: new_move[0] = self.last_avt[0] # print 'stop x', self.last_avt[0] if stop[1]: new_move[1] = self.last_avt[1] # print 'stop y', self.last_avt[1] # print 'new', new_move self.last_avt = [new_move[0], new_move[1]] avt.draw_to(new_move[0], -5, new_move[1]) self.map_avt_node.append( self.render2d.attach_new_node(avt.create())) # print self.map_avt_node[-1] # can't let too many nodes pile up if len(self.map_avt_node) > 299: # removing the node does not remove the object from the list for i, j in enumerate(self.map_avt_node): j.removeNode() if i > 49: break del self.map_avt_node[0:50] def check_color_match(self): # print 'match this', self.color_tolerance # print self.color_list check_color = [ j[0] < self.color_list[i] < j[1] for i, j in enumerate(self.color_tolerance) ] # print check_color if all(check_color): return True else: return False def give_reward(self): # clear the background self.base.setBackgroundColor(0.41, 0.41, 0.41) print 'give first reward' self.reward_count = 1 if self.reward: # log this self.reward.pumpOut() self.gave_reward = self.base.taskMgr.doMethodLater( self.config['pump_delay'], self.reward_loop, 'reward_loop') def end_loop(self): print 'end loop' # clear avatar map self.clear_avatar_map() # if there is a match set, return to center of color gradient, # set new match, if applicable self.set_next_trial() def clear_avatar_map(self): for i, j in enumerate(self.map_avt_node): j.removeNode() self.map_avt_node = [] def plot_match_square(self, corners): print 'plot match square' print corners match = LineSegs() match.setThickness(1.5) match.setColor(0, 0, 0) match.move_to(corners[0][0], -5, corners[1][0]) match.draw_to(corners[0][1], -5, corners[1][0]) match.draw_to(corners[0][1], -5, corners[1][1]) match.draw_to(corners[0][0], -5, corners[1][1]) match.draw_to(corners[0][0], -5, corners[1][0]) # print self.render2d self.match_square = self.render2d.attach_new_node(match.create()) def create_avatar_map_match_square(self, config=None): print 'make new square for map' if config is not None: config_dict = config else: config_dict = self.config # create square on avatar map for new color match map_color_match, factor = square.translate_color_map( config_dict, self.color_dict, self.color_match) tolerance = config_dict['tolerance'] * factor map_color_tolerance = [(i - tolerance, i + tolerance) for i in map_color_match] print map_color_tolerance if self.render2d: if self.match_square: self.match_square.removeNode() self.plot_match_square(map_color_tolerance) def set_next_trial(self): print 'set next trial' # move avatar back to beginning position, only matters for # showing card for next color match self.avatar.set_pos(-10, -10, 2) # set color_list with starting color # if random, won't use this again, but for manual, will # return to center # need to update self.config to new direction, if there is one if self.config.get('match_direction'): self.check_key_map() # return to center, otherwise random will start where you left off self.color_list = square.set_start_position_colors(self.config) # starting position for map avatar, just translate new color_list self.last_avt, self.avt_factor = square.translate_color_map( self.config, self.color_dict, self.color_list) print 'start color', self.color_list print self.color_dict # again need to update self.config for match if using keys self.color_match = square.set_match_colors(self.config, self.color_dict) # sets the tolerance for how close to a color for reward self.color_tolerance = [(i - self.config['tolerance'], i + self.config['tolerance']) for i in self.color_match] print 'color match', self.color_match print 'color tolerance', self.color_tolerance self.create_avatar_map_match_square(self.config) # start the game self.start_loop() def check_key_map(self): if self.config['colors'][0]: if self.inputs.key_map['r']: self.config['match_direction'] = ['right'] elif self.inputs.key_map['r'] is not None: self.config['match_direction'] = ['left'] elif self.config['colors'][1]: if self.inputs.key_map['f']: self.config['match_direction'] = ['front'] elif self.inputs.key_map['f'] is not None: self.config['match_direction'] = ['back'] def setup_display2(self, display_node): print 'setup display2' props = WindowProperties() props.set_cursor_hidden(True) props.set_foreground(False) if self.config.get('resolution'): props.setSize(700, 700) props.setOrigin(-int(self.config['resolution'][0] - 5), 5) else: props.setSize(300, 300) props.setOrigin(10, 10) window2 = self.base.openWindow(props=props, aspectRatio=1) lens = OrthographicLens() lens.set_film_size(2, 2) lens.setNearFar(-100, 100) self.render2d = NodePath('render2d') self.render2d.attach_new_node(display_node) camera2d = self.base.makeCamera(window2) camera2d.setPos(0, -10, 0) camera2d.node().setLens(lens) camera2d.reparentTo(self.render2d)
def __init__(self, mesh_path, progressive_texture_path): resolutions = [] f = tarfile.open(progressive_texture_path) for resolution_name in f.getnames(): toset = {'size': resolution_name[:-4], 'contents': f.extractfile(resolution_name).read()} texpnm = PNMImage() texpnm.read(StringStream(toset['contents']), 'something.jpg') newtex = Texture() newtex.load(texpnm) toset['texture'] = newtex resolutions.append(toset) self.resolutions = resolutions def aux_loader(fname): return resolutions[0]['contents'] mesh = collada.Collada(mesh_path, aux_file_loader=aux_loader) scene_members = getSceneMembers(mesh) base = ShowBase() rotateNode = GeomNode("rotater") rotatePath = render.attachNewNode(rotateNode) matrix = numpy.identity(4) if mesh.assetInfo.upaxis == collada.asset.UP_AXIS.X_UP: r = collada.scene.RotateTransform(0,1,0,90) matrix = r.matrix elif mesh.assetInfo.upaxis == collada.asset.UP_AXIS.Y_UP: r = collada.scene.RotateTransform(1,0,0,90) matrix = r.matrix rotatePath.setMat(Mat4(*matrix.T.flatten().tolist())) geom, renderstate, mat4 = scene_members[0] node = GeomNode("primitive") node.addGeom(geom) if renderstate is not None: node.setGeomState(0, renderstate) self.geomPath = rotatePath.attachNewNode(node) self.geomPath.setMat(mat4) wrappedNode = ensureCameraAt(self.geomPath, base.camera) base.disableMouse() attachLights(render) render.setShaderAuto() render.setTransparency(TransparencyAttrib.MDual, 1) base.render.analyze() KeyboardMovement() MouseDrag(wrappedNode) MouseScaleZoom(wrappedNode) MouseCamera() num_resolutions = len(resolutions) - 1 self.slider = DirectSlider(range=(0, num_resolutions), value=0, pageSize=1, command=self.sliderMoved, pos=(0, 0, -.9), scale=1) for key, val in uiArgs.iteritems(): self.slider.thumb[key] = val self.triText = OnscreenText(text="", pos=(-1,0.85), scale = 0.15, fg=(1, 0.5, 0.5, 1), align=TextNode.ALeft, mayChange=1) base.run()
import sys try: import _tkinter except: sys.exit("Please install python module 'Tkinter'") try: import Pmw except: sys.exit("Please install Python megawidgets") # Makes sure that Panda is configured to play nice with Tkinter from panda3d.core import * loadPrcFileData("", "want-tk true") # Open the Panda window from direct.showbase.ShowBase import ShowBase base = ShowBase() from direct.tkpanels.ParticlePanel import ParticlePanel pp = ParticlePanel() # Create the panel base.disableMouse() # Disable camera control to place it base.camera.setY(-10) # Place the camera base.setBackgroundColor( 0, 0, 0) # Most particle systems show up better on black backgrounds base.run()
class Device(): def __init__(self): self.base = ShowBase() self.model = self.base.loader.loadModel('device.egg') self.model.reparentTo(self.base.render) self.base.disableMouse() self.base.camera.setPos(0, -10, 0) self.model.setHpr(0,90,0) mat = Mat4(self.base.camera.getMat()) mat.invertInPlace() self.base.mouseInterfaceNode.setMat(mat) self.base.enableMouse() self.screen = self.model.find("**/pantalla") self.list_app = ListApp(self) self.music_app = MusicApp(self) self.dial_app = DialApp(self) self.apps = {} self.events = EventDispatcher(self, "Sony Ericsson W200") self.apps["init"] = InitApp(self) self.apps["Dial"] = self.display_dial_screen self.apps["menu"] = MainMenu(self) self.apps["Reproductor"] = self.play self.apps["Reproductor de Audio"] = self.display_list self.apps["Camara"] = CameraApp(self) self.apps["Album Fotografico"] = PhotoApp(self) self.apps["Llamadas"] = self.display_list self.apps["Contactos"] = self.display_list self.apps["Mensajes"] = self.display_list self.apps["Juegos"] = self.display_list self.apps["Utileria"] = self.display_list self.apps["Reproducir Todas"] = self.play self.apps["Lista de Albums"] = self.list_albums self.apps["Lista de Artistas"] = self.list_artists self.apps["Lista de Contactos"] = self.list_contacts self.apps["Dial Contact"] = self.dial_contact self.apps["Llamadas Perdidas"] = self.list_lost_calls self.apps["Llamadas Contestadas"] = self.list_answered_calls self.apps["Llamadas Marcadas"] = self.list_done_calls self.launch("init") def list_lost_calls(self, arg = None): manager = GestorRegistros() self.list_app.set_options(manager.get_logs_by_state("PERDIDA")) return self.list_app def list_answered_calls(self, arg = None): manager = GestorRegistros() self.list_app.set_options(manager.get_logs_by_state("RECIBIDA")) return self.list_app def list_done_calls(self, arg = None): manager = GestorRegistros() self.list_app.set_options(manager.get_logs_by_state("REALIZADA")) return self.list_app def dial_contact(self, arg = None): cntct = self.list_app.get_selected_option()[2] self.dial_app.write_number(cntct[1]) return self.dial_app def list_contacts(self, arg = None): manager = GestorContactos() self.list_app.set_options(manager.get_contactos()) return self.list_app def display_dial_screen(self, arg = None): self.dial_app.write_number(self.apps["init"].get_number()) return self.dial_app def display_list(self, option): temp_list = OptionManager.get_option_subtree(option) self.list_app.set_options(temp_list) return self.list_app def list_albums(self, arg = None): manager = GestorMusica() temp_list = manager.get_albums() self.list_app.set_options(temp_list) return self.list_app def list_artists(self, arg = None): manager = GestorMusica() temp_list = manager.get_artists() self.list_app.set_options(temp_list) return self.list_app def play(self, arg = None): args = self.list_app.get_selected_option() print "args:" + str(args) if args: print args manager = GestorMusica() temp_list = None if args[2] == "all": temp_list = manager.get_tracks() if args[2] == "artist": temp_list = manager.get_tracks_by_artist(args[0]) if args[2] == "album": temp_list = manager.get_tracks_by_album(args[0]) if temp_list: self.music_app.set_track_list(temp_list) print "Music loading succesfull" return self.music_app return None def run(self): self.base.run() def get_model(self): return self.model def get_base(self): return self.base def get_screen(self): return self.screen def repaint(self): self.screen.getTexture().reload() def launch(self, app_name): if app_name in self.apps: self.events.clear() self.screen.setTexture(loader.loadTexture( OptionManager.get_texture_filename()), 1) if "instancemethod" in str(type(self.apps[app_name])): app = self.apps[app_name](app_name) if app: app.renderer.set_title(app_name) app.activate(self.events) else: print "Launching " + app_name self.apps[app_name].activate(self.events) self.repaint() else: print "unknown command: " + app_name
class PlayWorld(object): def __init__(self, config=None): if config is None: self.config = {} execfile('play_config.py', self.config) else: self.config = config self.reward = None print self.config['pydaq'] if pydaq and self.config.setdefault('pydaq', True) is not None: self.reward = pydaq.GiveReward() self.reward_count = 0 # adjustment to speed so corresponds to gobananas task # 7 seconds to cross original environment # speed needs to be adjusted to both speed in original # environment and c_range of colors # self.speed = 0.05 * (self.c_range[1] - self.c_range[0]) # speed is own variable, so can be changed during training. self.speed = self.config['speed'] # need a multiplier to the joystick output to tolerable speed self.vel_base = 4 self.max_vel = [500, 500, 0] self.base = ShowBase() self.base.disableMouse() # self.base.setFrameRateMeter(True) # assume we are showing windows unless proven otherwise if self.config.get('win', True): # only need inputs if we have a window self.inputs = Inputs(self.base) props = WindowProperties() props.setCursorHidden(True) props.setForeground(True) print self.config.get('resolution') if self.config.get('resolution'): # main window props.set_size(int(self.config['resolution'][0]), int(self.config['resolution'][1])) # props.set_origin(1920, 0) props.set_origin(500, 0) else: props.set_size(600, 600) props.set_origin(400, 50) self.base.win.requestProperties(props) # print 'background color', self.base.getBackgroundColor() # field = self.base.loader.loadModel("../goBananas/models/play_space/field.bam") field = self.base.loader.loadModel("../goBananas/models/play_space/round_courtyard.bam") field.setPos(0, 0, 0) field.reparent_to(self.base.render) field_node_path = field.find('**/+CollisionNode') field_node_path.node().setIntoCollideMask(0) sky = self.base.loader.loadModel("../goBananas/models/sky/sky_kahana2.bam") sky.setPos(0, 0, 0) sky.setScale(1.6) sky.reparentTo(self.base.render) windmill = self.base.loader.loadModel("../goBananas/models/windmill/windmill.bam") windmill.setPos(-10, 30, -1) windmill.setScale(0.03) windmill.reparentTo(self.base.render) # mountain = self.base.loader.loadModel("../goBananas/models/mountain/mountain.bam") # mountain.setScale(0.0005) # mountain.setPos(10, 30, -0.5) # create the avatar self.avatar = NodePath(ActorNode("avatar")) self.avatar.reparentTo(self.base.render) self.avatar.setPos(0, 0, 1) self.avatar.setScale(0.5) pl = self.base.cam.node().getLens() pl.setFov(60) self.base.cam.node().setLens(pl) self.base.camera.reparentTo(self.avatar) # initialize task variables self.frame_task = None self.started_game = None self.showed_match = None self.gave_reward = None # initialize and start the game self.set_next_trial() # print 'end init' def start_loop(self): # need to get new match self.start_play() def start_play(self): print 'start play' # log this # print self.base.render.ls() self.frame_task = self.base.taskMgr.add(self.game_loop, "game_loop") self.frame_task.last = 0 # initiate task time of the last frame def game_loop(self, task): dt = task.time - task.last task.last = task.time velocity = self.inputs.poll_inputs(LVector3(0)) self.move_avatar(dt, velocity) return task.cont def reward_loop(self, task): self.reward_count += 1 if self.reward_count <= self.config['num_beeps']: if self.reward: # log this print 'give a bloody reward already' self.reward.pumpOut() print 'give reward' return task.again else: self.end_loop() return task.done def move_avatar(self, dt, velocity): # print 'velocity', self.velocity self.avatar.setH(self.avatar.getH() - velocity[0] * 1.1) move = LVector3(0, velocity[1], 0) self.avatar.setPos(self.avatar, move * dt * self.vel_base) def give_reward(self): # clear the background self.base.setBackgroundColor(0.41, 0.41, 0.41) print 'give first reward' self.reward_count = 1 if self.reward: # log this self.reward.pumpOut() self.gave_reward = self.base.taskMgr.doMethodLater(self.config['pump_delay'], self.reward_loop, 'reward_loop') def end_loop(self): print 'end loop' # clear avatar map # if there is a match set, return to center of color gradient, # set new match, if applicable self.set_next_trial() def set_next_trial(self): print 'set next trial' # move avatar back to beginning position, only matters for # showing card for next color match # self.avatar.set_pos(-10, -10, 2) # start the game self.start_loop() def check_key_map(self): if self.config['colors'][0]: if self.inputs.key_map['r']: self.config['match_direction'] = ['right'] elif self.inputs.key_map['r'] is not None: self.config['match_direction'] = ['left'] elif self.config['colors'][1]: if self.inputs.key_map['f']: self.config['match_direction'] = ['front'] elif self.inputs.key_map['f'] is not None: self.config['match_direction'] = ['back'] def setup_display2(self, display_node): print 'setup display2' props = WindowProperties() props.set_cursor_hidden(True) props.set_foreground(False) if self.config.get('resolution'): props.setSize(700, 700) props.setOrigin(-int(self.config['resolution'][0] - 5), 5) else: props.setSize(300, 300) props.setOrigin(10, 10) window2 = self.base.openWindow(props=props, aspectRatio=1) lens = OrthographicLens() lens.set_film_size(2, 2) lens.setNearFar(-100, 100) self.render2d = NodePath('render2d') self.render2d.attach_new_node(display_node) camera2d = self.base.makeCamera(window2) camera2d.setPos(0, -10, 0) camera2d.node().setLens(lens) camera2d.reparentTo(self.render2d)
def main(): from asyncio import get_event_loop from threading import Thread # server bits from server import tokenManager, requestCacheManager, responseMaker, make_shutdown from .defaults import CONNECTION_PORT, DATA_PORT # render setup from direct.showbase.ShowBase import ShowBase from panda3d.core import loadPrcFileData from panda3d.core import PStatClient from .render_manager import renderManager from .selection import BoxSel from .util.util import ui_text, console, exit_cleanup, frame_rate, startup_data from .ui import CameraControl, Axis3d, Grid3d, GuiFrame from .protocols import connectionServerProtocol, dataServerProtocol from .protocols import dataClientProtocol from .util.process_fixed import ProcessPoolExecutor_fixed as ProcessPoolExecutor from .keys import AcceptKeys # common event_loop = get_event_loop() ppe = ProcessPoolExecutor() # server tm = tokenManager() rcm = requestCacheManager(0) conServ = connectionServerProtocol(tm) datServ = dataServerProtocol(event_loop, responseMaker, rcm, tm, ppe) coro_conServer = event_loop.create_server(conServ, '127.0.0.1', CONNECTION_PORT, ssl=None) # TODO ssl coro_dataServer = event_loop.create_server(datServ, '127.0.0.1', DATA_PORT, ssl=None) # TODO ssl and this can be another box serverCon = event_loop.run_until_complete(coro_conServer) serverData = event_loop.run_until_complete(coro_dataServer) # client PStatClient.connect() #run pstats in console loadPrcFileData('','view-frustum-cull 0') base = ShowBase() base.setBackgroundColor(0,0,0) base.disableMouse() # TODO init all these into a dict or summat? startup_data() frame_rate() ut = ui_text() grid = Grid3d() axis = Axis3d() cc = CameraControl() frames = { 'data':GuiFrame('Data view') } rendMan = renderManager(event_loop, ppe) bs = BoxSel(frames) datCli_base = dataClientProtocol(rendMan.render_callback, rendMan.set_send_request, rendMan.cache, event_loop) datCli = datCli_base() datCli.connection_lost('START') eventThread = Thread(target=event_loop.run_forever) eventThread.start() con = console(locals(), True) shutdown = make_shutdown(event_loop, eventThread, serverCon, serverData, ppe) el = exit_cleanup(event_loop, ppe, datCli.transport, shutdown) ac = AcceptKeys() base.run()
class viewer(DirectObject): def __init__(self, data): preLoad = preLoading(data) self.base = ShowBase() self.base.disableMouse() self.base.camera.setPos(0, -100, 0) self.base.setBackgroundColor(1,1,1) self.max_x = preLoad[1] self.max_y = preLoad[2] self.max_z = preLoad[3] preLoad = preLoad[0] # Note: it isn't particularly efficient to make every face as a separate Geom. # instead, it would be better to create one Geom holding all of the faces. snode = GeomNode('square') for element in preLoad: snode.addGeom(makeSquare(element[0], element[1], element[2], element[3], element[4], element[5], element[6])) print('done') ''' square0 = makeSquare(-1, -1, -1, 1, -1, 1, colorInfo) square1 = makeSquare(-1, 1, -1, 1, 1, 1, colorInfo) square2 = makeSquare(-1, 1, 1, 1, -1, 1, colorInfo) square3 = makeSquare(-1, 1, -1, 1, -1, -1, colorInfo) square4 = makeSquare(-1, -1, -1, -1, 1, 1, colorInfo) square5 = makeSquare(1, -1, -1, 1, 1, 1, colorInfo) snode = GeomNode('square') snode.addGeom(square0) snode.addGeom(square1) snode.addGeom(square2) snode.addGeom(square3) snode.addGeom(square4) snode.addGeom(square5) ''' self.cube = render.attachNewNode(snode) # OpenGl by default only draws "front faces" (polygons whose vertices are # specified CCW). self.cube.setTwoSided(True) #self.accept("1", self.toggleLightsSide) self.accept("w", self.keyW) self.accept("s", self.keyS) self.accept("a", self.keyA) self.accept("d", self.keyD) self.accept("arrow_left", self.arrow_left) self.accept("arrow_right", self.arrow_right) self.accept("arrow_up", self.arrow_up) self.accept("arrow_down", self.arrow_down) self.accept("wheel_up", self.wheel_up) self.accept("wheel_down", self.wheel_down) self.LightsOn = False ''' slight = Spotlight('slight') slight.setColor((1, 1, 1, 1)) lens = PerspectiveLens() slight.setLens(lens) self.slnp = render.attachNewNode(slight) dlight = DirectionalLight('dlight') dlight.setShadowCaster(True, 32, 32) dlnp = render.attachNewNode(dlight) self.dlnp = render.attachNewNode(dlight) ''' self.base.run() def wheel_up(self): y = self.base.camera.getY() print("camera position y: ", y) self.base.camera.setY(y - 5) def wheel_down(self): y = self.base.camera.getY() print("camera position y: ", y) self.base.camera.setY(y + 5) def arrow_up(self): p = self.base.camera.getP() print("camera position Pitch: ", p) self.base.camera.setP(p + 5) def arrow_down(self): p = self.base.camera.getP() print("camera position Pitch: ", p) self.base.camera.setP(p - 5) def arrow_left(self): h = self.base.camera.getH() print("camera position Yaw: ", h) self.base.camera.setH(h - 5) def arrow_right(self): h = self.base.camera.getH() print("camera position Yaw: ", h) self.base.camera.setH(h + 5) def keyW(self): z = self.base.camera.getZ() print("camera position z: ", z) self.base.camera.setZ(z - 5) def keyS(self): z = self.base.camera.getZ() print("camera position z: ", z) self.base.camera.setZ(z + 5) def keyA(self): x = self.base.camera.getX() print("camera position x: ", x) self.base.camera.setX(x - 5) def keyD(self): x = self.base.camera.getX() print("camera position x: ", x) self.base.camera.setX(x + 5) '''
class PandaController (object): DEFAULT_FULLSCREEN = False DEFAULT_WIDTH = 800 DEFAULT_HEIGHT = 600 DEFAULT_FPS = 60 DEFAULT_FRAME_METER = False DEFAULT_MUSIC_VOLUME = .3 DEFAULT_SOUND_VOLUME = .1 DEFAULT_MAX_DELTA = 1. / 20. DEFAULT_SHADERS = True def __init__ (self): super (PandaController, self).__init__ () self._timer = Timer () self._timer.max_delta = self.DEFAULT_MAX_DELTA self._tasks = task.TaskGroup () self._tasks.add (self._panda_task) self._music = None self._mouse_task = None self._relative_mouse = False @property def timer (self): return self._timer @property def tasks (self): return self._tasks def start (self, title): cfg = GlobalConf ().child ('panda') self.set_defaults (cfg) self.base = ShowBase () self.base.disableMouse () self.audio = self.base.sfxManagerList [0] self.audio3d = Audio3DManager (self.audio, camera) self.audio3d.setListenerVelocityAuto () self.audio3d.setDropOffFactor (0.1) # HACK self.create_properties (title) self.update_properties (cfg) self.listen_conf (cfg) loadPrcFileData ("", "interpolate-frames 1") loadPrcFileData ("", "support-threads #f") path = getModelPath () path.prependPath ('./data') self.base.enableParticles () def loop (self): self._timer.reset () self._timer.loop (self._loop_fn) def _loop_fn (self, timer): task_count = 1 # _panda_task if self._relative_mouse: task_count += 1 # _mouse_task if self._tasks.count > task_count: return self._tasks.update (timer) return False def set_defaults (self, cfg): cfg.child ('fps').default (self.DEFAULT_FPS) cfg.child ('width').default (self.DEFAULT_WIDTH) cfg.child ('height').default (self.DEFAULT_HEIGHT) cfg.child ('fullscreen').default (self.DEFAULT_FULLSCREEN) cfg.child ('frame-meter').default (self.DEFAULT_FRAME_METER) cfg.child ('music-volume').default (self.DEFAULT_MUSIC_VOLUME) cfg.child ('sound-volume').default (self.DEFAULT_SOUND_VOLUME) def listen_conf (self, cfg): cfg.on_conf_nudge += self.update_properties cfg.child ('fps').on_conf_change += self.update_fps cfg.child ('frame-meter').on_conf_change += self.update_frame_meter cfg.child ('music-volume').on_conf_change += self.update_music_volume cfg.child ('sound-volume').on_conf_change += self.update_sound_volume self.audio.setVolume (cfg.child ('sound-volume').value) def create_properties (self, title): self._prop = WindowProperties () self._prop.setTitle (title) def relative_mouse (self): if not self._relative_mouse: self._prop.setCursorHidden (True) self._prop.setMouseMode (WindowProperties.MRelative) self.base.win.requestProperties (self._prop) self._mouse_task = self._tasks.add (MouseTask ()) self._mouse_task.on_mouse_move += lambda x, y: \ messenger.send ('mouse-move', [(x, y)]) self._relative_mouse = True def absolute_mouse (self): if self._relative_mouse: self._relative_mouse = False if self._mouse_task: self._mouse_task.kill () self._prop.setCursorHidden (False) self._prop.setMouseMode (WindowProperties.MAbsolute) self.base.win.requestProperties (self._prop) def has_shaders (self): return self.base.win.getGsg().getSupportsBasicShaders() == 0 def update_properties (self, cfg): self._prop.setSize (cfg.child ('width').value, cfg.child ('height').value) self._prop.setFullscreen (cfg.child ('fullscreen').value) self.base.win.requestProperties (self._prop) self._timer.fps = cfg.child ('fps').value self.base.setFrameRateMeter (cfg.child ('frame-meter').value) def update_frame_meter (self, cfg): self.base.setFrameRateMeter (cfg.value) def update_fps (self, cfg): self._timer.fps = cfg.value def update_music_volume (self, cfg): if self._music: self._music.setVolume (cfg.value) def update_sound_volume (self, cfg): if self.audio: self.audio.setVolume (cfg.value) def _panda_task (self, timer): taskMgr.step () return task.running def set_background_color (self, *color): base.setBackgroundColor (*color) def loop_music (self, file): if self._music: self._music.setLoop (False) self.tasks.add (task.sequence ( task.linear (self._music.setVolume, self._music.getVolume (), 0.0))) volume = GlobalConf ().path ('panda.music-volume').value self._music = loader.loadSfx (file) self._music.setLoop (True) self.tasks.add (task.sequence ( task.linear (self._music.setVolume, 0.0, volume, init = True))) self._music.play ()
def runViewer(mesh): scene_members = getSceneMembers(mesh) loadPrcFileData('', 'win-size 300 300') base = ShowBase() globNode = GeomNode("collada") nodePath = base.render.attachNewNode(globNode) rotateNode = GeomNode("rotater") rotatePath = nodePath.attachNewNode(rotateNode) matrix = numpy.identity(4) if mesh.assetInfo.upaxis == collada.asset.UP_AXIS.X_UP: r = collada.scene.RotateTransform(0,1,0,90) matrix = r.matrix elif mesh.assetInfo.upaxis == collada.asset.UP_AXIS.Y_UP: r = collada.scene.RotateTransform(1,0,0,90) matrix = r.matrix rotatePath.setMat(Mat4(*matrix.T.flatten().tolist())) basecollada = GeomNode("basecollada") basecolladaNP = rotatePath.attachNewNode(basecollada) for geom, renderstate, mat4 in scene_members: node = GeomNode("primitive") node.addGeom(geom) if renderstate is not None: node.setGeomState(0, renderstate) geomPath = basecolladaNP.attachNewNode(node) geomPath.setMat(mat4) for boundlight in mesh.scene.objects('light'): if len(boundlight.color) == 3: color = (boundlight.color[0], boundlight.color[1], boundlight.color[2], 1) else: color = boundlight.color if isinstance(boundlight, collada.light.BoundDirectionalLight): dl = DirectionalLight('dirLight') dl.setColor(Vec4(color[0], color[1], color[2], color[3])) lightNP = rotatePath.attachNewNode(dl) lightNP.lookAt(Point3(boundlight.direction[0],boundlight.direction[1],boundlight.direction[2])) elif isinstance(boundlight, collada.light.BoundAmbientLight): ambientLight = AmbientLight('ambientLight') ambientLight.setColor(Vec4(color[0], color[1], color[2], color[3])) lightNP = rotatePath.attachNewNode(ambientLight) elif isinstance(boundlight, collada.light.BoundPointLight): pointLight = PointLight('pointLight') pointLight.setColor(Vec4(color[0], color[1], color[2], color[3])) pointLight.setAttenuation(Vec3(boundlight.constant_att, boundlight.linear_att, boundlight.quad_att)) lightNP = rotatePath.attachNewNode(pointLight) lightNP.setPos(Vec3(boundlight.position[0], boundlight.position[1], boundlight.position[2])) elif isinstance(boundlight, collada.light.BoundSpotLight): spotLight = Spotlight('spotLight') spotLight.setColor(Vec4(color[0], color[1], color[2], color[3])) spotLight.setAttenuation(Vec3(boundlight.constant_att, boundlight.linear_att, boundlight.quad_att)) spotLight.setExponent(boundlight.falloff_exp) lightNP = rotatePath.attachNewNode(spotLight) lightNP.setPos(Vec3(boundlight.position[0], boundlight.position[1], boundlight.position[2])) lightNP.lookAt(Point3(boundlight.direction[0], boundlight.direction[1], boundlight.direction[2]), Vec3(boundlight.up[0], boundlight.up[1], boundlight.up[2])) else: print('Unknown light type', boundlight) continue base.render.setLight(lightNP) for boundcam in mesh.scene.objects('camera'): if isinstance(boundcam, collada.camera.BoundPerspectiveCamera): base.camera.reparentTo(rotatePath) base.camLens.setNear(boundcam.znear) base.camLens.setFar(boundcam.zfar) if boundcam.xfov is not None and boundcam.yfov is not None: #xfov + yfov base.camLens.setFov(boundcam.xfov, boundcam.yfov) elif boundcam.xfov is not None and boundcam.aspect_ratio is not None: #xfov + aspect_ratio base.camLens.setFov(boundcam.xfov) base.camLens.setAspectRatio(boundcam.aspect_ratio) elif boundcam.yfov is not None and boundcam.aspect_ratio is not None: #yfov + aspect_ratio #aspect_ratio = tan(0.5*xfov) / tan(0.5*yfov) xfov = math.degrees(2.0 * math.atan(boundcam.aspect_ratio * math.tan(math.radians(0.5 * boundcam.yfov)))) base.camLens.setFov(xfov, boundcam.yfov) elif boundcam.yfov is not None: #yfov only #aspect_ratio = tan(0.5*xfov) / tan(0.5*yfov) xfov = math.degrees(2.0 * math.atan(base.camLens.getAspectRatio() * math.tan(math.radians(0.5 * boundcam.yfov)))) base.camLens.setFov(xfov, boundcam.yfov) elif boundcam.xfov is not None: base.camLens.setFov(boundcam.xfov) base.camera.setPos(Vec3(boundcam.position[0], boundcam.position[1], boundcam.position[2])) base.camera.lookAt(Point3(boundcam.direction[0], boundcam.direction[1], boundcam.direction[2]), Vec3(boundcam.up[0], boundcam.up[1], boundcam.up[2])) elif isinstance(boundcam, collada.camera.BoundOrthographicCamera): lens = OrthographicLens() base.cam.node().setLens(lens) base.camLens = lens base.camera.reparentTo(rotatePath) base.camLens.setNear(boundcam.znear) base.camLens.setFar(boundcam.zfar) if boundcam.xmag is not None and boundcam.ymag is not None: #xmag + ymag base.camLens.setFilmSize(boundcam.xmag, boundcam.ymag) elif boundcam.xmag is not None and boundcam.aspect_ratio is not None: #xmag + aspect_ratio base.camLens.setFilmSize(boundcam.xmag) base.camLens.setAspectRatio(boundcam.aspect_ratio) elif boundcam.ymag is not None and boundcam.aspect_ratio is not None: #ymag + aspect_ratio xmag = boundcam.aspect_ratio * boundcam.ymag base.camLens.setFilmSize(xmag, boundcam.ymag) elif boundcam.ymag is not None: #ymag only xmag = base.camLens.getAspectRatio() * boundcam.ymag base.camLens.setFilmSize(xmag, boundcam.ymag) elif boundcam.xmag is not None: base.camLens.setFilmSize(boundcam.xmag) base.camera.setPos(Vec3(boundcam.position[0], boundcam.position[1], boundcam.position[2])) base.camera.lookAt(Point3(boundcam.direction[0], boundcam.direction[1], boundcam.direction[2]), Vec3(boundcam.up[0], boundcam.up[1], boundcam.up[2])) else: print('Unknown camera type', boundcam) continue base.disableMouse() base.render.setShaderAuto() base.render.setTransparency(TransparencyAttrib.MDual, 1) KeyboardMovement() MouseDrag(basecolladaNP) MouseScaleZoom(basecolladaNP) base.run()
def __init__(self, f_plane_node=None, exp='z =', root=None, x_minus=-gv.DEFAULT_3D_AXE, x_plus=gv.DEFAULT_3D_AXE, y_minus=-gv.DEFAULT_3D_AXE, y_plus=gv.DEFAULT_3D_AXE): ShowBase.__init__(self) # set window title props = WindowProperties() props.setTitle('z = ' + exp) # props.set_fixed_size(self) self.win.requestProperties(props) self.root = root self.x_minus = x_minus self.x_plus = x_plus self.y_minus = y_minus self.y_plus = y_plus repeater_m1 = Repeater('mouse1', 0.02) repeater_m3 = Repeater('mouse3', 0.02) self.scene = None if gv.is_debug_mode: self.scene = self.set_sceen() self.setBackgroundColor(gv.background_color) self.f_node_path = self.render.attachNewNode(f_plane_node) self.z_scale = 1 self.is_show_help = False self.z_scale_header = OnscreenText( text='z scale', fg=gv.widget_header_color, pos=(gv.widget_col_left + 0 * gv.widget_col_size, gv.widget_header_row), scale=gv.widget_text_scale) self.z_scale_value = OnscreenText( text=str(self.z_scale), fg=gv.widget_value_color, pos=(gv.widget_col_left + 0 * gv.widget_col_size, gv.widget_header_row - 1 * gv.widget_row_height), scale=gv.widget_text_scale) self.resolution_header = OnscreenText( text='Resolution', fg=gv.widget_header_color, pos=(gv.widget_col_left + 1 * gv.widget_col_size, gv.widget_header_row), scale=gv.widget_text_scale) self.resolution_value = OnscreenText( text=str(gv.points_in_list), fg=gv.widget_value_color, pos=(gv.widget_col_left + 1 * gv.widget_col_size, gv.widget_header_row - 1 * gv.widget_row_height), scale=gv.widget_text_scale) self.infi_header = OnscreenText( text='Infinity', fg=gv.widget_header_color, pos=(gv.widget_col_left + 2 * gv.widget_col_size, gv.widget_header_row), scale=gv.widget_text_scale) self.infi_value = OnscreenText( text=str(gv.INFINITY), fg=gv.widget_value_color, pos=(gv.widget_col_left + 2 * gv.widget_col_size, gv.widget_header_row - 1 * gv.widget_row_height), scale=gv.widget_text_scale) self.help_header = OnscreenText(text='help: h', fg=gv.widget_header_color, pos=(gv.widget_row_right_pos, gv.widget_header_row), scale=gv.widget_text_scale) self.help_value = OnscreenText(text='', fg=gv.widget_header_color, pos=(gv.widget_help_col, gv.widget_help_row), scale=gv.widget_text_scale, align=TextNode.ALeft) # enable my camera control ShowBase.disableMouse(self) # define the camera position with Radius Teta Fi coordinates self.reset_cam_pos() # handle events self.accept('arrow_up', self.move_cam_up) self.accept('arrow_up-repeat', self.move_cam_up) self.accept('arrow_down', self.move_cam_down) self.accept('arrow_down-repeat', self.move_cam_down) self.accept('mouse3', self.move_cam_right) self.accept('mouse3-repeat', self.move_cam_right) self.accept('arrow_right', self.move_cam_right) self.accept('arrow_right-repeat', self.move_cam_right) self.accept('mouse1', self.move_cam_left) self.accept('mouse1-repeat', self.move_cam_left) self.accept('arrow_left', self.move_cam_left) self.accept('arrow_left-repeat', self.move_cam_left) self.accept('wheel_up', self.zoom_in) self.accept('j', self.zoom_in) self.accept('j-repeat', self.zoom_in) self.accept('insert', self.zoom_in) self.accept('insert-repeat', self.zoom_in) self.accept('wheel_down', self.zoom_out) self.accept('m', self.zoom_out) self.accept('m-repeat', self.zoom_out) self.accept('delete', self.zoom_out) self.accept('delete-repeat', self.zoom_out) self.accept('4', self.move_down_x) self.accept('4-repeat', self.move_down_x) self.accept('6', self.move_up_x) self.accept('6-repeat', self.move_up_x) self.accept('2', self.move_down_y) self.accept('2-repeat', self.move_down_y) self.accept('8', self.move_up_y) self.accept('8-repeat', self.move_up_y) self.accept('page_down', self.move_down_z) self.accept('page_down-repeat', self.move_down_z) self.accept('page_up', self.move_up_z) self.accept('page_up-repeat', self.move_up_z) self.accept('l', self.move_down_z) self.accept('l-repeat', self.move_down_z) self.accept('o', self.move_up_z) self.accept('o-repeat', self.move_up_z) self.accept('0', self.reset_pos_00) self.accept('5', self.reset_pos_00) self.accept('a', self.scale_up_z) self.accept('a-repeat', self.scale_up_z) self.accept('z', self.scale_down_z) self.accept('z-repeat', self.scale_down_z) self.accept('s', lambda: self.change_resolution(12 / 10)) self.accept('x', lambda: self.change_resolution(10 / 12)) self.accept('d', lambda: self.change_infinity(2)) self.accept('c', lambda: self.change_infinity(0.5)) self.accept('h', self.toggle_help) self.accept('escape', self.hide_help)
def __init__(self, mesh_path, progressive_texture_path): resolutions = [] f = tarfile.open(progressive_texture_path) for resolution_name in f.getnames(): toset = { 'size': resolution_name[:-4], 'contents': f.extractfile(resolution_name).read() } texpnm = PNMImage() texpnm.read(StringStream(toset['contents']), 'something.jpg') newtex = Texture() newtex.load(texpnm) toset['texture'] = newtex resolutions.append(toset) self.resolutions = resolutions def aux_loader(fname): return resolutions[0]['contents'] mesh = collada.Collada(mesh_path, aux_file_loader=aux_loader) scene_members = getSceneMembers(mesh) base = ShowBase() rotateNode = GeomNode("rotater") rotatePath = render.attachNewNode(rotateNode) matrix = numpy.identity(4) if mesh.assetInfo.upaxis == collada.asset.UP_AXIS.X_UP: r = collada.scene.RotateTransform(0, 1, 0, 90) matrix = r.matrix elif mesh.assetInfo.upaxis == collada.asset.UP_AXIS.Y_UP: r = collada.scene.RotateTransform(1, 0, 0, 90) matrix = r.matrix rotatePath.setMat(Mat4(*matrix.T.flatten().tolist())) geom, renderstate, mat4 = scene_members[0] node = GeomNode("primitive") node.addGeom(geom) if renderstate is not None: node.setGeomState(0, renderstate) self.geomPath = rotatePath.attachNewNode(node) self.geomPath.setMat(mat4) wrappedNode = ensureCameraAt(self.geomPath, base.camera) base.disableMouse() attachLights(render) render.setShaderAuto() render.setTransparency(TransparencyAttrib.MDual, 1) base.render.analyze() KeyboardMovement() MouseDrag(wrappedNode) MouseScaleZoom(wrappedNode) MouseCamera() num_resolutions = len(resolutions) - 1 self.slider = DirectSlider(range=(0, num_resolutions), value=0, pageSize=1, command=self.sliderMoved, pos=(0, 0, -.9), scale=1) for key, val in uiArgs.iteritems(): self.slider.thumb[key] = val self.triText = OnscreenText(text="", pos=(-1, 0.85), scale=0.15, fg=(1, 0.5, 0.5, 1), align=TextNode.ALeft, mayChange=1) base.run()
def main(): from asyncio import get_event_loop from threading import Thread # server bits from server import tokenManager, requestCacheManager, responseMaker, make_shutdown from .defaults import CONNECTION_PORT, DATA_PORT # render setup from direct.showbase.ShowBase import ShowBase from panda3d.core import loadPrcFileData from panda3d.core import PStatClient from .render_manager import renderManager from .selection import BoxSel from .util.util import ui_text, console, exit_cleanup, frame_rate, startup_data from .ui import CameraControl, Axis3d, Grid3d, GuiFrame from .protocols import connectionServerProtocol, dataServerProtocol from .protocols import dataClientProtocol from .util.process_fixed import ProcessPoolExecutor_fixed as ProcessPoolExecutor from .keys import AcceptKeys # common event_loop = get_event_loop() ppe = ProcessPoolExecutor() # server tm = tokenManager() rcm = requestCacheManager(0) conServ = connectionServerProtocol(tm) datServ = dataServerProtocol(event_loop, responseMaker, rcm, tm, ppe) coro_conServer = event_loop.create_server(conServ, '127.0.0.1', CONNECTION_PORT, ssl=None) # TODO ssl coro_dataServer = event_loop.create_server( datServ, '127.0.0.1', DATA_PORT, ssl=None) # TODO ssl and this can be another box serverCon = event_loop.run_until_complete(coro_conServer) serverData = event_loop.run_until_complete(coro_dataServer) # client PStatClient.connect() #run pstats in console loadPrcFileData('', 'view-frustum-cull 0') base = ShowBase() base.setBackgroundColor(0, 0, 0) base.disableMouse() # TODO init all these into a dict or summat? startup_data() frame_rate() ut = ui_text() grid = Grid3d() axis = Axis3d() cc = CameraControl() frames = {'data': GuiFrame('Data view')} rendMan = renderManager(event_loop, ppe) bs = BoxSel(frames) datCli_base = dataClientProtocol(rendMan.render_callback, rendMan.set_send_request, rendMan.cache, event_loop) datCli = datCli_base() datCli.connection_lost('START') eventThread = Thread(target=event_loop.run_forever) eventThread.start() con = console(locals(), True) shutdown = make_shutdown(event_loop, eventThread, serverCon, serverData, ppe) el = exit_cleanup(event_loop, ppe, datCli.transport, shutdown) ac = AcceptKeys() base.run()
else: print("Connection not opened.") #error clause print("connecting to server") connection = ssh( "192.168.43.88", "pi", "raspberry" ) #will change if network is changed but is static on my hotspot #so not changing it for now #can't send multiple commands without closing channel, so one long one instead ########################## Start of renderer ###################################### #sets up the renderer base = ShowBase() base.disableMouse() #this position and orientation puts the camera at the back of the plane, facing the plane base.camera.setPos(0, 11000, 800) base.camera.setHpr(180, 0, 0) #"testingmats2.x" is the plane model #its named like that because I had to try many times before I got the mats to work with the .mtl file #it was originally named cube because it was an actual cube, and now theres no point in changing it cube = loader.loadModel("Testingmats2.x") #setscale is self explanatory cube.setScale(1) #attaches the plane to the renderer cube.reparentTo(base.render) #shows the "plane visualizer" text onscreen
import sys try: import _tkinter except: sys.exit("Please install python module 'Tkinter'") try: import Pmw except: sys.exit("Please install Python megawidgets") # Makes sure that Panda is configured to play nice with Tkinter from panda3d.core import * loadPrcFileData("", "want-tk true") # Open the Panda window from direct.showbase.ShowBase import ShowBase base = ShowBase() from direct.tkpanels.ParticlePanel import ParticlePanel pp = ParticlePanel() # Create the panel base.disableMouse() # Disable camera control to place it base.camera.setY(-10) # Place the camera base.setBackgroundColor(0, 0, 0) # Most particle systems show up better on black backgrounds base.run()