예제 #1
0
파일: camera.py 프로젝트: anossov/dorfdelf
    def __init__(self, extents, mouse, body, eye):
        self.extents = extents
        self.body = body
        self.eye = eye

        self.mouse = mouse

        self.keys = {
            'w': False,
            's': False,
            'd': False,
            'a': False,
        }

        self.drag = None
        self.zoomdrag = None
        self.moving = False
        self.panning = False

        self.accept_keyboard()
        self.accept('console-open', self.ignore_keyboard)
        self.accept('console-close', self.accept_keyboard)

        self.accept('mouse3', self.start_drag)
        self.accept('mouse3-up', self.end_drag)

        self.accept('mouse2', self.start_zoom)
        self.accept('mouse2-up', self.end_zoom)

        taskMgr.add(self.move_camera, "Move Camera")
예제 #2
0
    def __lerp(self, functorFunc, duration, blendType, taskName=None):
        """
        __lerp(self, functorFunc, float, string, string)
        Basic lerp functionality used by other lerps.
        Fire off a lerp. Make it a task if taskName given.
        """
        # functorFunc is a function which can be called to create a functor.
        # functor creation is defered so initial state (sampled in functorFunc)
        # will be appropriate for the time the lerp is spawned
        from direct.task import Task
        from direct.showbase import LerpBlendHelpers
        from direct.task.TaskManagerGlobal import taskMgr

        # upon death remove the functorFunc
        def lerpUponDeath(task):
            # Try to break circular references
            try:
                del task.functorFunc
            except:
                pass
            try:
                del task.lerp
            except:
                pass

        # make the task function
        def lerpTaskFunc(task):
            from pandac.Lerp import Lerp
            from pandac.ClockObject import ClockObject
            from direct.task.Task import Task, cont, done
            if task.init == 1:
                # make the lerp
                functor = task.functorFunc()
                task.lerp = Lerp(functor, task.duration, task.blendType)
                task.init = 0
            dt = globalClock.getDt()
            task.lerp.setStepSize(dt)
            task.lerp.step()
            if (task.lerp.isDone()):
                # Reset the init flag, in case the task gets re-used
                task.init = 1
                return(done)
            else:
                return(cont)

        # make the lerp task
        lerpTask = Task.Task(lerpTaskFunc)
        lerpTask.init = 1
        lerpTask.functorFunc = functorFunc
        lerpTask.duration = duration
        lerpTask.blendType = LerpBlendHelpers.getBlend(blendType)
        lerpTask.setUponDeath(lerpUponDeath)

        if (taskName == None):
            # don't spawn a task, return one instead
            return lerpTask
        else:
            # spawn the lerp task
            taskMgr.add(lerpTask, taskName)
            return lerpTask
 def leakTask(task=None, leakTaskName=leakTaskName):
     base = getBase()
     taskMgr.add(nullTask, uniqueName(leakTaskName))
     taskMgr.doMethodLater(1 << 31, nullDoLater, uniqueName(leakDoLaterName))
     taskMgr.doMethodLater(10, leakTask, 'doLeakTask-%s' % serialNum())
     if task:
         return task.done
예제 #4
0
 def recoverFromPickle(self):
     self.initialize()
     if self.selected is not None:
         self.grabModelNP.setPos(render, self.selected.getPos(render))
         self.grabModelNP.show()
     print "grabber sel ", self.selected, " isHidden() ", self.grabModelNP.isHidden(), '\n'
     taskMgr.add(self.scaleGrabber, 'scaleGrabber')
 def moveToFit(self):
     # How big is the active widget?
     widgetScale = base.direct.widget.scalingNode.getScale(render)
     maxScale = max(widgetScale[0], widgetScale[1], widgetScale[2])
     # At what distance does the widget fill 50% of the screen?
     camY = ((2 * base.direct.dr.near * (1.5 * maxScale)) /
             min(base.direct.dr.nearWidth, base.direct.dr.nearHeight))
     # Find a point this distance along the Y axis
     # MRM: This needs to be generalized to support non uniform frusta
     centerVec = Y_AXIS * camY
     # Before moving, record the relationship between the selected nodes
     # and the widget, so that this can be maintained
     base.direct.selected.getWrtAll()
     # Push state onto undo stack
     base.direct.pushUndo(base.direct.selected)
     # Remove the task to keep the widget attached to the object
     taskMgr.remove('followSelectedNodePath')
     # Spawn a task to keep the selected objects with the widget
     taskMgr.add(self.stickToWidgetTask, 'stickToWidget')
     # Spawn a task to move the widget
     ival = base.direct.widget.posInterval(CAM_MOVE_DURATION,
                                           Point3(centerVec),
                                           other=base.direct.camera,
                                           blendType='easeInOut')
     ival = Sequence(ival,
                     Func(lambda: taskMgr.remove('stickToWidget')),
                     name='moveToFit')
     ival.start()
예제 #6
0
def main():
    base = ShowBase()

    cm = CardMaker('')
    cm.set_frame(-.5, .5, -.5, .5)

    # Node which contains all the cards equally spaced apart and which is
    # animated to move the cards in front of the camera.
    cards = base.render.attach_new_node(PandaNode(''))
    cards.setPos(-2, 5, 0)
    cards.posInterval(2, Point3(-6, 5, 0)).loop()

    for i in range(5):
        card = cards.attach_new_node(cm.generate())
        card.setPos(i * 2, 0, 0)

    def on_every_frame(task):
        # Time which has elapsed since the last frame measured in units of
        # the time quota available at 60 fps (e.g. 1/60 second).
        time_quota = taskMgr.globalClock.get_dt() * 60

        # Print time use as percent of the 60-fps-quota.
        print(f'{round(time_quota * 100):4}', end='', flush=True)

        return Task.DSCont

    taskMgr.add(on_every_frame)
    taskMgr.run()
예제 #7
0
 def enable(self):
     # Kill existing task
     self.disable()
     # Initialize tracker
     self.tracker = base.direct.deviceManager.createTracker(self.device)
     # Update task
     taskMgr.add(self.updateTask, self.name + '-updateTask')
 def __init__(self):    
   ShowBase.__init__(self)
   
   
   self.clock_ = ClockObject()
   self.setupInput()    
   taskMgr.add(self.update,"update")
예제 #9
0
 def __spawnTask(self):
     # Spawn task
     self.__removeTask()
     taskName = self.getName() + '-play'
     task = Task(self.__playTask)
     task.interval = self
     taskMgr.add(task, taskName)
예제 #10
0
 def __init__(self):
     ShowBase.__init__(self)
     self.cam.setPos(0, -50, 10)
     self.setupCD()
     self.addSmiley()
     self.addFloor()
     taskMgr.add(self.updateSmiley, "UpdateSmiley")
예제 #11
0
def __lerp(self, functorFunc, duration, blendType, taskName=None):
    from direct.task import Task
    from direct.showbase import LerpBlendHelpers
    from direct.task.TaskManagerGlobal import taskMgr

    def lerpTaskFunc(task):
        from pandac.PandaModules import Lerp
        from pandac.PandaModules import ClockObject
        from direct.task.Task import Task, cont, done
        if task.init == 1:
            functor = task.functorFunc()
            task.lerp = Lerp(functor, task.duration, task.blendType)
            task.init = 0
        dt = globalClock.getDt()
        task.lerp.setStepSize(dt)
        task.lerp.step()
        if task.lerp.isDone():
            task.init = 1
            return done
        else:
            return cont

    lerpTask = Task.Task(lerpTaskFunc)
    lerpTask.init = 1
    lerpTask.functorFunc = functorFunc
    lerpTask.duration = duration
    lerpTask.blendType = LerpBlendHelpers.getBlend(blendType)
    if taskName == None:
        return lerpTask
    else:
        taskMgr.add(lerpTask, taskName)
        return lerpTask
    return
예제 #12
0
 def __spawnTask(self):
     # Spawn task
     self.__removeTask()
     taskName = self.getName() + '-play'
     task = Task(self.__playTask)
     task.interval = self
     taskMgr.add(task, taskName)
def __lerp(self, functorFunc, duration, blendType, taskName = None):
    from direct.task import Task
    from direct.showbase import LerpBlendHelpers
    from direct.task.TaskManagerGlobal import taskMgr

    def lerpTaskFunc(task):
        from pandac.PandaModules import Lerp
        from pandac.PandaModules import ClockObject
        from direct.task.Task import Task, cont, done
        if task.init == 1:
            functor = task.functorFunc()
            task.lerp = Lerp(functor, task.duration, task.blendType)
            task.init = 0
        dt = globalClock.getDt()
        task.lerp.setStepSize(dt)
        task.lerp.step()
        if task.lerp.isDone():
            task.init = 1
            return done
        else:
            return cont

    lerpTask = Task.Task(lerpTaskFunc)
    lerpTask.init = 1
    lerpTask.functorFunc = functorFunc
    lerpTask.duration = duration
    lerpTask.blendType = LerpBlendHelpers.getBlend(blendType)
    if taskName == None:
        return lerpTask
    else:
        taskMgr.add(lerpTask, taskName)
        return lerpTask
    return
예제 #14
0
파일: Npc.py 프로젝트: flips30240/VoxelDash
    def createEnemy(self, x, y, z):
        #nodes
        self.enemyBulletNode = BulletRigidBodyNode('PlayerBox')
        self.enemyBulletNode.setMass(1.0)
        self.enemyNp = self.renderDummy.attachNewNode(self.enemyBulletNode)
        self.enemyNp.setPos(x, y, z)
        print(x, y, z)

        #shapes
        shape = BulletBoxShape(Vec3(0.5, 0.5, 0.5))
        model = Cube(1, 1, 1)
        model.reparentTo(self.enemyNp)
        model.setPos(-.5, -.5, -.5)

        #nodes
        self.enemyBulletNode.addShape(shape)

        material = Material()
        material.setAmbient(VBase4(random.random(), random.random(), random.random(), random.random()))
        material.setDiffuse(VBase4(random.random(), random.random(), random.random(), random.random()))# -*- coding: utf-8 *-*
        material.setEmission(VBase4(random.random(), random.random(), random.random(), random.random()))
        #material.setSpecular(VBase4(random.random(), random.random(), random.random(), random.random()))
        material.setShininess(random.random())

        myTexture = loader.loadTexture("./textures/enemy.jpg")
        self.enemyNp.setTexture(myTexture)
        self.enemyNp.setMaterial(material)

        #bullet world
        self.world.attachRigidBody(self.enemyBulletNode)

        taskMgr.add(self.enemyUpdate, "EnemyUpdateTask#" + str(self.numNpc))
 def __init__(self):
     
     ShowBase.__init__(self)
     self.setupInput()
     self.setupStates()
     
     taskMgr.add(self.update,"update")
예제 #16
0
    def enableAvatarControls(self):
        """
        Activate the arrow keys, etc.
        """
        assert self.notify.debugStateCall(self)
        assert self.collisionsActive

        #*#if __debug__:
        #*#    self.accept("control-f3", self.spawnTest) #*#

        # remove any old
        if self.controlsTask:
            self.controlsTask.remove()
        # spawn the new task
        taskName = "AvatarControls-%s"%(id(self),)
        self.controlsTask = taskMgr.add(self.handleAvatarControls, taskName, 25)

        self.isAirborne = 0
        self.mayJump = 1

        if self.physVelocityIndicator:
            if self.indicatorTask:
                self.indicatorTask.remove()
            self.indicatorTask = taskMgr.add(
                self.avatarPhysicsIndicator,
                "AvatarControlsIndicator-%s"%(id(self),), 35)
예제 #17
0
    def __init__(self, extents, mouse, body, eye):
        self.extents = extents
        self.body = body
        self.eye = eye

        self.mouse = mouse

        self.keys = {
            'w': False,
            's': False,
            'd': False,
            'a': False,
        }

        self.drag = None
        self.zoomdrag = None
        self.moving = False
        self.panning = False

        self.accept_keyboard()
        self.accept('console-open', self.ignore_keyboard)
        self.accept('console-close', self.accept_keyboard)

        self.accept('mouse3', self.start_drag)
        self.accept('mouse3-up', self.end_drag)

        self.accept('mouse2', self.start_zoom)
        self.accept('mouse2-up', self.end_zoom)

        taskMgr.add(self.move_camera, "Move Camera")
예제 #18
0
    def __init__(self, world, worldNP):
        self.diamondbackChar = None

        self.world = world
        self.worldNP = worldNP

        # Store which keys are being pressed
        self.keyPressed = {"fwd": 0, "back": 0, "left": 0, "right": 0}

        # Setup everything
        self.createCharacter()
        self.setupKeys()

        self.isMoving = False
        taskMgr.add(self.move, "moveTask")

        self.pos = OnscreenText(text="POS",
                                style=3,
                                fg=(1, 1, 1, 1),
                                pos=(-0.02, 0.1),
                                scale=.07,
                                parent=base.a2dBottomRight,
                                align=TextNode.ARight)

        self.lerpAnimation(self.diamondbackChar, "idle")
예제 #19
0
파일: Messenger.py 프로젝트: Astron/panda3d
    def __dispatch(self, acceptorDict, event, sentArgs, foundWatch):
        for id in list(acceptorDict.keys()):
            # We have to make this apparently redundant check, because
            # it is possible that one object removes its own hooks
            # in response to a handler called by a previous object.
            #
            # NOTE: there is no danger of skipping over objects due to
            # modifications to acceptorDict, since the for..in above
            # iterates over a list of objects that is created once at
            # the start
            callInfo = acceptorDict.get(id)
            if callInfo:
                method, extraArgs, persistent = callInfo
                # If this object was only accepting this event once,
                # remove it from the dictionary
                if not persistent:
                    # This object is no longer listening for this event
                    eventDict = self.__objectEvents.get(id)
                    if eventDict and event in eventDict:
                        del eventDict[event]
                        if (len(eventDict) == 0):
                            del self.__objectEvents[id]
                        self._releaseObject(self._getObject(id))

                    del acceptorDict[id]
                    # If the dictionary at this event is now empty, remove
                    # the event entry from the Messenger altogether
                    if (event in self.__callbacks \
                            and (len(self.__callbacks[event]) == 0)):
                        del self.__callbacks[event]

                if __debug__:
                    if foundWatch:
                        print("Messenger: \"%s\" --> %s%s"%(
                            event,
                            self.__methodRepr(method),
                            tuple(extraArgs + sentArgs)))

                #print "Messenger: \"%s\" --> %s%s"%(
                #            event,
                #            self.__methodRepr(method),
                #            tuple(extraArgs + sentArgs))

                # It is important to make the actual call here, after
                # we have cleaned up the accept hook, because the
                # method itself might call accept() or acceptOnce()
                # again.
                assert hasattr(method, '__call__')

                # Release the lock temporarily while we call the method.
                self.lock.release()
                try:
                    result = method (*(extraArgs + sentArgs))
                finally:
                    self.lock.acquire()

                if hasattr(result, 'cr_await'):
                    # It's a coroutine, so schedule it with the task manager.
                    taskMgr.add(result)
예제 #20
0
    def __dispatch(self, acceptorDict, event, sentArgs, foundWatch):
        for id in list(acceptorDict.keys()):
            # We have to make this apparently redundant check, because
            # it is possible that one object removes its own hooks
            # in response to a handler called by a previous object.
            #
            # NOTE: there is no danger of skipping over objects due to
            # modifications to acceptorDict, since the for..in above
            # iterates over a list of objects that is created once at
            # the start
            callInfo = acceptorDict.get(id)
            if callInfo:
                method, extraArgs, persistent = callInfo
                # If this object was only accepting this event once,
                # remove it from the dictionary
                if not persistent:
                    # This object is no longer listening for this event
                    eventDict = self.__objectEvents.get(id)
                    if eventDict and event in eventDict:
                        del eventDict[event]
                        if (len(eventDict) == 0):
                            del self.__objectEvents[id]
                        self._releaseObject(self._getObject(id))

                    del acceptorDict[id]
                    # If the dictionary at this event is now empty, remove
                    # the event entry from the Messenger altogether
                    if (event in self.__callbacks \
                            and (len(self.__callbacks[event]) == 0)):
                        del self.__callbacks[event]

                if __debug__:
                    if foundWatch:
                        print("Messenger: \"%s\" --> %s%s"%(
                            event,
                            self.__methodRepr(method),
                            tuple(extraArgs + sentArgs)))

                #print "Messenger: \"%s\" --> %s%s"%(
                #            event,
                #            self.__methodRepr(method),
                #            tuple(extraArgs + sentArgs))

                # It is important to make the actual call here, after
                # we have cleaned up the accept hook, because the
                # method itself might call accept() or acceptOnce()
                # again.
                assert hasattr(method, '__call__')

                # Release the lock temporarily while we call the method.
                self.lock.release()
                try:
                    result = method (*(extraArgs + sentArgs))
                finally:
                    self.lock.acquire()

                if hasattr(result, 'cr_await'):
                    # It's a coroutine, so schedule it with the task manager.
                    taskMgr.add(result)
예제 #21
0
 def initializeManipVars(self, transformDir, transformOp, mPos3D, planeNormVec=None):
     self.currTransformDir = transformDir
     self.currPlaneColNorm = planeNormVec  # set the norm for the collision plane to be used in mouse1Dragging
     self.interFrameMousePosition = mPos3D
     self.currTransformOperation = transformOp
     self.isDragging = True
     taskMgr.add(self.handleDragging, 'mouse1Dragging')
     messenger.accept('mouse1-up', self, self.handleM1Up)
예제 #22
0
 def enable(self):
     # Kill existing task
     self.disable()
     # Accept button events
     self.acceptSwitchModeEvent()
     self.acceptUprightCameraEvent()
     # Update task
     taskMgr.add(self.updateTask, self.name + '-updateTask')
예제 #23
0
    def spawnUpdateObjectUITask(self):
        if self.currNodePath is None:
            return

        taskMgr.remove('_le_updateObjectUITask')
        t = Task.Task(self.updateObjectUITask)
        t.np = self.currNodePath
        taskMgr.add(t, '_le_updateObjectUITask')
예제 #24
0
 def __init__(self):
     ShowBase.__init__(self)
     self.init_shader()
     self.init_light_camera()
     self.init_bullet_engine()
     self.setup()
     self.init_input()
     taskMgr.add(self.update,'updateWorld')
예제 #25
0
 def __init__(self):
     LeakDetector.__init__(self)
     self._typeName2detector = {}
     self._createJob = None
     if ConfigVariableBool('leak-message-listeners', False):
         self._leakers = []
         self._leakTaskName = uniqueName('leak-message-listeners')
         taskMgr.add(self._leak, self._leakTaskName)
예제 #26
0
 def __spawnLocalCannonMoveTask(self):
     self.leftPressed = 0
     self.rightPressed = 0
     self.upPressed = 0
     self.downPressed = 0
     self.cannonMoving = 0
     task = Task(self.__localCannonMoveTask)
     task.lastPositionBroadcastTime = 0.0
     taskMgr.add(task, self.LOCAL_CANNON_MOVE_TASK)
예제 #27
0
 def startReaderPollTask(self):
     """ Task to handle datagrams from client """
     # Run this task just after the listener poll task
     if clusterSyncFlag:
         # Sync version
         taskMgr.add(self._syncReaderPollTask, "serverReaderPollTask", -39)
     else:
         # Asynchronous version
         taskMgr.add(self._readerPollTask, "serverReaderPollTask", -39)
예제 #28
0
    def send(self, event, sentArgs=[], taskChain=None):
        """
        Send this event, optionally passing in arguments

        event is usually a string.
        sentArgs is a list of any data that you want passed along to the
            handlers listening to this event.

        If taskChain is not None, it is the name of the task chain
        which should receive the event.  If taskChain is None, the
        event is handled immediately.  Setting a non-None taskChain
        will defer the event (possibly till next frame or even later)
        and create a new, temporary task within the named taskChain,
        but this is the only way to send an event across threads.
        """
        if Messenger.notify.getDebug() and not self.quieting.get(event):
            assert Messenger.notify.debug(
                'sent event: %s sentArgs = %s, taskChain = %s' %
                (event, sentArgs, taskChain))

        self.lock.acquire()
        try:
            foundWatch = 0
            if __debug__:
                if self.__isWatching:
                    for i in self.__watching.keys():
                        if str(event).find(i) >= 0:
                            foundWatch = 1
                            break
            acceptorDict = self.__callbacks.get(event)
            if not acceptorDict:
                if __debug__:
                    if foundWatch:
                        print(
                            "Messenger: \"%s\" was sent, but no function in Python listened."
                            % (event, ))
                return

            if taskChain:
                # Queue the event onto the indicated task chain.
                from direct.task.TaskManagerGlobal import taskMgr
                queue = self._eventQueuesByTaskChain.setdefault(taskChain, [])
                queue.append((acceptorDict, event, sentArgs, foundWatch))
                if len(queue) == 1:
                    # If this is the first (only) item on the queue,
                    # spawn the task to empty it.
                    taskMgr.add(self.__taskChainDispatch,
                                name='Messenger-%s' % (taskChain),
                                extraArgs=[taskChain],
                                taskChain=taskChain,
                                appendTask=True)
            else:
                # Handle the event immediately.
                self.__dispatch(acceptorDict, event, sentArgs, foundWatch)
        finally:
            self.lock.release()
예제 #29
0
    def __init__(self):
        DirectObject.__init__(self)

        # 人物动作
        self.walk = False
        self.reverse = False
        self.left = False
        self.right = False

        taskMgr.add(self.updateInput,"update input")
예제 #30
0
 def __init__(self):
     DirectObject(self)
     #所有状态
     self.__forward = False
     self.__back = False
     self.__left = False
     self.__right = False
     self.__setting = False  
     self.__attack = False
     taskMgr.add(self.updateInput,"update input")
 def restart(self):
     if self.eventQueue == None:
         self.eventQueue = EventQueue.getGlobalEventQueue()
     if self.eventHandler == None:
         if self.eventQueue == EventQueue.getGlobalEventQueue():
             self.eventHandler = EventHandler.getGlobalEventHandler()
         else:
             self.eventHandler = EventHandler(self.eventQueue)
     taskMgr.add(self.eventLoopTask, 'eventManager')
     return
예제 #32
0
    def __fireCannonTask(self, task):
        launchTime = task.fireTime
        results = self.__calcFlightResults(launchTime)
        startPos, startHpr, startVel, trajectory, timeOfImpact, hitWhat = results

        if not results:
            return

        self.notify.info('start position: ' + str(startPos))
        self.notify.info('start velocity: ' + str(startVel))
        self.notify.info('time of launch: ' + str(launchTime))
        self.notify.info('time of impact: ' + str(timeOfImpact))
        self.notify.info('location of impact: ' +
                         str(trajectory.getPos(timeOfImpact)))
        self.notify.info('start hpr: ' + str(startHpr))

        FlyingProp = self.gag

        self.generateGravity(FlyingProp)
        FlyingProp.reparentTo(render)
        FlyingProp.setPos(startPos)
        barrelHpr = self.barrel.getHpr(render)
        FlyingProp.setHpr(startHpr)
        #FlyingProp.setH(90)
        #self.gag.setPosHpr(0, 0, 100, 0, 0, 0) # this seems to be affecting the collision sphere btw
        info = {}
        info['trajectory'] = trajectory
        info['launchTime'] = launchTime
        info['timeOfImpact'] = timeOfImpact
        info['hitWhat'] = hitWhat
        info['flyingProp'] = self.gag
        info['hRot'] = self.cannonPosition[0]
        info['haveWhistled'] = 0
        info['maxCamPullback'] = CAMERA_PULLBACK_MIN
        self.flyColSphere = CollisionSphere(0, 0, 0, 1.2)
        self.flyColNode = CollisionNode('flySphere')
        self.flyColNode.setCollideMask(BitmaskGlobals.FloorBitmask
                                       | BitmaskGlobals.WallBitmask)
        self.flyColNode.addSolid(self.flyColSphere)
        self.flyColNodePath = self.gag.attachNewNode(self.flyColNode)
        self.flyColNodePath.setColor(1, 0, 0, 1)
        # self.flyColNodePath.show()
        self.handler = CollisionHandlerEvent()
        self.handler.setInPattern('cannonHit')
        # uh oh no work! :( << nevermind, should work now
        base.cTrav.addCollider(self.flyColNodePath, self.handler)
        print('Cannon pos: {0}'.format(self.cannon.getPos(render)))
        self.accept('cannonHit', self.__handleCannonHit)
        base.playSfx(self.sndCannonFire)
        flyTask = Task(self.__flyTask, 'flyTask')
        flyTask.info = info
        taskMgr.add(flyTask, 'flyTask')
        self.acceptOnce('stopFlyTask', self.__stopFlyTask)
        self.notify.info('done with __fireCannonTask')
        return Task.done
예제 #33
0
    def __init__(self):
        DirectObject.__init__(self)

        # 所有的状态类别
        self.__new_game = False
        self.__load_game = False
        self.__description = False
        self.__exit = False
        self.__select = False

        taskMgr.add(self.updateInput,"update input")
예제 #34
0
 def scheduleCallback(self, callback):
     assert self.notify.debugCall()
     if not self.__threaded:
         callback()
     else:
         taskName = ('%s-ThreadedTask-%s' %
                     (self.__name, TaskThreaded._Serial.next()))
         assert taskName not in self.__taskNames
         self.__taskNames.add(taskName)
         taskMgr.add(Functor(self.__doCallback, callback, taskName),
                     taskName)
예제 #35
0
파일: main.py 프로젝트: 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')
예제 #36
0
    def enableAvatarControls(self):
        """
        Activate the arrow keys, etc.
        """
        assert self.debugPrint("enableAvatarControls")
        assert self.collisionsActive

        taskName = "AvatarControls-%s" % (id(self), )
        # remove any old
        taskMgr.remove(taskName)
        # spawn the new task
        taskMgr.add(self.handleAvatarControls, taskName)
예제 #37
0
    def __init__(self):
        #Muestra un texto en pantalla, utilizando la interfaz 2D de Panda3D.
        #Posteriormente se actualizara con otros datos, por eso se mantiene la referencia
        self.title = OnscreenText(text="prueba 1", style=1, fg=(0,0,0,1), pos=(0.8,-0.95), scale = .07)

        #Lee los datos de configuracion de los clasificadores HAAR. En este caso, para deteccion de rostros en posicion frontal
        self.cascade = cv.Load("haarcascades\\haarcascade_frontalface_alt.xml")
        
        #Utiliza por defecto la camara para obtener las imagenes, y no guarda un archivo
        self.cameraHelper = CameraHelper(True, False, "d:\\face-detection.avi")
	
        #Crea una textura para utilizar como fondo, donde se mostraran las imagenes de video
	#CardMaker en realidad es un poligono rectangular, que es util para asociarlo al renderer2D, ya que
	#podremos hacer que ocupe toda la pantalla y mostrar nuestras imagenes como fondo.
        self.cardMaker = CardMaker("My Fullscreen Card");
        self.cardMaker.setFrameFullscreenQuad()

	#Agrega el rectangulo al renderer render2dp. Asi como existe render2d, existe uno adicional que es utilizado
	#en general para casos donde necesita mostrarse un fondo, sea estatico o de video. El render2d estandar,
	#por el contrario, se usa para mostrar informacion al usuario que siempre debe ser visible
        self.card = NodePath(self.cardMaker.generate())
        self.card.reparentTo(render2dp)
	
        #Le da baja prioridad para que los objetos dibujados posteriormente siempre se vean sobre ella
        base.cam2dp.node().getDisplayRegion(0).setSort(-20)
        
        #Crea un rectangulo que se utilizara para mostrar la imagen superpuesta sobre la cara
        self.faceMaker = CardMaker("Face Texture");
        self.faceImage = NodePath(self.faceMaker.generate())
        self.faceImage.setTexture(loader.loadTexture("margarita-glass3.png"))
        self.faceImage.reparentTo(aspect2d)
        #self.faceImage.reparentTo(render2d)
        self.faceImage.setTransparency(TransparencyAttrib.MAlpha)
        
        self.setup_handlers()
        self.setup_lights()

        self.count = 0
        
        #Establece un fondo negro
        #base.setBackgroundColor(0, 0, 0)

        #Carga el objeto tetera (incluido con Panda3D), y lo ubica en el mundo
        #self.teapot = loader.loadModel('models/teapot')
        #self.teapot.reparentTo(base.render)
        #self.teapot.setPos(-10, -10, -10)

        #Coloca la camara en el origen de coordenadas, y hace que apunte hacia la tetera
        #camera.setPos(0, 0, 0)
        #camera.lookAt(-10, -10, -10)

        taskMgr.add(self.onFrameChanged, "frameChange")
예제 #38
0
    def send(self, event, sentArgs=[], taskChain = None):
        """
        Send this event, optionally passing in arguments

        event is usually a string.
        sentArgs is a list of any data that you want passed along to the
            handlers listening to this event.

        If taskChain is not None, it is the name of the task chain
        which should receive the event.  If taskChain is None, the
        event is handled immediately.  Setting a non-None taskChain
        will defer the event (possibly till next frame or even later)
        and create a new, temporary task within the named taskChain,
        but this is the only way to send an event across threads.
        """
        if Messenger.notify.getDebug() and not self.quieting.get(event):
            assert Messenger.notify.debug(
                'sent event: %s sentArgs = %s, taskChain = %s' % (
                event, sentArgs, taskChain))

        self.lock.acquire()
        try:
            foundWatch=0
            if __debug__:
                if self.__isWatching:
                    for i in self.__watching.keys():
                        if str(event).find(i) >= 0:
                            foundWatch=1
                            break
            acceptorDict = self.__callbacks.get(event)
            if not acceptorDict:
                if __debug__:
                    if foundWatch:
                        print("Messenger: \"%s\" was sent, but no function in Python listened."%(event,))
                return

            if taskChain:
                # Queue the event onto the indicated task chain.
                from direct.task.TaskManagerGlobal import taskMgr
                queue = self._eventQueuesByTaskChain.setdefault(taskChain, [])
                queue.append((acceptorDict, event, sentArgs, foundWatch))
                if len(queue) == 1:
                    # If this is the first (only) item on the queue,
                    # spawn the task to empty it.
                    taskMgr.add(self.__taskChainDispatch, name = 'Messenger-%s' % (taskChain),
                                extraArgs = [taskChain], taskChain = taskChain,
                                appendTask = True)
            else:
                # Handle the event immediately.
                self.__dispatch(acceptorDict, event, sentArgs, foundWatch)
        finally:
            self.lock.release()
예제 #39
0
파일: main.py 프로젝트: tim-vu/bf3_nav_mesh
    def __init__(self, level, chunks):
        ShowBase.__init__(self)

        self.level = level

        self.disableMouse()

        wp = WindowProperties()
        #wp.setFullscreen(True)
        wp.setCursorHidden(True)
        wp.setMouseMode(WindowProperties.M_relative)
        #wp.setSize(800, 500)
        self.win.requestProperties(wp)

        self.camLens.setFov(VisualizerApp.FOV)

        self.keyMap = {
            'forward': 0,
            'backward': 0,
            'left': 0,
            'right': 0,
            'shift': 0
        }

        self.setBackgroundColor(0.53, 0.80, 0.92, 1)

        self.accept('escape', sys.exit)
        self.accept("a", self.set_key, ["left", True])
        self.accept("d", self.set_key, ["right", True])
        self.accept("w", self.set_key, ["forward", True])
        self.accept("s", self.set_key, ["backward", True])
        self.accept('lshift', self.set_key, ['shift', True])
        self.accept("a-up", self.set_key, ["left", False])
        self.accept("d-up", self.set_key, ["right", False])
        self.accept("w-up", self.set_key, ["forward", False])
        self.accept("s-up", self.set_key, ["backward", False])
        self.accept('lshift-up', self.set_key, ['shift', False])

        self.cameraMovementTask = taskMgr.add(self.camera_movement, "CameraMovement")
        self.cameraRotationTask = taskMgr.add(self.camera_rotation, 'CameraRotation')

        self.position_text = OnscreenText(text="Position: \nChunk: ", align=TextNode.ALeft, parent=self.pixel2d, fg=(1, 1, 1, 1), bg=(0, 0, 0, 0.7))
        self.position_text.setScale(18)
        self.position_text.setPos(5, -20)

        self.taskMgr.setupTaskChain('chunk_loader_chain', numThreads=6)

        self.create_lights()

        self.taskMgr.doMethodLater(0, self.load_chunks, 'Load Chunks', extraArgs=[chunks], appendTask=True)

        self.camera.setPos(-64 * 5, 54 * 5, 100)
예제 #40
0
파일: main.py 프로젝트: aforren1/3dhand
    def __init__(self, dev):
        ShowBase.__init__(self)

        render.setAntialias(AntialiasAttrib.MMultisample)
        render.setShaderAuto()  # gets us shadows

        self.dev = dev
        self.zeroing = None
        self.load_models()
        self.setup_lights()
        self.setup_camera()
        taskMgr.add(self.move_task, 'move')
        taskMgr.add(self.colour_change, 'col')
예제 #41
0
 def __decButtonDown(self, event):
     assert self.notify.debugStateCall(self)
     task = Task(self.__scrollByTask)
     task.setDelay(1.0 / self.__scrollSpeed)
     task.prevTime = 0.0
     task.delta = -1
     taskName = self.taskName("scroll")
     #print "decButtonDown: adding ", taskName
     taskMgr.add(task, taskName)
     self.scrollBy(task.delta)
     messenger.send('wakeup')
     if self.__decButtonCallback:
         self.__decButtonCallback()
예제 #42
0
        def setup_world(self):
            self.world_node = self.render.attachNewNode('World')
            self.world.setGravity(Vec3(0, 0, -9.81))

            # Landscape
            model = self.loader.loadModel("mesh/models/landscape/landscape")
            model.reparentTo(self.render)
            model.setScale(100)
            model.flatten_light()
            geom_nodes = model.findAllMatches('**/+GeomNode')
            geom_node = geom_nodes.getPath(0).node()
            geom_mesh = geom_node.getGeom(0)
            mesh = BulletTriangleMesh()
            mesh.add_geom(geom_mesh)
            ground_shape = BulletTriangleMeshShape(mesh, dynamic=False)

            ground_node = self.world_node.attachNewNode(
                BulletRigidBodyNode('Ground'))
            ground_node.node().addShape(ground_shape)
            '''
            if self.debug_mode:
                debug_node_path = self.world_node.attachNewNode(BulletDebugNode('Debug'))
                debug_node_path.show()
                debug_node_path.node().showNormals(True)
                self.world.setDebugNode(debug_node_path.node())
            '''
            self.debug_node_path = self.world_node.attachNewNode(
                BulletDebugNode('Debug'))
            self.debug_node_path.hide()
            self.world.setDebugNode(self.debug_node_path.node())

            ground_node.setPos(0, 0, 0)
            ground_node.setCollideMask(BitMask32.allOn())

            self.world.attachRigidBody(ground_node.node())

            # Character
            player = Player()

            # Other models
            path = 'mesh/models/bullet/pyramid'
            self.add_model(path, pos_x=50, pos_y=15, pos_z=370, scale=5)
            self.add_model(path, pos_x=30, pos_y=15, pos_z=370, scale=5)
            self.add_model(path, pos_x=70, pos_y=15, pos_z=390, scale=5)
            self.add_model(path, pos_x=50, pos_y=40, pos_z=360, scale=5)

            path = 'mesh/models/bullet/ball'
            self.add_model(path, pos_x=0, pos_y=15, pos_z=400, scale=8)
            self.add_model(path, pos_x=30, pos_y=40, pos_z=450, scale=8)

            taskMgr.add(self.update, 'updateWorld')
예제 #43
0
    def restart(self):
        if self.eventQueue is None:
            self.eventQueue = EventQueue.getGlobalEventQueue()

        if self.eventHandler is None:
            if self.eventQueue == EventQueue.getGlobalEventQueue():
                # If we are using the global event queue, then we also
                # want to use the global event handler.
                self.eventHandler = EventHandler.getGlobalEventHandler()
            else:
                # Otherwise, we need our own event handler.
                self.eventHandler = EventHandler(self.eventQueue)

        taskMgr.add(self.eventLoopTask, 'eventManager')
예제 #44
0
 def editStart(self, event):
     taskMgr.remove('guiEditTask')
     vWidget2render2d = self.getPos(ShowBaseGlobal.render2d)
     vMouse2render2d = Point3(event.getMouse()[0], 0, event.getMouse()[1])
     editVec = Vec3(vWidget2render2d - vMouse2render2d)
     if base.mouseWatcherNode.getModifierButtons().isDown(
             KeyboardButton.control()):
         t = taskMgr.add(self.guiScaleTask, 'guiEditTask')
         t.refPos = vWidget2render2d
         t.editVecLen = editVec.length()
         t.initScale = self.getScale()
     else:
         t = taskMgr.add(self.guiDragTask, 'guiEditTask')
         t.editVec = editVec
예제 #45
0
    def restart(self):
        if self.eventQueue == None:
            self.eventQueue = EventQueue.getGlobalEventQueue()

        if self.eventHandler == None:
            if self.eventQueue == EventQueue.getGlobalEventQueue():
                # If we are using the global event queue, then we also
                # want to use the global event handler.
                self.eventHandler = EventHandler.getGlobalEventHandler()
            else:
                # Otherwise, we need our own event handler.
                self.eventHandler = EventHandler(self.eventQueue)

        taskMgr.add(self.eventLoopTask, 'eventManager')
예제 #46
0
 def connect(self) -> None:
     # Handle connections and terminations
     self.manager = QueuedConnectionManager()
     # Wait for clients connection requests
     self.listener = QueuedConnectionListener(self.manager, 0)
     # Buffers incoming data from active connection
     self.reader = QueuedConnectionReader(self.manager, 0)
     # Transmit PyDatagrams to active connection
     self.writer = ConnectionWriter(self.manager, 0)
     # Open TCP Rendezvous to accept client connections with a limit
     self.socket = self.manager.openTCPServerRendezvous(
         self.port, self.backlog)
     self.listener.addConnection(self.socket)
     print("Server listening on port %s...." % str(self.port))
     # Listen for mew incoming connections
     taskMgr.add(self.handle_incoming_connections,
                 "Poll the connection listener", -39)
     # Listen for new datagrams
     taskMgr.add(self.handle_connection_data,
                 "Poll the connection reader", -40)
     # Listen for dropped connections
     taskMgr.add(self.handle_dropped_connections,
                 "Poll the dropped connection listener", -41)
     # See if game can be started
     taskMgr.add(self.start_game, "Start Game", -42)
예제 #47
0
    def __init__(self, audio_manager, listener_target = None, root = None,
                 taskPriority = 51):
        self.audio_manager = audio_manager
        self.listener_target = listener_target

        if (root==None):
            self.root = render
        else:
            self.root = root

        self.sound_dict = {}
        self.vel_dict = {}
        self.listener_vel = VBase3(0, 0, 0)

        taskMgr.add(self.update, "Audio3DManager-updateTask", taskPriority)
예제 #48
0
 def restart(self):
     if None in (EventManager.EventQueue, EventManager.EventHandler):
         from pandac.PandaModules import EventQueue, EventHandler
         EventManager.EventQueue = EventQueue
         EventManager.EventHandler = EventHandler
     if self.eventQueue == None:
         self.eventQueue = EventManager.EventQueue.getGlobalEventQueue()
     if self.eventHandler == None:
         if self.eventQueue == EventManager.EventQueue.getGlobalEventQueue():
             self.eventHandler = EventManager.EventHandler.getGlobalEventHandler()
         else:
             self.eventHandler = EventManager.EventHandler(self.eventQueue)
     from direct.task.TaskManagerGlobal import taskMgr
     taskMgr.add(self.eventLoopTask, 'eventManager')
     return
예제 #49
0
    def __init__(self, audio_manager, listener_target = None, root = None,
                 taskPriority = 51):
        self.audio_manager = audio_manager
        self.listener_target = listener_target

        if (root==None):
            self.root = render
        else:
            self.root = root

        self.sound_dict = {}
        self.vel_dict = {}
        self.listener_vel = VBase3(0, 0, 0)

        taskMgr.add(self.update, "Audio3DManager-updateTask", taskPriority)
예제 #50
0
 def startSmooth(self):
     """
     This function starts the task that ensures the node is
     positioned correctly every frame.  However, while the task is
     running, you won't be able to lerp the node or directly
     position it.
     """
     if not self.wantsSmoothing() or self.isDisabled() or self.isLocal():
         return
     if not self.smoothStarted:
         taskName = self.taskName("smooth")
         taskMgr.remove(taskName)
         self.reloadPosition()
         taskMgr.add(self.doSmoothTask, taskName)
         self.smoothStarted = 1
예제 #51
0
    def __init__(self, world, z):
        core.NodePath.__init__(self, 'slice-{}'.format(z))

        if Slice.master is None:
            Slice.master = MasterChunk(self.chunk_size, world.forms.values())

        self.world = world
        self.z = z

        self.chunks = {}
        self.hidden_chunks = {}

        self.setPos(0, 0, z)

        self.substances = [None] + [
            loader.loadTexture('media/textures/{}.png'.format(name),
                               anisotropicDegree=16,
                               minfilter=core.Texture.FTLinearMipmapLinear)
            for name in ['dirt', 'stone']
        ]

        self.hiddentexture = loader.loadTexture('media/textures/hidden.png',
                                                anisotropicDegree=16,
                                                minfilter=core.Texture.FTLinearMipmapLinear)
        self.hiddentexture.setWrapU(core.Texture.WMClamp)
        self.hiddentexture.setWrapV(core.Texture.WMClamp)

        self.show_stale_chunks = False

        self.updates = set()
        self.first_update_done = False

        self.task = taskMgr.add(self.perform_updates, 'Slice update')

        messenger.accept('console-command', self, self.command)
예제 #52
0
파일: Npc.py 프로젝트: flips30240/VoxelDash
    def shoot(self):
        self.ammoUsed = 0
        self.ammoUsed += 1
        #nodes
        node = BulletRigidBodyNode('Box')
        node.setMass(.1)
        ammoNode = render.attachNewNode(node)

        #shapes
        shape = BulletSphereShape(.2)
        model = Sphere(.2)
        model.reparentTo(ammoNode)
        model.setPos(0, 0, 0)

        #nodes
        node.addShape(shape)

        material = Material()
        material.setAmbient(VBase4(random.random(), random.random(), random.random(), random.random()))
        material.setDiffuse(VBase4(random.random(), random.random(), random.random(), random.random()))
        material.setEmission(VBase4(random.random(), random.random(), random.random(), random.random()))
        material.setShininess(random.random())

        #myTexture = loader.loadTexture("player.png")
        #ammoNode.setTexture(myTexture)
        ammoNode.setMaterial(material)

        ammoNode.setX(self.enemyNp.getX())
        ammoNode.setY(self.enemyNp.getY())
        ammoNode.setZ(self.enemyNp.getZ() + 1)

        force = Vec3(0, 0, 0)
        force.setY(5)
        force.setZ(1)
        force*=50
        force = render.getRelativeVector(self.player, force)

        ammoNode.node().applyCentralForce(force)

        print(force)

        #bullet world
        self.world.attachRigidBody(node)

        #taskMgr.remove('ammoDestroy')
        task = Task(self.destroyAmmoNode)
        taskMgr.add(task, 'ammoDestroy', extraArgs = [task, ammoNode, node, self.world])
예제 #53
0
 def add(self, job):
     pri = job.getPriority()
     jobId = job._getJobId()
     self._pri2jobId2job.setdefault(pri, {})
     self._pri2jobId2job[pri][jobId] = job
     self._jobId2pri[jobId] = pri
     self._pri2jobIds.setdefault(pri, [])
     self._pri2jobIds[pri].append(jobId)
     self._jobId2timeslices[jobId] = pri
     self._jobId2overflowTime[jobId] = 0.0
     self._jobIdGenerator = None
     if len(self._jobId2pri) == 1:
         taskMgr.add(self._process, JobManager.TaskName)
         self._highestPriority = pri
     elif pri > self._highestPriority:
         self._highestPriority = pri
     self.notify.debug('added job: %s' % job.getJobName())
     return
예제 #54
0
def send (self, orig_event, sent_args=[], task_chain=None):
    event = 'panda-' + orig_event
    self.lock.acquire()
    try:
        if task_chain:
            from direct.task.TaskManagerGlobal import taskMgr

            queue = self._patch_event_queues [task_chain]
            queue.append ((event, sent_args))
            if len (queue) == 1:
                taskMgr.add (self._patch_task_chain_forward,
                             name = '_patch_Messenger-%s' % (task_chain),
                             extraArgs = [task_chain],
                             taskChain = task_chain,
                             appendTask = True)
        else:
            self._patch_forward (event, sent_args)
    finally:
        self.lock.release()
예제 #55
0
 def enable(self, x):
     """Turn the buffer viewer on or off.  The initial state of the
     buffer viewer depends on the Config variable 'show-buffers'."""
     if (x != 0) and (x != 1):
         BufferViewer.notify.error('invalid parameter to BufferViewer.enable')
         return
     self.enabled = x
     self.dirty = 1
     if (x and self.task == 0):
         self.task = taskMgr.add(self.maintainReadout, "buffer-viewer-maintain-readout",
                                 priority=1)
    def restart(self):
        if None in (EventManager.EventQueue, EventManager.EventHandler):
            from pandac.PandaModules import EventQueue, EventHandler
            EventManager.EventQueue = EventQueue
            EventManager.EventHandler = EventHandler
        
        if self.eventQueue == None:
            self.eventQueue = EventManager.EventQueue.getGlobalEventQueue()

        if self.eventHandler == None:
            if self.eventQueue == EventManager.EventQueue.getGlobalEventQueue():
                # If we are using the global event queue, then we also
                # want to use the global event handler.
                self.eventHandler = EventManager.EventHandler.getGlobalEventHandler()
            else:
                # Otherwise, we need our own event handler.
                self.eventHandler = EventManager.EventHandler(self.eventQueue)

        # Should be safe to import the global taskMgr by now.
        from direct.task.TaskManagerGlobal import taskMgr
        taskMgr.add(self.eventLoopTask, 'eventManager')
예제 #57
0
 def send(self, event, sentArgs = [], taskChain = None):
     if Messenger.notify.getDebug() and not self.quieting.get(event):
         pass
     self.lock.acquire()
     try:
         foundWatch = 0
         acceptorDict = self.__callbacks.get(event)
         if not acceptorDict:
             return
         if taskChain:
             from direct.task.TaskManagerGlobal import taskMgr
             queue = self._eventQueuesByTaskChain.setdefault(taskChain, [])
             queue.append((acceptorDict,
              event,
              sentArgs,
              foundWatch))
             if len(queue) == 1:
                 taskMgr.add(self.__taskChainDispatch, name='Messenger-%s' % taskChain, extraArgs=[taskChain], taskChain=taskChain, appendTask=True)
         else:
             self.__dispatch(acceptorDict, event, sentArgs, foundWatch)
     finally:
         self.lock.release()
    def __prepareToStart(self):
        """ This is called internally when transitioning from S_ready
        to S_started.  It sets up whatever initial values are
        needed.  Assumes self.packageLock is held.  Returns False if
        there were no packages to download, and the state was
        therefore transitioned immediately to S_done. """

        if not self.needsDownload:
            self.state = self.S_done
            return False

        self.state = self.S_started

        assert not self.downloadTask
        self.downloadTask = taskMgr.add(
            self.__downloadPackageTask, 'downloadPackage',
            taskChain = self.taskChain)

        assert not self.progressTask
        self.progressTask = taskMgr.add(
            self.__progressTask, 'packageProgress')

        return True
예제 #59
0
 def add(self, job):
     pri = job.getPriority()
     jobId = job._getJobId()
     # store the job in the main table
     self._pri2jobId2job.setdefault(pri, {})
     self._pri2jobId2job[pri][jobId] = job
     # and also store a direct mapping from the job's ID to its priority
     self._jobId2pri[jobId] = pri
     # add the jobId onto the end of the list of jobIds for this priority
     self._pri2jobIds.setdefault(pri, [])
     self._pri2jobIds[pri].append(jobId)
     # record the job's relative timeslice count
     self._jobId2timeslices[jobId] = pri
     # init the overflow time tracking
     self._jobId2overflowTime[jobId] = 0.
     # reset the jobId round-robin
     self._jobIdGenerator = None
     if len(self._jobId2pri) == 1:
         taskMgr.add(self._process, JobManager.TaskName)
         self._highestPriority = pri
     elif pri > self._highestPriority:
         self._highestPriority = pri
     self.notify.debug('added job: %s' % job.getJobName())