Exemple #1
0
 def set_light_angle(self, angle):
     self.light_angle = angle
     self.light_quat.setFromAxisAngleRad(angle * pi / 180,
                                         LVector3.forward())
     self.light_dir = self.light_quat.xform(LVector3.up())
     cosA = self.light_dir.dot(LVector3.up())
     self.vector_to_star = self.light_dir
     if self.shadow_caster is not None:
         self.shadow_caster.set_direction(-self.light_dir)
     if self.directionalLight is not None:
         self.directionalLight.setDirection(-self.light_dir)
     if cosA >= 0:
         coef = sqrt(cosA)
         self.light_color = (1, coef, coef, 1)
         self.directionalLight.setColor(self.light_color)
         new_sky_color = self.skybox_color * cosA
         new_sky_color[3] = 1.0
         self.skybox.setColor(new_sky_color)
         if self.fog is not None:
             self.fog.fog_color = self.skybox_color * cosA
             self.fog.sun_color = self.sun_color * cosA
     else:
         self.light_color = (0, 0, 0, 1)
         self.directionalLight.setColor(self.light_color)
         self.skybox.setColor(self.light_color)
         if self.fog is not None:
             self.fog.fog_color = self.skybox_color * 0
             self.fog.sun_color = self.sun_color * 0
     self.terrain.update_shader()
 def set_perspective_lens(self, fov, near_plane, far_plane, pos, direction):
     transform_mat = Mat4.translate_mat(-pos)
     temp_lens = PerspectiveLens(fov, fov)
     temp_lens.set_film_offset(0, 0)
     temp_lens.set_near_far(near_plane, far_plane)
     temp_lens.set_view_vector(direction, LVector3.up())
     self.set_matrix_lens(transform_mat * temp_lens.get_projection_mat())
Exemple #3
0
    def start(self):
        #startPos = self.maze.find("**/start").getPos()
        #self.ballRoot.setPos(0.5, 0, 0)
        #self.ballV = LVector3(0, 0.5, 0)         # Initial velocity is 0
        #self.accelV = LVector3(0, 0, 0)        # Initial acceleration is 0

        self.ballVs = []
        self.accelVs = []
        for ballIndex in xrange(len(self.balls)):
            self.ballVs.append(LVector3(0, 0, 0))
            self.accelVs.append(LVector3(0, 0, 0))
            continue
        self.ballRoots[0].setPos(0.2, 1.05, -0.1)
        #self.ballVs[0] = LVector3(0, 0.0, 0)
        self.ballRoots[1].setPos(0.32, 1.2, -0.1)
        #self.ballRoots[2].setHpr(0, 0, 90)
        self.ballRoots[2].setPos(-0.4, 1.1, 0.4)
        axis = LVector3.up()
        prevRot = LRotationf(self.balls[2].getQuat())
        newRot = LRotationf(axis, 90)
        self.balls[2].setQuat(prevRot * newRot)

        # Create the movement task, but first make sure it is not already
        # running
        taskMgr.remove("rollTask")
        #taskMgr.remove("mouseTask")
        self.mainLoop = taskMgr.add(self.rollTask, "rollTask")
        #self.mainLoop = taskMgr.add(self.mouseTask, "mouseTask")

        return
Exemple #4
0
    def rollTask(self, task):
        dt = globalClock.getDt()

        # if dt is large, then there has been a # hiccup that could cause the ball to leave the field if this functions runs, so ignore the frame
        if dt > .2:
            return Task.cont

        # collision handler
        for i in range(self.cHandler.getNumEntries()):
            entry = self.cHandler.getEntry(i)
            name = entry.getIntoNode().getName()
            if name == "wall_collide":
                self.wallCollideHandler(entry)
            elif name == "ground_collide":
                self.groundCollideHandler(entry)

        # move the ball
        # update the velocity based on acceleration
            self.ballV += self.accelV * dt * ACCEL
        # prevent velocity from going above max velocity
        if self.ballV.lengthSquared() > MAX_SPEED_SQ:
            self.ballV.normalize()
            self.ballV *= MAX_SPEED
        # update the position based on the velocity
        self.ballRoot.setPos(self.ballRoot.getPos() + (self.ballV * dt))

        # rotate the ball
        prevRot = LRotationf(self.ball.getQuat())
        axis = LVector3.up().cross(self.ballV)
        newRot = LRotationf(axis, 45.5 * dt * self.ballV.length())
        self.ball.setQuat(prevRot * newRot)

        return Task.cont
Exemple #5
0
    def groundCollideHander(self, colEntry):
        newZ = colEntry.getSurfacePoint(render).getZ()
        self.ballRoot.setZ(newZ + 0.4)

        norm = colEntry.getSurfaceNormal(render)
        accelSide = norm.cross(LVector3.up())

        self.accelV = norm.cross(accelSide)
Exemple #6
0
 def update(self):
     radius = self.body.get_extend() / settings.scale
     self.shadow_caster.get_lens().set_film_size(radius * 2.1, radius * 2.1)
     self.shadow_caster.get_lens().setNear(
         -self.body.context.observer.infinity)
     self.shadow_caster.get_lens().setFar(
         self.body.context.observer.infinity)
     self.shadow_caster.get_lens().set_view_vector(
         LVector3(*-self.body.vector_to_star), LVector3.up())
Exemple #7
0
 def update(self):
     radius = self.body.get_extend() / settings.scale
     self.shadow_caster.get_lens().set_film_size(radius * 2.1, radius * 2.1)
     #The shadow frustum origin is at the light center which is one radius away from the object
     #So the near plane is 0 to coincide with the boundary of the object
     self.shadow_caster.get_lens().setNear(0)
     self.shadow_caster.get_lens().setFar(radius * 2)
     self.shadow_caster.get_lens().set_view_vector(
         LVector3(*-self.body.vector_to_star), LVector3.up())
    def set_perspective_lens(self, fov, near_plane, far_plane, pos, direction):
        transform_mat = Mat4.translate_mat(-pos)
        temp_lens = PerspectiveLens(fov, fov)
        temp_lens.set_film_offset(0, 0)
        temp_lens.set_near_far(near_plane, far_plane)
        temp_lens.set_view_vector(direction, LVector3.up())
        self.set_matrix_lens(transform_mat * temp_lens.get_projection_mat())

        hexahedron = temp_lens.make_bounds()
        center = (hexahedron.get_min() + hexahedron.get_max()) * 0.5
        self._bounds = BoundingSphere(pos + center, (hexahedron.get_max() - center).length())
Exemple #9
0
 def set_light_angle(self, angle):
     self.light_angle = angle
     self.light_quat.setFromAxisAngleRad(angle * pi / 180, LVector3.forward())
     self.light_dir = self.light_quat.xform(LVector3.up())
     cosA = self.light_dir.dot(LVector3.up())
     self.vector_to_star = self.light_dir
     if self.shadow_caster is not None:
         self.shadow_caster.set_direction(-self.light_dir)
     if self.directionalLight is not None:
         self.directionalLight.setDirection(-self.light_dir)
     if cosA >= 0:
         coef = sqrt(cosA)
         self.light_color = (1, coef, coef, 1)
         self.directionalLight.setColor(self.light_color)
         self.skybox.setColor(self.skybox_color * cosA)
     else:
         self.light_color = (1, 0, 0, 1)
         self.directionalLight.setColor(self.light_color)
         self.skybox.setColor(self.skybox_color * 0)
     self.update()
    def set_perspective_lens(self, fov, near_plane, far_plane, pos, direction):
        transform_mat = Mat4.translate_mat(-pos)
        temp_lens = PerspectiveLens(fov, fov)
        temp_lens.set_film_offset(0, 0)
        temp_lens.set_near_far(near_plane, far_plane)
        temp_lens.set_view_vector(direction, LVector3.up())
        self.set_matrix_lens(transform_mat * temp_lens.get_projection_mat())

        hexahedron = temp_lens.make_bounds()
        center = (hexahedron.get_min() + hexahedron.get_max()) * 0.5
        self._bounds = BoundingSphere(pos + center,
                                      (hexahedron.get_max() - center).length())
Exemple #11
0
 def set_light_angle(self, angle):
     self.light_angle = angle
     self.light_quat.setFromAxisAngleRad(angle * pi / 180,
                                         LVector3.forward())
     self.light_dir = self.light_quat.xform(-LVector3.up())
     cosA = self.light_dir.dot(-LVector3.up())
     if cosA >= 0:
         coef = sqrt(cosA)
         self.light_color = (1, coef, coef, 1)
         new_sky_color = self.skybox_color * cosA
         new_sky_color[3] = 1.0
         self.skybox.setColor(new_sky_color)
         if self.fog is not None:
             self.fog.fog_color = self.skybox_color * cosA
             self.fog.sun_color = self.sun_color * cosA
     else:
         self.light_color = (0, 0, 0, 1)
         self.skybox.setColor(self.light_color)
         if self.fog is not None:
             self.fog.fog_color = self.skybox_color * 0
             self.fog.sun_color = self.sun_color * 0
Exemple #12
0
    def groundCollideHandler(self, colEntry):
        # Set the ball to the appropriate Z value for it to be exactly on the
        # ground
        newZ = colEntry.getSurfacePoint(render).getZ()
        self.ballRoot.setZ(newZ + .4)

        # Find the acceleration direction. First the surface normal is crossed with
        # the up vector to get a vector perpendicular to the slope
        norm = colEntry.getSurfaceNormal(render)
        accelSide = norm.cross(LVector3.up())
        # Then that vector is crossed with the surface normal to get a vector that
        # points down the slope. By getting the acceleration in 3D like this rather
        # than in 2D, we reduce the amount of error per-frame, reducing jitter
        self.accelV = norm.cross(accelSide)
Exemple #13
0
    def rollTask(self, task):
        self.gesture_controler.track()
        dt = globalClock.getDt()

        if dt > 0.2:
            return Task.cont

        if self.gesture_controler.getPause():
            return Task.cont

        # if self.gesture_controler.getQuit():
        # print("Gesture: Quit. You will quit from the game.")
        # sys.exit()

        # if self.gesture_controler.getReset():
        # self.resetGame()
        # return Task.cont

        for i in range(self.cHandler.getNumEntries()):
            entry = self.cHandler.getEntry(i)
            name = entry.getIntoNode().getName()

            if name == "wall_collide":
                self.wallCollideHandler(entry)
            elif name == "ground_collide":
                self.groundCollideHander(entry)
            elif name == "loseTriggers":
                self.loseGame(entry)

        if self.gesture_controler.isMoving():
            cur_pos = self.gesture_controler.getPos()
            mpos = LPoint2f(cur_pos[0], cur_pos[1])
            # print(mpos)
            self.maze.setP(mpos.getY() * -10)
            self.maze.setR(mpos.getX() * 10)

        self.ballV += self.accelV * dt * ACCEL

        if self.ballV.lengthSquared() > MAX_SPEED_SQ:
            self.ballV.normalize()
            self.ballV *= MAX_SPEED

        self.ballRoot.setPos(self.ballRoot.getPos() + (self.ballV * dt))

        prevRot = LRotationf(self.ball.getQuat())
        axis = LVector3.up().cross(self.ballV)
        newRot = LRotationf(axis, 45.5 * dt * self.ballV.length())
        self.ball.setQuat(prevRot * newRot)

        return Task.cont
Exemple #14
0
    def rollTask(self, task):
        # Standard technique for finding the amount of time since the last
        # frame
        dt = base.clock.dt

        # If dt is large, then there has been a # hiccup that could cause the ball
        # to leave the field if this functions runs, so ignore the frame
        if dt > .2:
            return Task.cont

        # The collision handler collects the collisions. We dispatch which function
        # to handle the collision based on the name of what was collided into
        for i in range(self.cHandler.getNumEntries()):
            entry = self.cHandler.getEntry(i)
            name = entry.getIntoNode().getName()
            if name == "wall_collide":
                self.wallCollideHandler(entry)
            elif name == "ground_collide":
                self.groundCollideHandler(entry)
            elif name == "loseTrigger":
                self.loseGame(entry)

        # Read the mouse position and tilt the maze accordingly
        if base.mouseWatcherNode.hasMouse():
            mpos = base.mouseWatcherNode.getMouse()  # get the mouse position
            self.maze.setP(mpos.getY() * -10)
            self.maze.setR(mpos.getX() * 10)

        # Finally, we move the ball
        # Update the velocity based on acceleration
        self.ballV += self.accelV * dt * ACCEL
        # Clamp the velocity to the maximum speed
        if self.ballV.lengthSquared() > MAX_SPEED_SQ:
            self.ballV.normalize()
            self.ballV *= MAX_SPEED
        # Update the position based on the velocity
        self.ballRoot.setPos(self.ballRoot.getPos() + (self.ballV * dt))

        # This block of code rotates the ball. It uses something called a quaternion
        # to rotate the ball around an arbitrary axis. That axis perpendicular to
        # the balls rotation, and the amount has to do with the size of the ball
        # This is multiplied on the previous rotation to incrimentally turn it.
        prevRot = LRotationf(self.ball.getQuat())
        axis = LVector3.up().cross(self.ballV)
        newRot = LRotationf(axis, 45.5 * dt * self.ballV.length())
        self.ball.setQuat(prevRot * newRot)

        return Task.cont       # Continue the task indefinitely
Exemple #15
0
def test_frustum_intersection():
    f = create_frustum()
    assert not f.is_sphere_in(LPoint3d(), 0)
    assert f.is_sphere_in(LPoint3d(), 1.1)
    assert f.is_sphere_in(LPoint3d(0, 1.1, 0), 0)

    mat = LMatrix4()
    mat.set_rotate_mat(90, LVector3.up())
    f = create_frustum(mat=mat)
    assert not f.is_sphere_in(LPoint3d(), 0)
    assert f.is_sphere_in(LPoint3d(), 1.1)
    assert f.is_sphere_in(LPoint3d(-1.1, 0, 0), 0)
    assert not f.is_sphere_in(LPoint3d(0, 1.1, 0), 0)

    pos = LPoint3d(0, 1, 0)
    f = create_frustum(pos=pos)
    assert not f.is_sphere_in(LPoint3d(), 0)
    assert not f.is_sphere_in(LPoint3d(), 1.1)
    assert not f.is_sphere_in(LPoint3d(0, 1.1, 0), 0)
    assert f.is_sphere_in(LPoint3d(), 2.1)
    assert f.is_sphere_in(LPoint3d(0, 2.1, 0), 0)
Exemple #16
0
    def rollTask(self, task):
        # Standard technique for finding the amount of time since the last
        # frame
        dt = globalClock.getDt()

        # If dt is large, then there has been a # hiccup that could cause the ball
        # to leave the field if this functions runs, so ignore the frame
        if dt > .2:
            return Task.cont

        # if base.mouseWatcherNode.is_button_down('a'):
        #     self.holeRoot.setH(self.holeRoot.getH() + 1)
        #     print(self.holeRoot.getHpr())
        #     pass
        # if base.mouseWatcherNode.is_button_down('s'):
        #     self.holeRoot.setP(self.holeRoot.getP() + 1)
        #     print(self.holeRoot.getHpr())
        #     pass
        # if base.mouseWatcherNode.is_button_down('d'):
        #     self.holeRoot.setR(self.holeRoot.getR() + 1)
        #     print(self.holeRoot.getHpr())
        #     pass

        # go through different visualizations
        if base.mouseWatcherNode.is_button_down(
                'space') and self.showing == 'none':
            self.showing = 'parts'
            self.showingProgress = 0
            pass
        #print(self.showing)
        #print(self.showing)
        if self.showing == 'none':
            return Task.cont
        if self.showing == 'parts':
            self.showingProgress += 0.01
            #self.showingProgress += 1
            #print(self.showingProgress)
            scale = 2 - self.showingProgress
            scaleY = 1 + (scale - 1) * 0.5
            for planeIndex, planeNP in enumerate(self.planeNPs):
                center = self.planeCenters[planeIndex]
                planeNP.setPos(center[0] * scale, center[1] * scaleY,
                               center[2] * scale)
                planeNP.reparentTo(self.render)
                planeNP.setTwoSided(True)
                continue
            if self.showingProgress > 1:
                self.showing = 'moving'
                for planeIndex, planeNP in enumerate(self.planeNPs):
                    planeNP.removeNode()
                    continue
                self.planeScene.show()
                self.showingProgress = 1
            return Task.cont
        if self.showing == 'moving':
            self.showingProgress += 0.005
            #self.showingProgress += 1
            #print(self.showingProgress, np.sign(self.showingProgress - 0.5) * min(self.showingProgress % 0.5, 0.5 - self.showingProgress % 0.5) * 4)
            self.camera.setPos(
                np.sign(self.showingProgress - 0.5) *
                min(self.showingProgress % 0.5,
                    0.5 - self.showingProgress % 0.5) * 3, 0, 0)
            #self.camera.setHpr(angleDegrees, 0, 0)
            #self.camera.lookAt(0, 0, 0)
            self.camera.lookAt(0, 3, 0)
            if self.showingProgress > 1:
                self.showing = 'geometry'
                self.camera.setPos(0, 0, 0)
                #self.planeScene.removeNode()
                # for triNP in self.triNPs:
                #     triNP.show()
                #     continue
                self.showingProgress = 1
            return Task.cont
        if self.showing == 'geometry':
            self.showingProgress += 0.02
            if self.showingProgress > 1:
                #self.showing = 'image'
                self.showing = 'placement'
                self.showingProgress = 0
                self.holeRoot.show()
                self.inPortalRoot.show()
                self.outPortalRoot.show()
                self.inPortalTube.show()
                self.outPortalTube.show()
                for ballRoot in self.ballRoots:
                    ballRoot.show()
                    continue
                self.showingProgress = 0
                pass
            return Task.cont
        # if self.showing == 'placement':
        #     self.showingProgress += 0.005
        #         continue

        # mouse pose
        if self.mouseWatcherNode.hasMouse():
            mpos = self.mouseWatcherNode.getMouse()
            self.mpos = mpos
            self.pickerRay.setFromLens(self.camNode, mpos.getX(), mpos.getY())
            pass

        #if base.mouseWatcherNode.is_button_down('space') and self.showing == 'placement':
        if self.showing == 'placement':
            self.card.show()
            self.planeScene.removeNode()
            self.showing = 'image'
            pass
        # if base.mouseWatcherNode.is_button_down('space') and self.showing == 'image':
        #     for triNP in self.triNPs:
        #         triNP.hide()
        #         continue
        #     self.showing = 'start'
        #     pass

        # for each plane, check which horizontal plane it is sitting on
        self.ballGroundMap = {}
        for i in range(self.cHandler.getNumEntries()):
            entry = self.cHandler.getEntry(i)
            ballName = entry.getFromNode().getName()
            groundName = entry.getIntoNode().getName()
            if 'ball_ray_' not in ballName:
                continue
            if 'ground_' not in groundName:
                continue
            ballIndex = int(ballName[9:])
            groundIndex = int(groundName[7:])
            norm = -entry.getSurfaceNormal(render)
            if norm.length() == 0:
                continue
            norm = norm / norm.length()
            distance = norm.dot(
                entry.getSurfacePoint(render) -
                self.ballRoots[ballIndex].getPos())
            #print(distance)
            if distance < 0:
                continue
            if ballIndex not in self.ballGroundMap or distance < self.ballGroundMap[
                    ballIndex][1]:
                self.ballGroundMap[ballIndex] = (groundIndex, distance)
                pass
            continue

        # The collision handler collects the collisions. We dispatch which function
        # to handle the collision based on the name of what was collided into
        for i in range(self.cHandler.getNumEntries()):
            entry = self.cHandler.getEntry(i)
            fromName = entry.getFromNode().getName()
            #if 'mouseRay' in fromName:
            #continue
            name = entry.getIntoNode().getName()
            #if name == "plane_collide":
            if 'tri_' in name:
                self.planeCollideHandler(entry)
            #elif name == "wall_collide":
            #self.wallCollideHandler(entry)
            #elif name == "ground_collide":
            #self.groundCollideHandler(entry)
            elif 'ball_' in name:
                self.ballCollideHandler(entry)
            elif 'ground_' in name:
                self.groundCollideHandler(entry)
            elif 'hole' in name:
                self.score(entry)
            elif 'portal_' in name:
                self.portal(entry)
                pass
            continue

        # Read the mouse position and tilt the maze accordingly
        if base.mouseWatcherNode.hasMouse():
            mpos = base.mouseWatcherNode.getMouse()  # get the mouse position
            #self.maze.setP(mpos.getY() * -10)
            #self.maze.setR(mpos.getX() * 10)
            pass

        # if base.mouseWatcherNode.is_button_down('mouse1'):
        #     print(base.mouseWatcherNode.getMouseX())
        #     print(base.mouseWatcherNode.getMouseY())
        #     exit(1)

        # Finally, we move the ball
        # Update the velocity based on acceleration
        for ballIndex in xrange(len(self.balls)):
            if self.ballVs[ballIndex].length(
            ) < 1e-4 and self.ballVs[ballIndex].dot(
                    self.accelVs[ballIndex]) < -1e-4:
                self.ballVs[ballIndex] = LVector3(0, 0, 0)
                self.accelVs[ballIndex] = LVector3(0, 0, 0)
            else:
                self.ballVs[ballIndex] += self.accelVs[ballIndex] * dt * ACCEL
                pass
            #print('current speed', self.ballVs[ballIndex], self.accelVs[ballIndex])
            # Clamp the velocity to the maximum speed
            if self.ballVs[ballIndex].lengthSquared() > MAX_SPEED_SQ:
                self.ballVs[ballIndex].normalize()
                self.ballVs[ballIndex] *= MAX_SPEED
                pass
            #print(self.ballVs[ballIndex], self.accelVs[ballIndex], self.ballRoots[ballIndex].getPos())

            # Update the position based on the velocity
            self.ballRoots[ballIndex].setPos(
                self.ballRoots[ballIndex].getPos() +
                (self.ballVs[ballIndex] * dt))

            # This block of code rotates the ball. It uses something called a quaternion
            # to rotate the ball around an arbitrary axis. That axis perpendicular to
            # the balls rotation, and the amount has to do with the size of the ball
            # This is multiplied on the previous rotation to incrimentally turn it.
            prevRot = LRotationf(self.balls[ballIndex].getQuat())
            axis = LVector3.up().cross(self.ballVs[ballIndex])
            newRot = LRotationf(
                axis,
                np.rad2deg(dt * self.ballVs[ballIndex].length() /
                           self.ballSize))
            self.balls[ballIndex].setQuat(prevRot * newRot)
            continue

        self.cueRoot.setPos(self.cuePos[0], self.cuePos[1], self.cuePos[2])
        return Task.cont  # Continue the task indefinitely
Exemple #17
0
    def __init__(self, args):
        CosmoniumBase.__init__(self)

        if args.config is not None:
            self.config_file = args.config
        else:
            self.config_file = 'ralph-data/ralph.yaml'
        self.splash = RalphSplash()
        self.ralph_config = RalphConfigParser()
        if self.ralph_config.load_and_parse(self.config_file) is None:
            sys.exit(1)
        self.water = self.ralph_config.water

        self.has_water = True
        self.fullscreen = False
        self.shadow_caster = None
        self.light_angle = None
        self.light_dir = LVector3.up()
        self.vector_to_star = self.light_dir
        self.light_quat = LQuaternion()
        self.light_color = (1.0, 1.0, 1.0, 1.0)
        self.directionalLight = None

        self.observer = RalphCamera(self.cam, self.camLens)
        self.observer.init()

        self.distance_to_obs = 2.0  #Can not be 0 !
        self.height_under = 0.0
        self.scene_position = LVector3()
        self.scene_scale_factor = 1
        self.scene_rel_position = LVector3()
        self.scene_orientation = LQuaternion()
        self.model_body_center_offset = LVector3()
        self.world_body_center_offset = LVector3()
        self.context = self
        self.size = self.ralph_config.tile_size  #TODO: Needed by populator

        #Size of an edge seen from 4 units above
        self.edge_apparent_size = (1.0 * self.ralph_config.tile_size /
                                   self.ralph_config.tile_density) / (
                                       4.0 * self.observer.pixel_size)
        print("Apparent size:", self.edge_apparent_size)

        self.win.setClearColor((135.0 / 255, 206.0 / 255, 235.0 / 255, 1))

        # Set up the environment
        #
        # Create some lighting
        self.vector_to_obs = base.cam.get_pos()
        self.vector_to_obs.normalize()
        if True:
            self.shadow_caster = ShadowMap(1024)
            self.shadow_caster.create()
            self.shadow_caster.set_lens(
                self.ralph_config.shadow_size,
                -self.ralph_config.shadow_box_length / 2.0,
                self.ralph_config.shadow_box_length / 2.0, -self.light_dir)
            self.shadow_caster.set_pos(
                self.light_dir * self.ralph_config.shadow_box_length / 2.0)
            self.shadow_caster.bias = 0.1
        else:
            self.shadow_caster = None

        self.ambientLight = AmbientLight("ambientLight")
        self.ambientLight.setColor(
            (settings.global_ambient, settings.global_ambient,
             settings.global_ambient, 1))
        self.directionalLight = DirectionalLight("directionalLight")
        self.directionalLight.setDirection(-self.light_dir)
        self.directionalLight.setColor(self.light_color)
        self.directionalLight.setSpecularColor(self.light_color)
        render.setLight(render.attachNewNode(self.ambientLight))
        render.setLight(render.attachNewNode(self.directionalLight))

        render.setShaderAuto()
        base.setFrameRateMeter(True)

        self.create_terrain()
        for component in self.ralph_config.layers:
            self.terrain.add_component(component)
            self.terrain_shape.add_linked_object(component)

        if self.ralph_config.fog_parameters is not None:
            self.fog = Fog(**self.ralph_config.fog_parameters)
            self.terrain.add_after_effect(self.fog)
        else:
            self.fog = None
        self.surface = self.terrain_object

        self.create_instance()
        self.create_tile(0, 0)
        self.skybox_init()

        self.set_light_angle(45)

        # Create the main character, Ralph

        ralphStartPos = LPoint3()
        self.ralph = Actor(
            "ralph-data/models/ralph", {
                "run": "ralph-data/models/ralph-run",
                "walk": "ralph-data/models/ralph-walk"
            })
        self.ralph.reparentTo(render)
        self.ralph.setScale(.2)
        self.ralph.setPos(ralphStartPos + (0, 0, 0.5))
        self.ralph_shape = InstanceShape(self.ralph)
        self.ralph_shape.parent = self
        self.ralph_shape.set_owner(self)
        self.ralph_shape.create_instance()
        self.ralph_appearance = ModelAppearance(self.ralph)
        self.ralph_appearance.set_shadow(self.shadow_caster)
        self.ralph_shader = BasicShader()
        self.ralph_shader.add_shadows(ShaderShadowMap())
        self.ralph_appearance.bake()
        self.ralph_appearance.apply(self.ralph_shape, self.ralph_shader)
        self.ralph_shader.apply(self.ralph_shape, self.ralph_appearance)
        self.ralph_shader.update(self.ralph_shape, self.ralph_appearance)

        # Create a floater object, which floats 2 units above ralph.  We
        # use this as a target for the camera to look at.

        self.floater = NodePath(PandaNode("floater"))
        self.floater.reparentTo(self.ralph)
        self.floater.setZ(2.0)

        self.ralph_body = NodePathHolder(self.ralph)
        self.ralph_floater = NodePathHolder(self.floater)

        self.follow_cam = FollowCam(self, self.cam, self.ralph, self.floater)

        self.nav = RalphNav(self.ralph, self.ralph_floater, self.cam,
                            self.observer, self, self.follow_cam)
        self.nav.register_events(self)

        self.accept("escape", sys.exit)
        self.accept("control-q", sys.exit)
        self.accept("w", self.toggle_water)
        self.accept("h", self.print_debug)
        self.accept("f2", self.connect_pstats)
        self.accept("f3", self.toggle_filled_wireframe)
        self.accept("shift-f3", self.toggle_wireframe)
        self.accept("f5", self.bufferViewer.toggleEnable)
        self.accept('f8', self.toggle_lod_freeze)
        self.accept("shift-f8", self.terrain_shape.dump_tree)
        self.accept('control-f8', self.toggle_split_merge_debug)
        self.accept('shift-f9', self.toggle_bb)
        self.accept('control-f9', self.toggle_frustum)
        self.accept("f10", self.save_screenshot)
        self.accept('alt-enter', self.toggle_fullscreen)
        self.accept('{', self.incr_ambient, [-0.05])
        self.accept('}', self.incr_ambient, [+0.05])

        taskMgr.add(self.move, "moveTask")

        # Set up the camera
        self.follow_cam.update()
        self.distance_to_obs = self.cam.get_z() - self.get_height(
            self.cam.getPos())
        render.set_shader_input("camera", self.cam.get_pos())

        self.terrain.update_instance(LPoint3d(*self.cam.getPos()), None)
Exemple #18
0
 def update_shadow_caster(self):
     radius = self.get_extend() / settings.scale
     self.shadow_caster.get_lens().set_film_size(radius * 2.1, radius * 2.1)
     self.shadow_caster.get_lens().setNear(-self.context.observer.infinity)
     self.shadow_caster.get_lens().setFar(self.context.observer.infinity)
     self.shadow_caster.get_lens().set_view_vector(LVector3(*-self.vector_to_star), LVector3.up())
     if self.custom_shadows:
         self.shadow_caster.set_pos(self.sunLight.getPos())
Exemple #19
0
 def set_lens(self, size, near, far, direction):
     lens = self.node.get_lens()
     lens.set_film_size(size)
     lens.setNear(near)
     lens.setFar(far)
     lens.set_view_vector(LVector3(*direction), LVector3.up())
Exemple #20
0
    def rollTask(self, task):
        # Standard technique for finding the amount of time since the last
        # frame
        #print("\r",self.maze.getR(), self.maze.getP(), self.ballRoot.getPos(), end="")

        dt = globalClock.getDt()
        print("\r{:.3} fps      ".format(1 / dt), end="")

        # If dt is large, then there has been a # hiccup that could cause the ball
        # to leave the field if this functions runs, so ignore the frame
        if dt > .2:
            return Task.cont

        #print(action)
        if action == "start":
            a = 1

        elif action == "stop":
            while action == "stop":
                a = 0

    # elif action == "restart": in Line 531

        elif action == "coord":
            a = 1
            #ALGUNA CRIDA A METODE DE NARCIS/MARC

        key_down = base.mouseWatcherNode.is_button_down

        if self.ready_to_solve:

            if key_down(KeyboardButton.ascii_key('d')):
                screenshot = self.camera2_buffer.getScreenshot()
                if screenshot:
                    v = memoryview(screenshot.getRamImage()).tolist()
                    img = np.array(v, dtype=np.uint8)
                    img = img.reshape(
                        (screenshot.getYSize(), screenshot.getXSize(), 4))
                    img = img[::-1]
                    #self.digitizer.set_src_img(img)
                    #self.digitizer.digitalize_source()
                    cv2.imshow('img', img)
                    #cv2.waitKey(0)

            if key_down(KeyboardButton.ascii_key('s')):
                print("Screenshot!")
                self.camera2_buffer.saveScreenshot("screenshot.jpg")

            # The collision handler collects the collisions. We dispatch which function
            # to handle the collision based on the name of what was collided into
            for i in range(self.cHandler.getNumEntries()):
                entry = self.cHandler.getEntry(i)
                name = entry.getIntoNode().getName()
                if action == "restart":
                    self.loseGame(entry)
                if name == "wall_col":
                    self.wallCollideHandler(entry)
                elif name == "ground_col":
                    self.groundCollideHandler(entry)
                elif name == "loseTrigger":
                    vr.restart = 1
                    global th
                    th = threading.Thread(target=listenVoice)
                    th.start()
                    self.loseGame(entry)

            # Read the mouse position and tilt the maze accordingly
            # Rotation axes use (roll, pitch, heave)
            """
            if base.mouseWatcherNode.hasMouse():
                mpos = base.mouseWatcherNode.getMouse()  # get the mouse position
                self.maze.setP(mpos.getY() * -10)
                self.maze.setR(mpos.getX() * 10)
            """

            ballPos = self.get_ball_position()
            #print("BALL POS: ", ballPos)

            posFPixel = self.path[self.indexPuntActual]

            xFinal = posFPixel[1]  #posFPixel[1]/np.shape(laberint)[0]*13 - 6.5
            yFinal = posFPixel[
                0]  #-(posFPixel[0]/np.shape(laberint)[1]*13.5 - 6.8)

            dist = math.sqrt((xFinal - ballPos[1])**2 +
                             (yFinal - ballPos[0])**2)

            if (dist < self.minDist):
                if (self.indexPuntActual == len(self.path) - 1):
                    print("SOLVED!!", end="")

                while (self.aStar.distance(
                    (ballPos[0], ballPos[1]), self.path[self.indexPuntActual])
                       < self.pas):
                    if (self.indexPuntActual < len(self.path) - 1):
                        self.indexPuntActual += 1
                    else:
                        break

            # ball pos (y,x)

            #print("END POS: ", self.digitizer.endPos)

            if voice_solving:
                p_rotation = dir_veu[0]
                r_rotation = dir_veu[1]
                if p_rotation == 0 and r_rotation == 0 and ballPos is not None:
                    p_rotation, r_rotation = self.pid.getPR(
                        ballPos[1], ballPos[0], ballPos[1], ballPos[0],
                        self.maze.getP(), self.maze.getR(), dt)

            else:
                p_rotation = 0
                r_rotation = 0
                #print(ballPos, dist)

                #print(ballPos)

                if ballPos is not None:

                    p_rotation, r_rotation = self.pid.getPR(
                        ballPos[1], ballPos[0], xFinal, yFinal,
                        self.maze.getP(), self.maze.getR(), dt)
                    #print(p_rotation, r_rotation)

            if key_down(KeyboardButton.up()):
                p_rotation = -1
            elif key_down(KeyboardButton.down()):
                p_rotation = 1

            if key_down(KeyboardButton.left()):
                r_rotation = -1
            elif key_down(KeyboardButton.right()):
                r_rotation = 1

            self.rotateMaze(p_rotation, r_rotation)

            # Finally, we move the ball
            # Update the velocity based on acceleration
            self.ballV += self.accelV * dt * ACCEL
            # Clamp the velocity to the maximum speed
            if self.ballV.lengthSquared() > MAX_SPEED_SQ:
                self.ballV.normalize()
                self.ballV *= MAX_SPEED
            # Update the position based on the velocity
            self.ballRoot.setPos(self.ballRoot.getPos() + (self.ballV * dt))
            #print(self.ballRoot.getPos())

            # This block of code rotates the ball. It uses something called a quaternion
            # to rotate the ball around an arbitrary axis. That axis perpendicular to
            # the balls rotation, and the amount has to do with the size of the ball
            # This is multiplied on the previous rotation to incrimentally turn it.
            prevRot = LRotationf(self.ball.getQuat())
            axis = LVector3.up().cross(self.ballV)
            newRot = LRotationf(axis, 45.5 * dt * self.ballV.length())
            self.ball.setQuat(prevRot * newRot)

        elif key_down(KeyboardButton.ascii_key('1')):
            self.solve()

        if key_down(KeyboardButton.ascii_key('i')):
            self.light.setY(self.light.getY() + 10 * dt)
        elif key_down(KeyboardButton.ascii_key('k')):
            self.light.setY(self.light.getY() - 10 * dt)

        if key_down(KeyboardButton.ascii_key('j')):
            self.light.setX(self.light.getX() - 10 * dt)
        elif key_down(KeyboardButton.ascii_key('l')):
            self.light.setX(self.light.getX() + 10 * dt)

        if key_down(KeyboardButton.ascii_key('u')):
            self.lightColor += 10000 * dt
            self.light.node().setColor(
                (self.lightColor, self.lightColor, self.lightColor, 1))
        elif key_down(KeyboardButton.ascii_key('o')):
            self.lightColor -= 10000 * dt
            self.light.node().setColor(
                (self.lightColor, self.lightColor, self.lightColor, 1))

        if key_down(KeyboardButton.ascii_key('8')):
            self.alightColor += 1 * dt
            self.ambientL.node().setColor(
                (self.alightColor, self.alightColor, self.alightColor, 1))
        elif key_down(KeyboardButton.ascii_key('9')):
            self.alightColor -= 1 * dt
            self.ambientL.node().setColor(
                (self.alightColor, self.alightColor, self.alightColor, 1))

        if key_down(KeyboardButton.ascii_key('r')):
            base.trackball.node().set_pos(0, 200, 0)
            base.trackball.node().set_hpr(0, 60, 0)

        return Task.cont  # Continue the task indefinitely
Exemple #21
0
    def __init__(self):
        CosmoniumBase.__init__(self)

        config = RalphConfigParser()
        (self.noise, self.biome_noise, self.terrain_control, self.terrain_appearance, self.water, self.fog) = config.load_and_parse('ralph-data/ralph.yaml')

        self.tile_density = 64
        self.default_size = 128
        self.max_vertex_size = 64
        self.max_lod = 10

        self.size = 128 * 8
        self.max_distance = 1.001 * self.size * sqrt(2)
        self.noise_size = 512
        self.biome_size = 128
        self.noise_scale = 0.5 * self.size / self.default_size
        self.objects_density = int(25 * (1.0 * self.size / self.default_size) * (1.0 * self.size / self.default_size))
        self.objects_density = 250
        self.height_scale = 100 * 5.0
        self.has_water = True
        self.fullscreen = False
        self.shadow_caster = None
        self.light_angle = None
        self.light_dir = LVector3.up()
        self.vector_to_star = self.light_dir
        self.light_quat = LQuaternion()
        self.light_color = (1.0, 1.0, 1.0, 1.0)
        self.directionalLight = None
        self.shadow_size = self.default_size / 8
        self.shadow_box_length = self.height_scale

        self.observer = RalphCamera(self.cam, self.camLens)
        self.observer.init()

        self.distance_to_obs = float('inf')
        self.height_under = 0.0
        self.scene_position = LVector3()
        self.scene_scale_factor = 1
        self.scene_orientation = LQuaternion()

        #Size of an edge seen from 4 units above
        self.edge_apparent_size = (1.0 * self.size / self.tile_density) / (4.0 * self.observer.pixel_size)
        print("Apparent size:", self.edge_apparent_size)

        self.win.setClearColor((135.0/255, 206.0/255, 235.0/255, 1))

        # This is used to store which keys are currently pressed.
        self.keyMap = {
            "left": 0, "right": 0, "forward": 0, "backward": 0,
            "cam-left": 0, "cam-right": 0, "cam-up": 0, "cam-down": 0,
            "sun-left": 0, "sun-right": 0,
            "turbo": 0}

        # Set up the environment
        #
        # Create some lighting
        self.vector_to_obs = base.cam.get_pos()
        self.vector_to_obs.normalize()
        if True:
            self.shadow_caster = ShadowCaster(1024)
            self.shadow_caster.create()
            self.shadow_caster.set_lens(self.shadow_size, -self.shadow_box_length / 2.0, self.shadow_box_length / 2.0, -self.light_dir)
            self.shadow_caster.set_pos(self.light_dir * self.shadow_box_length / 2.0)
            self.shadow_caster.bias = 0.1
        else:
            self.shadow_caster = None

        self.ambientLight = AmbientLight("ambientLight")
        self.ambientLight.setColor((settings.global_ambient, settings.global_ambient, settings.global_ambient, 1))
        self.directionalLight = DirectionalLight("directionalLight")
        self.directionalLight.setDirection(-self.light_dir)
        self.directionalLight.setColor(self.light_color)
        self.directionalLight.setSpecularColor(self.light_color)
        render.setLight(render.attachNewNode(self.ambientLight))
        render.setLight(render.attachNewNode(self.directionalLight))

        render.setShaderAuto()
        base.setFrameRateMeter(True)

        self.create_terrain()
        self.create_populator()
        self.terrain_shape.set_populator(self.object_collection)
        self.create_tile(0, 0)
        self.skybox_init()

        self.set_light_angle(45)

        # Create the main character, Ralph

        ralphStartPos = LPoint3()
        self.ralph = Actor("ralph-data/models/ralph",
                           {"run": "ralph-data/models/ralph-run",
                            "walk": "ralph-data/models/ralph-walk"})
        self.ralph.reparentTo(render)
        self.ralph.setScale(.2)
        self.ralph.setPos(ralphStartPos + (0, 0, 0.5))
        self.ralph_shape = InstanceShape(self.ralph)
        self.ralph_shape.parent = self
        self.ralph_shape.set_owner(self)
        self.ralph_shape.create_instance()
        self.ralph_appearance = ModelAppearance(self.ralph)
        self.ralph_appearance.set_shadow(self.shadow_caster)
        self.ralph_shader = BasicShader()
        self.ralph_appearance.bake()
        self.ralph_appearance.apply(self.ralph_shape, self.ralph_shader)
        self.ralph_shader.apply(self.ralph_shape, self.ralph_appearance)
        self.ralph_shader.update(self.ralph_shape, self.ralph_appearance)

        # Create a floater object, which floats 2 units above ralph.  We
        # use this as a target for the camera to look at.

        self.floater = NodePath(PandaNode("floater"))
        self.floater.reparentTo(self.ralph)
        self.floater.setZ(2.0)

        # Accept the control keys for movement and rotation

        self.accept("escape", sys.exit)
        self.accept("control-q", sys.exit)
        self.accept("arrow_left", self.setKey, ["left", True])
        self.accept("arrow_right", self.setKey, ["right", True])
        self.accept("arrow_up", self.setKey, ["forward", True])
        self.accept("arrow_down", self.setKey, ["backward", True])
        self.accept("shift", self.setKey, ["turbo", True])
        self.accept("a", self.setKey, ["cam-left", True], direct=True)
        self.accept("s", self.setKey, ["cam-right", True], direct=True)
        self.accept("u", self.setKey, ["cam-up", True], direct=True)
        self.accept("u-up", self.setKey, ["cam-up", False])
        self.accept("d", self.setKey, ["cam-down", True], direct=True)
        self.accept("d-up", self.setKey, ["cam-down", False])
        self.accept("o", self.setKey, ["sun-left", True], direct=True)
        self.accept("o-up", self.setKey, ["sun-left", False])
        self.accept("p", self.setKey, ["sun-right", True], direct=True)
        self.accept("p-up", self.setKey, ["sun-right", False])
        self.accept("arrow_left-up", self.setKey, ["left", False])
        self.accept("arrow_right-up", self.setKey, ["right", False])
        self.accept("arrow_up-up", self.setKey, ["forward", False])
        self.accept("arrow_down-up", self.setKey, ["backward", False])
        self.accept("shift-up", self.setKey, ["turbo", False])
        self.accept("a-up", self.setKey, ["cam-left", False])
        self.accept("s-up", self.setKey, ["cam-right", False])
        self.accept("w", self.toggle_water)
        self.accept("h", self.print_debug)
        self.accept("f2", self.connect_pstats)
        self.accept("f3", self.toggle_filled_wireframe)
        self.accept("shift-f3", self.toggle_wireframe)
        self.accept("f5", self.bufferViewer.toggleEnable)
        self.accept("f8", self.terrain_shape.dump_tree)
        self.accept('alt-enter', self.toggle_fullscreen)

        taskMgr.add(self.move, "moveTask")

        # Game state variables
        self.isMoving = False

        # Set up the camera
        self.camera.setPos(self.ralph.getX(), self.ralph.getY() + 10, 2)
        self.camera_height = 2.0
        render.set_shader_input("camera", self.camera.get_pos())

        self.cTrav = CollisionTraverser()

        self.ralphGroundRay = CollisionRay()
        self.ralphGroundRay.setOrigin(0, 0, 9)
        self.ralphGroundRay.setDirection(0, 0, -1)
        self.ralphGroundCol = CollisionNode('ralphRay')
        self.ralphGroundCol.addSolid(self.ralphGroundRay)
        self.ralphGroundCol.setFromCollideMask(CollideMask.bit(0))
        self.ralphGroundCol.setIntoCollideMask(CollideMask.allOff())
        self.ralphGroundColNp = self.ralph.attachNewNode(self.ralphGroundCol)
        self.ralphGroundHandler = CollisionHandlerQueue()
        self.cTrav.addCollider(self.ralphGroundColNp, self.ralphGroundHandler)

        # Uncomment this line to see the collision rays
        #self.ralphGroundColNp.show()

        # Uncomment this line to show a visual representation of the
        # collisions occuring
        #self.cTrav.showCollisions(render)

        #self.terrain_shape.test_lod(LPoint3d(*self.ralph.getPos()), self.distance_to_obs, self.pixel_size, self.terrain_appearance)
        #self.terrain_shape.update_lod(LPoint3d(*self.ralph.getPos()), self.distance_to_obs, self.pixel_size, self.terrain_appearance)
        #self.terrain.shape_updated()
        self.terrain.update_instance(LPoint3d(*self.ralph.getPos()), None)
Exemple #22
0
 def set_direction(self, direction):
     lens = self.node.get_lens()
     lens.set_view_vector(LVector3(*direction), LVector3.up())