Example #1
0
def drawLeaf(
        nodePath,
        vdata,
        pos=LVector3(0, 0, 0),
        vecList=[LVector3(0, 0, 1),
                 LVector3(1, 0, 0),
                 LVector3(0, -1, 0)],
        scale=0.125):

    # use the vectors that describe the direction the branch grows to make the right
    # rotation matrix
    newCs = LMatrix4(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
    newCs.setRow(0, vecList[2])  # right
    newCs.setRow(1, vecList[1])  # up
    newCs.setRow(2, vecList[0])  # forward
    newCs.setRow(3, (0, 0, 0))
    newCs.setCol(3, (0, 0, 0, 1))

    axisAdj = LMatrix4.scaleMat(scale) * newCs * LMatrix4.translateMat(pos)

    # orginlly made the leaf out of geometry but that didnt look good
    # I also think there should be a better way to handle the leaf texture other than
    # hardcoding the filename
    leafModel = loader.loadModel('models/shrubbery')
    leafTexture = loader.loadTexture('models/material-10-cl.png')

    leafModel.reparentTo(nodePath)
    leafModel.setTexture(leafTexture, 1)
    leafModel.setTransform(TransformState.makeMat(axisAdj))
Example #2
0
    def get_bone_transform_mat(self, bone_transform_array, bone_index):
        """
        Returns the transform related to the given bone. The transform is returned as a 4-dimensions transform matrix.

        bone_transform_array : Array containing all the bones transformations

        bone_index : Index of the bone transformation to retrieve.
        """

        if bone_index < len(bone_transform_array):
            bone_transform = bone_transform_array[bone_index]
            if bone_transform is not None:
                position = bone_transform.position
                orientation = bone_transform.orientation
                transform_mat = LMatrix4()
                compose_matrix(transform_mat, LVector3(1), LVector3(0),
                               self.convert_quaternion(orientation).get_hpr(),
                               self.convert_vector(position).get_xyz())
                return self.coord_mat_inv * transform_mat * self.coord_mat
            else:
                print(
                    "ERROR: No transform data for bone {}".format(bone_index))
        else:
            print("ERROR: Invalid bone index {}".format(bone_index))
        return LMatrix4.ident_mat()
Example #3
0
File: main.py Project: MarcMDE/LASO
    def start(self):
        # The maze model also has a locator in it for where to start the ball
        # To access it we use the find command
        #startPos = self.maze.find("**/start").getPos()
        startPos = (MAZES_START_POS[self.maze_i][0],
                    MAZES_START_POS[self.maze_i][1], MAZE_HEIGHT + BALL_OFFSET)
        self.ballRoot.setPos(startPos)

        if not self.ready_to_solve:
            self.ballRoot.hide()

        self.pid = pid(startPos[0], startPos[1])
        # INICIALITZAR A* AMB LABERINT HARDCODEJAT, S'HA DE CANVIAR

        # ----------- self.path_matrix, self.path = self.aStar.a_star(laberint, 26, 10, 465, 448, 89, 461) -----------------

        self.indexPuntActual = 0

        self.ballV = LVector3(0, 0, 0)  # Initial velocity is 0
        self.accelV = LVector3(0, 0, 0)  # Initial acceleration is 0

        # Create the movement task, but first make sure it is not already
        # running
        taskMgr.remove("rollTask")
        self.mainLoop = taskMgr.add(self.rollTask, "rollTask")
Example #4
0
 def update_instance(self, camera_pos, orientation):
     body = self.parent
     if body.is_emissive() and (not body.resolved or isinstance(body, DeepSpaceObject)):
         if body.scene_position != None:
             self.instance.setPos(*body.scene_position)
             scale = abs(self.context.observer.pixel_size * body.get_label_size() * body.scene_distance)
         else:
             scale = 0.0
     else:
         offset = body.get_apparent_radius() * 1.01
         rel_front_pos = body.rel_position - orientation.xform(LPoint3d(0, offset, 0))
         vector_to_obs = LVector3d(-rel_front_pos)
         distance_to_obs = vector_to_obs.length()
         vector_to_obs /= distance_to_obs
         position, distance, scale_factor = self.get_real_pos_rel(rel_front_pos, distance_to_obs, vector_to_obs)
         self.instance.setPos(*position)
         scale = abs(self.context.observer.pixel_size * body.get_label_size() * distance)
     color = body.get_label_color() * self.fade
     self.look_at.set_pos(LVector3(*(orientation.xform(LVector3d.forward()))))
     self.label_instance.look_at(self.look_at, LVector3(), LVector3(*(orientation.xform(LVector3d.up()))))
     color[3] = 1.0
     self.label.setTextColor(color)
     if scale < 1e-7:
         print("Label too far", self.get_name())
         scale = 1e-7
     self.instance.setScale(scale)
Example #5
0
def makeFractalTree(bodydata, nodePath, length, pos=LVector3(0, 0, 0), numIterations=11, numCopies=4, vecList=[LVector3(0, 0, 1), LVector3(1, 0, 0), LVector3(0, -1, 0)]):
    if numIterations > 0:

        drawBody(nodePath, bodydata, pos, vecList, length.getX())

        # move foward along the right axis
        newPos = pos + vecList[0] * length.length()

        # only branch every third level (sorta)
        if numIterations % 3 == 0:
            # decrease dimensions when we branch
            length = LVector3(
                length.getX() / 2, length.getY() / 2, length.getZ() / 1.1)
            for i in range(numCopies):
                makeFractalTree(bodydata, nodePath, length, newPos,
                                numIterations - 1, numCopies, randomAxis(vecList))
        else:
            # just make another branch connected to this one with a small
            # variation in direction
            makeFractalTree(bodydata, nodePath, length, newPos,
                            numIterations - 1, numCopies, smallRandomAxis(vecList))

    else:
        drawBody(nodePath, bodydata, pos, vecList, length.getX(), False)
        drawLeaf(nodePath, bodydata, pos, vecList)
Example #6
0
    def setup(self):
        self.worldNP = render.attach_new_node('World')

        # World
        self.debugNP = self.worldNP.attach_new_node(BulletDebugNode('Debug'))
        self.debugNP.show()
        self.debugNP.node().show_wireframe(True)
        self.debugNP.node().show_constraints(True)
        self.debugNP.node().show_bounding_boxes(False)
        self.debugNP.node().show_normals(False)

        self.world = BulletWorld()
        self.world.set_gravity(LVector3(0, 0, -9.81))
        self.world.set_debug_node(self.debugNP.node())

        # Box A
        shape = BulletBoxShape(LVector3(0.5, 0.5, 0.5))

        bodyA = BulletRigidBodyNode('Box A')
        bodyNP = self.worldNP.attach_new_node(bodyA)
        bodyNP.node().add_shape(shape)
        bodyNP.set_collide_mask(BitMask32.all_on())
        bodyNP.set_pos(-3, 0, 4)

        visNP = loader.load_model('models/box.egg')
        visNP.clear_model_nodes()
        visNP.reparent_to(bodyNP)

        self.world.attach(bodyA)

        # Box B
        shape = BulletBoxShape(LVector3(0.5, 0.5, 0.5))

        bodyB = BulletRigidBodyNode('Box B')
        bodyNP = self.worldNP.attach_new_node(bodyB)
        bodyNP.node().add_shape(shape)
        bodyNP.node().set_mass(1.0)
        bodyNP.node().set_deactivation_enabled(False)
        bodyNP.set_collide_mask(BitMask32.all_on())
        bodyNP.set_pos(0, 0, 0)

        visNP = loader.load_model('models/box.egg')
        visNP.clear_model_nodes()
        visNP.reparent_to(bodyNP)

        self.world.attach(bodyB)

        # Slider
        frameA = TransformState.make_pos_hpr(LPoint3(2, 0, 0),
                                             LVector3(0, 0, 45))
        frameB = TransformState.make_pos_hpr(LPoint3(0, -3, 0),
                                             LVector3(0, 0, 0))

        slider = BulletSliderConstraint(bodyA, bodyB, frameA, frameB, True)
        slider.set_debug_draw_size(2.0)
        slider.set_lower_linear_limit(0)
        slider.set_upper_linear_limit(6)
        slider.set_lower_angular_limit(-60)
        slider.set_upper_angular_limit(60)
        self.world.attach(slider)
    def setup_world_lightning(self):
        """
        Sets up the ambient and specular lighting of the world
        :return:
        """
        ambientLight = AmbientLight("ambientLight")
        ambientLight.setColor((2, 2, 2, 1))
        directionalLight = DirectionalLight("directionalLight")
        directionalLight.setShadowCaster(True)
        directionalLight.setDirection(LVector3(-1, -1, -1))
        directionalLight.setColor((.5, .5, .5, 1))

        dir_light_node = self.render.attachNewNode(directionalLight)
        # dir_light_node.setPos(10, 2, 7)
        # dir_light_node.lookAt(2, 2, 0)
        self.render.setLight(dir_light_node)
        self.render.setLight(self.render.attachNewNode(ambientLight))
        spot = Spotlight("Spot")
        spot.setColorTemperature(9000)
        spot.setColor(LVector3(1, 1, 1))
        light = self.render.attachNewNode(spot)
        light.node().setScene(self.render)
        light.node().setShadowCaster(True)
        # light.node().showFrustum()
        light.node().getLens().setFov(40)
        light.node().getLens().setNearFar(2, 100)
        # light.setPos(10, 2, 7)
        light.setPos(10, 20, 20)
        light.lookAt(2, 2, 0)
        self.render.setLight(light)
Example #8
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
Example #9
0
    def addLight(self, id, parent, attenuation, position, color, specular,
                 stroboscopic, spot, lookat):
        if spot:
            slight = Spotlight(id)
            slight.setColor(VBase4(1, 1, 1, 1))
            lens = PerspectiveLens()
            slight.setLens(lens)
            light = render.attachNewNode(slight)
            light.setPos(LVector3(position[0], position[1], position[2]))
            if lookat == None:
                light.lookAt(parent)
            else:
                light.lookAt(render.find("**/" + lookat))
        else:
            light = parent.attachNewNode(PointLight(id))
            light.node().setAttenuation(attenuation)
            light.setPos(LVector3(position[0], position[1], position[2]))
        light.node().setColor(color)
        light.node().setSpecularColor(specular)
        render.setLight(light)
        self.light_elements[id] = light
        if stroboscopic:
            self.stroboscopic_lights.append(id)

        if id:
            self.nodes_by_id[id] = light
        return light
 def cardmaker_debug(self):
     for node in render2d.find_all_matches("pfm"):
         node.remove_node()
     for text in base.a2dBottomLeft.find_all_matches("*"):
         text.remove_node()
     width = 0.2  # render2d coordinates range: [-1..1]
     # Pseudo-normalize our PfmFile for better contrast.
     normalized_pfm = PfmFile(self.RotorPFM)
     max_p = LVector3()
     normalized_pfm.calc_min_max(LVector3(), max_p)
     normalized_pfm *= 1.0 / max_p.x
     # Put it in a texture
     tex = Texture()
     tex.load(normalized_pfm)
     # Apply the texture to a quad and put it in the lower left corner.
     cm = CardMaker("pfm")
     cm.set_frame(0, width, 0,
         width / normalized_pfm.get_x_size() * normalized_pfm.get_y_size())
     card = base.render2d.attach_new_node(cm.generate())
     card.set_pos(-1, 0, -1)        
     card.set_texture(tex)
     # Display max value text
     self.genLabelText(-3,
                       "Max value: {:.3f} == {:.2f}m".format(max_p.x,
                         max_p.x * self.terrain_scale.z),
                       parent="a2dBottomLeft")
Example #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())
     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()
Example #12
0
    def update_action(self):
        # Get the time that elapsed since last frame.  We multiply this with
        # the desired speed in order to find out with which distance to move
        # in order to achieve that desired speed.
        dt = globalClock.getDt()

        # If a move-button is pressed, move in the specified direction.
        click_data, device_path = self.get_digital_action_state(
            self.action_trackpad_click)
        analog_data, device_path = self.get_analog_action_value(
            self.action_trackpad_pos)
        if click_data and analog_data is not None:
            x, y = analog_data.x, analog_data.y
            if x < -0.4:
                self.tracking_space.setH(self.tracking_space.getH() + 60 * dt)
            if x > 0.4:
                self.tracking_space.setH(self.tracking_space.getH() - 60 * dt)
            if y > 0.1:
                orientation = self.hmd_anchor.get_quat(render)
                vector = orientation.xform(LVector3(0, 1, 0))
                vector[2] = 0
                vector.normalize()
                self.tracking_space.setPos(self.tracking_space.getPos() +
                                           vector * (5 * dt))
            if y < -0.1:
                orientation = self.hmd_anchor.get_quat()
                vector = orientation.xform(LVector3(0, 1, 0))
                vector[2] = 0
                vector.normalize()
                self.tracking_space.setPos(self.tracking_space,
                                           vector * (-5 * dt))
Example #13
0
 def __init__(self, pos=Point3(0), face=None):
     MapWritable.__init__(self, base.document)
     self.uv = LTexCoord(0, 0)
     self.tangent = LVector3(1, 0, 0)
     self.binormal = LVector3(0, 0, 1)
     self.pos = pos
     self.face = face
def lettuce_leaf_pair(baby, direction, showBase):
    x, y = direction
    leaf1 = LettuceLeaf(baby, showBase)
    leaf1.start_position = LVector3(x, y, random() * 3 + 2) * .001
    leaf2 = LettuceLeaf(baby, showBase)
    leaf2.start_position = LVector3(-x, -y, random() * 3 + 2) * .001
    return [leaf1, leaf2]
Example #15
0
    def start(self):
        startPos = self.maze.find("**/start").getPos()
        self.ballRoot.setPos(startPos)
        self.ballV = LVector3(0, 0, 0)
        self.accelV = LVector3(0, 0, 0)

        taskMgr.remove("roolTask")
        self.mainLoop = taskMgr.add(self.rollTask, "rollTask")
 def reset_vehicle(self):
     reset_pos = self.vehicleNP.get_pos()
     reset_pos.z += 3
     self.vehicleNP.node().clear_forces()
     self.vehicleNP.node().set_linear_velocity(LVector3(0))
     self.vehicleNP.node().set_angular_velocity(LVector3(0))
     self.vehicleNP.set_pos(reset_pos)
     self.vehicleNP.set_hpr(LVector3(0))
Example #17
0
 def get_scale(self):
     if self.scale is not None:
         scale = self.scale
     elif self.oblateness is not None:
         scale = LVector3(1.0, 1.0, 1.0 - self.oblateness) * self.radius
     else:
         scale = LVector3(self.radius, self.radius, self.radius)
     return scale
Example #18
0
    def start(self):
        startPos = Point3(self.start_pos[0], self.start_pos[1], 2)
        self.ballRoot.setPos(startPos)
        self.ballV = LVector3(0, 0, 0)  # Initial velocity is 0
        self.accelV = LVector3(0, 0, 0)  # Initial acceleration is 0

        taskMgr.remove("rollTask")
        self.mainLoop = taskMgr.add(self.rollTask, "rollTask")
Example #19
0
    def setup(self):
        self.worldNP = render.attach_new_node('World')

        # World
        self.debugNP = self.worldNP.attach_new_node(BulletDebugNode('Debug'))
        self.debugNP.show()

        self.world = BulletWorld()
        self.world.set_gravity(LVector3(0, 0, -9.81))
        self.world.set_debug_node(self.debugNP.node())

        # Ground
        shape = BulletPlaneShape(LVector3(0, 0, 1), 0)

        #img = PNMImage(Filename('models/elevation.png'))
        #shape = BulletHeightfieldShape(img, 1.0, ZUp)

        np = self.worldNP.attach_new_node(BulletRigidBodyNode('Ground'))
        np.node().add_shape(shape)
        np.set_pos(0, 0, -1)
        np.set_collide_mask(BitMask32.all_on())

        self.world.attach(np.node())

        # Box
        shape = BulletBoxShape(LVector3(1.0, 3.0, 0.3))

        np = self.worldNP.attach_new_node(BulletRigidBodyNode('Box'))
        np.node().set_mass(10.0)
        np.node().add_shape(shape)
        np.set_pos(3, 0, 4)
        np.setH(20.0)
        np.set_collide_mask(BitMask32.all_on())

        self.world.attach(np.node())

        # Character
        self.crouching = False

        h = 1.75
        w = 0.4
        shape = BulletCapsuleShape(w, h - 2 * w, ZUp)
        self.character = BulletCharacterControllerNode(shape, 0.4, 'Player')
        self.characterNP = self.worldNP.attach_new_node(self.character)
        self.characterNP.set_pos(-2, 0, 14)
        self.characterNP.set_h(45)
        self.characterNP.set_collide_mask(BitMask32.all_on())
        self.world.attach(self.character)

        self.actorNP = Actor(
            'samples/roaming-ralph/models/ralph.egg.pz', {
                'run': 'samples/roaming-ralph/models/ralph-run.egg.pz',
                'walk': 'samples/roaming-ralph/models/ralph-walk.egg.pz'
            })
        self.actorNP.reparent_to(self.characterNP)
        self.actorNP.set_scale(0.3048)  # 1ft = 0.3048m
        self.actorNP.setH(180)
        self.actorNP.set_pos(0, 0, -1)
Example #20
0
    def setup(self):
        self.worldNP = render.attach_new_node('World')

        # World
        self.debugNP = self.worldNP.attach_new_node(BulletDebugNode('Debug'))
        self.debugNP.show()
        self.debugNP.node().show_wireframe(True)
        self.debugNP.node().show_constraints(True)
        self.debugNP.node().show_bounding_boxes(False)
        self.debugNP.node().show_normals(False)

        self.world = BulletWorld()
        self.world.set_gravity(LVector3(0, 0, -9.81))
        self.world.set_debug_node(self.debugNP.node())

        # Box A
        shape = BulletBoxShape(LVector3(0.5, 0.5, 0.5))

        bodyA = BulletRigidBodyNode('Box A')
        bodyNP = self.worldNP.attach_new_node(bodyA)
        bodyNP.node().add_shape(shape)
        bodyNP.set_collide_mask(BitMask32.all_on())
        bodyNP.set_pos(-2, 0, 1)

        visNP = loader.load_model('models/box.egg')
        visNP.clear_model_nodes()
        visNP.reparent_to(bodyNP)

        self.world.attach(bodyA)

        # Box B
        shape = BulletBoxShape(LVector3(0.5, 0.5, 0.5))

        bodyB = BulletRigidBodyNode('Box B')
        bodyNP = self.worldNP.attach_new_node(bodyB)
        bodyNP.node().add_shape(shape)
        bodyNP.node().set_mass(1.0)
        bodyNP.node().set_deactivation_enabled(False)
        bodyNP.set_collide_mask(BitMask32.all_on())
        bodyNP.set_pos(2, 0, 1)

        visNP = loader.load_model('models/box.egg')
        visNP.clear_model_nodes()
        visNP.reparent_to(bodyNP)

        self.world.attach(bodyB)

        # Hinge
        pivotA = LPoint3(2, 0, 0)
        pivotB = LPoint3(-4, 0, 0)
        axisA = LVector3(0, 0, 1)
        axisB = LVector3(0, 0, 1)

        hinge = BulletHingeConstraint(bodyA, bodyB, pivotA, pivotB, axisA,
                                      axisB, True)
        hinge.set_debug_draw_size(2.0)
        hinge.set_limit(-90, 120, softness=0.9, bias=0.3, relaxation=1.0)
        self.world.attach(hinge)
 def setupLights(self, direc=(0, 45, -45), point=(0,0,0), color=(0.2, 0.2, 0.2, 1)):  # This function sets up some default lighting
     ambientLight = AmbientLight("ambientLight")
     ambientLight.setColor((.8, .8, .8, 1))
     directionalLight = DirectionalLight("directionalLight")
     directionalLight.setDirection(LVector3(direc))
     directionalLight.setPoint(LVector3(point))
     directionalLight.setColor(color)
     render.setLight(render.attachNewNode(directionalLight))
     render.setLight(render.attachNewNode(ambientLight))
    def setup(self):
        self.worldNP = render.attach_new_node('World')

        # World
        self.debugNP = self.worldNP.attach_new_node(BulletDebugNode('Debug'))
        self.debugNP.show()
        self.debugNP.node().show_wireframe(True)
        self.debugNP.node().show_constraints(True)
        self.debugNP.node().show_bounding_boxes(False)
        self.debugNP.node().show_normals(False)

        self.world = BulletWorld()
        self.world.set_gravity(LVector3(0, 0, -9.81))
        self.world.set_debug_node(self.debugNP.node())

        # Box A
        shape = BulletBoxShape(LVector3(0.5, 0.5, 0.5))

        bodyA = BulletRigidBodyNode('Box A')
        bodyNP = self.worldNP.attach_new_node(bodyA)
        bodyNP.node().add_shape(shape)
        bodyNP.set_collide_mask(BitMask32.all_on())
        bodyNP.set_pos(-2, 0, 4)

        visNP = loader.load_model('models/box.egg')
        visNP.clear_model_nodes()
        visNP.reparent_to(bodyNP)

        self.world.attach(bodyA)

        # Box B
        shape = BulletBoxShape(LVector3(0.5, 0.5, 0.5))

        bodyB = BulletRigidBodyNode('Box B')
        bodyNP = self.worldNP.attach_new_node(bodyB)
        bodyNP.node().add_shape(shape)
        bodyNP.node().set_mass(1.0)
        bodyNP.node().set_deactivation_enabled(False)
        bodyNP.set_collide_mask(BitMask32.all_on())
        bodyNP.set_pos(0, 0, 0)

        visNP = loader.load_model('models/box.egg')
        visNP.clear_model_nodes()
        visNP.reparent_to(bodyNP)

        self.world.attach(bodyB)

        # Cone
        frameA = TransformState.make_pos_hpr(LPoint3(0, 0, -2),
                                             LVector3(0, 0, 90))
        frameB = TransformState.make_pos_hpr(LPoint3(-5, 0, 0),
                                             LVector3(0, 0, 0))

        cone = BulletConeTwistConstraint(bodyA, bodyB, frameA, frameB)
        cone.set_debug_draw_size(2.0)
        cone.set_limit(30, 45, 170, softness=1.0, bias=0.3, relaxation=8.0)
        self.world.attach(cone)
    def setup(self):
        self.worldNP = render.attach_new_node('World')

        # World
        self.debugNP = self.worldNP.attach_new_node(BulletDebugNode('Debug'))
        self.debugNP.show()

        self.world = BulletWorld()
        self.world.set_gravity(LVector3(0, 0, -9.81))
        self.world.set_debug_node(self.debugNP.node())

        # Ground
        shape = BulletPlaneShape(LVector3(0, 0, 1), 0)

        np = self.worldNP.attach_new_node(BulletRigidBodyNode('Ground'))
        np.node().add_shape(shape)
        np.set_pos(0, 0, 0)
        np.set_collide_mask(BitMask32(0x0f))

        self.world.attach(np.node())

        # Box
        shape = BulletBoxShape(LVector3(0.5, 0.5, 0.5))

        np = self.worldNP.attach_new_node(BulletRigidBodyNode('Box'))
        np.node().set_mass(1.0)
        np.node().add_shape(shape)
        np.set_pos(0, 0, 4)
        np.set_collide_mask(BitMask32(0x0f))

        self.world.attach(np.node())

        self.boxNP = np
        visualNP = loader.load_model('models/box.egg')
        visualNP.reparent_to(self.boxNP)

        # Sphere
        shape = BulletSphereShape(0.6)

        np = self.worldNP.attach_new_node(BulletRigidBodyNode('Sphere'))
        np.node().set_mass(1.0)
        np.node().add_shape(shape)
        np.set_pos(3, 0, 4)
        np.set_collide_mask(BitMask32(0x0f))

        self.world.attach(np.node())

        # Cone
        shape = BulletConeShape(0.6, 1.0)

        np = self.worldNP.attach_new_node(BulletRigidBodyNode('Cone'))
        np.node().set_mass(1.0)
        np.node().add_shape(shape)
        np.set_pos(6, 0, 4)
        np.set_collide_mask(BitMask32(0x0f))

        self.world.attach(np.node())
Example #24
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())
Example #25
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())
    def setup(self):
        self.worldNP = render.attach_new_node('World')

        # World
        self.debugNP = self.worldNP.attach_new_node(BulletDebugNode('Debug'))
        self.debugNP.show()
        self.debugNP.node().show_wireframe(True)
        self.debugNP.node().show_constraints(True)
        self.debugNP.node().show_bounding_boxes(False)
        self.debugNP.node().show_normals(False)

        self.world = BulletWorld()
        self.world.set_gravity(LVector3(0, 0, -9.81))
        self.world.set_debug_node(self.debugNP.node())

        # Box A
        shape = BulletBoxShape(LVector3(0.5, 0.5, 0.5))

        bodyA = BulletRigidBodyNode('Box A')
        bodyNP = self.worldNP.attach_new_node(bodyA)
        bodyNP.node().add_shape(shape)
        bodyNP.set_collide_mask(BitMask32.all_on())
        bodyNP.set_pos(-1, 0, 4)

        visNP = loader.load_model('models/box.egg')
        visNP.clear_model_nodes()
        visNP.reparent_to(bodyNP)

        self.world.attach(bodyA)

        # Box B
        shape = BulletBoxShape(LVector3(0.5, 0.5, 0.5))

        bodyB = BulletRigidBodyNode('Box B')
        bodyNP = self.worldNP.attach_new_node(bodyB)
        bodyNP.node().add_shape(shape)
        bodyNP.node().set_mass(1.0)
        bodyNP.node().set_deactivation_enabled(False)
        bodyNP.node().setLinearDamping(0.6)
        bodyNP.node().setAngularDamping(0.6)
        bodyNP.set_collide_mask(BitMask32.all_on())
        bodyNP.set_pos(2, 0, 0)

        visNP = loader.load_model('models/box.egg')
        visNP.clear_model_nodes()
        visNP.reparent_to(bodyNP)

        self.world.attach(bodyB)

        # Spherical Constraint
        pivotA = LPoint3(2, 0, 0)
        pivotB = LPoint3(0, 0, 4)

        joint = BulletSphericalConstraint(bodyA, bodyB, pivotA, pivotB)
        joint.set_debug_draw_size(2.0)
        self.world.attach(joint)
Example #27
0
    def __init__(self, showbase, usersData, gameData):
        DirectObject.__init__(self)

        self.showbase = showbase
        self.usersData = usersData
        self.gameData = gameData

        random.seed(self.gameData.randSeed)

        # Initialize the collision traverser.
        self.cTrav = CollisionTraverser()

        # Initialize the handler.
        self.collHandEvent = CollisionHandlerEvent()
        self.collHandEvent.addInPattern('into-%in')

        self.world = World(showbase)

        self.ambientLight = showbase.render.attachNewNode(
            AmbientLight("ambientLight"))
        # Set the color of the ambient light
        self.ambientLight.node().setColor((.1, .1, .1, 1))
        # add the newly created light to the lightAttrib
        # showbase.render.setLight(self.ambientLight)

        self.spotlight = None

        numberOfPlayers = len(self.usersData)
        for index, user in enumerate(self.usersData):
            user.centipede = Centipede(showbase, index, numberOfPlayers,
                                       self.addToCollisions)
            if user.thisPlayer:
                self.centipede = user.centipede
                self.centipede.attachRing(showbase)

                self.spotlight = self.centipede.head.attachNewNode(
                    PointLight("playerSpotlight"))
                self.spotlight.setPos(LVector3(0, 0, 8))
                # Now we create a spotlight. Spotlights light objects in a given cone
                # They are good for simulating things like flashlights
                self.spotlight.node().setAttenuation(
                    LVector3(.025, 0.0005, 0.0001))
                self.spotlight.node().setColor((0.35, 0.35, .35, 1))
                self.spotlight.node().setSpecularColor((0.01, 0.01, 0.01, 1))

                showbase.render.setLight(self.spotlight)

        self.perPixelEnabled = True
        self.shadowsEnabled = True
        #if self.spotlight:
        #    self.spotlight.node().setShadowCaster(True, 512, 512)
        showbase.render.setShaderAuto()

        self.foods = []
        for i in range(self.gameData.maxFoods):
            self.foods.append(Food(self.showbase, i, self.addToCollisions))
Example #28
0
    def regenTree(self):
        forest = render.findAllMatches("Tree Holder")
        forest.detach()

        bodydata = GeomVertexData("body vertices", self.format, Geom.UHStatic)

        treeNodePath = NodePath("Tree Holder")
        makeFractalTree(bodydata, treeNodePath, LVector3(4, 4, 7),
                        LVector3(0, 0, 0), self.numIterations, self.numCopies)

        treeNodePath.setTexture(self.barkTexture, 1)
        treeNodePath.reparentTo(render)
Example #29
0
 def configure_shape(self):
     if self.scale is not None:
         scale = self.scale
     elif self.oblateness is not None:
         scale = LVector3(1.0, 1.0, 1.0 - self.oblateness) * self.radius
     else:
         scale = LVector3(self.radius, self.radius, self.radius)
     #TODO: should be done on all components
     if self.surface is not None:
         self.surface.set_scale(scale)
     if self.clouds is not None:
         self.clouds.set_scale(scale)
Example #30
0
    def Square(self):
        format = GeomVertexFormat.getV3n3cpt2()
        vdata = GeomVertexData('cube', format, Geom.UHDynamic)

        vertex = GeomVertexWriter(vdata, 'vertex')
        ################################
        #
        # FACE 1
        #
        ################################
        vert1 = LVector3(self.pos.getX(), self.pos.getY(), self.pos.getZ())
        vert2 = LVector3(vert1.getX() + self.len, vert1.getY(), vert1.getZ())
        vert3 = LVector3(vert2.getX(), vert2.getY() + self.wid, vert2.getZ())
        vert4 = LVector3(vert1.getX(), vert1.getY() + self.wid, vert1.getZ())

        vertex.addData3(vert1)
        vertex.addData3(vert2)
        vertex.addData3(vert3)
        vertex.addData3(vert4)

        normal = GeomVertexWriter(vdata, 'normal')
        norm = (vert4 - vert1).cross(vert2 - vert1)
        norm.normalize()

        normal.addData3(norm)
        normal.addData3(norm)
        normal.addData3(norm)
        normal.addData3(norm)

        color = GeomVertexWriter(vdata, 'color')
        color.addData4f(self.color)
        color.addData4f(self.color)
        color.addData4f(self.color)
        color.addData4f(self.color)

        texcoord = GeomVertexWriter(vdata, 'texcoord')
        texcoord.addData2f(1, 0)
        texcoord.addData2f(1, 1)
        texcoord.addData2f(0, 1)
        texcoord.addData2f(0, 0)

        tris = GeomTriangles(Geom.UHDynamic)

        tris.addVertices(0, 3, 1)
        tris.addVertices(1, 3, 2)

        square = Geom(vdata)
        square.addPrimitive(tris)
        self.prim = square

        self.model = GeomNode(self.name)
        self.model.addGeom(self.prim)
Example #31
0
 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())
Example #32
0
    def __init__(self):
        # Initialize the ShowBase class from which we inherit, which will
        # create a window and set up everything we need for rendering into it.
        ShowBase.__init__(self)

        # This code puts the standard title and instruction text on screen
        self.title = OnscreenText(text="Panda3D: Tutorial - Tasks",
                                  parent=base.a2dBottomRight, scale=.07,
                                  align=TextNode.ARight, pos=(-0.1, 0.1),
                                  fg=(1, 1, 1, 1), shadow=(0, 0, 0, 0.5))
        self.escapeText = genLabelText("ESC: Quit", 0)
        self.leftkeyText = genLabelText("[Left Arrow]: Turn Left (CCW)", 1)
        self.rightkeyText = genLabelText("[Right Arrow]: Turn Right (CW)", 2)
        self.upkeyText = genLabelText("[Up Arrow]: Accelerate", 3)
        self.spacekeyText = genLabelText("[Space Bar]: Fire", 4)

        # Disable default mouse-based camera control.  This is a method on the
        # ShowBase class from which we inherit.
        self.disableMouse()

        # Load the background starfield.
        self.setBackgroundColor((0, 0, 0, 1))
        self.bg = loadObject("stars.jpg", scale=146, depth=200,
                             transparency=False)

        # Load the ship and set its initial velocity.
        self.ship = loadObject("ship.png")
        self.setVelocity(self.ship, LVector3.zero())

        # A dictionary of what keys are currently being pressed
        # The key events update this list, and our task will query it as input
        self.keys = {"turnLeft": 0, "turnRight": 0,
                     "accel": 0, "fire": 0}

        self.accept("escape", sys.exit)  # Escape quits
        # Other keys events set the appropriate value in our key dictionary
        self.accept("arrow_left",     self.setKey, ["turnLeft", 1])
        self.accept("arrow_left-up",  self.setKey, ["turnLeft", 0])
        self.accept("arrow_right",    self.setKey, ["turnRight", 1])
        self.accept("arrow_right-up", self.setKey, ["turnRight", 0])
        self.accept("arrow_up",       self.setKey, ["accel", 1])
        self.accept("arrow_up-up",    self.setKey, ["accel", 0])
        self.accept("space",          self.setKey, ["fire", 1])

        # Now we create the task. taskMgr is the task manager that actually
        # calls the function each frame. The add method creates a new task.
        # The first argument is the function to be called, and the second
        # argument is the name for the task.  It returns a task object which
        # is passed to the function each frame.
        self.gameTask = taskMgr.add(self.gameLoop, "gameLoop")

        # Stores the time at which the next bullet may be fired.
        self.nextBullet = 0.0

        # This list will stored fired bullets.
        self.bullets = []

        # Complete initialization by spawning the asteroids.
        self.spawnAsteroids()
Example #33
0
    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())
 def __init__(self, game):
     self.game = game
     self.cells = {}
     self.cells_by_collider = {}
     self.cell_picker_world = NodePath('cell_picker_world')
     self.ray = CollisionRay()
     self.ray.setDirection(LVector3.down())
     cnode = CollisionNode('cell_raycast_cnode')
     self.ray_nodepath = self.cell_picker_world.attachNewNode(cnode)
     self.ray_nodepath.node().addSolid(self.ray)
     self.ray_nodepath.node().setIntoCollideMask(0) # not for colliding into
     self.ray_nodepath.node().setFromCollideMask(1)
     self.traverser = CollisionTraverser('traverser')
     self.last_known_cell = None