Example #1
0
    def __init__(self, cr):
        DistributedObject.__init__(self, cr)
        #self.model = loader.loadModel('environment')
        #self.model.setZ(0)
        #self.builder = Builder(self, "map.txt", "development")

        plane = CollisionPlane(Plane(Vec3(0, 0, 1), Point3(0, 0, 0)))
        cnode = CollisionNode('cnode')
        cnode.setIntoCollideMask(BitMask32.bit(1))
        cnode.setFromCollideMask(BitMask32.bit(1))
        cnode.addSolid(plane)
        self.planeNP = self.model.attachNewNode(cnode)
        self.planeNP.show()

        # Setup a traverser for the picking collisions
        self.picker = CollisionTraverser()
        # Setup mouse ray
        self.pq = CollisionHandlerQueue()
        # Create a collision Node
        pickerNode = CollisionNode('MouseRay')
        # set the nodes collision bitmask
        pickerNode.setFromCollideMask(BitMask32.bit(1))
        # create a collision ray
        self.pickerRay = CollisionRay()
        # add the ray as a solid to the picker node
        pickerNode.addSolid(self.pickerRay)
        # create a nodepath with the camera to the picker node
        self.pickerNP = base.camera.attachNewNode(pickerNode)
        # add the nodepath to the base traverser
        self.picker.addCollider(self.pickerNP, self.pq)

        print "model loaded"
        #TODO: check how to load multiple levels and set players in specific levels!
        self.accept("mouse1", self.mouseClick)
Example #2
0
 def __set_ai_meshes(self):
     return
     # if we attach these meshes (or even only one mesh, box, sphere,
     # whatever) then the collision between the goal and the vehicle doesn't
     # work properly
     h = .5
     boxsz = self.cfg['box_size']
     hs = []
     hs += [
         h / 2 + boxsz[2] * 2 + self.cfg['box_pos'][2] +
         self.cfg['center_mass_offset']
     ]
     hs += [
         -h / 2 - boxsz[2] * 2 + self.cfg['box_pos'][2] +
         self.cfg['center_mass_offset']
     ]
     for _h in hs:
         shape = BulletBoxShape((boxsz[0], boxsz[1], h))
         ghost = GhostNode('Vehicle')
         pos = TransformState.makePos((0, 0, _h))
         ghost.node.addShape(shape, pos)
         self.ai_meshes += [self.eng.attach_node(ghost.node)]
         car_names = self.cprops.race_props.season_props.car_names
         car_idx = car_names.index(self.cprops.name)
         car_bit = BitMask32.bit(BitMasks.car(car_idx))
         ghost_bit = BitMask32.bit(BitMasks.ghost)
         mask = car_bit | ghost_bit
         self.ai_meshes[-1].set_collide_mask(mask)
         self.eng.phys_mgr.attach_ghost(ghost.node)
Example #3
0
 def __set_collision_mesh(self):
     fpath = self.cprops.race_props.coll_path % self.cprops.name
     try:
         self.coll_mesh = self.eng.load_model(fpath)
     except OSError:  # new cars don't have collision meshes
         self.coll_mesh = self.eng.load_model(
             fpath.replace('capsule', 'car'))
     # chassis_shape = BulletConvexHullShape()
     # for geom in self.eng.lib.find_geoms(
     #         self.coll_mesh, self.cprops.race_props.coll_name):
     #     chassis_shape.add_geom(geom.node().get_geom(0),
     #                            geom.get_transform())
     # self.mediator.gfx.nodepath.get_node().add_shape(chassis_shape)
     chassis_shape = BulletBoxShape(tuple(self.cfg['box_size']))
     boxpos = self.cfg['box_pos']
     boxpos[2] += self.cfg['center_mass_offset']
     pos = TransformState.makePos(tuple(boxpos))
     self.mediator.gfx.nodepath.p3dnode.add_shape(chassis_shape, pos)
     car_names = [player.car for player in self._players]
     car_idx = car_names.index(self.cprops.name)
     car_bit = BitMask32.bit(BitMasks.car(car_idx))
     ghost_bit = BitMask32.bit(BitMasks.ghost)
     track_bit = BitMask32.bit(BitMasks.track_merged)
     mask = car_bit | ghost_bit | track_bit
     self.mediator.gfx.nodepath.set_collide_mask(mask)
Example #4
0
 def makeNew(self, pos, nor, parent=None):
     """Makes a new bullet hole."""
     if parent == None:
         parent = self.container
     else:
         # Add a subnode to the parent, if it's not already there
         child = parent.find('bullet-holes')
         if child.isEmpty():
             parent = parent.attachNewNode('bullet-holes')
         else:
             parent = child
     newhole = NodePath(self.card.generate())
     newhole.reparentTo(parent)
     newhole.lookAt(render, Point3(newhole.getPos(render) - nor))
     newhole.setR(newhole, random() * 360.0)
     newhole.setPos(render, pos)
     # Offset it a little to avoid z-fighting
     # Increase this value if you still see it.
     newhole.setY(newhole, -.001 - random() * 0.01)
     del newhole
     # We don't want one batch per bullet hole, so flatten it.
     # This could be made smarter to preserve culling, but
     # I have yet to see a performance loss.
     # The clearTexture() is a necessary hack.
     parent.clearTexture()
     parent.flattenStrong()
     parent.setTexture(self.texture)
     parent.setTransparency(TransparencyAttrib.MDual)
     parent.setShaderOff(1)
     parent.hide(BitMask32.bit(
         2))  # Invisible to volumetric lighting camera (speedup)
     parent.hide(BitMask32.bit(3))  # Invisible to shadow cameras (speedup)
    def InitCollision(self):
        #
        ray = CollisionRay(0, 0, 5, 0, 0, -1)
        self.HeroC = self.Hero.attachNewNode(CollisionNode('cnode'))
        self.HeroC.node().addSolid(ray)
        self.HeroC.show()
        self.HeroC.node().setIntoCollideMask(BitMask32.allOff())
        self.HeroC.node().setFromCollideMask(BitMask32.bit(2))

        plane1 = CollisionPolygon(Point3(-10, -10, 0.1), Point3(-2, -10, 0.1),
                                  Point3(-2, 10, 0.1), Point3(-10, 10, 0.1))
        plane2 = CollisionPolygon(Point3(-2, -10, 0.1), Point3(1, -10, -0.9),
                                  Point3(1, 10, -0.9), Point3(-2, 10, 0.1))
        plane3 = CollisionPolygon(Point3(1, -10, -0.9), Point3(5, -10, -0.9),
                                  Point3(5, 10, -0.9), Point3(1, 10, -0.9))

        self.LevelCP = self.dummy.attachNewNode(CollisionNode('cnodeLevel'))
        self.LevelCP.node().addSolid(plane1)
        self.LevelCP.node().addSolid(plane2)
        self.LevelCP.node().addSolid(plane3)

        self.LevelCP.show()
        self.LevelCP.node().setIntoCollideMask(BitMask32.bit(2))

        self.Handlernya = CollisionHandlerQueue()
        # self.HandlerCS = CollisionHandlerEvent()
        # self.HandlerCS.addInPattern('into-g')
        traverser.addCollider(self.HeroC, self.Handlernya)
        # traverser.addCollider(self.HeroCS,self.HandlerCS)
        traverser.traverse(render)
Example #6
0
 def plot_eye_trace(self, first_eye):
     # print 'plot trace'
     # if plotting too many eye positions, things slow down and
     # python goes into lala land. Never need more than 500, and
     # last 300 is definitely plenty, so every time it hits 500,
     # get rid of first 200.
     if len(self.eye_nodes) > 500:
         # print('get rid of eye nodes', len(self.eye_nodes))
         # Since this just removes the node, but doesn't delete
         # the object in the list, can do this in a for loop,
         for index in range(200):
             self.eye_nodes[index].removeNode()
         # now get rid of the empty nodes in eye_nodes
         # print('new length', len(self.eye_nodes))
         self.eye_nodes = self.eye_nodes[200:]
         # print('new length', len(self.eye_nodes))
     eye = LineSegs()
     # eye.setThickness(2.0)
     eye.setThickness(2.0)
     # print 'last', last_eye
     # print 'now', self.current_eye_data
     eye.moveTo(first_eye[0], 55, first_eye[1])
     for data_point in self.current_eye_data:
         eye.drawTo(data_point[0], 55, data_point[1])
     # print('plotted eye', eye_data_to_plot)
     node = self.base.render.attachNewNode(eye.create(True))
     node.show(BitMask32.bit(0))
     node.hide(BitMask32.bit(1))
     self.eye_nodes.append(node)
Example #7
0
 def show_window(self, target_pos):
     # draw line around target representing how close the subject has to be looking to get reward
     # print('show window around square', square_pos)
     tolerance = self.plot_variables[
         self.text_dict['Tolerance']] / self.deg_per_pixel
     # print 'tolerance in pixels', tolerance
     # print 'square', square[0], square[2]
     eye_window = LineSegs()
     eye_window.setThickness(2.0)
     eye_window.setColor(1, 0, 0, 1)
     angle_radians = radians(360)
     for i in range(50):
         a = angle_radians * i / 49
         y = tolerance * sin(a)
         x = tolerance * cos(a)
         eye_window.drawTo((x + target_pos[0], 55, y + target_pos[1]))
     # draw a radius line
     # eye_window.moveTo(square[0], 55, square[2])
     # eye_window.drawTo(square[0], 55, square[2] + self.plot_variables[self.text_dict['Tolerance']])
     # print 'distance drawn', self.distance((square[0], square[2]), (square[0], square[2] + self.plot_variables[self.text_dict['Tolerance']]))
     # True optimizes the line segments, which sounds useful
     node = self.base.render.attachNewNode(eye_window.create(True))
     node.show(BitMask32.bit(0))
     node.hide(BitMask32.bit(1))
     self.eye_window.append(node)
    def __init__(self, cr):
        DistributedObject.__init__(self, cr)
        #self.model = loader.loadModel('environment')
        #self.model.setZ(0)
        #self.builder = Builder(self, "map.txt", "development")


        plane = CollisionPlane(Plane(Vec3(0, 0, 1), Point3(0, 0, 0)))
        cnode = CollisionNode('cnode')
        cnode.setIntoCollideMask(BitMask32.bit(1))
        cnode.setFromCollideMask(BitMask32.bit(1))
        cnode.addSolid(plane)
        self.planeNP = self.model.attachNewNode(cnode)
        self.planeNP.show()

        # Setup a traverser for the picking collisions
        self.picker = CollisionTraverser()
        # Setup mouse ray
        self.pq = CollisionHandlerQueue()
        # Create a collision Node
        pickerNode = CollisionNode('MouseRay')
        # set the nodes collision bitmask
        pickerNode.setFromCollideMask(BitMask32.bit(1))
        # create a collision ray
        self.pickerRay = CollisionRay()
        # add the ray as a solid to the picker node
        pickerNode.addSolid(self.pickerRay)
        # create a nodepath with the camera to the picker node
        self.pickerNP = base.camera.attachNewNode(pickerNode)
        # add the nodepath to the base traverser
        self.picker.addCollider(self.pickerNP, self.pq)

        print "model loaded"
        #TODO: check how to load multiple levels and set players in specific levels!
        self.accept("mouse1", self.mouseClick)
Example #9
0
    def __init__(self):
        self.initialize()
        self.WALLS = self.MAZE.find("**/Wall.004")
        self.WALLS.node().setIntoCollideMask(BitMask32.bit(0))
        # collision with the ground. different bit mask
        #self.mazeGround = self.maze.find("**/ground_collide")
        #self.mazeGround.node().setIntoCollideMask(BitMask32.bit(1))
        self.MAZEGROUND = self.MAZE.find("**/Cube.004")
        self.MAZEGROUND.node().setIntoCollideMask(BitMask32.bit(1))
        # add collision to the rock
        cs = CollisionSphere(0, 0, 0, 0.5)
        self.cnodePath = self.rock.attachNewNode(CollisionNode('cnode'))
        self.cnodePath.node().addSolid(cs)
        self.cnodePath.show()
        self.cnodePath.node().setIntoCollideMask(BitMask32.bit(0))
        # load the ball and attach it to the scene.
        # it is on a dummy node so that we can rotate the ball
        # without rotating the ray that will be attached to it

        # CollisionTraversers calculate collisions
        self.cTrav = CollisionTraverser()
        #self.cTrav.showCollisions(render)
        #self.cTrav.showCollisions(render)
        # A list collision handler queue
        self.cHandler = CollisionHandlerQueue()
        # add collision nodes to the traverse.
        # maximum nodes per traverser: 32
        self.cTrav.addCollider(self.ballSphere,self.cHandler)
        self.cTrav.addCollider(self.ballGroundColNp,self.cHandler)
        self.cTrav.addCollider(self.cnodePath, self.cHandler)
        # collision traversers have a built-in tool to visualize collisons
        #self.cTrav.showCollisions(render)
        self.start()
Example #10
0
    def setupCollisions(self):
        self.collTrav = CollisionTraverser()

        # rapid collisions detected using below plus FLUID pos
        self.collTrav.setRespectPrevTransform(True)

        self.playerGroundSphere = CollisionSphere(0, 1.5, -1.5, 1.5)
        self.playerGroundCol = CollisionNode('playerSphere')
        self.playerGroundCol.addSolid(self.playerGroundSphere)

        # bitmasks
        self.playerGroundCol.setFromCollideMask(BitMask32.bit(0))
        self.playerGroundCol.setIntoCollideMask(BitMask32.allOff())
        self.world.setGroundMask(BitMask32.bit(0))
        self.world.setWaterMask(BitMask32.bit(0))

        # and done
        self.playerGroundColNp = self.player.attach(self.playerGroundCol)
        self.playerGroundHandler = CollisionHandlerQueue()
        self.collTrav.addCollider(self.playerGroundColNp,
                                  self.playerGroundHandler)

        # DEBUG as per video:
        if (self.debug == True):
            self.playerGroundColNp.show()
            self.collTrav.showCollisions(self.render)
Example #11
0
 def bitmask(self):
     b_m = BitMask32.bit(BitMasks.general) | BitMask32.bit(BitMasks.track)
     car_names = [player.car for player in self.__players]
     cars_idx = list(range(len(car_names)))
     cars_idx.remove(car_names.index(self.mediator.name))
     for bitn in cars_idx: b_m = b_m | BitMask32.bit(BitMasks.car(bitn))
     return b_m
    def addRalph(self, pos):
        ralphStartPos = pos
        self.ralph = Actor("models/ralph",
                                 {"run":"models/ralph-run",
                                  "walk":"models/ralph-walk"})
        self.ralph.reparentTo(render)
        self.ralph.setScale(.2)
        self.ralph.setPos(ralphStartPos)
        self.cTrav = CollisionTraverser()

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

        self.camGroundRay = CollisionRay()
        self.camGroundRay.setOrigin(0,0,1000)
        self.camGroundRay.setDirection(0,0,-1)
        self.camGroundCol = CollisionNode('camRay')
        self.camGroundCol.addSolid(self.camGroundRay)
        self.camGroundCol.setFromCollideMask(BitMask32.bit(0))
        self.camGroundCol.setIntoCollideMask(BitMask32.allOff())
        self.camGroundColNp = base.camera.attachNewNode(self.camGroundCol)
        self.camGroundHandler = CollisionHandlerQueue()
        self.cTrav.addCollider(self.camGroundColNp, self.camGroundHandler)
Example #13
0
  def start(self):
    if self.bgColour!=None: base.setBackgroundColor(self.bgColour)

    if self.model!=None:
      self.model.show()
      self.model.hide(BitMask32.bit(1)) # Hide from the reflection camera
      self.model.hide(BitMask32.bit(2)) # Hide from the volumetric lighting camera
      self.model.hide(BitMask32.bit(3)) # Hide from the shadow camera(s), if any
Example #14
0
def _treeMe(level2Root, positions, uuids, geomCollide, center = None, side = None, radius = None, request_hash = b'Fake'):  # TODO in theory this could be multiprocessed
    """ Divide the space covered by all the objects into an oct tree and then
        replace cubes with 512 objects with spheres radius = (side**2 / 2)**.5
        for some reason this massively improves performance even w/o the code
        for mouse over adding and removing subsets of nodes.
    """

    num_points = len(positions)

    if center == None:  # branch predictor should take care of this?
        center = np.mean(positions, axis=0)
        radius = np.max(np.linalg.norm(positions - center))
        side = ((4/3) * radius**2) ** .5
        radius += 2

    if num_points <= 0:
        return False

    def nextLevel():
        bitmasks =  [ np.zeros_like(uuids,dtype=np.bool_) for _ in range(8) ]  # ICK there must be a better way of creating bitmasks

        partition = positions > center
        
        #the 8 conbinatorial cases
        for i in range(num_points):
            index = octit(partition[i])
            bitmasks[index][i] = True
        output = []
        for i in range(8):
            branch = bitmasks[i]  # this is where we can multiprocess
            new_center = center + TREE_LOGIC[i] * side * .5  #FIXME we pay a price here when we calculate the center of an empty node
            subSet = positions[branch]
            zap = treeMe(level2Root, subSet, uuids[branch], geomCollide[branch], new_center, side * .5, radius * .5)
            output.append(zap)

        return output

    #This method can also greatly accelerate the neighbor traversal because it reduces the total number of nodes needed
    if num_points < TREE_MAX_POINTS:  # this generates fewer nodes (faster) and the other vairant doesnt help w/ selection :(
        l2Node = level2Root.attachNewNode(CollisionNode("%s.%s"%(request_hash,center)))
        l2Node.node().addSolid(CollisionSphere(center[0],center[1],center[2],radius*2))
        l2Node.node().setIntoCollideMask(BitMask32.bit(BITMASK_COLL_MOUSE))
        #l2Node.show()

        for p,uuid,geom in zip(positions,uuids,geomCollide):
            childNode = l2Node.attachNewNode(CollisionNode("%s"%uuid))  #XXX TODO
            childNode.node().addSolid(CollisionSphere(p[0],p[1],p[2],geom)) # we do it this way because it keeps framerates WAY higher dont know why
            childNode.node().setIntoCollideMask(BitMask32.bit(BITMASK_COLL_CLICK))
            childNode.setPythonTag('uuid',uuid)
            #childNode.show()
        return True

        if num_points < 3:  # FIXME NOPE STILL get too deep recursion >_< and got it with a larger cutoff >_<
            #print("detect a branch with 1")
            return nextLevel()

    return nextLevel()
Example #15
0
    def setUpCamera(self):
        """ puts camera behind the player in third person """
        
        
        # Set up the camera
        # Adding the camera to actor is a simple way to keep the camera locked
        # in behind actor regardless of actor's movement.
        base.camera.reparentTo(self.actor)
        # We don't actually want to point the camera at actors's feet.
        # This value will serve as a vertical offset so we can look over the actor
        self.cameraTargetHeight = 0.5
        # How far should the camera be from the actor
        self.cameraDistance = 10
        # Initialize the pitch of the camera
        self.cameraPitch = 45
        
        # The mouse moves rotates the camera so lets get rid of the cursor
        props = WindowProperties()
        props.setCursorHidden(True)
        base.win.requestProperties(props)
        
        #set up FOV
        pl =  base.cam.node().getLens()
        pl.setFov(70)
        base.cam.node().setLens(pl)
        
        # A CollisionRay beginning above the camera and going down toward the
        # ground is used to detect camera collisions and the height of the
        # camera above the ground. A ray may hit the terrain, or it may hit a
        # rock or a tree.  If it hits the terrain, we detect the camera's
        # height.  If it hits anything else, the camera is in an illegal
        # position.
        """
TODO::        This will need to be changed to bullet
        """
        self.cTrav = CollisionTraverser()
        self.groundRay = CollisionRay()
        self.groundRay.setOrigin(0,0,1000)
        self.groundRay.setDirection(0,0,-1)
        self.groundCol = CollisionNode('camRay')
        self.groundCol.addSolid(self.groundRay)
        self.groundCol.setFromCollideMask(BitMask32.bit(1))
        self.groundCol.setIntoCollideMask(BitMask32.allOff())
        self.groundColNp = base.camera.attachNewNode(self.groundCol)
        self.groundHandler = CollisionHandlerQueue()
        self.cTrav.addCollider(self.groundColNp, self.groundHandler)
        
        # We will detect anything obstructing the camera's view of the player

        self.cameraRay = CollisionSegment((0,0,self.cameraTargetHeight),(0,5,5))
        self.cameraCol = CollisionNode('cameraRay')
        self.cameraCol.addSolid(self.cameraRay)
        self.cameraCol.setFromCollideMask(BitMask32.bit(0))
        self.cameraCol.setIntoCollideMask(BitMask32.allOff())
        self.cameraColNp = self.actor.attachNewNode(self.cameraCol)
        self.cameraColHandler = CollisionHandlerQueue()
        self.cTrav.addCollider(self.cameraColNp, self.cameraColHandler)
Example #16
0
 def __set_collision_mesh(self):
     fpath = self.props.coll_path % self.mdt.name
     self.coll_mesh = loader.loadModel(fpath)
     chassis_shape = BulletConvexHullShape()
     for geom in PhysMgr().find_geoms(self.coll_mesh, self.props.coll_name):
         chassis_shape.addGeom(geom.node().getGeom(0), geom.getTransform())
     self.mdt.gfx.nodepath.node().addShape(chassis_shape)
     self.mdt.gfx.nodepath.setCollideMask(
         BitMask32.bit(1)
         | BitMask32.bit(2 + self.props.cars.index(self.mdt.name)))
Example #17
0
 def setup_interactiongeometries(self):
     """
     set up collision rays, spheres, and planes for mouse manipulation
     :return: None
     author: weiwei
     date: 20161110
     """
     # create a trackball ray and set its bitmask to 8
     # the trackball ray must be a subnode of cam since we will
     # transform the clicked point (in the view of the cam) to the world coordinate system
     # using the ray
     self.tracker_cn = CollisionNode("tracker")
     self.tracker_ray = CollisionRay()
     self.tracker_cn.addSolid(self.tracker_ray)
     self.tracker_cn.setFromCollideMask(BitMask32.bit(8))
     self.tracker_cn.setIntoCollideMask(BitMask32.allOff())
     self.tracker_np = self.base.cam.attachNewNode(self.tracker_cn)
     # create an inverted collision sphere and puts it into a collision node
     # its bitmask is set to 8, and it will be the only collidable object at bit 8
     self.trackball_cn = CollisionNode("trackball")
     self.trackball_cn.addSolid(
         CollisionSphere(self.lookatpos_pdv3[0], self.lookatpos_pdv3[1],
                         self.lookatpos_pdv3[2], self.camdist))
     self.trackball_cn.setFromCollideMask(BitMask32.allOff())
     self.trackball_cn.setIntoCollideMask(BitMask32.bit(8))
     self.trackball_np = self.base.render.attachNewNode(self.trackball_cn)
     # self.trackball_np.show()
     # This creates a collision plane for mouse track
     self.trackplane_cn = CollisionNode("trackplane")
     self.trackplane_cn.addSolid(
         CollisionPlane(
             Plane(
                 Point3(-self.base.cam.getMat().getRow3(1)),
                 Point3(self.lookatpos_pdv3[0], self.lookatpos_pdv3[1],
                        0.0))))
     self.trackplane_cn.setFromCollideMask(BitMask32.allOff())
     self.trackplane_cn.setIntoCollideMask(BitMask32.bit(8))
     self.trackplane_np = self.base.render.attachNewNode(self.trackplane_cn)
     # self.trackplane_np.show()
     # creates a traverser to do collision testing
     self.ctrav = CollisionTraverser()
     # creates a queue type handler to receive the collision event info
     self.chandler = CollisionHandlerQueue()
     # register the ray as a collider with the traverser,
     # and register the handler queue as the handler to be used for the collisions.
     self.ctrav.addCollider(self.tracker_np, self.chandler)
     # create a pickerray
     self.picker_cn = CollisionNode('picker')
     self.picker_ray = CollisionRay()
     self.picker_cn.addSolid(self.picker_ray)
     self.picker_cn.setFromCollideMask(BitMask32.bit(7))
     self.picker_cn.setIntoCollideMask(BitMask32.allOff())
     self.picker_np = self.base.cam.attachNewNode(self.picker_cn)
     self.ctrav.addCollider(self.picker_np, self.chandler)
Example #18
0
 def __init__(self,
              parent_node_np: NodePath,
              num_lasers: int = 2,
              distance: float = 50,
              enable_show=False):
     super(SideDetector, self).__init__(parent_node_np, num_lasers,
                                        distance, enable_show)
     self.set_start_phase_offset(90)
     self.node_path.hide(CamMask.RgbCam | CamMask.Shadow | CamMask.Shadow
                         | CamMask.DepthCam)
     self.mask = BitMask32.bit(
         CollisionGroup.ContinuousLaneLine) | BitMask32.bit(
             CollisionGroup.BrokenLaneLine)
Example #19
0
    def __init__(self, _main):
        self.main = _main
        self.name = ""
        self.points = 0
        self.health = 100.0
        self.runSpeed = 1.8
        self.keyMap = {
            "left":False,
            "right":False,
            "up":False,
            "down":False
            }
        base.camera.setPos(0,0,0)
        self.model = loader.loadModel("Player")
        self.model.find('**/+SequenceNode').node().stop()
        self.model.find('**/+SequenceNode').node().pose(0)
        base.camera.setP(-90)
        self.playerHud = Hud()
        self.playerHud.hide()
        self.model.hide()

        # Weapons: size=2, 0=main, 1=offhand
        self.mountSlot = []
        self.activeWeapon = None
        self.isAutoActive = False
        self.trigger = False
        self.lastShot = 0.0
        self.fireRate = 0.0

        self.playerTraverser = CollisionTraverser()
        self.playerEH = CollisionHandlerEvent()
        ## INTO PATTERNS
        self.playerEH.addInPattern('intoPlayer-%in')
        #self.playerEH.addInPattern('colIn-%fn')
        self.playerEH.addInPattern('intoHeal-%in')
        self.playerEH.addInPattern('intoWeapon-%in')
        ## OUT PATTERNS
        self.playerEH.addOutPattern('outOfPlayer-%in')
        playerCNode = CollisionNode('playerSphere')
        playerCNode.setFromCollideMask(BitMask32.bit(1))
        playerCNode.setIntoCollideMask(BitMask32.bit(1))
        self.playerSphere = CollisionSphere(0, 0, 0, 0.6)
        playerCNode.addSolid(self.playerSphere)
        self.playerNP = self.model.attachNewNode(playerCNode)
        self.playerTraverser.addCollider(self.playerNP, self.playerEH)
        #self.playerNP.show()

        self.playerPusher = CollisionHandlerPusher()
        self.playerPusher.addCollider(self.playerNP, self.model)
        self.playerPushTraverser = CollisionTraverser()
        self.playerPushTraverser.addCollider(self.playerNP, self.playerPusher)
Example #20
0
 def handLoader(self):
     self.palm_R = self.loader.loadModel("%s/palm_R" % LOAD_HAND_FROM) # @UndefinedVariable
     self.palm_R_collider = self.palm_R.find("**/palm_R_collider")
     self.palm_R_collider.node().setIntoCollideMask(BitMask32.bit(0))
     self.fing_R = [self.loader.loadModel("%s/fing%i_R" % (LOAD_HAND_FROM, i+1)) for i in range(5)] # @UndefinedVariable
     self.midd_R = [self.loader.loadModel("%s/m%i_R"    % (LOAD_HAND_FROM, i+1)) for i in range(5)] # @UndefinedVariable
     self.base_R = [self.loader.loadModel("%s/b%i_R"    % (LOAD_HAND_FROM, i+1)) for i in range(5)] # @UndefinedVariable
     self.fing_R_collider = [self.fing_R[i].find("**/fing%i_R_collider" % (i+1)) for i in range(5)] # @UndefinedVariable
     self.midd_R_collider = [self.midd_R[i].find("**/m%i_R_collider" % (i+1)) for i in range(5)] # @UndefinedVariable
     self.base_R_collider = [self.base_R[i].find("**/b%i_R_collider" % (i+1)) for i in range(5)] # @UndefinedVariable
     self.palm_L = self.loader.loadModel("%s/palm_L" % LOAD_HAND_FROM) # @UndefinedVariable
     self.palm_R_collider = self.palm_L.find("**/palm_L_collider")
     self.palm_R_collider.node().setIntoCollideMask(BitMask32.bit(0))
     self.fing_L = [self.loader.loadModel("%s/fing%i_L" % (LOAD_HAND_FROM, i+1)) for i in range(5)] # @UndefinedVariable
     self.midd_L = [self.loader.loadModel("%s/m%i_L"    % (LOAD_HAND_FROM, i+1)) for i in range(5)] # @UndefinedVariable
     self.base_L = [self.loader.loadModel("%s/b%i_L"    % (LOAD_HAND_FROM, i+1)) for i in range(5)] # @UndefinedVariable
     self.fing_L_collider = [self.fing_L[i].find("**/fing%i_L_collider" % (i+1)) for i in range(5)] # @UndefinedVariable
     self.midd_L_collider = [self.midd_L[i].find("**/m%i_L_collider" % (i+1)) for i in range(5)] # @UndefinedVariable
     self.base_L_collider = [self.base_L[i].find("**/b%i_L_collider" % (i+1)) for i in range(5)] # @UndefinedVariable
     
     self.palm_R.setScale(self.handScale, self.handScale, self.handScale*1.5)
     self.palm_L.setScale(self.handScale, self.handScale, self.handScale*1.5)
     for f in self.fing_R: f.setScale(self.handScale, self.handScale*1.5, self.handScale*1.5)
     for f in self.midd_R: f.setScale(self.handScale, self.handScale*1.5, self.handScale*1.5)
     for f in self.base_R: f.setScale(self.handScale, self.handScale*1.5, self.handScale*1.5)
     for f in self.fing_L: f.setScale(self.handScale, self.handScale*1.5, self.handScale*1.5)
     for f in self.midd_L: f.setScale(self.handScale, self.handScale*1.5, self.handScale*1.5)
     for f in self.base_L: f.setScale(self.handScale, self.handScale*1.5, self.handScale*1.5)
     for f in self.fing_R_collider: f.node().setIntoCollideMask(BitMask32.bit(0))
     for f in self.midd_R_collider: f.node().setIntoCollideMask(BitMask32.bit(0))
     for f in self.base_R_collider: f.node().setIntoCollideMask(BitMask32.bit(0))
     for f in self.fing_L_collider: f.node().setIntoCollideMask(BitMask32.bit(0))
     for f in self.midd_L_collider: f.node().setIntoCollideMask(BitMask32.bit(0))
     for f in self.base_L_collider: f.node().setIntoCollideMask(BitMask32.bit(0))
Example #21
0
  def __init__(self,manager,xml):
    self.surface = getWaterSurface(manager)
    self.surface.reparentTo(render)
    self.surface.hide(BitMask32.bit(1)) # Invisible to reflection camera (speedup)
    self.surface.hide(BitMask32.bit(2)) # Invisible to volumetric lighting camera (speedup)
    self.surface.hide(BitMask32.bit(3)) # Invisible to shadow cameras (speedup)
    self.surface.setShader(loader.loadShader(manager.get('paths').getConfig().find('shaders').get('path')+'/water.cg'))
    self.surface.setShaderInput('time', 0.0, 0.0, 0.0, 0.0)
    ntex = loader.loadTexture(manager.get('paths').getConfig().find('textures').get('path')+'/water-normal.png')
    ntex.setMinfilter(Texture.FTLinearMipmapLinear)
    self.surface.setShaderInput('normal', ntex)
    self.surface.setShaderInput('camera', base.cam)
    self.surface.setTransparency(TransparencyAttrib.MDual, 10)
    self.surface.setTwoSided(True)

    self.surface.setShaderInput('waveInfo', Vec4(0.4, 0.4, 0.4, 0))
    self.surface.setShaderInput('param2', Vec4(-0.015,0.005, 0.05, 0.05))
    self.surface.setShaderInput('param3', Vec4(0.7, 0.3, 0, 0))
    self.surface.setShaderInput('param4', Vec4(2.0, 0.5, 0.5, 0.0))
    #self.surface.setShaderInput('speed', Vec4(-.8, -.4, -.9, .3))
    self.surface.setShaderInput('speed', Vec4(0.2, -1.2, -0.2, -0.7))
    self.surface.setShaderInput('deepcolor', Vec4(0.0,0.3,0.5,1.0))
    self.surface.setShaderInput('shallowcolor', Vec4(0.0,1.0,1.0,1.0))
    self.surface.setShaderInput('reflectioncolor', Vec4(0.95,1.0,1.0,1.0))
    self.surface.hide()

    self.wbuffer = base.win.makeTextureBuffer('water', 512, 512)
    self.wbuffer.setClearColorActive(True)
    self.wbuffer.setClearColor(base.win.getClearColor())
    self.wcamera = base.makeCamera(self.wbuffer)
    if manager.get('sky') != None and manager.get('sky').model != None:
      self.sky = manager.get('sky').model.copyTo(self.wcamera)
      self.sky.setTwoSided(True)
      self.sky.setSz(self.sky, -1)
      self.sky.setClipPlaneOff(1)
      self.sky.show()
      self.sky.hide(BitMask32.bit(0)) # Hide for normal camera
      self.sky.hide(BitMask32.bit(2)) # Hide for volumetric lighting camera
      self.sky.hide(BitMask32.bit(3)) # Hide for shadow camera(s), if any
    else:
      self.sky = None
    self.wcamera.reparentTo(render)
    self.wcamera.node().setLens(base.camLens)
    self.wcamera.node().setCameraMask(BitMask32.bit(1))
    self.surface.hide(BitMask32.bit(1))
    wtexture = self.wbuffer.getTexture()
    wtexture.setWrapU(Texture.WMClamp)
    wtexture.setWrapV(Texture.WMClamp)
    wtexture.setMinfilter(Texture.FTLinearMipmapLinear)
    self.surface.setShaderInput('reflection', wtexture)
    self.wplane = Plane(Vec3(0, 0, 1), Point3(0, 0, 0))
    self.wplanenp = render.attachNewNode(PlaneNode('water', self.wplane))
    tmpnp = NodePath('StateInitializer')
    tmpnp.setClipPlane(self.wplanenp)
    tmpnp.setAttrib(CullFaceAttrib.makeReverse())
    self.wcamera.node().setInitialState(tmpnp.getState())

    #self.fog = Fog('UnderwaterFog')
    #self.fog.setColor(0.0,0.3,0.5)
    self.fogEnabled = False
Example #22
0
    def _add_chassis(self, pg_physics_world: PGPhysicsWorld):
        para = self.get_config()
        self.LENGTH = self.vehicle_config["vehicle_length"]
        self.WIDTH = self.vehicle_config["vehicle_width"]
        chassis = BaseVehicleNode(BodyName.Base_vehicle, self)
        chassis.setIntoCollideMask(BitMask32.bit(CollisionGroup.EgoVehicle))
        chassis_shape = BulletBoxShape(
            Vec3(self.WIDTH / 2, self.LENGTH / 2,
                 para[Parameter.vehicle_height] / 2))
        ts = TransformState.makePos(
            Vec3(0, 0, para[Parameter.chassis_height] * 2))
        chassis.addShape(chassis_shape, ts)
        heading = np.deg2rad(-para[Parameter.heading] - 90)
        chassis.setMass(para[Parameter.mass])
        self.chassis_np = self.node_path.attachNewNode(chassis)
        # not random spawn now
        self.chassis_np.setPos(Vec3(*self.spawn_place, 1))
        self.chassis_np.setQuat(
            LQuaternionf(math.cos(heading / 2), 0, 0, math.sin(heading / 2)))
        chassis.setDeactivationEnabled(False)
        chassis.notifyCollisions(
            True
        )  # advance collision check, do callback in pg_collision_callback
        self.dynamic_nodes.append(chassis)

        chassis_beneath = BulletGhostNode(BodyName.Base_vehicle_beneath)
        chassis_beneath.setIntoCollideMask(
            BitMask32.bit(CollisionGroup.EgoVehicleBeneath))
        chassis_beneath.addShape(chassis_shape)
        self.chassis_beneath_np = self.chassis_np.attachNewNode(
            chassis_beneath)
        self.dynamic_nodes.append(chassis_beneath)

        self.system = BulletVehicle(pg_physics_world.dynamic_world, chassis)
        self.system.setCoordinateSystem(ZUp)
        self.dynamic_nodes.append(
            self.system
        )  # detach chassis will also detach system, so a waring will generate

        if self.render:
            if self.MODEL is None:
                model_path = 'models/ferra/scene.gltf'
                self.MODEL = self.loader.loadModel(
                    AssetLoader.file_path(model_path))
                self.MODEL.setZ(para[Parameter.vehicle_vis_z])
                self.MODEL.setY(para[Parameter.vehicle_vis_y])
                self.MODEL.setH(para[Parameter.vehicle_vis_h])
                self.MODEL.set_scale(para[Parameter.vehicle_vis_scale])
            self.MODEL.instanceTo(self.chassis_np)
Example #23
0
 def fire(self):
     WeaponPhys.fire(self)
     b_m = BitMask32.bit(BitMasks.general)
     car_names = [player.car for player in self._players]
     cars_idx = list(range(len(car_names)))
     cars_idx.remove(car_names.index(self.car.name))
     for bitn in cars_idx:
         b_m = b_m | BitMask32.bit(BitMasks.car(bitn))
     self.n_p.set_collide_mask(b_m)
     self.eng.phys_mgr.add_collision_obj(self.node)
     self.node.set_python_tag('car', self.mediator.logic.car)
     self.rot_mat = Mat4()
     rot_deg = self.parent.h + self.rot_deg
     self.rot_mat.set_rotate_mat(rot_deg, (0, 0, 1))
     self.update_tsk = taskMgr.add(self.update_weapon, 'update_weapon')
Example #24
0
 def setup_text(self, name, text_frag, position):
     text_node = TextNode(name)
     if not text_frag:
         text_node.setText(name)
     elif name == 'Tolerance':
         # always start in manual, so tolerance meaningless
         text_node.setText('')
     else:
         text_node.setText(name + ': ' + str(text_frag))
     text_node_path = self.base.render.attach_new_node(text_node)
     text_node_path.setScale(25)
     text_node_path.setPos(position)
     text_node_path.show(BitMask32.bit(0))
     text_node_path.hide(BitMask32.bit(1))
     return text_node
Example #25
0
    def _add_chassis(self, pg_physics_world: PGPhysicsWorld):
        para = self.get_config()
        chassis = BulletRigidBodyNode(BodyName.Ego_vehicle_top)
        chassis.setIntoCollideMask(BitMask32.bit(self.COLLISION_MASK))
        chassis_shape = BulletBoxShape(
            Vec3(para[Parameter.vehicle_width] / 2,
                 para[Parameter.vehicle_length] / 2,
                 para[Parameter.vehicle_height] / 2))
        ts = TransformState.makePos(
            Vec3(0, 0, para[Parameter.chassis_height] * 2))
        chassis.addShape(chassis_shape, ts)
        heading = np.deg2rad(-para[Parameter.heading] - 90)
        chassis.setMass(para[Parameter.mass])
        self.chassis_np = self.node_path.attachNewNode(chassis)
        # not random born now
        self.chassis_np.setPos(Vec3(*self.born_place, 1))
        self.chassis_np.setQuat(
            LQuaternionf(np.cos(heading / 2), 0, 0, np.sin(heading / 2)))
        chassis.setDeactivationEnabled(False)
        chassis.notifyCollisions(True)  # advance collision check
        self.pg_world.physics_world.dynamic_world.setContactAddedCallback(
            PythonCallbackObject(self._collision_check))
        self.dynamic_nodes.append(chassis)

        chassis_beneath = BulletGhostNode(BodyName.Ego_vehicle)
        chassis_beneath.setIntoCollideMask(BitMask32.bit(self.COLLISION_MASK))
        chassis_beneath.addShape(chassis_shape)
        self.chassis_beneath_np = self.chassis_np.attachNewNode(
            chassis_beneath)
        self.dynamic_nodes.append(chassis_beneath)

        self.system = BulletVehicle(pg_physics_world.dynamic_world, chassis)
        self.system.setCoordinateSystem(ZUp)
        self.dynamic_nodes.append(
            self.system
        )  # detach chassis will also detach system, so a waring will generate
        self.LENGTH = para[Parameter.vehicle_length]
        self.WIDTH = para[Parameter.vehicle_width]

        if self.render:
            model_path = 'models/ferra/scene.gltf'
            self.chassis_vis = self.loader.loadModel(
                AssetLoader.file_path(model_path))
            self.chassis_vis.setZ(para[Parameter.vehicle_vis_z])
            self.chassis_vis.setY(para[Parameter.vehicle_vis_y])
            self.chassis_vis.setH(para[Parameter.vehicle_vis_h])
            self.chassis_vis.set_scale(para[Parameter.vehicle_vis_scale])
            self.chassis_vis.reparentTo(self.chassis_np)
Example #26
0
    def create_object(self):
        from panda3d.core import Filename, NodePath, BitMask32
        from direct.actor.Actor import Actor
        from panda3d.bullet import BulletRigidBodyNode, BulletCapsuleShape

        from game_system.resources import ResourceManager
        f = Filename.fromOsSpecific(ResourceManager.get_absolute_path(ResourceManager["TestAI"]["lp_char_bs.egg"]))
        model = Actor(f)

        bullet_node = BulletRigidBodyNode("TestAIBulletNode")
        bullet_nodepath = NodePath(bullet_node)

        bullet_node.set_angular_factor((0, 0, 1))

        shape = BulletCapsuleShape(0.3, 1.4, 2)
        bullet_node.addShape(shape)
        bullet_node.setMass(1.0)

        model.reparentTo(bullet_nodepath)
        model.set_hpr(180, 0, 0)
        model.set_pos(0, 0, -1)

        bullet_nodepath.set_collide_mask(BitMask32.bit(0))
        bullet_nodepath.set_python_tag("actor", model)

        return bullet_nodepath
Example #27
0
    def initMouseFields(showBase):
        if Utils.NEW_CN is None:
            Utils.NEW_CN = showBase.camera.attachNewNode(Utils.CN)
            Utils.CN.setFromCollideMask(BitMask32.bit(1))

            Utils.CN.addSolid(Utils.CR)
            Utils.CT.addCollider(Utils.NEW_CN, Utils.CHQ)
Example #28
0
    def _add_side_walk2bullet(self, lane_start, lane_end, middle, radius=0.0, direction=0):
        length = norm(lane_end[0] - lane_start[0], lane_end[1] - lane_start[1])
        body_node = BulletRigidBodyNode(BodyName.Side_walk)
        body_node.setActive(False)
        body_node.setKinematic(False)
        body_node.setStatic(True)
        side_np = self.side_walk_node_path.attachNewNode(body_node)
        shape = BulletBoxShape(Vec3(1 / 2, 1 / 2, 1 / 2))
        body_node.addShape(shape)
        body_node.setIntoCollideMask(BitMask32.bit(Block.LANE_LINE_COLLISION_MASK))
        self.dynamic_nodes.append(body_node)

        if radius == 0:
            factor = 1
        else:
            if direction == 1:
                factor = (1 - self.SIDE_WALK_LINE_DIST / radius)
            else:
                factor = (1 + self.SIDE_WALK_WIDTH / radius) * (1 + self.SIDE_WALK_LINE_DIST / radius)
        direction_v = lane_end - lane_start
        vertical_v = (-direction_v[1], direction_v[0]) / numpy.linalg.norm(direction_v)
        middle += vertical_v * (self.SIDE_WALK_WIDTH / 2 + self.SIDE_WALK_LINE_DIST)
        side_np.setPos(panda_position(middle, 0))
        theta = -numpy.arctan2(direction_v[1], direction_v[0])
        side_np.setQuat(LQuaternionf(numpy.cos(theta / 2), 0, 0, numpy.sin(theta / 2)))
        side_np.setScale(
            length * factor, self.SIDE_WALK_WIDTH, self.SIDE_WALK_THICKNESS * (1 + 0.1 * numpy.random.rand())
        )
        if self.render:
            side_np.setTexture(self.ts_color, self.side_texture)
            self.side_walk.instanceTo(side_np)
Example #29
0
    def __init__(self, world, pos, hpr):
        super(Flame, self).__init__()

        self.shape = BulletBoxShape(Vec3(0.1,0.05,0.05))
        self.bnode = BulletRigidBodyNode()
        self.bnode.setMass(1.0)
        self.bnode.addShape(self.shape)

        self.np = utilities.app.render.attachNewNode(self.bnode)

        self.world =world 
        self.anim = list()
        self.anim.append(utilities.loadObject("flame1", depth=0))
        self.anim.append(utilities.loadObject("flame2", depth=0))
        self.anim.append(utilities.loadObject("flame3", depth=0))
        world.bw.attachRigidBody(self.bnode)

        self.curspr = 0
        self.obj = self.anim[self.curspr]
        self.obj.show() 
        self.livetime = 0
        self.delta = 0

        self.pos = pos
        self.pos.y = Flame.depth
        #self.pos.z -= 0.2 
        self.hpr = hpr
        self.vel = Point2()
        self.vel.x = cos(world.player.angle)*Flame.speed
        self.vel.y = sin(world.player.angle)*Flame.speed

        tv = Vec3(self.vel.x, 0, self.vel.y)
        # this makes the shot miss the target if the player has any velocity
        tv += world.player.bnode.getLinearVelocity()

        self.bnode.setLinearVelocity(tv)

        tv.normalize()

        # initial position of RB and draw plane
        self.np.setHpr(hpr)
        self.np.setPos(pos+tv/2)

        self.bnode.setAngularFactor(Vec3(0,0,0))
        self.bnode.setLinearFactor(Vec3(1,0,1))
        self.bnode.setGravity(Vec3(0,0,0))

        self.bnode.setCcdMotionThreshold(1e-7)
        self.bnode.setCcdSweptSphereRadius(0.10)

        self.bnode.notifyCollisions(True)
        self.bnode.setIntoCollideMask(BitMask32.bit(1))
        self.bnode.setPythonTag("Entity", self)
        self.noCollideFrames = 4

        for a in self.anim:
            a.hide()
            a.reparentTo(self.np)
            a.setScale(0.25, 1, 0.25)
            a.setPos(0, -0.1,0)
Example #30
0
 def __init__(self):
     self.shadowBuffer = base.win.makeTextureBuffer('Shadow Buffer', 2048,
                                                    2048)
     self.shadowBuffer.setClearColorActive(True)
     self.shadowBuffer.setClearColor((0, 0, 0, 1))
     self.shadowCamera = base.makeCamera(self.shadowBuffer)
     self.shadowCamera.reparentTo(render)
     self.lens = base.camLens
     self.lens.setAspectRatio(1 / 1)
     self.shadowCamera.node().setLens(self.lens)
     self.shadowCamera.node().setCameraMask(BitMask32.bit(1))
     self.initial = NodePath('initial')
     self.initial.setColor(0.75, 0.75, 0.75, 1, 1)
     self.initial.setTextureOff(2)
     self.initial.setMaterialOff(2)
     self.initial.setLightOff(2)
     self.shadowCamera.node().setInitialState(self.initial.getState())
     self.shadowCamera.setPos(-10, 0, 20)
     self.shadowCamera.lookAt(0, 0, 0)
     self.filters = CommonFilters(self.shadowBuffer, self.shadowCamera)
     self.filters.setBlurSharpen(0.1)
     self.shadowTexture = self.shadowBuffer.getTexture()
     self.imageObject = OnscreenImage(image=self.shadowTexture,
                                      pos=(-0.75, 0, 0.75),
                                      scale=0.2)
Example #31
0
    def perceive(self, vehicle_position, heading_theta, pg_physics_world: PGPhysicsWorld):
        """
        Call me to update the perception info
        """
        # coordinates problem here! take care
        pg_start_position = panda_position(vehicle_position, 1.0)
        self.detection_results = []

        # lidar calculation use pg coordinates
        mask = BitMask32.bit(PGTrafficVehicle.COLLISION_MASK)
        laser_heading = np.arange(0, self.laser_num) * self.radian_unit + heading_theta
        point_x = self.perceive_distance * np.cos(laser_heading) + vehicle_position[0]
        point_y = self.perceive_distance * np.sin(laser_heading) + vehicle_position[1]
        # ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
        for laser_index in range(self.laser_num):
            # # coordinates problem here! take care
            laser_end = panda_position((point_x[laser_index], point_y[laser_index]), 1.0)
            result = pg_physics_world.dynamic_world.rayTestClosest(pg_start_position, laser_end, mask)
            self.detection_results.append(result)
            if self.cloud_points is not None:
                if result.hasHit():
                    curpos = result.getHitPos()
                else:
                    curpos = laser_end
                self.cloud_points[laser_index].setPos(curpos)
Example #32
0
 def __init__(self, n=9999, bins=9, show=False):
     collideRoot = render.attachNewNode('collideRoot')
     bases = [
         np.cumsum(np.random.randint(-1, 2, (n, 3)), axis=0)
         for i in range(bins)
     ]
     type_ = GeomPoints
     runs = []
     for base in bases:
         runs.append(smipleMake(index_counter, base, type_))
     r = 0
     for nodes in runs:
         #pos = np.random.randint(-100,100,3)
         print(nodes)
         node, _ = nodes()
         nd = render.attachNewNode(node)
         #nd.setPos(*pos)
         #nd.setRenderModeThickness(5)
         #XXX TODO XXX collision objects
         n = 0
         for position in bases[
                 r]:  #FIXME this is hella slow, the correct way to do this is to detach and reattach CollisionNodes as they are needed...
             #TODO to change the color of a selected node we will need something a bit more ... sophisticated
             cNode = collideRoot.attachNewNode(
                 CollisionNode('collider obj,vert %s,%s' %
                               (r, n)))  #ultimately used to index??
             cNode.node().addSolid(CollisionSphere(0, 0, 0, .5))
             cNode.node().setIntoCollideMask(
                 BitMask32.bit(BITMASK_COLL_CLICK))
             cNode.setPos(nd, *position)
             if show:
                 cNode.show()
             n += 1
         r += 1
     embed()
Example #33
0
    def __initSceneGraph(self):
        
        self.point_path = self.host_planet.point_path.attachNewNode("unit_center_node")
        self.model_path = self.point_path.attachNewNode("unit_node")
        self.model_path.reparentTo(self.point_path)
        self.model_path.setPos(Vec3(0,6,0))
        
        self.model_path.setPythonTag('pyUnit', self)
        
        rad = 1
        cnode = CollisionNode("coll_sphere_node")
        cnode.addSolid(CollisionBox(Point3(-rad,-rad,-rad),Point3(rad,rad,rad)))
        cnode.setIntoCollideMask(BitMask32.bit(1))
        cnode.setTag('unit', str(id(self)))
        self.cnode_path = self.model_path.attachNewNode(cnode)
        #self.cnode_path.show()
        
        tex = loader.loadTexture("models/billboards/flare.png")
        cm = CardMaker('quad')
        cm.setFrameFullscreenQuad()
        self.quad_path = self.model_path.attachNewNode(cm.generate())
        self.quad_path.setTexture(tex)
        self.quad_path.setTransparency(TransparencyAttrib.MAlpha)
        self.quad_path.setBillboardPointEye()

        self.quad_path.setColor(self.player.color)
Example #34
0
    def __init__(self, world):
        super(Player, self).__init__()

        self.obj = utilities.loadObject("player", depth=20)

        self.world = world 
        self.health = 100
        self.inventory = dict()

        self.depth = self.obj.getPos().y

        self.location = Point2(0,0)
        self.velocity = Vec3(0)
        self.pt = 0.0

        self.shape = BulletBoxShape(Vec3(0.3, 1.0, 0.49))
        self.bnode = BulletRigidBodyNode('Box')
        self.bnode.setMass(1.0)
        self.bnode.setAngularVelocity(Vec3(0))
        self.bnode.setAngularFactor(Vec3(0))
        self.bnode.addShape(self.shape)
        self.bnode.setLinearDamping(0.95)
        self.bnode.setLinearSleepThreshold(0)

        world.bw.attachRigidBody(self.bnode)
        self.bnode.setPythonTag("Entity", self)
        self.bnode.setIntoCollideMask(BitMask32.bit(0))

        self.node = utilities.app.render.attachNewNode(self.bnode)
        self.node.setPos(self.obj.getPos())

        self.obj.setPos(0,0,0)
        self.obj.setScale(1)
        self.obj.reparentTo(self.node)
        self.node.setPos(self.location.x, self.depth, self.location.y)
Example #35
0
    def __init__(self, render, objid, start_pos, gameclient):
        self.client = gameclient
        self.id = objid
        self.motion_controller = None
        self.is_player = False

        # state  management
        self.isAnimating = False
        self.state = state.IDLE

        self.render = render  # scene graph root

        #  create the panda3d actor: just load a default model for now
        self.actor = Actor("models/ralph", {
            "run": "models/ralph-run",
            "walk": "models/ralph-walk"
        })

        self.actor.reparentTo(render)
        self.actor.setScale(.2)
        self.actor.setPos(start_pos)

        # prepare collision handling
        self.cTrav = CollisionTraverser()
        self.GroundRay = CollisionRay()
        self.GroundRay.setOrigin(0, 0, 1000)
        self.GroundRay.setDirection(0, 0, -1)
        self.GroundCol = CollisionNode('actorRay')
        self.GroundCol.addSolid(self.GroundRay)
        self.GroundCol.setFromCollideMask(BitMask32.bit(0))
        self.GroundCol.setIntoCollideMask(BitMask32.allOff())
        self.GroundColNp = self.actor.attachNewNode(self.GroundCol)
        self.GroundHandler = CollisionHandlerQueue()
        self.cTrav.addCollider(self.GroundColNp, self.GroundHandler)
Example #36
0
	def __init__(self, render, player):
		self.username = player.getUsername()
		self.isMoving = False
		self.render = render

		self.keyMap = {"left":0, "right":0, "forward":0, "cam-left":0, "cam-right":0}

		#self.actor = Actor("models/ralph", {"run":"models/ralph-run", "walk":"models/ralph-walk"})
		self.actor = Actor("models/panda-model",
                                {"walk": "models/panda-walk4"})
		self.actor.reparentTo(render)
		self.actor.setScale(0.002, 0.002, 0.002)
		self.actor.setPos(player.getX(), player.getY(), player.getZ())
		self.actor.setH(player.getH())	
		
		#self.actor.loop("walk")
		
		self.cTrav = CollisionTraverser()
		self.GroundRay = CollisionRay()
		self.GroundRay.setOrigin(0,0,1000)
		self.GroundRay.setDirection(0,0,-1)
		self.GroundCol = CollisionNode('actorRay')
		self.GroundCol.addSolid(self.GroundRay)
		self.GroundCol.setFromCollideMask(BitMask32.bit(0))
		self.GroundCol.setIntoCollideMask(BitMask32.allOff())
		self.GroundColNp = self.actor.attachNewNode(self.GroundCol)
		self.GroundHandler = CollisionHandlerQueue()
		self.cTrav.addCollider(self.GroundColNp, self.GroundHandler)
    def init_nodes_to_chsess_board(self):
        self.squareRoot = self.render_fsm_ref.render.attachNewNode(
            "squareRoot")
        # For each square
        for i in range(64):
            # Load, parent, color, and position the model (a single square
            # polygon)
            self.squares[i] = loader.loadModel(
                "ChessRender/data/chess_board/square")
            #self.squares[i].setTexture(self.SquareTexture(i))
            self.squares[i].reparentTo(self.squareRoot)
            self.squares[i].setPos(self.SquareUnderCubePos3D(i))
            #self.squares[i].setColor(self.SquareColor(i))

            self.cubes[i] = self.objMngr.load_cube()
            self.cubes[i].setColor(self.SquareColor(i))
            self.cubes[i].reparentTo(self.squareRoot)
            self.cubes[i].setPos(self.SquarePos(i))
            self.cubes[i].setScale(0.5)

            #self.cubes[i].setShaderAuto()

            self.cubes[i].setColor(self.SquareColor(i))
            self.cubes[i].setTexture(self.SquareTexture(i))

            # Set the model itself to be collideable with the ray. If this model was
            # any more complex than a single polygon, you should set up a collision
            # sphere around it instead. But for single polygons this works
            # fine.
            self.squares[i].find("**/polygon").node().setIntoCollideMask(
                BitMask32.bit(1))
            # Set a tag on the square's node so we can look up what square this is
            # later during the collision pass
            self.squares[i].find("**/polygon").node().setTag('square', str(i))
Example #38
0
    def __init__(self, location, player, cmap, world):
        super(Catcher, self).__init__(location)
        self.player = player
        self.cmap = cmap

        self.obj = utilities.loadObject("robot", depth=20)

        self.world = world 
        self.health = 100

        self.depth = self.obj.getPos().y

        self.location = location 
        self.velocity = Vec3(0)

        self.shape = BulletBoxShape(Vec3(0.5, 1.0, 0.5))
        self.bnode = BulletRigidBodyNode('Box')
        self.bnode.setMass(0.1)
        self.bnode.setAngularVelocity(Vec3(0))
        self.bnode.setAngularFactor(Vec3(0))
        self.bnode.addShape(self.shape)
        self.bnode.setLinearDamping(0.75)
        self.bnode.setLinearSleepThreshold(0)

        world.bw.attachRigidBody(self.bnode)
        self.bnode.setPythonTag("entity", self)
        self.bnode.setIntoCollideMask(BitMask32.bit(0))

        self.node = utilities.app.render.attachNewNode(self.bnode)
        self.node.setPos(self.obj.getPos())

        self.obj.setPos(0,0,0)
        self.obj.setScale(1)
        self.obj.reparentTo(self.node)
        self.node.setPos(self.location.x, self.depth, self.location.y)
    def create(self):
        # Create voxelize camera
        self.voxelizeCamera = Camera("VoxelizeCamera")
        self.voxelizeCamera.setCameraMask(BitMask32.bit(4))
        self.voxelizeCameraNode = Globals.render.attachNewNode(self.voxelizeCamera)
        self.voxelizeLens = OrthographicLens()
        self.voxelizeLens.setFilmSize(self.voxelGridSize * 2, self.voxelGridSize * 2)
        self.voxelizeLens.setNearFar(0.0, self.voxelGridSize * 2)
        self.voxelizeCamera.setLens(self.voxelizeLens)
        self.voxelizeCamera.setTagStateKey("VoxelizePassShader")
        Globals.render.setTag("VoxelizePassShader", "Default")

        # Create voxelize tareet
        self.target = RenderTarget("VoxelizePass")
        self.target.setSize(self.voxelGridResolution * self.gridResolutionMultiplier)

        if self.pipeline.settings.useDebugAttachments:
            self.target.addColorTexture()
        else:
            self.target.setColorWrite(False)

        self.target.setCreateOverlayQuad(False)
        self.target.setSource(self.voxelizeCameraNode, Globals.base.win)
        self.target.prepareSceneRender()
        self.target.setActive(False)
Example #40
0
 def placeItem(self, item):
     # Add ground collision detector to the health item
     self.collectGroundRay = CollisionRay()
     self.collectGroundRay.setOrigin(0,0,300)
     self.collectGroundRay.setDirection(0,0,-1)
     self.collectGroundCol = CollisionNode('colRay')
     self.collectGroundCol.addSolid(self.collectGroundRay)
     self.collectGroundCol.setFromCollideMask(BitMask32.bit(0))
     self.collectGroundCol.setIntoCollideMask(BitMask32.allOff())
     self.collectGroundColNp = item.attachNewNode(self.collectGroundCol)
     self.collectGroundHandler = CollisionHandlerQueue()
     base.cTrav.addCollider(self.collectGroundColNp, self.collectGroundHandler)
     
     placed = False;
     while placed == False:
         # re-randomize position
         item.setPos(-random.randint(0,140),-random.randint(0,40),0)
         
         base.cTrav.traverse(render)
         
         # Get Z position from terrain collision
         entries = []
         for j in range(self.collectGroundHandler.getNumEntries()):
             entry = self.collectGroundHandler.getEntry(j)
             entries.append(entry)
         entries.sort(lambda x,y: cmp(y.getSurfacePoint(render).getZ(),
                                      x.getSurfacePoint(render).getZ()))
     
         if (len(entries)>0) and (entries[0].getIntoNode().getName() == "terrain"):
             item.setZ(entries[0].getSurfacePoint(render).getZ()+1)
             placed = True
             
     # remove placement collider
     self.collectGroundColNp.removeNode()
Example #41
0
    def __init__(self, fulcrum, terrain):
        TerrainCamera.__init__(self)

        self.terrain = terrain
        self.fulcrum = fulcrum
        # in behind Ralph regardless of ralph's movement.
        self.camNode.reparentTo(fulcrum)
        # How far should the camera be from Ralph
        self.cameraDistance = 30
        # Initialize the pitch of the camera
        self.cameraPitch = 10
        self.focus = self.fulcrum.attachNewNode("focus")

        self.maxDistance = 500.0
        self.minDistance = 2
        self.maxPitch = 80
        self.minPitch = -70

        # We will detect the height of the terrain by creating a collision
        # ray and casting it downward toward the terrain.  One ray will
        # start above ralph's head.
        # A ray may hit the terrain, or it may hit a rock or a tree.  If it
        # hits the terrain, we can detect the height.  If it hits anything
        # else, we rule that the move is illegal.
        self.cTrav = CollisionTraverser()
        self.cameraRay = CollisionSegment(self.fulcrum.getPos(), (0, 5, 5))
        self.cameraCol = CollisionNode('cameraRay')
        self.cameraCol.addSolid(self.cameraRay)
        self.cameraCol.setFromCollideMask(BitMask32.bit(0))
        self.cameraCol.setIntoCollideMask(BitMask32.allOff())
        self.cameraColNp = self.fulcrum.attachNewNode(self.cameraCol)
        self.cameraColHandler = CollisionHandlerQueue()
        self.cTrav.addCollider(self.cameraColNp, self.cameraColHandler)
Example #42
0
    def __init__(self, render, objid, start_pos, gameclient):
        self.client = gameclient
        self.id = objid
        self.motion_controller = None
        self.is_player = False
        
        # state  management
        self.isAnimating = False
        self.state = state.IDLE
        
        self.render = render    # scene graph root
        
        #  create the panda3d actor: just load a default model for now
        self.actor = Actor("models/ralph",
                            {"run":"models/ralph-run",
                             "walk":"models/ralph-walk"})
                             
        self.actor.reparentTo(render)
        self.actor.setScale(.2)
        self.actor.setPos(start_pos)

        # prepare collision handling
        self.cTrav = CollisionTraverser()
        self.GroundRay = CollisionRay()
        self.GroundRay.setOrigin(0,0,1000)
        self.GroundRay.setDirection(0,0,-1)
        self.GroundCol = CollisionNode('actorRay')
        self.GroundCol.addSolid(self.GroundRay)
        self.GroundCol.setFromCollideMask(BitMask32.bit(0))
        self.GroundCol.setIntoCollideMask(BitMask32.allOff())
        self.GroundColNp = self.actor.attachNewNode(self.GroundCol)
        self.GroundHandler = CollisionHandlerQueue()
        self.cTrav.addCollider(self.GroundColNp, self.GroundHandler)
Example #43
0
 def __init__(self,n=9999,bins=9,show=False):
     collideRoot = render.attachNewNode('collideRoot')
     bases = [np.cumsum(np.random.randint(-1,2,(n,3)),axis=0) for i in range(bins)]
     type_ = GeomPoints
     runs = []
     for base in bases:
         runs.append(smipleMake(index_counter,base,type_))
     r = 0
     for nodes in runs:
         #pos = np.random.randint(-100,100,3)
         print(nodes)
         node,_ = nodes()
         nd = render.attachNewNode(node)
         #nd.setPos(*pos)
         #nd.setRenderModeThickness(5)
         #XXX TODO XXX collision objects
         n = 0 
         for position in bases[r]: #FIXME this is hella slow, the correct way to do this is to detach and reattach CollisionNodes as they are needed...
             #TODO to change the color of a selected node we will need something a bit more ... sophisticated
             cNode = collideRoot.attachNewNode(CollisionNode('collider obj,vert %s,%s'%(r,n))) #ultimately used to index??
             cNode.node().addSolid(CollisionSphere(0,0,0,.5))
             cNode.node().setIntoCollideMask(BitMask32.bit(BITMASK_COLL_CLICK))
             cNode.setPos(nd,*position)
             if show:
                 cNode.show()
             n+=1
         r+=1
     embed()
Example #44
0
            
    def placeCollectibles(self):
        self.placeCol = render.attachNewNode("Collectible-Placeholder")
        self.placeCol.setPos(0,0,0)
        
        # Add the health items to the placeCol node
        for i in range(self.numObjects):
            # Load in the health item model
            self.collect = loader.loadModel("models/trex")
            self.collect.setPos(0,0,0)
            self.collect.reparentTo(self.placeCol)
	    self.collect.setScale(0.1)
	    self.tex3= loader.loadTexture("models/Face.jpg")
	    self.collect.setTexture(self.tex3,1)
            
            self.placeItem(self.collect)
            
            # Add spherical collision detection
            colSphere = CollisionSphere(0,0,0,1)
            sphereNode = CollisionNode('colSphere')
            sphereNode.addSolid(colSphere)
            sphereNode.setFromCollideMask(BitMask32.allOff())
            sphereNode.setIntoCollideMask(BitMask32.bit(0))
            sphereNp = self.collect.attachNewNode(sphereNode)
            sphereColHandler = CollisionHandlerQueue()
Example #45
0
    def __initSceneGraph(self):

        #load various texture stages of the planet
        self.forge_tex = TextureStage('forge')
        self.forge_tex.setMode(TextureStage.MDecal)
        self.nexus_tex = TextureStage('nexus')
        self.nexus_tex.setMode(TextureStage.MDecal)
        self.extractor_phylon_ge_tex = TextureStage('extractor_phylon_ge')
        self.extractor_phylon_ge_tex.setMode(TextureStage.MDecal)
        
        # Parent node for relative position (no scaling)
        self.point_path = self.parent_star.point_path.attachNewNode("planet_node")
        self.point_path.setPos(self.position)
        
        #Models & textures
        self.model_path = loader.loadModel("models/planets/planet_sphere")
        self.model_path.setTexture(SphericalBody.dead_planet_tex, 1)
        self.model_path.reparentTo(self.point_path)
        self.model_path.setScale(self.radius)
        self.model_path.setPythonTag('pyPlanet', self);
        
        cnode = CollisionNode("coll_sphere_node")
        cnode.setTag('planet', str(id(self)))
        #We use no displacement (0,0,0) and no scaling factor (1)
        cnode.addSolid(CollisionSphere(0,0,0,1))
        cnode.setIntoCollideMask(BitMask32.bit(1))
        # Reparenting the collision sphere so that it 
        # matches the planet perfectly.
        self.cnode_path = self.model_path.attachNewNode(cnode)
        
        self.lines = LineNodePath(parent = self.parent_star.point_path, thickness = 4.0, colorVec = Vec4(1.0, 1.0, 1.0, 0.2))
        self.quad_path = None
Example #46
0
    
    def placeHealthItems(self):
        self.placeholder = render.attachNewNode("HealthItem-Placeholder")
        self.placeholder.setPos(0,0,0)
        
        # Add the health items to the placeholder node
        for i in range(5):
            # Load in the health item model
            self.foodchick = loader.loadModel("models/chicken2")
            self.foodchick.setPos(0,0,0)
            self.foodchick.reparentTo(self.placeholder)
	    #self.tex2=self.setTexture("models/orange.jpg")
	    #self.foodchick.setTexture(self.tex2,1)
	    #self.tex2= loader.loadTexture("models/orange.jpg")
	    #self.foodchick.setTexture(self.tex1,1)
	

            
            self.placeItem(self.foodchick)
            
            # Add spherical collision detection
            healthSphere = CollisionSphere(0,0,0,1)
            sphereNode = CollisionNode('healthSphere')
            sphereNode.addSolid(healthSphere)
            sphereNode.setFromCollideMask(BitMask32.allOff())
            sphereNode.setIntoCollideMask(BitMask32.bit(0))
            sphereNp = self.foodchick.attachNewNode(sphereNode)
            sphereColHandler = CollisionHandlerQueue()
Example #47
0
 def __set_submodels(self):
     print 'loaded track model'
     for submodel in self.model.getChildren():
         if not submodel.getName().startswith(self.props.empty_name):
             submodel.flatten_light()
     self.model.hide(BitMask32.bit(0))
     self.__load_empties()
    def setupCollisions(self):
        #make a collision traverser, set it to default
        base.cTrav = CollisionTraverser()
        
        
        #self.cHandler = CollisionHandlerEvent()
        self.cHandler = CollisionHandlerPusher()
        
        #set the pattern for the event sent on collision
        # "%in" is substituted with the name of the into object
        #self.cHandler.setInPattern("hit-%in")
        
        cSphere = CollisionSphere((0,0,0), 10) #panda is scaled way down!
        cNode = CollisionNode("vtol")
        cNode.addSolid(cSphere)
        #panda is *only* a from object
        cNode.setFromCollideMask(BitMask32.bit(0))
        cNode.setIntoCollideMask(BitMask32.allOff())
        cNodePath = self.vtol.attachNewNode(cNode)
#        cNodePath.show()
        base.cTrav.addCollider(cNodePath, self.cHandler)
        self.cHandler.addCollider(cNodePath, self.vtol)
        #for b1 in self.house2:
        cTube1 = CollisionTube((-0.4,3,3), (-0.4,3,20), 6.8)
        cTube2 = CollisionTube((-0.4,-3,3), (-0.4,-3,20), 6.8)
        cNode = CollisionNode("models/houses/building")
        cNode.addSolid(cTube1)
        cNode.addSolid(cTube2)
        cNodePath = self.house2.attachNewNode(cNode)
        cTube1 = CollisionTube((-0.4,3,3), (-0.4,3,20), 6.8)
        cTube2 = CollisionTube((-0.4,-3,3), (-0.4,-3,20), 6.8)
        cNode = CollisionNode("models/houses/church")
        cNode.addSolid(cTube1)
        cNode.addSolid(cTube2)
        cNodePath = self.house1.attachNewNode(cNode)
Example #49
0
    def __init__(self):
        #selection detection
        self.picker = CollisionTraverser()
        self.pq = CollisionHandlerQueue()
        self.pickerNode = CollisionNode('mouseRay')
        self.pickerNP = camera.attachNewNode(self.pickerNode)
        #self.pickerNode.setFromCollideMask(GeomNode.getDefaultCollideMask()) #TODO WOW geometry collision is SUPER slow...
        self.pickerNode.setFromCollideMask(BitMask32.bit(BITMASK_COLL_CLICK))
        #render.find('**selectable').node().setIntoCollideMask(BitMask32.bit(1))
        self.pickerRay = CollisionRay()
        self.pickerNode.addSolid(self.pickerRay)
        self.picker.addCollider(self.pickerNP, self.pq)
        #self.picker.showCollisions(render)

        #box selection detection HINT: start with drawing the 2d thing yo!

        self.__shift__ = False
        self.accept("shift", self.shiftOn)
        self.accept("shift-up", self.shiftOff)

        self.__ctrl__ = False
        self.accept("control", self.ctrlOn)
        self.accept("control-up", self.ctrlOff)

        #mouse handling
        self.accept("mouse1", self.clickHandler)
        self.accept("shift-mouse1", self.clickHandler)
        self.accept("mouse1-up", self.releaseHandler)

        #dragging
        self.dragTask = taskMgr.add(self.dragTask, 'dragTask')
Example #50
0
    def _add_box_body(self, lane_start, lane_end, middle, parent_np: NodePath,
                      line_type, line_color):
        length = norm(lane_end[0] - lane_start[0], lane_end[1] - lane_start[1])
        if LineType.prohibit(line_type):
            node_name = BodyName.White_continuous_line if line_color == LineColor.GREY else BodyName.Yellow_continuous_line
        else:
            node_name = BodyName.Broken_line
        body_node = BulletGhostNode(node_name)
        body_node.set_active(False)
        body_node.setKinematic(False)
        body_node.setStatic(True)
        body_np = parent_np.attachNewNode(body_node)
        shape = BulletBoxShape(
            Vec3(length / 2, Block.LANE_LINE_WIDTH / 2,
                 Block.LANE_LINE_GHOST_HEIGHT))
        body_np.node().addShape(shape)
        mask = Block.CONTINUOUS_COLLISION_MASK if line_type != LineType.BROKEN else Block.BROKEN_COLLISION_MASK
        body_np.node().setIntoCollideMask(BitMask32.bit(mask))
        self.static_nodes.append(body_np.node())

        body_np.setPos(panda_position(middle,
                                      Block.LANE_LINE_GHOST_HEIGHT / 2))
        direction_v = lane_end - lane_start
        theta = -numpy.arctan2(direction_v[1], direction_v[0])
        body_np.setQuat(
            LQuaternionf(numpy.cos(theta / 2), 0, 0, numpy.sin(theta / 2)))
Example #51
0
    def __initSceneGraph(self):
        # Parent node for relative position (no scaling)
        self.point_path = render.attachNewNode("star_node")
        self.point_path.setPos(self.position)
        
        #For transforming the object with scaling, colors, shading, etc.
        # Hosting the actual 3d model object.
        #Models & textures
        self.flare_ts = TextureStage('flare')
        self.flare_ts.setMode(TextureStage.MModulateGlow)
        self.model_path = loader.loadModel("models/stars/planet_sphere")
        self.model_path.setTexture(SphericalBody.star_dead_tex, 1)
        self.model_path.reparentTo(self.point_path)
        self.model_path.setScale(self.radius)
        self.model_path.setPythonTag('pyStar', self);
        
        # Collision sphere for object picking
        #-----------------------------------------------------
        # As described in the Tut-Chessboard.py sample: "If this model was
        # any more complex than a single polygon, you should set up a collision
        # sphere around it instead."
        cnode = CollisionNode("coll_sphere_node")
        cnode.setTag('star', str(id(self)))
        #We use no displacement (0,0,0) and no scaling factor (1)
        cnode.addSolid(CollisionSphere(0,0,0,1))
        cnode.setIntoCollideMask(BitMask32.bit(1))
        self.cnode_path = self.model_path.attachNewNode(cnode)
        #For temporary testing, display collision sphere.
#        self.cnode_path.show()
        self.quad_path = None
Example #52
0
    def __init__(self, position=(0, 0, 0), color=(1, 1, 1, 1)):
        # получаем уникальный ключ объекта - текущий индекс
        self.key = str(Block.current_index)
        # увеличиваем индекс
        Block.current_index += 1
        # флаг выделенного блока
        self.selected = False
        # загружаем модель блока
        self.block = loader.loadModel('block')
        # и текстуру к ней
        tex = loader.loadTexture('block.png')
        # устанавливаем текстуру на модель
        self.block.setTexture(tex)
        # устанавливаем учёт прозрачности цвета
        self.block.setTransparency(TransparencyAttrib.MAlpha)
        # перемещение модели в рендер, смена родителя
        self.block.reparentTo(render)
        # устанавливаем позицию модели
        self.block.setPos(position)
        # устанавливаем цвет модели
        self.color = color
        self.block.setColor(self.color)

        # настраиваем объект для определения выделения
        # вместе с моделью загружается и геометрия столкновения
        # ищем узел геометрии столкновения
        collisionNode = self.block.find("*").node()
        # устанавливаем такую же маску ДО как и у луча выделения
        collisionNode.setIntoCollideMask(BitMask32.bit(1))
        # устанавливаем тег, чтобы потом определить что именно мы выделили
        collisionNode.setTag('key', self.key)
    def __init__(self):
        #Create a buffer for storing the shadow texture,
        #the higher the buffer size the better quality the shadow.
        self.shadowBuffer = base.win.makeTextureBuffer("Shadow Buffer",2048,2048)
        self.shadowBuffer.setClearColorActive(True)
        self.shadowBuffer.setClearColor((0,0,0,1))

        self.shadowCamera = base.makeCamera(self.shadowBuffer)
        self.shadowCamera.reparentTo(render)

        self.lens = base.camLens
        self.lens.setAspectRatio(1/1)
        self.shadowCamera.node().setLens(self.lens)
        self.shadowCamera.node().setCameraMask(BitMask32.bit(1))

        #Make everything rendered by the shadow camera grey:
        self.initial = NodePath('initial')
        self.initial.setColor(.75,.75,.75,1,1)
        self.initial.setTextureOff(2)
        self.initial.setMaterialOff(2)
        self.initial.setLightOff(2)
        self.shadowCamera.node().setInitialState(self.initial.getState())

        #The cameras pos effects the shadows dirrection:
        self.shadowCamera.setPos(-10, 0,20)
        self.shadowCamera.lookAt(0,0,0)

        #Make the shadows soft by bluring the screen:
        self.filters = CommonFilters(self.shadowBuffer,self.shadowCamera)
        self.filters.setBlurSharpen(.1)

        self.shadowTexture = self.shadowBuffer.getTexture()

        #Draw the shadowTexture on sceen:
        self.imageObject = OnscreenImage(image = self.shadowTexture,pos = (-.75,0,.75),scale=.2)
    def __init__(self, fulcrum, terrain):
        TerrainCamera.__init__(self)

        self.terrain = terrain
        self.fulcrum = fulcrum
        # in behind Ralph regardless of ralph's movement.
        self.camNode.reparentTo(fulcrum)
        # How far should the camera be from Ralph
        self.cameraDistance = 30
        # Initialize the pitch of the camera
        self.cameraPitch = 10
        self.focus = self.fulcrum.attachNewNode("focus")
        
        self.maxDistance = 500.0
        self.minDistance = 2
        self.maxPitch = 80
        self.minPitch = -70
        
        # We will detect the height of the terrain by creating a collision
        # ray and casting it downward toward the terrain.  One ray will
        # start above ralph's head.
        # A ray may hit the terrain, or it may hit a rock or a tree.  If it
        # hits the terrain, we can detect the height.  If it hits anything
        # else, we rule that the move is illegal.
        self.cTrav = CollisionTraverser() 
        self.cameraRay = CollisionSegment(self.fulcrum.getPos(), (0, 5, 5))
        self.cameraCol = CollisionNode('cameraRay')
        self.cameraCol.addSolid(self.cameraRay)
        self.cameraCol.setFromCollideMask(BitMask32.bit(0))
        self.cameraCol.setIntoCollideMask(BitMask32.allOff())
        self.cameraColNp = self.fulcrum.attachNewNode(self.cameraCol)
        self.cameraColHandler = CollisionHandlerQueue()
        self.cTrav.addCollider(self.cameraColNp, self.cameraColHandler) 
Example #55
0
    def __init__(self):
        ShowBase.__init__(self)

        # Create a traverser and a handler
        self.cTrav = CollisionTraverser()
        self.cQueue = CollisionHandlerQueue()

        # Create the collision node that will store the collision
        # ray solid 
        self.pickerNode = CollisionNode('mouseRay')
        # Set bitmask for efficiency, only hit from objects with same mask
        self.pickerNode.setFromCollideMask(BitMask32.bit(1))
        # Attach collision node to camera, since that is the source
        self.pickerNP = camera.attachNewNode(self.pickerNode)

        # Add collision solid(ray) to collision node
        self.pickerRay = CollisionRay()
        self.pickerNode.addSolid(self.pickerRay)
        # Add collidable node(pickerNP) to the traverser
        # Collisions detected when traversed will go to cQueue
        self.cTrav.addCollider(self.pickerNP, self.cQueue)

        # Create visible sphere
        self.tmpSphere = self.loader.loadModel("models/misc/sphere")
        self.tmpSphere.reparentTo(self.render)
        self.tmpSphere.setColor(1, 1, 1, 1)
        self.tmpSphere.setPos(0, 100, 0)
        
        # Create collision sphere and attach to tmpSphere
        cSphere = CollisionSphere(0, 0, 0, 3)
        cnodePath = self.tmpSphere.attachNewNode(CollisionNode('cnode'))
        # Add collision solid(sphere) to collision node
        # Because tmpSphere/cSphere is child of render, which we traverse
        # later, it becomes a from collider automatically, we don't
        # need to addCollider since that is only for from collision nodes
        cnodePath.node().addSolid(cSphere)
        # Set bitmask to match the from collisionnode mask for efficiency
        cnodePath.setCollideMask(BitMask32.bit(1))
        # Show the collision sphere visibly, for debugging.
        cnodePath.show()
        # Set a custom tag on the collision node which becomes available
        # inside the collision event stored in the collision handler
        cnodePath.setTag('someTag', '1')

        # Add task to run every frame - set collision solid(ray)
        # to start at the current camera position, 
        self.mouseTask = taskMgr.add(self.mouseTask, 'mouseTask')
  def setup(self):
    self.worldNP = render.attachNewNode('World')

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

    self.world = BulletWorld()
    self.world.setGravity(Vec3(0, 0, -9.81))
    self.world.setDebugNode(self.debugNP.node())

    # Ground
    shape = BulletPlaneShape(Vec3(0, 0, 1), -1)

    np = self.worldNP.attachNewNode(BulletRigidBodyNode('Ground'))
    np.node().addShape(shape)
    np.setPos(0, 0, -1)
    np.setCollideMask(BitMask32.bit(0))

    self.world.attachRigidBody(np.node())

    # Boxes
    self.boxes = [None,]*6

    for i in range(6):
      shape = BulletBoxShape(Vec3(0.5, 0.5, 0.5))

      np = self.worldNP.attachNewNode(BulletRigidBodyNode('Box-1'))
      np.node().setMass(1.0)
      np.node().addShape(shape)

      self.world.attachRigidBody(np.node())

      self.boxes[i] = np

      visualNP = loader.loadModel('models/box.egg')
      visualNP.reparentTo(np)

    self.boxes[0].setPos(-3, -3, 0)
    self.boxes[1].setPos( 0, -3, 0)
    self.boxes[2].setPos( 3, -3, 0)
    self.boxes[3].setPos(-3,  3, 0)
    self.boxes[4].setPos( 0,  3, 0)
    self.boxes[5].setPos( 3,  3, 0)

    self.boxes[0].setCollideMask(BitMask32.bit(1))
    self.boxes[1].setCollideMask(BitMask32.bit(2))
    self.boxes[2].setCollideMask(BitMask32.bit(3))
    self.boxes[3].setCollideMask(BitMask32.bit(1))
    self.boxes[4].setCollideMask(BitMask32.bit(2))
    self.boxes[5].setCollideMask(BitMask32.bit(3))

    self.boxNP = self.boxes[0]

    self.world.setGroupCollisionFlag(0, 1, True)
    self.world.setGroupCollisionFlag(0, 2, True)
    self.world.setGroupCollisionFlag(0, 3, True)

    self.world.setGroupCollisionFlag(1, 1, False)
    self.world.setGroupCollisionFlag(1, 2, True)
Example #57
0
 def initCollisionRay(self, originZ, dirZ):
     ray = CollisionRay(0,0,originZ,0,0,dirZ)
     collNode = CollisionNode('playerRay')
     collNode.addSolid(ray)
     collNode.setFromCollideMask(BitMask32.bit(1))
     collNode.setIntoCollideMask(BitMask32.allOff())
     collRayNP = self.playerNode.attachNewNode(collNode)
     collRayNP.show()
     return collRayNP
 def __init__(self, main_cam_node):
     self._main_cam_node = main_cam_node
     self._main_cam_node.node().set_camera_mask(BitMask32.bit(1))
     self.containers = {
         "shadow": self.StateContainer("Shadows", 2, False),
         "voxelize": self.StateContainer("Voxelize", 3, False),
         "envmap": self.StateContainer("Envmap", 4, True),
         "forward": self.StateContainer("Forward", 5, True),
     }
 def loadCursorPicker(self):
     self.picker = CollisionTraverser()
     self.pq     = CollisionHandlerQueue()
     self.pickerNode = CollisionNode('mouseRay')
     self.pickerNP = camera.attachNewNode(self.pickerNode)
     self.pickerNode.setFromCollideMask(BitMask32.bit(1))
     self.pickerRay = CollisionRay()
     self.pickerNode.addSolid(self.pickerRay)
     self.picker.addCollider(self.pickerNP, self.pq)
Example #60
0
 def buttonCreator(self, buttonRoot):
     button = loader.loadModel("models/button") # @UndefinedVariable
     button.setScale(0.3,0.4,0.25)
     button.reparentTo(self.buttonList[buttonRoot]) # @UndefinedVariable
     buttonMesh = button.find("**/mesh_button")
     myTexture = self.loader.loadTexture('tex/start_%i.png' %(buttonRoot+1))
     buttonMesh.setTexture(myTexture,1)
     buttonCollider = button.find("**/collider_button")
     buttonCollider.node().setFromCollideMask(BitMask32.bit(0))
     self.cTrav.addCollider(buttonCollider, self.cHandler)