Exemple #1
0
    def __updateParticleParent(self):
        if not CIGlobals.isNodePathOk(self.waterStreamParent):
            return

        time = globalClock.getFrameTime()

        streamPos = self.waterStreamParent.getPos(render)
        distance = self.sprayParticleDist

        if self.isLocal():
            camQuat = camera.getQuat(render)
            pFrom = camera.getPos(render)
            push = (streamPos - pFrom).length()
            pFrom += camQuat.xform(Vec3.forward()) * push
            pTo = pFrom + camQuat.xform(
                Vec3.forward()) * (self.sprayParticleDist +
                                   (pFrom - streamPos).length())
            hitPos = Point3(pTo)
            result = base.physicsWorld.rayTestClosest(pFrom, pTo,
                                                      CIGlobals.WorldGroup)
            if result.hasHit():
                node = result.getNode()
                hitPos = result.getHitPos()
                distance = (hitPos - streamPos).length()

            if time - self.lastSprayTime >= self.SprayTraceIval and not self.released:
                if result.hasHit():
                    self.__doSplat(distance, hitPos)
                self.getFPSCam().addViewPunch(
                    Vec3(random.uniform(-0.6, 0.6), random.uniform(0.25, 1.0),
                         0.0))
                self.primaryFirePress(True)
                self.lastSprayTime = time

        else:
            pFrom = self.avatar.getPos(render) + self.avatar.getEyePoint() + (
                1, 0, 0)
            quat = Quat()
            quat.setHpr(
                self.avatar.getHpr(render) + (0, self.avatar.lookPitch, 0))
            pTo = pFrom + quat.xform(
                Vec3.forward()) * (self.sprayParticleDist +
                                   (pFrom - streamPos).length())
            hitPos = Point3(pTo)
            hit = PhysicsUtils.rayTestClosestNotMe(
                self.avatar, pFrom, pTo,
                CIGlobals.WorldGroup | CIGlobals.LocalAvGroup)
            if hit is not None:
                hitPos = hit.getHitPos()
                distance = (hitPos - streamPos).length()

        self.waterStreamParent.lookAt(render, hitPos)

        if self.sprayParticle:
            system = self.sprayParticle.getParticlesNamed('particles-1')
            # Make the particles die off at the hit point.
            lifespan = min(
                1, distance / self.sprayParticleDist) * self.sprayParticleLife
            system.factory.setLifespanBase(lifespan)
Exemple #2
0
    def update(self, task=None):
        """
        Updates position of sounds in the 3D audio system. Will be called automatically
        in a task.
        """
        # Update the positions of all sounds based on the objects
        # to which they are attached

        # The audio manager is not active so do nothing
        if hasattr(self.audio_manager, "getActive"):
            if self.audio_manager.getActive()==0:
                return Task.cont

        for known_object in self.sound_dict.keys():
            tracked_sound = 0
            while tracked_sound < len(self.sound_dict[known_object]):
                sound = self.sound_dict[known_object][tracked_sound]
                pos = known_object.getPos(self.root)
                vel = self.getSoundVelocity(sound)
                sound.set3dAttributes(pos[0], pos[1], pos[2], vel[0], vel[1], vel[2])
                tracked_sound += 1

        # Update the position of the listener based on the object
        # to which it is attached
        if self.listener_target:
            pos = self.listener_target.getPos(self.root)
            forward = self.root.getRelativeVector(self.listener_target, Vec3.forward())
            up = self.root.getRelativeVector(self.listener_target, Vec3.up())
            vel = self.getListenerVelocity()
            self.audio_manager.audio3dSetListenerAttributes(pos[0], pos[1], pos[2], vel[0], vel[1], vel[2], forward[0], forward[1], forward[2], up[0], up[1], up[2])
        else:
            self.audio_manager.audio3dSetListenerAttributes(0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1)
        return Task.cont
Exemple #3
0
    def onMouseMoveTransforming3D(self, vp):
        now = self.getPointOnGizmo()

        gizmoOrigin = self.getGizmoOrigin()
        gizmoDir = self.getGizmoDirection(self.widget.activeAxis.axisIdx)
        ref = Vec3.forward()
        if gizmoDir == ref:
            ref = Vec3.right()

        nowVec = Vec3(now - gizmoOrigin).normalized()
        origVec = Vec3(self.transformStart - gizmoOrigin).normalized()

        axisToHprAxis = {
            0: 1,  # pitch
            1: 2,  # roll
            2: 0  # yaw
        }

        snap = not vp.mouseWatcher.isButtonDown(KeyboardButton.shift())

        origAngle = origVec.signedAngleDeg(
            ref, self.getGizmoDirection(self.widget.activeAxis.axisIdx))
        angle = nowVec.signedAngleDeg(
            ref, self.getGizmoDirection(self.widget.activeAxis.axisIdx))
        hpr = Vec3(0)
        if snap:
            ang = round(-(angle - origAngle) / 15) * 15
        else:
            ang = -(angle - origAngle)
        hpr[axisToHprAxis[self.widget.activeAxis.axisIdx]] = ang
        self.toolVisRoot.setHpr(hpr)
Exemple #4
0
 def handleKeyboardEvent(self, task):
     keys = self.keys
     
     dt = globalClock.getDt()
     impulse = Vec3(0, 0, 0)
     increment = self._impulseIncrement * dt
     
     above_limit = self.is_above_limit
     
     for key, vec in (("left", Vec3.left()),
                      ("right", Vec3.right()),
                      ("up", Vec3.forward()),
                      ("down", Vec3.back())):
         if keys[key] and (not above_limit or self.is_braking(vec)):
             impulse += vec * increment
     
     self.addImpulse(impulse)
     
     # If Equismo was not hit by an enemy look at the movement direction.
     # Otherwise look at the enemy until Equismo turns around.
     if not self._hit:
         self.face(self.velocity)
     
     elif ((impulse.length() > 0) and
           (self.velocity.length() > 0.5) and
           (not self.is_braking(impulse))):
                 self._hit = False
     
     self.doWalkAnimation(impulse)
     
     return task.cont
Exemple #5
0
    def updateCamera(self, x, y):
        factor = 0.01
        dX = (self.mousePrevX - x) * factor
        dY = (self.mousePrevY - y) * factor

        if self.mouseDown1:
            self._rotateTheta(dX * math.pi * self.rotateMag)
            self._rotatePhi(-dY * math.pi * self.rotateMag)

        if self.mouseDown2:
            vecX = self.target.getRelativeVector(self.base.camera,
                                                 Vec3.right())
            vecY = self.target.getRelativeVector(self.base.camera,
                                                 Vec3.forward())
            vecY.setZ(0.0)
            vecY.normalize()
            offset = (vecX * dX * self.moveMag) + (vecY * dY * self.moveMag)
            self.target.setPos(self.target, offset)

        if self.mouseDown3:
            self.zoom(dY * self.zoomMag)

        self.mousePrevX = x
        self.mousePrevY = y

        # Update camera position
        position = Point3(0.0, 0.0, 0.0)
        position.setX(self.r * math.cos(self.theta) * math.sin(self.phi))
        position.setY(self.r * math.sin(self.theta) * math.sin(self.phi))
        position.setZ(self.r * math.cos(self.phi))
        self.base.camera.setPos(position)
        self.base.camera.lookAt(self.target)
    def __init__(self):
        PhysicsNodePath.__init__(self, 'can')

        self.shapeGroup = BitMask32.allOn()

        sph = BulletCylinderShape(0.5, 1.2, ZUp)
        rbnode = BulletRigidBodyNode('can_body')
        rbnode.setMass(10.0)
        rbnode.addShape(sph)
        rbnode.setCcdMotionThreshold(1e-7)
        rbnode.setCcdSweptSphereRadius(0.5)

        self.mdl = loader.loadModel("phase_5/models/props/can.bam")
        self.mdl.setScale(11.0)
        self.mdl.setZ(-0.55)
        self.mdl.reparentTo(self)
        self.mdl.showThrough(CIGlobals.ShadowCameraBitmask)

        self.setupPhysics(rbnode)

        #self.makeShadow(0.2)

        self.reparentTo(render)
        self.setPos(base.localAvatar.getPos(render))
        self.setQuat(base.localAvatar.getQuat(render))

        dir = self.getQuat(render).xform(Vec3.forward())
        amp = 10
        self.node().setLinearVelocity(dir * amp)
Exemple #7
0
    def handleKeyboardEvent(self, task):
        keys = self.keys

        dt = globalClock.getDt()
        impulse = Vec3(0, 0, 0)
        increment = self._impulseIncrement * dt

        above_limit = self.is_above_limit

        for key, vec in (("left", Vec3.left()), ("right", Vec3.right()),
                         ("up", Vec3.forward()), ("down", Vec3.back())):
            if keys[key] and (not above_limit or self.is_braking(vec)):
                impulse += vec * increment

        self.addImpulse(impulse)

        # If Equismo was not hit by an enemy look at the movement direction.
        # Otherwise look at the enemy until Equismo turns around.
        if not self._hit:
            self.face(self.velocity)

        elif ((impulse.length() > 0) and (self.velocity.length() > 0.5)
              and (not self.is_braking(impulse))):
            self._hit = False

        self.doWalkAnimation(impulse)

        return task.cont
Exemple #8
0
    def updateCamera(self, task):
        if self.base.mouseWatcherNode.hasMouse():
            # Register camera controls
            mouseX = self.base.mouseWatcherNode.getMouseX()
            mouseY = self.base.mouseWatcherNode.getMouseY()
            dX = self.mousePrevX - mouseX
            dY = self.mousePrevY - mouseY

            if self.mouseDown1:
                self.rotateTheta(dX * math.pi * self.rotateMag)
                self.rotatePhi(-dY * math.pi * self.rotateMag)

            if self.mouseDown2:
                vecX = self.target.getRelativeVector(self.base.camera, Vec3.right())
                vecY = self.target.getRelativeVector(self.base.camera, Vec3.forward())
                vecY.setZ(0.0)
                vecY.normalize()
                offset = (vecX * dX * self.moveMag) + (vecY * dY * self.moveMag)
                self.target.setPos(self.target, offset)

            if self.mouseDown3:
                self.zoom(dY * self.zoomMag)

            self.mousePrevX = mouseX
            self.mousePrevY = mouseY

            # Update camera position
            position = Point3(0.0, 0.0, 0.0)
            position.setX(self.r * math.cos(self.theta) * math.sin(self.phi))
            position.setY(self.r * math.sin(self.theta) * math.sin(self.phi))
            position.setZ(self.r * math.cos(self.phi))
            self.base.camera.setPos(position)
            self.base.camera.lookAt(self.target)

        return task.cont
    def step(self, task):
        distance = ClockObject.getGlobalClock().getDt() * self.speed

        rotMat = Mat3.rotateMatNormaxis(self.avatar.getH(), Vec3.up())
        step = Vec3(rotMat.xform(Vec3.forward() * distance))
        self.avatar.setFluidPos(Point3(self.avatar.getPos() + step))

        return Task.cont
Exemple #10
0
    def start(self):
        Gag.start(self)

        self.hitSfx.play()

        gag = self.gag
        if self.isLocal():
            vm = self.getViewModel()
            fpsCam = self.getFPSCam()
            fpsCam.setVMAnimTrack(
                Sequence(ActorInterval(vm, "sg_shoot_begin"),
                         ActorInterval(vm, "sg_shoot_end"),
                         Func(vm.loop, "sg_idle")))
            gag = self.getVMGag()

        nozzle = gag.find("**/joint_nozzle")

        if self.isLocal() and base.localAvatar.battleControls:
            if base.localAvatar.isFirstPerson():
                self.getFPSCam().resetViewPunch()
                self.getFPSCam().addViewPunch(
                    Vec3(random.uniform(-0.6, 0.6),
                         random.uniform(-0.25, -0.5), 0.0))
                startPos = camera.getPos(render)
            else:
                startPos = nozzle.getPos(render)
            hitPos = PhysicsUtils.getHitPosFromCamera()
        else:
            startPos = nozzle.getPos(render)
            quat = Quat()
            quat.setHpr(
                self.avatar.getHpr(render) + (0, self.avatar.lookPitch, 0))
            hitPos = quat.xform(Vec3.forward() * 10000)
            hit = PhysicsUtils.rayTestClosestNotMe(
                self.avatar, startPos, hitPos,
                CIGlobals.WorldGroup | CIGlobals.LocalAvGroup)
            if hit is not None:
                hitPos = hit.getHitPos()

        pellet = WaterPellet(self.isLocal())
        pellet.addToWorld(nozzle.getPos(render),
                          lookAt=hitPos,
                          velo=Vec3.forward() * self.pelletSpeed)

        if self.isLocal():
            base.localAvatar.sendUpdate('usedGag', [self.id])
Exemple #11
0
 def zoom_out(self, amount):
     camera_direction = self.camera.get_parent().get_relative_vector(
         self.camera, Vec3.forward())
     new_pos = self.camera.get_pos(
     ) - camera_direction * self.zoom_speed * amount
     if new_pos.length() < self.max_distance:
         self.camera.set_pos(new_pos)
     else:
         self.camera.set_pos(-camera_direction * self.max_distance)
Exemple #12
0
    def _handleShotSomething(self, intoNP, hitPos, distance):
        avNP = intoNP.getParent()

        if base.localAvatarReachable() and self.isLocal():
            for obj in base.avatars:
                if CIGlobals.isAvatar(obj) and obj.getKey() == avNP.getKey():
                    obj.handleHitByToon(self.avatar, self.getID(), distance)

        vm = self.getViewModel()
        fpsCam = self.getFPSCam()
        track = Sequence()

        if action == self.actionIdle:
            track.append(Func(vm.loop, "idle"))
        elif action == self.actionDraw:
            track.append(ActorInterval(vm, "draw"))
        elif action == self.actionPump:
            track.append(Func(self.pumpSound.play))
            track.append(ActorInterval(vm, "pump"))

        elif action == self.actionFire:
            camQuat = camera.getQuat(render)
            pFrom = camera.getPos(render)
            pTo = pFrom + camQuat.xform(Vec3.forward() * 10000)
            hitPos = Point3(pTo)
            result = base.physicsWorld.rayTestClosest(pFrom, pTo,
                                                      CIGlobals.WorldGroup)
            if result.hasHit():
                node = result.getNode()
                hitPos = result.getHitPos()
                distance = (hitPos - pFrom).length()
                self._handleShotSomething(NodePath(node), hitPos, distance)

            self.clip -= 1
            fpsCam = self.getFPSCam()
            if base.localAvatar.isFirstPerson():
                fpsCam.addViewPunch(
                    Vec3(random.uniform(-2, 2), random.uniform(2, 1), 0))

            base.localAvatar.sendUpdate('usedGag', [self.id])

            track.append(Func(self.fireSound.play))
            track.append(ActorInterval(vm, "fire"))

        elif action == self.actionDblFire:
            track.append(Func(self.dblFireSound.play))
            track.append(ActorInterval(vm, "altfire"))
        elif action == self.actionReload:
            sound = random.choice(self.reloadSounds)
            track.append(Func(sound.play))
            track.append(ActorInterval(vm, "reload2"))
        elif action == self.actionBeginReload:
            track.append(ActorInterval(vm, "reload1"))
        elif action == self.actionEndReload:
            track.append(ActorInterval(vm, "reload3"))

        fpsCam.setVMAnimTrack(track)
Exemple #13
0
    def zoom_in(self, amount):
        camera_direction = self.camera.get_parent().get_relative_vector(
            self.camera, Vec3.forward())
        new_pos = self.camera.get_pos(
        ) + camera_direction * self.zoom_speed * amount

        if new_pos.length() < self.min_distance:
            self.camera.set_pos(-camera_direction * self.min_distance)
        elif new_pos.length() >= 0 and new_pos.get_y() >= 0:
            self.camera.set_pos(new_pos)
    def __handleUse(self, task):
        #if self.mode == LocalControls.MThirdPerson:
        #    return task.cont

        time = globalClock.getFrameTime()
        use = inputState.isSet('use')
        if use:
            # see if there is anything for us to use.

            distance = 7.5
            camQuat = base.camera.getQuat(render)
            camFwd = camQuat.xform(Vec3.forward())
            camPos = base.camera.getPos(render)
            if self.mode == self.MFirstPerson:
                start = camPos
            else:
                # Move the line out to their character.
                # This prevents the player from using things that
                # are behind their character, but in front of
                # the camera.
                laPos = base.localAvatar.getPos(render)
                camToPlyr = (camPos.getXy() - laPos.getXy()).length()
                start = camPos + (camFwd * camToPlyr)
            stop = start + (camFwd * distance)
            hit = PhysicsUtils.rayTestClosestNotMe(base.localAvatar, start,
                                                   stop,
                                                   CIGlobals.UseableGroup)

            somethingToUse = False
            if hit is not None:
                node = hit.getNode()
                if node.hasPythonTag("useableObject"):
                    somethingToUse = True
                    obj = node.getPythonTag("useableObject")
                    if obj.canUse():
                        if self.currentObjectUsing != obj:
                            if self.currentObjectUsing is not None:
                                self.currentObjectUsing.stopUse()
                            obj.startUse()
                            self.lastUseObjectTime = time
                        elif time - self.lastUseObjectTime >= obj.useIval:
                            obj.use()
                            self.lastUseObjectTime = time

                        self.currentObjectUsing = obj

            if not somethingToUse and not self.lastUse:
                self.useInvalidSound.play()
        else:
            if self.currentObjectUsing is not None:
                self.currentObjectUsing.stopUse()
                self.currentObjectUsing = None

        self.lastUse = use
        return task.cont
Exemple #15
0
 def setupLaserVec(self):
     traceStart = self.getPos() + self.getEyePosition()
     if self.target:
         entPos = self.target.entity.getPos(
         ) + self.target.entity.getEyePosition()
         self.laserVec = [traceStart, entPos]
     else:
         self.laserVec = [
             traceStart,
             traceStart + self.getQuat().xform(Vec3.forward() * 50)
         ]
Exemple #16
0
def getHitPosFromCamera(mask=CIGlobals.WallGroup | CIGlobals.FloorGroup
                        | CIGlobals.StreetVisGroup,
                        dist=1000.0,
                        push=0.0):
    camQuat = base.camera.getQuat(render)
    forward = camQuat.xform(Vec3.forward())
    pFrom = base.camera.getPos(render)
    pFrom += forward * push
    pTo = pFrom + (forward * dist)
    result = base.physicsWorld.rayTestClosest(pFrom, pTo, mask)
    if result.hasHit():
        return result.getHitPos()
    return pTo
    def activate(self):
        if self.pressIval:
            self.pressIval.finish()
            self.pressIval = None

        posDelta = (self.maxs - self.mins)
        posDelta.componentwiseMult(Vec3.forward() * 0.9)
        duration = posDelta.length() / self.speed
        startPos = self.origin
        endPos = self.origin + posDelta
        self.pressIval = Sequence(Func(self.pressSound.play), LerpPosInterval(self, duration, endPos, startPos))
        if self.wait != -1:
           self.pressIval.append(Wait(self.wait))
           self.pressIval.append(LerpPosInterval(self, duration, startPos, endPos))
        self.pressIval.start()
Exemple #18
0
 def camera_task(self, task):
     if self.mouseWatcherNode.hasMouse():
         x = self.mouseWatcherNode.getMouseX()
         y = self.mouseWatcherNode.getMouseY()
         orientation = self.render.getRelativeVector(
             self.camera, Vec3.forward())
         self.position.x += orientation.x * self.movement.y
         self.position.y += orientation.y * self.movement.y
         self.position.z = self.movement.z + elevation(
             self.position.x, self.position.y)
         self.movement.x = 0
         self.movement.y = 0
         self.camera.setPos(self.position)
         self.camera.setHpr(-x * 180, y * 90, 0)
     return Task.cont
Exemple #19
0
 def __init__(self, parent, model):
     PhysicalNode.__init__(self, parent, model, "equismo")
     
     self.mass = 500.0
     
     self.addCollisionSphere(1.2)
     
     self._impulseIncrement = 4.0
     self._speedLimit = 5.0
     self._turningSpeed = 0.2
     
     self._hit = False
     self._currentDirection = Vec3.forward()
     self._currentAngle = 0
     
     self.setScale(0.8)
     
     # Little "hack" to fix orientation
     # Seems that the model has its eyes in the back?!
     self.actor.setH(180)
     
     #-----------------------------------------------------------------------
     # KeyboardEventHandler initialization
     #-----------------------------------------------------------------------
     self.keys = dict.fromkeys("left right up down".split(), 0)
     set_key = self.keys.__setitem__
     self.bindings = (
         ("w", set_key, ["up", 1]),
         ("a", set_key, ["left", 1]),
         ("s", set_key, ["down", 1]),
         ("d", set_key, ["right", 1]),
         
         ("w-up", set_key, ["up", 0]),
         ("a-up", set_key, ["left", 0]),
         ("s-up", set_key, ["down", 0]),
         ("d-up", set_key, ["right", 0]),
         
         ("arrow_up", set_key, ["up", 1]),
         ("arrow_left", set_key, ["left", 1]),
         ("arrow_down", set_key, ["down", 1]),
         ("arrow_right", set_key, ["right", 1]),
         
         ("arrow_up-up", set_key, ["up", 0]),
         ("arrow_left-up", set_key, ["left", 0]),
         ("arrow_down-up", set_key, ["down", 0]),
         ("arrow_right-up", set_key, ["right", 0]),
     )
Exemple #20
0
    def __init__(self, parent, model):
        PhysicalNode.__init__(self, parent, model, "equismo")

        self.mass = 500.0

        self.addCollisionSphere(1.2)

        self._impulseIncrement = 4.0
        self._speedLimit = 5.0
        self._turningSpeed = 0.2

        self._hit = False
        self._currentDirection = Vec3.forward()
        self._currentAngle = 0

        self.setScale(0.8)

        # Little "hack" to fix orientation
        # Seems that the model has its eyes in the back?!
        self.actor.setH(180)

        #-----------------------------------------------------------------------
        # KeyboardEventHandler initialization
        #-----------------------------------------------------------------------
        self.keys = dict.fromkeys("left right up down".split(), 0)
        set_key = self.keys.__setitem__
        self.bindings = (
            ("w", set_key, ["up", 1]),
            ("a", set_key, ["left", 1]),
            ("s", set_key, ["down", 1]),
            ("d", set_key, ["right", 1]),
            ("w-up", set_key, ["up", 0]),
            ("a-up", set_key, ["left", 0]),
            ("s-up", set_key, ["down", 0]),
            ("d-up", set_key, ["right", 0]),
            ("arrow_up", set_key, ["up", 1]),
            ("arrow_left", set_key, ["left", 1]),
            ("arrow_down", set_key, ["down", 1]),
            ("arrow_right", set_key, ["right", 1]),
            ("arrow_up-up", set_key, ["up", 0]),
            ("arrow_left-up", set_key, ["left", 0]),
            ("arrow_down-up", set_key, ["down", 0]),
            ("arrow_right-up", set_key, ["right", 0]),
        )
Exemple #21
0
    def task_move_camera(self, key="", mouse="", speed=15):  # pylint: disable=unused-argument

        pos = numpy.array(self.camera.getPos())
        dir_ = self.render.getRelativeVector(self.camera, Vec3.forward())

        dx = numpy.array([dir_[1], -dir_[0], 0]) * speed
        dy = dir_ * speed
        # dz = numpy.array([0,0,1]) * speed

        # lef right
        if key == 'a':
            pos -= dx
            pos = self.correct_camera_distance(pos)
        elif key == 'd':
            pos += dx
            pos = self.correct_camera_distance(pos)
        # forward backward
        elif key == 'arrow_up' or key == 'wheel_up':
            pos += dy * 10
        elif key == 'arrow_down' or key == 'wheel_down':
            pos -= dy * 10
        # up down
        elif key == "w":
            pos = self.up_down(pos, speed)
            pos = self.correct_camera_distance(pos)
        elif key == "s":
            pos = self.up_down(pos, -speed)
            pos = self.correct_camera_distance(pos)
        elif key == 'mouse1':
            self.mouse1_down = True
            mw = self.mouseWatcherNode
            self.mouse_x_old = mw.getMouseX()
            self.mouse_y_old = mw.getMouseY()
        elif key == 'mouse1-up':
            self.mouse1_down = False

        self.camera.setPos(*pos)
        self.camera.setR(0)
        box_center = self.box.center
        if self.box.dimensions < 3:
            box_center = self._project3d(box_center)
        self.camera.lookAt(Vec3(*box_center[:3]))

        return Task.cont
Exemple #22
0
    def updateCamera(self, task):
        if self.base.mouseWatcherNode.hasMouse():
            # Register camera controls
            mouseX = self.base.mouseWatcherNode.getMouseX()
            mouseY = self.base.mouseWatcherNode.getMouseY()
            dX = self.mousePrevX - mouseX
            dY = self.mousePrevY - mouseY

            if self.mouseDown1:
                self.rotateTheta(dX * (math.pi / 2.0))
                self.rotatePhi(-dY * (math.pi / 2.0))

            if self.mouseDown2:
                self.offset.setX(self.offset.getX() + dX * 10)
                self.offset.setY(self.offset.getY() + dY * 10)

            if self.mouseDown3:
                self.zoom(dY * 50)

            self.mousePrevX = mouseX
            self.mousePrevY = mouseY

            # Update camera position
            self.position.setX(self.r * math.cos(self.theta) *
                               math.sin(self.phi))
            self.position.setY(self.r * math.sin(self.theta) *
                               math.sin(self.phi))
            self.position.setZ(self.r * math.cos(self.phi))

            vecX = self.base.render.getRelativeVector(self.base.camera,
                                                      Vec3.right())
            vecY = self.base.render.getRelativeVector(self.base.camera,
                                                      Vec3.forward())
            vecY.setZ(0.0)
            vecY.normalize()
            offsetWorld = (vecX * self.offset.getX()) + (vecY *
                                                         self.offset.getY())

            self.base.camera.setPos(self.position + offsetWorld)
            self.base.camera.lookAt(self.target + offsetWorld)

        return task.cont
    def update(self, task=None):
        """
        Updates position of sounds in the 3D audio system. Will be called automatically
        in a task.
        """
        # Update the positions of all sounds based on the objects
        # to which they are attached

        # The audio manager is not active so do nothing
        if hasattr(self.audio_manager, "getActive"):
            if self.audio_manager.getActive() == 0:
                return Task.cont

        for known_object, sounds in list(self.sound_dict.items()):
            node_path = known_object.getNodePath()
            if not node_path:
                # The node has been deleted.
                del self.sound_dict[known_object]
                continue

            pos = node_path.getPos(self.root)

            for sound in sounds:
                vel = self.getSoundVelocity(sound)
                sound.set3dAttributes(pos[0], pos[1], pos[2], vel[0], vel[1],
                                      vel[2])

        # Update the position of the listener based on the object
        # to which it is attached
        if self.listener_target:
            pos = self.listener_target.getPos(self.root)
            forward = self.root.getRelativeVector(self.listener_target,
                                                  Vec3.forward())
            up = self.root.getRelativeVector(self.listener_target, Vec3.up())
            vel = self.getListenerVelocity()
            self.audio_manager.audio3dSetListenerAttributes(
                pos[0], pos[1], pos[2], vel[0], vel[1], vel[2], forward[0],
                forward[1], forward[2], up[0], up[1], up[2])
        else:
            self.audio_manager.audio3dSetListenerAttributes(
                0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1)
        return Task.cont
Exemple #24
0
    def task_mouse_move(self, task):  # pylint: disable=unused-argument
        if self.mouse1_down:
            mw = self.mouseWatcherNode
            speed = 5000
            if mw.hasMouse():

                if mw.is_button_down('shift'):
                    speed = 1500
                else:
                    speed = 5000

                pos = numpy.array(self.camera.getPos())
                dir_ = self.render.getRelativeVector(self.camera,
                                                     Vec3.forward())

                self.mouse_x = mw.getMouseX()
                self.mouse_y = mw.getMouseY()

                mouse_dx = self.mouse_x_old - self.mouse_x
                mouse_dy = self.mouse_y_old - self.mouse_y

                dx = numpy.array([dir_[1], -dir_[0], 0]) * mouse_dx
                dpos = dx * speed
                pos += dpos
                pos = self.up_down(pos, mouse_dy * speed)

                self.mouse_x_old = self.mouse_x
                self.mouse_y_old = self.mouse_y

                pos = self.correct_camera_distance(pos)

                self.camera.setPos(*pos)
                self.camera.setR(0)
                box_center = self.box.center
                if self.box.dimensions < 3:
                    box_center = self._project3d(box_center)
                self.camera.lookAt(Vec3(*box_center[:3]))

        return Task.cont
Exemple #25
0
    def update(self, task=None):
        """
        Updates position of sounds in the 3D audio system. Will be called automatically
        in a task.
        """
        # Update the positions of all sounds based on the objects
        # to which they are attached

        # The audio manager is not active so do nothing
        if hasattr(self.audio_manager, "getActive"):
            if self.audio_manager.getActive() == 0:
                return Task.cont

        for known_object in self.sound_dict.keys():
            tracked_sound = 0
            while tracked_sound < len(self.sound_dict[known_object]):
                sound = self.sound_dict[known_object][tracked_sound]
                pos = known_object.getPos(self.root)
                vel = self.getSoundVelocity(sound)
                sound.set3dAttributes(pos[0], pos[1], pos[2], vel[0], vel[1],
                                      vel[2])
                tracked_sound += 1

        # Update the position of the listener based on the object
        # to which it is attached
        if self.listener_target:
            pos = self.listener_target.getPos(self.root)
            forward = self.root.getRelativeVector(self.listener_target,
                                                  Vec3.forward())
            up = self.root.getRelativeVector(self.listener_target, Vec3.up())
            vel = self.getListenerVelocity()
            self.audio_manager.audio3dSetListenerAttributes(
                pos[0], pos[1], pos[2], vel[0], vel[1], vel[2], forward[0],
                forward[1], forward[2], up[0], up[1], up[2])
        else:
            self.audio_manager.audio3dSetListenerAttributes(
                0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1)
        return Task.cont
Exemple #26
0
    def update(self, task=None):
        """
        Updates position of sounds in the 3D audio system. Will be called automatically
        in a task.
        """
        # Update the positions of all sounds based on the objects
        # to which they are attached

        # The audio manager is not active so do nothing
        if hasattr(self.audio_manager, "getActive"):
            if self.audio_manager.getActive()==0:
                return Task.cont

        for known_object, sounds in list(self.sound_dict.items()):
            node_path = known_object.getNodePath()
            if not node_path:
                # The node has been deleted.
                del self.sound_dict[known_object]
                continue

            pos = node_path.getPos(self.root)

            for sound in sounds:
                vel = self.getSoundVelocity(sound)
                sound.set3dAttributes(pos[0], pos[1], pos[2], vel[0], vel[1], vel[2])

        # Update the position of the listener based on the object
        # to which it is attached
        if self.listener_target:
            pos = self.listener_target.getPos(self.root)
            forward = self.root.getRelativeVector(self.listener_target, Vec3.forward())
            up = self.root.getRelativeVector(self.listener_target, Vec3.up())
            vel = self.getListenerVelocity()
            self.audio_manager.audio3dSetListenerAttributes(pos[0], pos[1], pos[2], vel[0], vel[1], vel[2], forward[0], forward[1], forward[2], up[0], up[1], up[2])
        else:
            self.audio_manager.audio3dSetListenerAttributes(0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1)
        return Task.cont
Exemple #27
0
def processModel(path):
    scene = loadModel(path)
    if scene.isEmpty():
        print("Error converting `{0}`!".format(path))
        return

    fPath = Filename.fromOsSpecific(path)
    outputPath = Filename.toOsSpecific(
        Filename("bam2smd/" + fPath.getDirname() + "/" +
                 fPath.getBasenameWoExtension() + "/"))
    if not os.path.exists(outputPath):
        os.makedirs(outputPath)

    isCharacter = not scene.find("**/+Character").isEmpty()
    isAnimation = not scene.find("**/+AnimBundleNode").isEmpty()

    if not isAnimation:
        if isCharacter:
            nodes = Skeleton(scene.findAllMatches("**/+Character"))
        else:
            nodes = Skeleton(None)

        names = {}

        for geomNp in scene.findAllMatches("**/+GeomNode"):
            smd = "version 1\n"

            smd += str(nodes)

            smd += "skeleton\n"
            smd += "time 0\n"
            if isCharacter:
                boneIds = sorted(nodes.bones.keys())
                for iBone in range(len(boneIds)):
                    boneId = boneIds[iBone]
                    bone = nodes.bones[boneId]
                    if isinstance(bone, CharacterJoint):
                        boneTform = bone.getTransformState()
                        pos = boneTform.getPos()
                        boneMat = boneTform.getMat().getUpper3()
                        #boneMat.transposeInPlace()
                        rot = mat3NormalizedToEulO(boneMat)
                    else:
                        pos = Vec3()
                        rot = Vec3()
                    smd += boneFrameString(boneId, pos, rot)
            else:
                smd += "0  0 0 0  0 0 0\n"
            smd += "end\n"

            smd += "triangles\n"
            for geom in geomNp.node().getGeoms():
                geom = geom.decompose()
                vdata = geom.getVertexData()
                blendTable = vdata.getTransformBlendTable()
                for prim in geom.getPrimitives():
                    numTris = prim.getNumPrimitives()
                    for nTri in range(numTris):
                        start = prim.getPrimitiveStart(nTri)
                        end = prim.getPrimitiveEnd(nTri)

                        smd += "no_material\n"

                        for primVert in range(start, end):
                            vertIdx = prim.getVertex(primVert)

                            reader = GeomVertexReader(vdata)

                            reader.setColumn(InternalName.getVertex())
                            reader.setRow(vertIdx)
                            pos = reader.getData3f()

                            uv = Vec2(0, 0)
                            if vdata.hasColumn(InternalName.getTexcoord()):
                                reader.setColumn(InternalName.getTexcoord())
                                reader.setRow(vertIdx)
                                uv = reader.getData2f()

                            norm = Vec3.forward()
                            if vdata.hasColumn(InternalName.getNormal()):
                                reader.setColumn(InternalName.getNormal())
                                reader.setRow(vertIdx)
                                norm = reader.getData3f()

                            smd += "0  {0:.6f} {1:.6f} {2:.6f}  {3:.6f} {4:.6f} {5:.6f}  {6:.6f} {7:.6f}  ".format(
                                pos[0], pos[1], pos[2], norm[0], norm[1],
                                norm[2], uv[0], uv[1])
                            if (isCharacter and blendTable
                                    and vdata.getNumArrays() > 1
                                    and vdata.getArray(1).hasColumn(
                                        InternalName.getTransformBlend())):
                                reader.setColumn(
                                    1,
                                    vdata.getArray(
                                        1).getArrayFormat().getColumn(
                                            InternalName.getTransformBlend()))
                                reader.setRow(vertIdx)
                                nBlend = reader.getData1i()
                                blend = blendTable.getBlend(nBlend)
                                numTransforms = blend.getNumTransforms()
                                smd += "{0} ".format(numTransforms)
                                for nTransform in range(numTransforms):
                                    transform = blend.getTransform(nTransform)
                                    if isinstance(transform,
                                                  JointVertexTransform):
                                        boneId = nodes.getBoneId(
                                            transform.getJoint())
                                        smd += "{0} {1:.6f} ".format(
                                            boneId,
                                            blend.getWeight(nTransform))
                            else:
                                smd += "1 0 1.0"
                            smd += "\n"
            smd += "end\n"

            smdFile = geomNp.getName()
            if len(smdFile) == 0:
                smdFile = getUnknownName()
            elif names.get(smdFile, 0) > 0:
                smdFile = smdFile + "_{0}".format(names[smdFile])
                names[smdFile] += 1
            else:
                names[smdFile] = 1
            smdFile += ".smd"

            outFile = open(outputPath + "\\" + smdFile, "w")
            outFile.write(smd)
            outFile.flush()
            outFile.close()
    else:
        bundles = scene.findAllMatches("**/+AnimBundleNode")
        bundle = bundles[0].node().getBundle()
        nodes = Skeleton(bundles)

        smd = "version 1\n"

        smd += str(nodes)

        smd += "skeleton\n"
        numFrames = bundle.getNumFrames()
        boneIds = sorted(nodes.bones.keys())
        for iFrame in range(numFrames):
            smd += "time {0}\n".format(iFrame)
            for iBone in range(len(boneIds)):
                bone = nodes.getBone(boneIds[iBone])
                if isinstance(bone, AnimChannelACMatrixSwitchType):
                    boneFrameMat = Mat4()
                    bone.getValueNoScaleShear(iFrame, boneFrameMat)
                    boneFrameTransform = TransformState.makeMat(boneFrameMat)
                    pos = boneFrameTransform.getPos()
                    rotMat = boneFrameMat.getUpper3()
                    #rotMat.transposeInPlace()
                    rot = mat3NormalizedToEulO(rotMat)
                    smd += boneFrameString(boneIds[iBone], pos, rot)

        smd += "end\n"

        smdFile = fPath.getBasenameWoExtension() + ".smd"
        outFile = open(outputPath + "\\" + smdFile, "w")
        outFile.write(smd)
        outFile.flush()
        outFile.close()
 def enterNormal(self):
     self.notify.debug('enterNormal')
     self.setAnimState('Catching', 1.0)
     if self.isLocal:
         self.activity.orthoWalk.start()
     self.toon.lerpLookAt(Vec3.forward() + Vec3.up(), time=0.2, blink=0)
Exemple #29
0
    def __updateParticleParent(self, task=None):
        time = globalClock.getFrameTime()

        streamPos = self.waterStreamParent.getPos(render)
        distance = self.sprayParticleDist

        if self.isLocal():
            if base.localAvatar.backpack.getSupply(self.id) <= 0:
                base.localAvatar.b_gagThrow(self.id)
                return task.done

            camQuat = camera.getQuat(render)
            pFrom = camera.getPos(render)
            push = (streamPos - pFrom).length()
            pFrom += camQuat.xform(Vec3.forward()) * push
            pTo = pFrom + camQuat.xform(
                Vec3.forward()) * (self.sprayParticleDist +
                                   (pFrom - streamPos).length())
            hitPos = Point3(pTo)
            result = base.physicsWorld.rayTestClosest(pFrom, pTo,
                                                      CIGlobals.WorldGroup)
            if result.hasHit():
                node = result.getNode()
                hitPos = result.getHitPos()
                distance = (hitPos - streamPos).length()
                if time - self.lastDmgTime >= self.dmgIval:
                    self._handleSprayCollision(NodePath(node), hitPos,
                                               distance)
                    self.lastDmgTime = time

            if time - self.lastSprayTime >= self.dmgIval:
                self.getFPSCam().addViewPunch(
                    Vec3(random.uniform(-0.6, 0.6), random.uniform(0.25, 1.0),
                         0.0))
                base.localAvatar.sendUpdate('usedGag', [self.id])
                self.lastSprayTime = time

        else:
            pFrom = self.avatar.getPos(render) + self.avatar.getEyePoint() + (
                1, 0, 0)
            quat = Quat()
            quat.setHpr(
                self.avatar.getHpr(render) + (0, self.avatar.lookPitch, 0))
            pTo = pFrom + quat.xform(
                Vec3.forward()) * (self.sprayParticleDist +
                                   (pFrom - streamPos).length())
            hitPos = Point3(pTo)
            hit = PhysicsUtils.rayTestClosestNotMe(
                self.avatar, pFrom, pTo,
                CIGlobals.WorldGroup | CIGlobals.LocalAvGroup)
            if hit is not None:
                hitPos = hit.getHitPos()
                distance = (hitPos - streamPos).length()

        self.waterStreamParent.lookAt(render, hitPos)

        if self.sprayParticle:
            system = self.sprayParticle.getParticlesNamed('particles-1')
            # Make the particles die off at the hit point.
            lifespan = min(
                1, distance / self.sprayParticleDist) * self.sprayParticleLife
            system.factory.setLifespanBase(lifespan)

        if task:
            return task.cont
 def exitNormal(self):
     self.setAnimState('off', 1.0)
     if self.isLocal:
         self.activity.orthoWalk.stop()
     self.toon.lerpLookAt(Vec3.forward(), time=0.2, blink=0)
Exemple #31
0
    def handleAvatarControls(self, task):
        """
        Check on the arrow keys and update the avatar.
        """
        # get the button states:
        run = inputState.isSet("run")
        forward = inputState.isSet("forward")
        reverse = inputState.isSet("reverse")
        turnLeft = inputState.isSet("turnLeft")
        turnRight = inputState.isSet("turnRight")
        slideLeft = inputState.isSet("slideLeft")
        slideRight = inputState.isSet("slideRight")
        jump = inputState.isSet("jump")

        avatarControlForwardSpeed = 0
        avatarControlReverseSpeed = 0
        avatarControlSLeftSpeed = 0
        avatarControlSRightSpeed = 0

        if forward:
            if not self.hasSetForwardInitTime:
                self.forwardInitTime = globalClock.getFrameTime()
                self.hasSetForwardInitTime = True
                self.isAtZeroForward = False
                self.hasSetForwardStopTime = False
            timeSinceForwardSet = globalClock.getFrameTime() - self.forwardInitTime
            if timeSinceForwardSet == 0:
                avatarControlForwardSpeed = 0.0
            else:
                avatarControlForwardSpeed = min((timeSinceForwardSet / self.avatarControlForwardSpeed) * 750,
                                            self.avatarControlForwardSpeed)
        else:
            if self.hasSetForwardInitTime:
                self.hasSetForwardInitTime = False
            if not self.hasSetForwardStopTime:
                self.forwardStopTime = globalClock.getFrameTime()
                self.hasSetForwardStopTime = True
            timeSinceForwardStop = globalClock.getFrameTime() - self.forwardStopTime
            if timeSinceForwardStop == 0:
                avatarControlForwardSpeed = 16.0
            elif not self.isAtZeroForward:
                avatarControlForwardSpeed = self.avatarControlForwardSpeed - (timeSinceForwardStop * 50)
                if avatarControlForwardSpeed <= 0.5:
                    avatarControlForwardSpeed = 0.0
                    self.isAtZeroForward = True
                    self.hasSetForwardStopTime = False

        if reverse:
            if not self.hasSetReverseInitTime:
                self.reverseInitTime = globalClock.getFrameTime()
                self.hasSetReverseInitTime = True
                self.isAtZeroReverse = False
                self.hasSetReverseStopTime = False
            timeSinceReverseSet = globalClock.getFrameTime() - self.reverseInitTime
            if timeSinceReverseSet == 0:
                avatarControlReverseSpeed = 0.0
            else:
                avatarControlReverseSpeed = min((timeSinceReverseSet / self.avatarControlReverseSpeed) * 400,
                                            self.avatarControlReverseSpeed)
        else:
            if self.hasSetReverseInitTime:
                self.hasSetReverseInitTime = False
            if not self.hasSetReverseStopTime:
                self.reverseStopTime = globalClock.getFrameTime()
                self.hasSetReverseStopTime = True
            timeSinceReverseStop = globalClock.getFrameTime() - self.reverseStopTime
            if timeSinceReverseStop == 0:
                avatarControlReverseSpeed = 16.0
            elif not self.isAtZeroReverse:
                avatarControlReverseSpeed = self.avatarControlReverseSpeed - (timeSinceReverseStop * 20)
                if avatarControlReverseSpeed <= 0.5:
                    avatarControlReverseSpeed = 0.0
                    self.isAtZeroReverse = True
                    self.hasSetReverseStopTime = False

        if slideLeft:
            if not self.hasSetSLeftInitTime:
                self.sLeftInitTime = globalClock.getFrameTime()
                self.hasSetSLeftInitTime = True
                self.isAtZeroSLeft = False
                self.hasSetSLeftStopTime = False
            timeSinceSLeftSet = globalClock.getFrameTime() - self.sLeftInitTime
            if timeSinceSLeftSet == 0:
                avatarControlSLeftSpeed = 0.0
            else:
                avatarControlSLeftSpeed = min((timeSinceSLeftSet / self.avatarControlForwardSpeed) * 750,
                                            self.avatarControlForwardSpeed)
        else:
            if self.hasSetSLeftInitTime:
                self.hasSetSLeftInitTime = False
            if not self.hasSetSLeftStopTime:
                self.sLeftStopTime = globalClock.getFrameTime()
                self.hasSetSLeftStopTime = True
            timeSinceSLeftStop = globalClock.getFrameTime() - self.sLeftStopTime
            if timeSinceSLeftStop == 0:
                avatarControlSLeftSpeed = 16.0
            elif not self.isAtZeroSLeft:
                avatarControlSLeftSpeed = self.avatarControlForwardSpeed - (timeSinceSLeftStop * 50)
                if avatarControlSLeftSpeed <= 0.5:
                    avatarControlSLeftSpeed = 0.0
                    self.isAtZeroSLeft = True
                    self.hasSetSLeftStopTime = False

        if slideRight:
            if not self.hasSetSRightInitTime:
                self.sRightInitTime = globalClock.getFrameTime()
                self.hasSetSRightInitTime = True
                self.isAtZeroSRight = False
                self.hasSetSRightStopTime = False
            timeSinceSRightSet = globalClock.getFrameTime() - self.sRightInitTime
            if timeSinceSRightSet == 0:
                avatarControlSRightSpeed = 0.0
            else:
                avatarControlSRightSpeed = min((timeSinceSRightSet / self.avatarControlForwardSpeed) * 750,
                                            self.avatarControlForwardSpeed)
        else:
            if self.hasSetSRightInitTime:
                self.hasSetSRightInitTime = False
            if not self.hasSetSRightStopTime:
                self.sRightStopTime = globalClock.getFrameTime()
                self.hasSetSRightStopTime = True
            timeSinceSRightStop = globalClock.getFrameTime() - self.sRightStopTime
            if timeSinceSRightStop == 0:
                avatarControlSRightSpeed = 16.0
            elif not self.isAtZeroSRight:
                avatarControlSRightSpeed = self.avatarControlForwardSpeed - (timeSinceSRightStop * 50)
                if avatarControlSRightSpeed <= 0.5:
                    avatarControlSRightSpeed = 0.0
                    self.isAtZeroSRight = True
                    self.hasSetSRightStopTime = False

        # Check for Auto-Run
        #if 'localAvatar' in __builtins__:
        #    if base.localAvatar and base.localAvatar.getAutoRun():
        #        forward = 1
        #        reverse = 0

        # Determine what the speeds are based on the buttons:
        self.speed=(avatarControlForwardSpeed or
                    -avatarControlReverseSpeed)
        # Slide speed is a scaled down version of forward speed
        # Note: you can multiply a factor in here if you want slide to
        # be slower than normal walk/run. Let's try full speed.
        #self.slideSpeed=(slideLeft and -self.avatarControlForwardSpeed*0.75 or
        #                 slideRight and self.avatarControlForwardSpeed*0.75)
        self.slideSpeed=(-avatarControlSLeftSpeed or
                        avatarControlSRightSpeed)
        self.rotationSpeed=not (slideLeft or slideRight) and (
                (turnLeft and self.avatarControlRotateSpeed) or
                (turnRight and -self.avatarControlRotateSpeed))

        if self.speed and self.slideSpeed:
            self.speed *= GravityWalker.DiagonalFactor
            self.slideSpeed *= GravityWalker.DiagonalFactor

        debugRunning = inputState.isSet("debugRunning")
        if(debugRunning):
            self.speed*=base.debugRunningMultiplier
            self.slideSpeed*=base.debugRunningMultiplier
            self.rotationSpeed*=1.25

        if self.needToDeltaPos:
            self.setPriorParentVector()
            self.needToDeltaPos = 0
        if self.wantDebugIndicator:
            self.displayDebugInfo()
        if self.lifter.isOnGround():
            if self.isAirborne:
                self.isAirborne = 0
                assert self.debugPrint("isAirborne 0 due to isOnGround() true")
                impact = self.lifter.getImpactVelocity()
                if impact < -30.0:
                    messenger.send("jumpHardLand")
                    self.startJumpDelay(0.3)
                else:
                    messenger.send("jumpLand")
                    if impact < -5.0:
                        self.startJumpDelay(0.2)
                    # else, ignore the little potholes.
            assert self.isAirborne == 0
            self.priorParent = Vec3.zero()
            if jump and self.mayJump:
                # The jump button is down and we're close
                # enough to the ground to jump.
                self.lifter.addVelocity(self.avatarControlJumpForce)
                messenger.send("jumpStart")
                self.isAirborne = 1
                assert self.debugPrint("isAirborne 1 due to jump")
        else:
            if self.isAirborne == 0:
                assert self.debugPrint("isAirborne 1 due to isOnGround() false")
            self.isAirborne = 1

        self.__oldPosDelta = self.avatarNodePath.getPosDelta(render)
        # How far did we move based on the amount of time elapsed?
        self.__oldDt = ClockObject.getGlobalClock().getDt()
        dt=self.__oldDt

        # Check to see if we're moving at all:
        self.moving = self.speed or self.slideSpeed or self.rotationSpeed or (self.priorParent!=Vec3.zero())
        if self.moving:
            distance = dt * self.speed
            slideDistance = dt * self.slideSpeed
            rotation = dt * self.rotationSpeed

            # Take a step in the direction of our previous heading.
            if distance or slideDistance or self.priorParent != Vec3.zero():
                # rotMat is the rotation matrix corresponding to
                # our previous heading.
                rotMat=Mat3.rotateMatNormaxis(self.avatarNodePath.getH(), Vec3.up())
                if self.isAirborne:
                    forward = Vec3.forward()
                else:
                    contact = self.lifter.getContactNormal()
                    forward = contact.cross(Vec3.right())
                    # Consider commenting out this normalize.  If you do so
                    # then going up and down slops is a touch slower and
                    # steeper terrain can cut the movement in half.  Without
                    # the normalize the movement is slowed by the cosine of
                    # the slope (i.e. it is multiplied by the sign as a
                    # side effect of the cross product above).
                    forward.normalize()
                self.vel=Vec3(forward * distance)
                if slideDistance:
                    if self.isAirborne:
                        right = Vec3.right()
                    else:
                        right = forward.cross(contact)
                        # See note above for forward.normalize()
                        right.normalize()
                    self.vel=Vec3(self.vel + (right * slideDistance))
                self.vel=Vec3(rotMat.xform(self.vel))
                step=self.vel + (self.priorParent * dt)
                self.avatarNodePath.setFluidPos(Point3(
                        self.avatarNodePath.getPos()+step))
            self.avatarNodePath.setH(self.avatarNodePath.getH()+rotation)
        else:
            self.vel.set(0.0, 0.0, 0.0)
        if self.moving or jump:
            messenger.send("avatarMoving")
        return Task.cont
Exemple #32
0
    def camTask(self, task):
        # query the mouse
        mouse_dx = 0
        mouse_dy = 0

        # if we have a mouse and the right button is depressed
        if base.mouseWatcherNode.hasMouse():
            if self.keyMap["mouse3"] != 0:
                self.mouse_accum.update()
            else:
                self.mouse_accum.reset()

        mouse_dx = self.mouse_accum.dx
        mouse_dy = self.mouse_accum.dy

        self.rXSpeed = fabs(self.mouse_accum.dx) * (self.cam_speed + 1) * max(5 * 1000 / self.xres, 3)
        self.rYSpeed = fabs(self.mouse_accum.dy) * (self.cam_speed + 1) * max(3 * 1000 / self.yres, 1)

        if self.keyMap["cam-left"] != 0 or mouse_dx < 0:
            if self.rSpeed < 160:
                self.rSpeed += 80 * globalClock.getDt()

            if mouse_dx != 0:
                self.camHeading += self.rXSpeed * globalClock.getDt()
            else:
                self.camHeading += self.rSpeed * globalClock.getDt()

            if self.camHeading > 360.0:
                self.camHeading = self.camHeading - 360.0
        elif self.keyMap["cam-right"] != 0 or mouse_dx > 0:
            if self.rSpeed < 160:
                self.rSpeed += 80 * globalClock.getDt()

            if mouse_dx != 0:
                self.camHeading -= self.rXSpeed * globalClock.getDt()
            else:
                self.camHeading -= self.rSpeed * globalClock.getDt()

            if self.camHeading < 0.0:
                self.camHeading = self.camHeading + 360.0
        else:
            self.rSpeed = 80

        if mouse_dy > 0:
            self.camPitch += self.rYSpeed * globalClock.getDt()
        elif mouse_dy < 0:
            self.camPitch -= self.rYSpeed * globalClock.getDt()

        # set camera heading and pitch
        base.camera.setHpr(self.camHeading, self.camPitch, 0)

        # viewer position (camera) movement control
        v = render.getRelativeVector(base.camera, Vec3.forward())
        if not self.flyMode:
            v.setZ(0.0)

        move_speed = self.cam_speeds[self.cam_speed]
        if self.keyMap["forward"] == 1:
            self.campos += v * move_speed * globalClock.getDt()
        if self.keyMap["backward"] == 1:
            self.campos -= v * move_speed * globalClock.getDt()

        # actually move the camera
        lastPos = base.camera.getPos()
        base.camera.setPos(self.campos)
        # self.plnp.setPos(self.campos)      # move the point light with the viewer position

        # WALKMODE: simple collision detection
        # we simply check a ray from slightly below the "eye point" straight down
        # for geometry collisions and if there are any we detect the point of collision
        # and adjust the camera's Z accordingly
        if self.flyMode == 0:
            # move the camera to where it would be if it made the move
            # the colliderNode moves with it
            # base.camera.setPos(self.campos)
            # check for collissons
            self.cTrav.traverse(render)
            entries = []
            for i in range(self.camGroundHandler.getNumEntries()):
                entry = self.camGroundHandler.getEntry(i)
                entries.append(entry)
                # print 'collision'
            entries.sort(lambda x, y: cmp(y.getSurfacePoint(render).getZ(), x.getSurfacePoint(render).getZ()))

            if len(entries) > 0:  # and (entries[0].getIntoNode().getName() == "terrain"):
                # print len(entries)
                self.campos.setZ(entries[0].getSurfacePoint(render).getZ() + self.eyeHeight)
            else:
                self.campos = lastPos
                base.camera.setPos(self.campos)

            # if (base.camera.getZ() < self.player.getZ() + 2.0):
            #    base.camera.setZ(self.player.getZ() + 2.0)

        # update loc and hpr display
        pos = base.camera.getPos()
        hpr = base.camera.getHpr()
        self.inst2.setText("Loc: %.2f, %.2f, %.2f" % (pos.getX(), pos.getY(), pos.getZ()))
        self.inst3.setText("Hdg: %.2f, %.2f, %.2f" % (hpr.getX(), hpr.getY(), hpr.getZ()))
        return task.cont
 def exitNormal(self):
     self.setAnimState('off', 1.0)
     if self.isLocal:
         self.activity.orthoWalk.stop()
     self.toon.lerpLookAt(Vec3.forward(), time=0.2, blink=0)
 def enterNormal(self):
     self.notify.debug('enterNormal')
     self.setAnimState('Catching', 1.0)
     if self.isLocal:
         self.activity.orthoWalk.start()
     self.toon.lerpLookAt(Vec3.forward() + Vec3.up(), time=0.2, blink=0)
Exemple #35
0
    def camTask(self, task):
        if globals.hasClickedSpawn:
           base.camera.setPos(globals.selectedSpawnPoint3D)
           self.campos = globals.selectedSpawnPoint3D
           globals.hasClickedSpawn = False
        elif globals.hasClickedGrid:
            base.camera.setPos(globals.selectedGridPoint3D)
            self.campos = globals.selectedGridPoint3D
            globals.hasClickedGrid = False
        else:
            # query the mouse
            mouse_dx = 0
            mouse_dy = 0


            # if we have a mouse and the right button is depressed
            if base.mouseWatcherNode.hasMouse():
                if self.keyMap["mouse3"] != 0:
                    self.mouse_accum.update()
                else:
                    self.mouse_accum.reset()

            mouse_dx = self.mouse_accum.dx
            mouse_dy = self.mouse_accum.dy

            self.rXSpeed = fabs(self.mouse_accum.dx) * (self.cam_speed+1) * max(5 * 1000/self.xres,3)
            self.rYSpeed = fabs(self.mouse_accum.dy) * (self.cam_speed+1) * max(3 * 1000/self.yres,1)
            
            if (self.keyMap["cam-left"]!=0 or mouse_dx < 0):
                if self.rSpeed < 160:
                    self.rSpeed += 80 * globalClock.getDt()

                if mouse_dx != 0:
                    self.camHeading += self.rXSpeed * globalClock.getDt()
                else:
                    self.camHeading += self.rSpeed * globalClock.getDt()

                if self.camHeading > 360.0:
                    self.camHeading = self.camHeading - 360.0
            elif (self.keyMap["cam-right"]!=0 or mouse_dx > 0):
                if self.rSpeed < 160:
                    self.rSpeed += 80 * globalClock.getDt()

                if mouse_dx != 0:
                    self.camHeading -= self.rXSpeed * globalClock.getDt()
                else:
                    self.camHeading -= self.rSpeed * globalClock.getDt()

                if self.camHeading < 0.0:
                    self.camHeading = self.camHeading + 360.0
            else:
                self.rSpeed = 80

            if mouse_dy > 0:
                self.camPitch += self.rYSpeed * globalClock.getDt()
            elif mouse_dy < 0:
                self.camPitch -= self.rYSpeed * globalClock.getDt()
            
            # set camera heading and pitch
            base.camera.setHpr(self.camHeading, self.camPitch, 0)

            # viewer position (camera) movement control
            v = render.getRelativeVector(base.camera, Vec3.forward())
            if not self.flyMode:
                v.setZ(0.0)
        
            move_speed = self.cam_speeds[self.cam_speed]
            if self.keyMap["forward"] == 1:
                self.campos += v * move_speed * globalClock.getDt()
            if self.keyMap["backward"] == 1:
                self.campos -= v * move_speed * globalClock.getDt()            

            # actually move the camera
            lastPos = base.camera.getPos()
            base.camera.setPos(self.campos)
            # self.plnp.setPos(self.campos)      # move the point light with the viewer position

            # WALKMODE: simple collision detection
            # we simply check a ray from slightly below the "eye point" straight down
            # for geometry collisions and if there are any we detect the point of collision
            # and adjust the camera's Z accordingly
            if self.flyMode == 0:   
                # move the camera to where it would be if it made the move 
                # the colliderNode moves with it
                # base.camera.setPos(self.campos)
                # check for collissons
                self.cTrav.traverse(render)
                entries = []
                for i in range(self.camGroundHandler.getNumEntries()):
                    entry = self.camGroundHandler.getEntry(i)
                    entries.append(entry)
                    # print 'collision'
                entries.sort(lambda x,y: cmp(y.getSurfacePoint(render).getZ(),
                                             x.getSurfacePoint(render).getZ()))
                                     
                if (len(entries) > 0): # and (entries[0].getIntoNode().getName() == "terrain"):
                    # print len(entries)
                    self.campos.setZ(entries[0].getSurfacePoint(render).getZ()+self.eyeHeight)
                else:
                    self.campos = lastPos
                    base.camera.setPos(self.campos)
        
                #if (base.camera.getZ() < self.player.getZ() + 2.0):
                #    base.camera.setZ(self.player.getZ() + 2.0)


            # update loc and hpr display
            pos = base.camera.getPos()
            hpr = base.camera.getHpr()
            self.inst2.setText('Loc: %.2f, %.2f, %.2f' % (pos.getX(), pos.getY(), pos.getZ()))
            self.inst3.setText('Hdg: %.2f, %.2f, %.2f' % (hpr.getX(), hpr.getY(), hpr.getZ()))
        return task.cont
    def release(self):
        Gag.release(self)
        base.audio3d.attachSoundToObject(self.woosh, self.gag)
        base.playSfx(self.woosh, node=self.gag)

        if self.isLocal() and base.localAvatar.battleControls:
            if base.localAvatar.isFirstPerson():
                # Add a small kick to the camera to give more feedback
                self.getFPSCam().addViewPunch(
                    Vec3(random.uniform(.5, 1), random.uniform(-.5, -1), 0))

                startPos = camera.getPos(render) + camera.getQuat(
                    render).xform(Vec3.right())
                push = 0.0
            else:
                startPos = self.handJoint.getPos(render)
                push = (startPos - camera.getPos(render)).length()
            hitPos = PhysicsUtils.getHitPosFromCamera()
        else:
            startPos = self.handJoint.getPos(render)
            quat = Quat()
            quat.setHpr(
                self.avatar.getHpr(render) + (0, self.avatar.lookPitch, 0))
            hitPos = quat.xform(Vec3.forward() * self.power)
            hit = PhysicsUtils.rayTestClosestNotMe(
                self.avatar, startPos, hitPos,
                CIGlobals.WorldGroup | CIGlobals.LocalAvGroup)
            if hit is not None:
                hitPos = hit.getHitPos()

        throwDir = (hitPos - startPos).normalized()
        endPos = startPos + (throwDir * self.power) - (0, 0, 90)

        entity = self.gag

        if not entity:
            entity = self.build()

        gagRoot = render.attachNewNode('gagRoot')
        gagRoot.setPos(startPos)

        entity.reparentTo(render)
        entity.setPos(0, 0, 0)
        entity.headsUp(throwDir)
        rot = entity.getHpr(render)
        entity.reparentTo(gagRoot)
        entity.setHpr(rot[0], -90, 0)
        self.gag = None

        if not self.handJoint:
            self.handJoint = self.avatar.find('**/def_joint_right_hold')

        track = FlightProjectileInterval(gagRoot,
                                         startPos=startPos,
                                         endPos=endPos,
                                         gravityMult=1.07,
                                         duration=2.5)
        event = self.avatar.uniqueName('throwIvalDone') + '-' + str(
            hash(entity))
        track.setDoneEvent(event)
        base.acceptOnce(event, self.__handlePieIvalDone, [entity])
        track.start()

        if self.isLocal():
            collider = self.buildCollisions(entity)
            self.entities.append([gagRoot, track, collider])
            base.localAvatar.sendUpdate('usedGag', [self.id])
        else:
            self.entities.append([gagRoot, track, NodePath()])
        self.reset()
Exemple #37
0
    def __updateTask(self, task):
        # TODO -- This function does a lot of math, I measured it to take .5 ms on my laptop
        #         That's a lot of time for something miniscule like sway and bob.

        dt = globalClock.getDt()
        time = globalClock.getFrameTime()

        if base.localAvatar.isFirstPerson():
            eyePoint = base.localAvatar.getEyePoint()
            if base.localAvatar.walkControls.crouching:
                eyePoint[2] = eyePoint[2] / 2.0
            eyePoint[2] = CIGlobals.lerpWithRatio(eyePoint[2],
                                                  self.lastEyeHeight, 0.4)
            self.lastEyeHeight = eyePoint[2]

        camRootAngles = Vec3(0)

        # Mouse look around
        mw = base.mouseWatcherNode
        if mw.hasMouse():
            md = base.win.getPointer(0)
            center = Point2(base.win.getXSize() / 2, base.win.getYSize() / 2)

            xDist = md.getX() - center.getX()
            yDist = md.getY() - center.getY()

            sens = self.__getMouseSensitivity()

            angular = -(xDist * sens) / dt
            base.localAvatar.walkControls.controller.setAngularMovement(
                angular)
            camRootAngles.setY(self.lastPitch - yDist * sens)

            if camRootAngles.getY() > FPSCamera.MaxP:
                camRootAngles.setY(FPSCamera.MaxP)
                yDist = 0
            elif camRootAngles.getY() < FPSCamera.MinP:
                yDist = 0
                camRootAngles.setY(FPSCamera.MinP)

            base.win.movePointer(0, int(center.getX()), int(center.getY()))

        if base.localAvatar.isFirstPerson():
            # Camera / viewmodel bobbing
            vmBob = Point3(0)
            vmAngles = Vec3(0)
            vmRaise = Point3(0)
            camBob = Point3(0)

            maxSpeed = base.localAvatar.walkControls.BattleRunSpeed * 16.0

            speed = base.localAvatar.walkControls.speeds.length() * 16.0
            speed = max(-maxSpeed, min(maxSpeed, speed))

            bobOffset = CIGlobals.remapVal(speed, 0, maxSpeed, 0.0, 1.0)

            self.bobTime += (time - self.lastBobTime) * bobOffset
            self.lastBobTime = time

            # Calculate the vertical bob
            cycle = self.bobTime - int(
                self.bobTime / self.BobCycleMax) * self.BobCycleMax
            cycle /= self.BobCycleMax
            if cycle < self.BobUp:
                cycle = math.pi * cycle / self.BobUp
            else:
                cycle = math.pi + math.pi * (cycle - self.BobUp) / (1.0 -
                                                                    self.BobUp)

            verticalBob = speed * 0.005
            verticalBob = verticalBob * 0.3 + verticalBob * 0.7 * math.sin(
                cycle)
            verticalBob = max(-7.0, min(4.0, verticalBob))
            verticalBob /= 16.0

            # Calculate the lateral bob
            cycle = self.bobTime - int(
                self.bobTime / self.BobCycleMax * 2) * self.BobCycleMax * 2
            cycle /= self.BobCycleMax * 2
            if cycle < self.BobUp:
                cycle = math.pi * cycle / self.BobUp
            else:
                cycle = math.pi + math.pi * (cycle - self.BobUp) / (1.0 -
                                                                    self.BobUp)

            lateralBob = speed * 0.005
            lateralBob = lateralBob * 0.3 + lateralBob * 0.7 * math.sin(cycle)
            lateralBob = max(-7.0, min(4.0, lateralBob))
            lateralBob /= 16.0

            # Apply bob, but scaled down a bit
            vmBob.set(lateralBob * 0.8, 0, verticalBob * 0.1)
            # Z bob a bit more
            vmBob[2] += verticalBob * 0.1
            # Bob the angles
            vmAngles[2] += verticalBob * 0.5
            vmAngles[1] -= verticalBob * 0.4
            vmAngles[0] -= lateralBob * 0.3

            # ================================================================
            # Viewmodel lag/sway

            angles = self.camRoot.getHpr(render)
            quat = Quat()
            quat.setHpr(angles)
            invQuat = Quat()
            invQuat.invertFrom(quat)

            maxVMLag = 1.5
            lagforward = quat.getForward()
            if dt != 0.0:
                lagdifference = lagforward - self.lastFacing
                lagspeed = 5.0
                lagdiff = lagdifference.length()
                if (lagdiff > maxVMLag) and (maxVMLag > 0.0):
                    lagscale = lagdiff / maxVMLag
                    lagspeed *= lagscale

                self.lastFacing = CIGlobals.extrude(self.lastFacing,
                                                    lagspeed * dt,
                                                    lagdifference)
                self.lastFacing.normalize()
                lfLocal = invQuat.xform(lagdifference)
                vmBob = CIGlobals.extrude(vmBob, 5.0 / 16.0, lfLocal * -1.0)

            pitch = angles[1]
            if pitch > 180:
                pitch -= 360
            elif pitch < -180:
                pitch += 360

            vmBob = CIGlobals.extrude(vmBob, pitch * (0.035 / 16),
                                      Vec3.forward())
            vmBob = CIGlobals.extrude(vmBob, pitch * (0.03 / 16), Vec3.right())
            vmBob = CIGlobals.extrude(vmBob, pitch * (0.02 / 16), Vec3.up())

            # ================================================================

            vmRaise.set(
                0, 0, 0
            )  #(0, abs(camRootAngles.getY()) * -0.002, camRootAngles.getY() * 0.002)
            camBob.set(0, 0, 0)

            # Apply bob, raise, and sway to the viewmodel.
            self.viewModel.setPos(vmBob + vmRaise + self.lastVMPos)
            self.vmRoot2.setHpr(vmAngles)
            self.camRoot.setPos(eyePoint + camBob)

        newPitch = camRootAngles.getY()

        if abs(newPitch - self.lastPitch) > self.PitchUpdateEpsilon:
            # Broadcast where our head is looking
            head = base.localAvatar.getPart("head")
            if head and not head.isEmpty():
                # Constrain the head pitch a little bit so it doesn't look like their head snapped
                headPitch = max(-47, newPitch)
                headPitch = min(75, headPitch)
                base.localAvatar.b_setLookPitch(headPitch)

        self.lastPitch = newPitch

        if base.localAvatar.isFirstPerson():
            # Apply punch angle
            self.decayPunchAngle()
            camRootAngles += self.punchAngle

        self.camRoot.setHpr(camRootAngles)

        return task.cont