Exemplo n.º 1
0
 def __init__(self):
     # The basics
     ShowBase.__init__(self)
     base.disableMouse()
     base.setBackgroundColor(0.1, 0.1, 0.1)
     base.setFrameRateMeter(True)
     PStatClient.connect()
     self.accept("escape", sys.exit)
     # Camera
     self.camera_orbit = base.render.attach_new_node("Camera orbit")
     self.camera_pitch = self.camera_orbit.attach_new_node("Camera pitch")
     base.camera.reparent_to(self.camera_pitch)
     base.camera.set_pos(0, -30, 0)
     # Camera control
     self.camera_movement = (0, 0)
     self.accept("arrow_up",       self.change_camera_movement, [ 0, -1])
     self.accept("arrow_up-up",    self.change_camera_movement, [ 0,  1])
     self.accept("arrow_down",     self.change_camera_movement, [ 0,  1])
     self.accept("arrow_down-up",  self.change_camera_movement, [ 0, -1])
     self.accept("arrow_left",     self.change_camera_movement, [-1,  0])
     self.accept("arrow_left-up",  self.change_camera_movement, [ 1,  0])
     self.accept("arrow_right",    self.change_camera_movement, [ 1,  0])
     self.accept("arrow_right-up", self.change_camera_movement, [-1,  0])
     base.taskMgr.add(self.move_camera, "Move camera")
     # Object
     self.model = self.create_model()
     self.model.reparent_to(base.render)
     taskMgr.add(self.refresh_shader_vars, "Refresh shaders variables", sort = 49)
     self.accept("r", self.reload_shader)
Exemplo n.º 2
0
    def __init__(self, experiment_structure, profile_on=False):
        super().__init__()
        self.current_stim_num = 0
        self.stim_classes = experiment_structure['stim_classes']
        self.stim_values = experiment_structure['stim_values']
        self.stim_durations = experiment_structure['stim_durations']
        self.stim_change_times = np.cumsum(
            self.stim_durations)  #times to switch
        self.bgcolor = (1, 1, 1, 1)

        #Set up profiling if desired
        if profile_on:
            PStatClient.connect()

        #Window properties
        self.windowProps = WindowProperties()
        self.windowProps.setSize(512, 512)

        #Create scenegraph
        cm = CardMaker('card')
        cm.setFrameFullscreenQuad()
        self.card = self.aspect2d.attachNewNode(cm.generate())
        self.card.setScale(np.sqrt(8))
        self.card.setColor(self.bgcolor)  #make this an add mode

        #Set initial texture
        self.taskMgr.add(self.set_stim_task, "set_stimulus_class")
Exemplo n.º 3
0
def main():
    """Console script for LayerView."""
    args = _get_parser().parse_args()

    # PStats
    pstat_host: str = args.pstat_host
    if pstat_host:
        if args.pstat_port:
            pstat_port: int = args.pstat_port
        else:
            pstat_port: int = _PSTAT_PORT_DEFAULT
            print(f"PStats port not specified, falling back to {pstat_port}")

        print(f"Connecting to PStats server at {pstat_host}:{pstat_port}")
        # noinspection PyArgumentList
        PStatClient.connect(pstat_host, pstat_port)
    elif not pstat_host and args.pstat_port:
        print("--pstats-port was specified without --pstats-host")
        return 1

    gcode_path: Optional[Path] = None
    if args.gcode_path:
        gcode_path = Path(args.gcode_path).absolute()

    # Run app
    app = App(argv=sys.argv, gcode_path=gcode_path)
    app.show()
    return app.exec_()
Exemplo n.º 4
0
 def __init__(self):
     # The basics
     ShowBase.__init__(self)
     base.disableMouse()
     base.setBackgroundColor(0.1, 0.1, 0.1)
     base.setFrameRateMeter(True)
     PStatClient.connect()
     self.accept("escape", sys.exit)
     # Camera
     self.camera_orbit = base.render.attach_new_node("Camera orbit")
     self.camera_pitch = self.camera_orbit.attach_new_node("Camera pitch")
     base.camera.reparent_to(self.camera_pitch)
     base.camera.set_pos(0, -30, 0)
     # Camera control
     self.camera_movement = (0, 0)
     self.accept("arrow_up", self.change_camera_movement, [0, -1])
     self.accept("arrow_up-up", self.change_camera_movement, [0, 1])
     self.accept("arrow_down", self.change_camera_movement, [0, 1])
     self.accept("arrow_down-up", self.change_camera_movement, [0, -1])
     self.accept("arrow_left", self.change_camera_movement, [-1, 0])
     self.accept("arrow_left-up", self.change_camera_movement, [1, 0])
     self.accept("arrow_right", self.change_camera_movement, [1, 0])
     self.accept("arrow_right-up", self.change_camera_movement, [-1, 0])
     base.taskMgr.add(self.move_camera, "Move camera")
     # Object
     self.model = self.create_model()
     self.model.reparent_to(base.render)
     taskMgr.add(self.refresh_shader_vars,
                 "Refresh shaders variables",
                 sort=49)
     self.accept("r", self.reload_shader)
Exemplo n.º 5
0
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()
Exemplo n.º 6
0
    def __init__(self):
        self.loadDefaultConfig()
        self.loadLocalConfig()

        if ConfigVariableBool("want-pstats", False):
            PStatClient.connect()

        # Set up some global objects
        self.globalClock = ClockObject.getGlobalClock()
        # We will manually manage the clock
        self.globalClock.setMode(ClockObject.MSlave)
        builtins.globalClock = self.globalClock

        self.vfs = VirtualFileSystem.getGlobalPtr()

        # For tasks that run every application frame
        self.taskMgr = TaskManagerGlobal.taskMgr
        builtins.taskMgr = self.taskMgr

        # For tasks that run every simulation tick
        self.simTaskMgr = Task.TaskManager()
        self.simTaskMgr.mgr = AsyncTaskManager("sim")
        builtins.simTaskmgr = self.simTaskMgr

        self.eventMgr = EventManagerGlobal.eventMgr
        builtins.eventMgr = self.eventMgr

        self.messenger = MessengerGlobal.messenger
        builtins.messenger = self.messenger

        self.loader = Loader(self)
        builtins.loader = self.loader

        builtins.base = self

        # What is the current frame number?
        self.frameCount = 0
        # Time at beginning of current frame
        self.frameTime = self.globalClock.getRealTime()
        # How long did the last frame take.
        self.deltaTime = 0

        #
        # Variables pertaining to simulation ticks.
        #

        self.prevRemainder = 0
        self.remainder = 0
        # What is the current overall simulation tick?
        self.tickCount = 0
        # How many ticks are we going to run this frame?
        self.totalTicksThisFrame = 0
        # How many ticks have we run so far this frame?
        self.currentTicksThisFrame = 0
        # What tick are we currently on this frame?
        self.currentFrameTick = 0
        # How many simulations ticks are we running per-second?
        self.ticksPerSec = 60
        self.intervalPerTick = 1.0 / self.ticksPerSec
Exemplo n.º 7
0
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()
Exemplo n.º 8
0
Arquivo: main.py Projeto: onze/goLive
 def enterInit(self):
    '''
    init of main/global structures
    '''
    self.screen = Screen()
    if ConfigVariableBool('stats').getValue():
       self.update_gaming=pstat(self.update_gaming)
       PStatClient.connect()         
    taskMgr.add(self.update, 'GameClient.update')
    self.acceptOnce('escape',self.demand,extraArgs=['Quit'])
    self.demand('Intro')
Exemplo n.º 9
0
    def __init__(self):
        """Setup this app."""
        ShowBase.__init__(self)

        #Setup window
        wnd_props = WindowProperties()
        wnd_props.set_title("Neo Impressive Title")
        #wnd_props.set_origin(0, 0)
        wnd_props.set_size(1024, 768)
        self.win.request_properties(wnd_props)

        self.set_background_color(0, .5, 1, 1)

        #Init GUI sub-system
        self.gui = GUI(self)
        self.gui.run()

        #Init app state
        self.state = APP_STATE_LOGO
        self.logo_delay = 600

        #Start title music
        self.title_music = loader.loadMusic("./data/sounds/title.ogg")
        self.title_music.set_loop(True)
        self.title_music.play()

        #Setup collision detection
        self.cTrav = CollisionTraverser()

        self.portal_handler = CollisionHandlerEvent()
        self.portal_handler.add_in_pattern("%fn-entered-%in")

        #Init other sub-systems
        self.cam_mgr = CameraManager()
        self.world_mgr = WorldManager()

        #Setup lighting
        self.ambient = AmbientLight("Ambient Light")
        self.ambient.set_color(Vec4(.5, .5, .5, 1))
        self.ambient_np = self.render.attach_new_node(self.ambient)
        self.render.set_light(self.ambient_np)

        self.sun = DirectionalLight("Sun")
        self.sun_np = self.render.attach_new_node(self.sun)
        self.sun_np.set_p(-135)
        self.render.set_light(self.sun_np)

        #Setup auto-shaders
        self.render.set_shader_auto()

        #Debug stats
        #self.messenger.toggle_verbose()
        PStatClient.connect()
Exemplo n.º 10
0
    def __init__(self,
                 tex_classes,
                 stim_params,
                 initial_tex_ind=0,
                 window_size=512,
                 window_name="InputControlStim",
                 profile_on=False,
                 fps=30,
                 save_path=None):
        super().__init__()

        self.current_tex_num = initial_tex_ind
        self.previous_tex_num = None
        self.tex_classes = tex_classes
        self.stim_params = stim_params
        self.window_size = window_size
        self.stimulus_initialized = False  # for setting up first stim (don't clear cards they don't exist)
        self.fps = fps
        self.profile_on = profile_on
        self.save_path = save_path
        if self.save_path:
            self.filestream = utils.save_initialize(save_path, tex_classes,
                                                    stim_params)
        else:
            self.filestream = None
        self.scale = np.sqrt(
            8)  #so it can handle arbitrary rotations and shifts
        self.window_name = window_name

        #Window properties
        self.window_props = WindowProperties()
        self.window_props.setSize(self.window_size, self.window_size)
        self.set_title(self.window_name)

        # Set frame rate
        ShowBaseGlobal.globalClock.setMode(ClockObject.MLimited)
        ShowBaseGlobal.globalClock.setFrameRate(self.fps)

        #Set up profiling if desired
        if self.profile_on:
            PStatClient.connect()  # this will only work if pstats is running
            ShowBaseGlobal.base.setFrameRateMeter(True)  #Show frame rate

        #Set initial texture(s)
        self.set_stimulus(str(self.current_tex_num))

        # Set up event handlers (accept) and tasks (taskMgr) for dynamics
        self.accept('stim0', self.set_stimulus, ['0'])
        self.accept('stim1', self.set_stimulus, ['1'])
        self.accept('stim2', self.set_stimulus, ['2'])
        # Wrinkle: should we set this here or there?
        self.taskMgr.add(self.move_textures, "move textures")
Exemplo n.º 11
0
 def __igLoop(self):
     if self.renderRequested:
         self.graphicsEngine.renderFrame()
         #self.graphicsEngine.syncFrame()
         #self.graphicsEngine.readyFlip()
         self.graphicsEngine.flipFrame()
         #self.graphicsEngine.openWindows()
         self.renderRequested = False
     else:
         #self.graphicsEngine.flipFrame()
         self.globalClock.tick()
         PStatClient.mainTick()
     throwNewFrame()
    def tryStartPstats(self):
        """ Starts the 'text-stats' PStatClient and connects to that client, in order
        to make pstats generate timings """
        self.procHandle = None

        if not PStatClient.getGlobalPstats().isConnected() and self.startDummyPstats:
            self.debug("Starting dummy pstats (text-stats)")
            nullFile = open(os.devnull, 'w')
            self.procHandle = subprocess.Popen(["text-stats"], stdout=nullFile, stderr=nullFile)
            atexit.register(self.stopPstats)
            PStatClient.connect()
        else:
            self.debug("PStats already running")
Exemplo n.º 13
0
    def __init__(self,
                 tex,
                 angle=0,
                 velocity=0.1,
                 fps=30,
                 window_name="ShowTexMoving",
                 window_size=None,
                 profile_on=False):
        super().__init__()
        self.tex = tex
        if window_size is None:
            self.window_size = self.tex.texture_size
        else:
            self.window_size = window_size
        self.angle = angle
        self.velocity = velocity
        self.texture_stage = TextureStage("texture_stage")
        self.window_name = window_name

        # Set frame rate (fps)
        ShowBaseGlobal.globalClock.setMode(ClockObject.MLimited)
        ShowBaseGlobal.globalClock.setFrameRate(fps)

        #Set up profiling if desired
        if profile_on:
            PStatClient.connect(
            )  # this will only work if pstats is running: see readme
            ShowBaseGlobal.base.setFrameRateMeter(True)  #Show frame rate
            self.center_indicator = None

        #Window properties set up
        self.window_properties = WindowProperties()
        self.window_properties.setSize(self.window_size, self.window_size)
        self.window_properties.setTitle(window_name)
        ShowBaseGlobal.base.win.requestProperties(self.window_properties)

        #Create scenegraph, attach stimulus to card.
        cm = CardMaker('card')
        cm.setFrameFullscreenQuad()
        self.card = self.aspect2d.attachNewNode(cm.generate())
        # Scale is so it can handle arbitrary rotations and shifts in binocular case
        self.card.setScale(np.sqrt(8))
        self.card.setColor(
            (1, 1, 1, 1)
        )  # makes it bright when bright (default combination with card is add)
        self.card.setTexture(self.texture_stage, self.tex.texture)
        self.card.setTexRotate(self.texture_stage, self.angle)

        if self.velocity != 0:
            #Add task to taskmgr to translate texture
            self.taskMgr.add(self.moveTextureTask, "moveTextureTask")
Exemplo n.º 14
0
    def __init__(self,
                 tex_classes,
                 stim_params,
                 window_size=512,
                 profile_on=False,
                 fps=30,
                 save_path=None):
        super().__init__()

        self.tex_classes = tex_classes
        self.current_tex_num = 0
        self.stim_params = stim_params
        self.window_size = window_size
        self.stimulus_initialized = False  #to handle case from -1 (uninitalize) to 0 (first stim)
        self.fps = fps
        self.save_path = save_path
        if self.save_path:
            self.filestream = utils.save_initialize(save_path, tex_classes,
                                                    stim_params)
        else:
            self.filestream = None

        #Window properties
        self.windowProps = WindowProperties()
        self.windowProps.setSize(self.window_size, self.window_size)
        self.set_title("Initializing")

        #Create scenegraph
        cm = CardMaker('card')
        cm.setFrameFullscreenQuad()
        self.card = self.aspect2d.attachNewNode(cm.generate())
        self.card.setScale(np.sqrt(8))
        self.texture_stage = TextureStage("texture_stage")

        # Set frame rate
        ShowBaseGlobal.globalClock.setMode(ClockObject.MLimited)
        ShowBaseGlobal.globalClock.setFrameRate(
            self.fps)  #can lock this at whatever

        if profile_on:
            PStatClient.connect()
            ShowBaseGlobal.base.setFrameRateMeter(True)

        #Set initial texture
        self.set_stimulus(str(self.current_tex_num))

        # Set up event handlers and tasks
        self.accept('0', self.set_stimulus, ['0'])  #event handler
        self.accept('1', self.set_stimulus, ['1'])
        self.taskMgr.add(self.move_texture_task, "move_texture")  #task
Exemplo n.º 15
0
 def __init__(self):
     ShowBase.__init__(self)
     logging.basicConfig(level=logging.DEBUG)
     log.info("initializing...")
     #
     self.disableMouse()
     self.setFrameRateMeter(True)
     self.render.setShaderAuto()
     #
     gameplay=Gameplay(self)
     gameplay.start()
     #
     PStatClient.connect()
     #
     log.info("done initializing")
def pstats(host='localhost', port=5185):
    """ Tell the AI to connect a PStatsClient to the server specified. """
    conn = PStatClient.connect(host, port)
    if conn:
        return "%s has successfully opened a PStat connection to %s:%d" % (
            simbase.air.distributedDistrict.getName(), host, port)
    return "%s was unable to open a PStat connection to %s:%d." % (
        simbase.air.distributedDistrict.getName(), host, port)
Exemplo n.º 17
0
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()
Exemplo n.º 18
0
    def __pstats(self, event):
        box = event.GetEventObject()
        box.Disable()

        if box.GetValue():
            if not self.getProcesses('pstats'):
                subprocess.Popen([self.getPStatsPath()])

            PStatClient.connect()
        else:
            PStatClient.disconnect()

            for process in self.getProcesses('pstats'):
                process.kill()

        taskMgr.doMethodLater(1, lambda task: box.Enable(),
                              'enableElement-%d' % id(box))
Exemplo n.º 19
0
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 pstats(host='localhost', port=5185):
    """ Tell the AI to connect a PStatsClient to the server specified. """
    conn = PStatClient.connect(host, port)
    if conn:
        return "%s has successfully opened a PStat connection to %s:%d" % (
            simbase.air.distributedDistrict.getName(), host, port)
    return "%s was unable to open a PStat connection to %s:%d." % (
        simbase.air.distributedDistrict.getName(), host, port)
Exemplo n.º 21
0
    def go(self):
        if (PStatClient.connect() == 0):
            # No pstat server - create it, then try and connect again...
            self.pstats = subprocess.Popen(['pstats'])

            # Need to give pstats some time to warm up - use a do latter task...
            def tryAgain(task):
                PStatClient.connect()

            taskMgr.doMethodLater(0.5, tryAgain, 'pstats again')
Exemplo n.º 22
0
    def run_with_profiling(self, *args, **kwargs):
        import cProfile
        from trosnoth.utils.profiling import KCacheGrindOutputter

        try:
            from panda3d.core import PStatClient
            PStatClient.connect()
        except ImportError:
            pass

        prof = cProfile.Profile()

        try:
            prof.runcall(self.run_twisted, *args, **kwargs)
        except SystemExit:
            pass
        finally:
            kg = KCacheGrindOutputter(prof)
            with open('trosnoth.log', 'w') as f:
                kg.output(f)
Exemplo n.º 23
0
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 togglePStats(self):
     if PStatClient.isConnected():
         PStatClient.disconnect()
     else:
         # in production, show stats viewer on the server
         if base.config.GetBool("pstats-view-on-server", False):
             PStatClient.connect("127.0.0.1" if not metadata.IS_PRODUCTION
                                 else "gameserver.coginvasion.online")
         else:
             PStatClient.connect("127.0.0.1")
Exemplo n.º 25
0
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?
Exemplo n.º 26
0
    def run(self):
        while self.running:

            # Manually advance the clock
            now = self.globalClock.getRealTime()
            self.deltaTime = now - self.frameTime
            self.frameTime = now

            self.globalClock.setFrameTime(self.frameTime)
            self.globalClock.setDt(self.deltaTime)
            self.globalClock.setFrameCount(self.frameCount)

            # Tick PStats if we are connected
            PStatClient.mainTick()

            self.preRunFrame()

            self.runFrame()

            self.postRunFrame()

            self.frameCount += 1
Exemplo n.º 27
0
 def update(self, entities_by_filter):
     context = base.device_listener.read_context('debug')
     if context['quit']:
         sys.exit()
     if context['pdb']:
         import pdb
         pdb.set_trace()
     if context['pstats']:
         base.pstats = True
         PStatClient.connect()
     if context['frame_rate_meter']:
         self.frame_rate_meter = not self.frame_rate_meter
         base.set_frame_rate_meter(self.frame_rate_meter)
     if context['console']:
         if not hasattr(base, 'console'):
             print("No console present.")
             return
         self.console_open = not self.console_open
         if self.console_open:
             base.console.node().show()
         else:
             base.console.node().hide()
Exemplo n.º 28
0
 def __init__(self, create_model=True):
     # The basics
     ShowBase.__init__(self)
     base.disableMouse()
     base.setBackgroundColor(0, 0, 0)
     base.setFrameRateMeter(True)
     PStatClient.connect()
     self.accept("escape", sys.exit)
     # Camera
     self.camera_orbit = base.render.attach_new_node("Camera orbit")
     self.camera_pitch = self.camera_orbit.attach_new_node("Camera pitch")
     base.camera.reparent_to(self.camera_pitch)
     base.camera.set_pos(0, -10, 0)
     self.rotation_mode = False
     self.mouse_pos = None
     self.accept("mouse3", self.set_rotation_mode, [True])
     self.accept("mouse3-up", self.set_rotation_mode, [False])
     self.accept("wheel_up", self.move_camera_distance, [-1])
     self.accept("wheel_down", self.move_camera_distance, [1])
     base.taskMgr.add(self.move_camera, "Move camera")
     # Object
     if create_model:
         self.create_model()
Exemplo n.º 29
0
 def __init__(self, create_model=True):
     # The basics
     ShowBase.__init__(self)
     base.disableMouse()
     base.setBackgroundColor(0, 0, 0)
     base.setFrameRateMeter(True)
     PStatClient.connect()
     self.accept("escape", sys.exit)
     # Camera
     self.camera_orbit = base.render.attach_new_node("Camera orbit")
     self.camera_pitch = self.camera_orbit.attach_new_node("Camera pitch")
     base.camera.reparent_to(self.camera_pitch)
     base.camera.set_pos(0, -10, 0)
     self.rotation_mode = False
     self.mouse_pos = None
     self.accept("mouse3", self.set_rotation_mode, [True])
     self.accept("mouse3-up", self.set_rotation_mode, [False])
     self.accept("wheel_up", self.move_camera_distance, [-1])
     self.accept("wheel_down", self.move_camera_distance, [1])
     base.taskMgr.add(self.move_camera, "Move camera")
     # Object
     if create_model:
         self.create_model()
Exemplo n.º 30
0
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
Exemplo n.º 31
0
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
Exemplo n.º 32
0
    def __init__(self):
        ShowBase.__init__(self)

        #input setup
        self.keys = {"w": 0, "t": 0}

        #socket init
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.socket.connect((host, port))

        self.toSend = Queue.Queue(1000)
        self.toProcess = Queue.Queue(1000)
        self.level = None

        self.socket.setblocking(False)

        self.taskMgr.add(self.play, "play")
        self.keyboardSetup()
        self.msg()
        self.requestLevel()
        self.msg()
        print "PStatClient.connect:", PStatClient.connect("localhost", 5185)
Exemplo n.º 33
0
	def __init__(self):
		ShowBase.__init__(self)

		#input setup
		self.keys={"w"      :0,
				   "t"      :0
				   }

		#socket init
		self.socket= socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		self.socket.connect((host,port))

		self.toSend    =Queue.Queue(1000)
		self.toProcess =Queue.Queue(1000)
		self.level=None

		self.socket.setblocking(False)

		self.taskMgr.add(self.play,"play")
		self.keyboardSetup()
		self.msg()
		self.requestLevel()
		self.msg()
		print "PStatClient.connect:",PStatClient.connect("localhost" ,5185)
Exemplo n.º 34
0
    def __init__(self):
        DirectObject.__init__(self)

        if ConfigVariableBool("want-pstats", False):
            PStatClient.connect()

        self.docTitle = ""
        self.viewportName = ""

        self.renderRequested = False

        ###################################################################
        # Minimal emulation of ShowBase glue code. Note we're not using
        # ShowBase because there's too much going on in there that assumes
        # too much (one camera, one lens, one aspect2d, lots of bloat).

        self.graphicsEngine = GraphicsEngine.getGlobalPtr()
        self.pipe = GraphicsPipeSelection.getGlobalPtr().makeDefaultPipe()
        if not self.pipe:
            self.notify.error("No graphics pipe is available!")
            return

        self.globalClock = ClockObject.getGlobalClock()
        # Since we have already started up a TaskManager, and probably
        # a number of tasks; and since the TaskManager had to use the
        # TrueClock to tell time until this moment, make sure the
        # globalClock object is exactly in sync with the TrueClock.
        trueClock = TrueClock.getGlobalPtr()
        self.globalClock.setRealTime(trueClock.getShortTime())
        self.globalClock.tick()
        builtins.globalClock = self.globalClock

        self.loader = CogInvasionLoader(self)
        self.graphicsEngine.setDefaultLoader(self.loader.loader)
        builtins.loader = self.loader

        self.taskMgr = taskMgr
        builtins.taskMgr = self.taskMgr

        self.dgTrav = DataGraphTraverser()

        self.dataRoot = NodePath("data")
        self.hidden = NodePath("hidden")

        self.aspect2d = NodePath("aspect2d")
        builtins.aspect2d = self.aspect2d

        # Messages that are sent regardless of the active document.
        self.messenger = messenger
        builtins.messenger = self.messenger

        builtins.base = self
        builtins.hidden = self.hidden

        ###################################################################

        self.clickTrav = CollisionTraverser()

        # All open documents.
        self.documents = []
        # The focused document.
        self.document = None

        TextNode.setDefaultFont(
            loader.loadFont("resources/models/fonts/consolas.ttf"))

        self.initialize()
    def _showDebugOutput(self):
        """ Lists the available debug options """
        print "\n" * 5
        print "DEBUG MENU"
        print "-" * 50
        print "Select an option:"
        print "\t(1) Connect to pstats"
        print "\t(2) Toggle frame rate meter"
        print "\t(3) Reset to initial position"
        print "\t(4) Display camera position"
        print "\t(5) Show scene graph"
        print "\t(6) Open placement window"
        print "\t(7) Analyze VRAM"
        print

        selectedOption = raw_input("Which do you want to choose?: ")

        try:
            selectedOption = int(selectedOption.strip())
        except:
            print "Option has to be a valid number!"
            return False

        if selectedOption < 1 or selectedOption > 7:
            print "Invalid option!"
            return False

        # pstats
        if selectedOption == 1:
            print "Connecting to pstats .."
            print "If you have no pstats running, this will take 5 seconds to timeout .."
            PStatClient.connect()

        # frame rate meter
        elif selectedOption == 2:
            print "Toggling frame rate meter .."
            self.showbase.setFrameRateMeter(not self.showbase.frameRateMeter)

        # initial position
        elif selectedOption == 3:
            print "Reseting camera position / hpr .."
            self._resetToInitial()

        # display camera pos
        elif selectedOption == 4:
            print "Debug information:"
            print "\tCamera is at", self.showbase.cam.getPos(self.showbase.render)
            print "\tCamera hpr is", self.showbase.cam.getHpr(self.showbase.render)

        # show scene graph
        elif selectedOption == 5:
            print "SCENE GRAPH:"
            print "-" * 50
            self.showbase.render.ls()
            print "-" * 50
            print
            print "ANALYZED:"
            print "-" * 50
            self.showbase.render.analyze()
            print "-" * 50

        # placement window
        elif selectedOption == 6:
            print "Opening placement window. You need tkinter installed to be able to use it"
            self.showbase.render.place()
            # print "It seems .place() is currently not working. Sorry!!"
    
        # vram analyszs
        elif selectedOption == 7:
            print "Analyzing VRAM ..."
            MemoryMonitor.analyzeMemory()
    def updateTimings(self):


        client = PStatClient.getGlobalPstats()
        gpuData = Globals.base.win.getGsg().getPstatsGpuData()
        numEvents = gpuData.getNumEvents()
        # gpuData.sortTime()

        if numEvents < 1:
            # Somehow pstats didn't start, nothing we can do about that
            self.numSamples = 0
            self.averagedEntries = [("~Please start & connect to pstats!", 0)]
            return

        dataset = {}
        lastStarts = {}


        for eventIdx in xrange(gpuData.getNumEvents()):
            collectorIdx = gpuData.getTimeCollector(eventIdx)
            collector = client.getCollector(collectorIdx)
            fname = collector.getFullname()

            if fname.count(":") >= 2:
                eventTime = gpuData.getTime(eventIdx)
                isStart = gpuData.isStart(eventIdx)
                
                if isStart:
                    lastStarts[fname] = eventTime
                else:
                    if fname not in lastStarts or lastStarts[fname] < 0:
                        print "ERROR: Overlapping time"

                    start = lastStarts[fname]
                    dur = eventTime - start
                    if fname in dataset:
                        dataset[fname] += dur
                    else:
                        dataset[fname] = dur

                    lastStarts[fname] = -1

        entries = []
        for key, val in dataset.iteritems():
            entries.append((key, val))

        # Create sum
        ftime = 0.0
        for key, dur in entries:
            ftime += dur

        entries.append(("~Total GPU Time", ftime))

        # Compute averages
        for name, dur in entries:
            if name in self.averages:
                self.averages[name] = self.averages[name][1:] + [dur]
            else:
                self.averages[name] = [0.0] * self.avgSamples
        # Generate list 
        self.averagedEntries = []

        for key, val in self.averages.iteritems():
            avg = sum(val) / float(self.avgSamples)
            self.averagedEntries.append((key, avg))

        self.averagedEntries.sort(key=lambda x: -x[1])
Exemplo n.º 37
0
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')
Exemplo n.º 38
0
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()
Exemplo n.º 39
0
    def _showDebugOutput(self):
        print "\n" * 5
        print "DEBUG MENU"
        print "-" * 50
        print "Select an option:"
        print "\t(1) Connect to pstats"
        print "\t(2) Toggle frame rate meter"
        print "\t(3) Reset to initial position"
        print "\t(4) Display camera position"
        print "\t(5) Show scene graph"
        print "\t(6) Open placement window"
        print

        selectedOption = raw_input("Which do you want to choose?: ")

        try:
            selectedOption = int(selectedOption.strip())
        except:
            print "Option has to be a valid number!"
            return False

        if selectedOption < 1 or selectedOption > 6:
            print "Invalid option!"
            return False

        # pstats
        if selectedOption == 1:
            print "Connecting to pstats .."
            print "If you have no pstats running, this will take 5 seconds to timeout .."
            PStatClient.connect()

        # frame rate meter
        elif selectedOption == 2:
            print "Toggling frame rate meter .."
            self.showbase.setFrameRateMeter(not self.showbase.frameRateMeter)

        # initial position
        elif selectedOption == 3:
            print "Reseting camera position / hpr .."
            self._resetToInitial()

        # display camera pos
        elif selectedOption == 4:
            print "Debug information:"
            print "\tCamera is at", self.showbase.cam.getPos(
                self.showbase.render)
            print "\tCamera hpr is", self.showbase.cam.getHpr(
                self.showbase.render)

        # show scene graph
        elif selectedOption == 5:
            print "SCENE GRAPH:"
            print "-" * 50
            self.showbase.render.ls()
            print "-" * 50
            print
            print "ANALYZED:"
            print "-" * 50
            self.showbase.render.analyze()
            print "-" * 50

        # placement window
        elif selectedOption == 6:
            print "Opening placement window. You need tkinter installed to be able to use it"
            self.showbase.render.place()
Exemplo n.º 40
0
    def __init__(self,
                 tex,
                 stim_angles=(0, 0),
                 strip_angle=0,
                 position=(0, 0),
                 velocities=(0, 0),
                 strip_width=4,
                 fps=30,
                 window_size=None,
                 window_name='BinocularDrift',
                 profile_on=False):
        super().__init__()
        self.tex = tex
        if window_size == None:
            self.window_size = tex.texture_size
        else:
            self.window_size = window_size
        self.mask_position_card = position
        self.mask_position_uv = (utils.card2uv(self.mask_position_card[0]),
                                 utils.card2uv(self.mask_position_card[1]))
        self.scale = np.sqrt(
            8)  #so it can handle arbitrary rotations and shifts
        self.left_texture_angle = stim_angles[0]
        self.right_texture_angle = stim_angles[1]
        self.left_velocity = velocities[0]
        self.right_velocity = velocities[1]
        self.strip_angle = strip_angle  #this will change fairly frequently
        self.fps = fps
        self.window_name = window_name
        self.profile_on = profile_on

        #Set window title and size
        self.window_properties = WindowProperties()
        self.window_properties.setSize(self.window_size, self.window_size)
        self.window_properties.setTitle(self.window_name)
        ShowBaseGlobal.base.win.requestProperties(
            self.window_properties)  #base is a panda3d global

        #CREATE MASK ARRAYS
        self.left_mask_array = 255 * np.ones(
            (self.tex.texture_size, self.tex.texture_size), dtype=np.uint8)
        self.left_mask_array[:, self.tex.texture_size // 2 -
                             strip_width // 2:] = 0
        self.right_mask_array = 255 * np.ones(
            (self.tex.texture_size, self.tex.texture_size), dtype=np.uint8)
        self.right_mask_array[:, :self.tex.texture_size // 2 +
                              strip_width // 2] = 0

        #TEXTURE STAGES FOR LEFT CARD
        self.left_texture_stage = TextureStage('left_texture_stage')
        #Mask
        self.left_mask = Texture("left_mask_texture")
        self.left_mask.setup2dTexture(self.tex.texture_size,
                                      self.tex.texture_size,
                                      Texture.T_unsigned_byte,
                                      Texture.F_luminance)
        self.left_mask.setRamImage(self.left_mask_array)
        self.left_mask_stage = TextureStage('left_mask_array')
        #Multiply the texture stages together
        self.left_mask_stage.setCombineRgb(TextureStage.CMModulate,
                                           TextureStage.CSTexture,
                                           TextureStage.COSrcColor,
                                           TextureStage.CSPrevious,
                                           TextureStage.COSrcColor)

        #TEXTURE STAGES FOR RIGHT CARD
        self.right_texture_stage = TextureStage('right_texture_stage')
        #Mask
        self.right_mask = Texture("right_mask_texture")
        self.right_mask.setup2dTexture(self.tex.texture_size,
                                       self.tex.texture_size,
                                       Texture.T_unsigned_byte,
                                       Texture.F_luminance)
        self.right_mask.setRamImage(self.right_mask_array)
        self.right_mask_stage = TextureStage('right_mask_stage')
        #Multiply the texture stages together
        self.right_mask_stage.setCombineRgb(TextureStage.CMModulate,
                                            TextureStage.CSTexture,
                                            TextureStage.COSrcColor,
                                            TextureStage.CSPrevious,
                                            TextureStage.COSrcColor)

        #CREATE CARDS/SCENEGRAPH
        cm = CardMaker('stimcard')
        cm.setFrameFullscreenQuad()
        #self.setBackgroundColor((0,0,0,1))
        self.left_card = self.aspect2d.attachNewNode(cm.generate())
        self.right_card = self.aspect2d.attachNewNode(cm.generate())
        self.left_card.setAttrib(ColorBlendAttrib.make(ColorBlendAttrib.M_add))
        self.right_card.setAttrib(ColorBlendAttrib.make(
            ColorBlendAttrib.M_add))

        #ADD TEXTURE STAGES TO CARDS
        self.left_card.setTexture(self.left_texture_stage, self.tex.texture)
        self.left_card.setTexture(self.left_mask_stage, self.left_mask)
        self.right_card.setTexture(self.right_texture_stage, self.tex.texture)
        self.right_card.setTexture(self.right_mask_stage, self.right_mask)
        self.setBackgroundColor(
            (0, 0, 0, 1))  # without this the cards will appear washed out

        #TRANSFORMS
        #Masks
        self.mask_transform = self.trs_transform()
        self.left_card.setTexTransform(self.left_mask_stage,
                                       self.mask_transform)
        self.right_card.setTexTransform(self.right_mask_stage,
                                        self.mask_transform)
        #Left texture
        self.left_card.setTexScale(self.left_texture_stage, 1 / self.scale)
        self.left_card.setTexRotate(self.left_texture_stage,
                                    self.left_texture_angle)
        #Right texture
        self.right_card.setTexScale(self.right_texture_stage, 1 / self.scale)
        self.right_card.setTexRotate(self.right_texture_stage,
                                     self.right_texture_angle)

        #Set dynamic transforms
        if self.left_velocity != 0 and self.right_velocity != 0:
            self.taskMgr.add(self.textures_update, "move_both")
        elif self.left_velocity != 0 and self.right_velocity == 0:
            self.taskMgr.add(self.left_texture_update, "move_left")
        elif self.left_velocity == 0 and self.right_velocity != 0:
            self.taskMgr.add(self.right_texture_update, "move_right")

        # Set frame rate
        ShowBaseGlobal.globalClock.setMode(ClockObject.MLimited)
        ShowBaseGlobal.globalClock.setFrameRate(
            self.fps)  #can lock this at whatever

        #Set up profiling if desired
        if profile_on:
            PStatClient.connect()  # this will only work if pstats is running
            ShowBaseGlobal.base.setFrameRateMeter(True)  #Show frame rate
            # Following will show a small x at the center
            self.title = OnscreenText("x",
                                      style=1,
                                      fg=(1, 1, 1, 1),
                                      bg=(0, 0, 0, .8),
                                      pos=self.mask_position_card,
                                      scale=0.05)
Exemplo n.º 41
0
    def __init__(self,
                 tex,
                 stim_angles=(0, 0),
                 initial_angle=0,
                 initial_position=(0, 0),
                 velocities=(0, 0),
                 strip_width=4,
                 fps=30,
                 window_size=None,
                 window_name='position control',
                 profile_on=False,
                 save_path=None):
        super().__init__()
        self.render.setAntialias(AntialiasAttrib.MMultisample)
        self.aspect2d.prepareScene(
            ShowBaseGlobal.base.win.getGsg())  # pre-loads world
        self.tex = tex
        if window_size == None:
            self.window_size = tex.texture_size
        else:
            self.window_size = window_size
        self.mask_position_card = initial_position
        self.strip_width = strip_width
        self.scale = np.sqrt(
            8)  #so it can handle arbitrary rotations and shifts
        self.strip_angle = initial_angle  #this will change fairly frequently
        self.stim_angles = stim_angles
        self.left_texture_angle = self.stim_angles[
            0] + self.strip_angle  #make this a property
        self.right_texture_angle = self.stim_angles[1] + self.strip_angle
        self.left_velocity = velocities[0]
        self.right_velocity = velocities[1]
        self.fps = fps
        self.window_name = window_name
        self.profile_on = profile_on
        print(save_path)
        self.save_path = save_path
        if self.save_path:
            initial_params = {
                'angles': stim_angles,
                'initial_angle': self.strip_angle,
                'velocities': velocities,
                'strip_width': self.strip_width,
                'initial_position': initial_position
            }
            print(tex, initial_params)
            self.filestream = utils.save_initialize(self.save_path, [tex],
                                                    [initial_params])
            print(self.filestream)
        else:
            self.filestream = None

        #Set window title and size
        self.window_properties = WindowProperties()
        self.window_properties.setSize(self.window_size, self.window_size)
        self.window_properties.setTitle(self.window_name)
        ShowBaseGlobal.base.win.requestProperties(
            self.window_properties)  #base is a panda3d global

        # Set frame rate
        ShowBaseGlobal.globalClock.setMode(ClockObject.MLimited)
        ShowBaseGlobal.globalClock.setFrameRate(
            self.fps)  #can lock this at whatever

        #CREATE MASK ARRAYS
        self.left_mask_array = 255 * np.ones(
            (self.tex.texture_size, self.tex.texture_size), dtype=np.uint8)
        self.left_mask_array[:, self.tex.texture_size // 2 -
                             self.strip_width // 2:] = 0
        self.right_mask_array = 255 * np.ones(
            (self.tex.texture_size, self.tex.texture_size), dtype=np.uint8)
        self.right_mask_array[:, :self.tex.texture_size // 2 +
                              self.strip_width // 2] = 0

        #TEXTURE STAGES FOR LEFT CARD
        self.left_texture_stage = TextureStage('left_texture_stage')
        #Mask
        self.left_mask = Texture("left_mask_texture")
        self.left_mask.setup2dTexture(self.tex.texture_size,
                                      self.tex.texture_size,
                                      Texture.T_unsigned_byte,
                                      Texture.F_luminance)
        self.left_mask.setRamImage(self.left_mask_array)
        self.left_mask_stage = TextureStage('left_mask_array')
        #Multiply the texture stages together
        self.left_mask_stage.setCombineRgb(TextureStage.CMModulate,
                                           TextureStage.CSTexture,
                                           TextureStage.COSrcColor,
                                           TextureStage.CSPrevious,
                                           TextureStage.COSrcColor)

        #TEXTURE STAGES FOR RIGHT CARD
        self.right_texture_stage = TextureStage('right_texture_stage')
        #Mask
        self.right_mask = Texture("right_mask_texture")
        self.right_mask.setup2dTexture(self.tex.texture_size,
                                       self.tex.texture_size,
                                       Texture.T_unsigned_byte,
                                       Texture.F_luminance)
        self.right_mask.setRamImage(self.right_mask_array)
        self.right_mask_stage = TextureStage('right_mask_stage')
        #Multiply the texture stages together
        self.right_mask_stage.setCombineRgb(TextureStage.CMModulate,
                                            TextureStage.CSTexture,
                                            TextureStage.COSrcColor,
                                            TextureStage.CSPrevious,
                                            TextureStage.COSrcColor)

        #CREATE CARDS/SCENEGRAPH
        cm = CardMaker('stimcard')
        cm.setFrameFullscreenQuad()
        #self.setBackgroundColor((0,0,0,1))
        self.left_card = self.aspect2d.attachNewNode(cm.generate())
        self.right_card = self.aspect2d.attachNewNode(cm.generate())
        self.left_card.setAttrib(ColorBlendAttrib.make(ColorBlendAttrib.M_add))
        self.right_card.setAttrib(ColorBlendAttrib.make(
            ColorBlendAttrib.M_add))

        #ADD TEXTURE STAGES TO CARDS
        self.left_card.setTexture(self.left_texture_stage, self.tex.texture)
        self.left_card.setTexture(self.left_mask_stage, self.left_mask)
        self.right_card.setTexture(self.right_texture_stage, self.tex.texture)
        self.right_card.setTexture(self.right_mask_stage, self.right_mask)
        self.setBackgroundColor(
            (0, 0, 0, 1))  # without this the cards will appear washed out
        #self.left_card.setAntialias(AntialiasAttrib.MMultisample)
        #self.right_card.setAntialias(AntialiasAttrib.MMultisample)
        #TRANSFORMS
        # Masks
        self.mask_transform = self.trs_transform()
        self.left_card.setTexTransform(self.left_mask_stage,
                                       self.mask_transform)
        self.right_card.setTexTransform(self.right_mask_stage,
                                        self.mask_transform)

        # Textures
        # Left
        self.left_card.setTexScale(self.left_texture_stage, 1 / self.scale)
        self.left_card.setTexRotate(self.left_texture_stage,
                                    self.left_texture_angle)
        # Right
        self.right_card.setTexScale(self.right_texture_stage, 1 / self.scale)
        self.right_card.setTexRotate(self.right_texture_stage,
                                     self.right_texture_angle)

        #Set task manager(s) for textures
        if self.left_velocity != 0 and self.right_velocity != 0:
            self.taskMgr.add(self.textures_update, "move_both")
        elif self.left_velocity != 0 and self.right_velocity == 0:
            self.taskMgr.add(self.left_texture_update, "move_left")
        elif self.left_velocity == 0 and self.right_velocity != 0:
            self.taskMgr.add(self.right_texture_update, "move_right")

        # Event handler to process the messages
        self.accept("stim", self.process_stim, [])

        #Set up profiling if desired
        if profile_on:
            PStatClient.connect()  # this will only work if pstats is running
            ShowBaseGlobal.base.setFrameRateMeter(True)  #Show frame rate
Exemplo n.º 42
0
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')
Exemplo n.º 43
0
 def connect_pstats(self):
     PStatClient.connect()
Exemplo n.º 44
0
 def pstats():
     base.pstats = True
     PStatClient.connect()