def step(self): self.rotate_light() self.graphicsEngine.renderFrame() image = self.get_camera_image() TransformState.garbageCollect() RenderState.garbageCollect() return
def __init__(self,name,parent_np , physics_world, tr = TransformState.makeIdentity()): """ Sector(NodePath parent_np, TransformState tr = TransformState.makeIdentity() Creates a level Sector object which ensures that all objects in it only move in the x and z directions relative to the sector. The z and x vectors lie on the plane with +X pointing to the right and +Z pointing up. +Y is perpedicular to the plane into the screen from the user's perspective @param parent_np: NodePath to the parent of the sector, usually is the Level object that contains the sector. @param physics_world: The physics world @param tf: Transform of the sector relative to the parent_np NodePath """ NodePath.__init__(self,name) self.reparentTo(parent_np) self.setTransform(self,tr) self.physics_world_ = physics_world # creating 2d motion plane self.motion_plane_np_ = self.attachNewNode(BulletRigidBodyNode(self.getName() + '-motion-plane')) self.motion_plane_np_.node().setMass(0) self.motion_plane_np_.node().setIntoCollideMask(CollisionMasks.NO_COLLISION) self.motion_plane_np_.node().addShape(BulletPlaneShape(Vec3(0,1,0),0)) self.physics_world_.attach(self.motion_plane_np_.node()) self.motion_plane_np_.reparentTo(parent_np) self.motion_plane_np_.setTransform(self,TransformState.makeIdentity()) # game objects self.object_constraints_dict_ = {} # stores tuples of the form (String,BulletConstraint) # sector transitions self.sector_transitions_ = [] self.destination_sector_dict_ = {}
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 start(self): for component in self.node.data: if isinstance(component, Rigidbody): # Check if parent has rigidbody, and use that node if it does for p_component in self.node.parent.data: if isinstance(p_component, Rigidbody): self.parent_path = p_component.body_path self.update_parent = False if self.parent_path is None: parent_node = BulletRigidBodyNode(self.node.parent.name + "_node") parent_node.set_mass(0) self.parent_path = EComponent.panda_root_node.attach_new_node(parent_node) self.parent_path.setPos(helper.np_vec3_to_panda(self.node.parent.transform.get_world_translation())) rot = np.degrees(self.node.parent.transform.get_world_rotation()) self.parent_path.setHpr(LVector3f(rot[1], rot[0], rot[2])) self.parent_path.setScale(helper.np_vec3_to_panda(self.node.parent.transform.get_world_scale())) # Create constraint child_transform = TransformState.make_pos(LVector3f(0, 0, 0)) node_pos = self.node.transform.get_translation() * self.node.transform.get_world_scale() parent_transform = TransformState.make_pos(helper.np_vec3_to_panda(node_pos)) constraint = BulletConeTwistConstraint(component.body_path.node(), self.parent_path.node(), child_transform, parent_transform) constraint.set_limit(float(self.property_vals["swing_1"]), float(self.property_vals["swing_2"]), float(self.property_vals["max_twist"])) EComponent.physics_world.attachConstraint(constraint)
def _clear_state_cache(self, task=None): """ Task which repeatedly clears the state cache to avoid storing unused states. """ task.delayTime = 2.0 TransformState.clear_cache() RenderState.clear_cache() return task.again
def sweepRay(self, startp,endp): tsFrom = TransformState.makePos(Point3(0, 0, 0)) tsTo = TransformState.makePos(Point3(10, 0, 0)) shape = BulletSphereShape(0.5) penetration = 0.0 result = self.world.sweepTestClosest(shape, tsFrom, tsTo, penetration) return result
def __init__(self, texture_array, scale=0.2, window_size=512, texture_size=512): super().__init__() self.scale = scale self.current_scale = 1 self.texture_array = texture_array self.texture_dtype = type(self.texture_array.flat[0]) self.ndims = self.texture_array.ndim self.center_shift = TransformState.make_pos2d((-0.5, -0.5)) self.shift_back = TransformState.make_pos2d((0.5, 0.5)) #Create texture stage self.texture = Texture("Stimulus") self.texture.setup2dTexture(texture_size, texture_size, Texture.T_unsigned_byte, Texture.F_luminance) self.texture.setWrapU(Texture.WM_clamp) self.texture.setWrapV(Texture.WM_clamp) self.texture.setRamImageAs(self.texture_array, "L") self.textureStage = TextureStage("Stimulus") #Create scenegraph cm = CardMaker('card1') cm.setFrameFullscreenQuad() self.card1 = self.aspect2d.attachNewNode(cm.generate()) self.card1.setTexture(self.textureStage, self.texture) #ts, tx if self.scale != 0: self.taskMgr.add(self.scaleTextureTask, "scaleTextureTask")
def test_node_prev_transform(): identity = TransformState.make_identity() t1 = TransformState.make_pos((1, 0, 0)) t2 = TransformState.make_pos((2, 0, 0)) t3 = TransformState.make_pos((3, 0, 0)) node = PandaNode("node") assert node.transform == identity assert node.prev_transform == identity assert not node.has_dirty_prev_transform() node.transform = t1 assert node.transform == t1 assert node.prev_transform == identity assert node.has_dirty_prev_transform() node.transform = t2 assert node.transform == t2 assert node.prev_transform == identity assert node.has_dirty_prev_transform() node.reset_prev_transform() assert node.transform == t2 assert node.prev_transform == t2 assert not node.has_dirty_prev_transform() node.transform = t3 assert node.prev_transform == t2 assert node.has_dirty_prev_transform() PandaNode.reset_all_prev_transform() assert node.transform == t3 assert node.prev_transform == t3 assert not node.has_dirty_prev_transform()
def __preventPenetration(self): if self.noClip: return prevPeneCollector.start() maxIter = 10 fraction = 1.0 #if self.__spam: # lines = LineSegs() # lines.setColor(1, 0, 0, 1) # lines.setThickness(2) collisions = Vec3(0) offset = Point3(0, 0, self.__capsuleOffset) while (fraction > 0.01 and maxIter > 0): currentTarget = self.__targetPos + collisions tsFrom = TransformState.makePos(self.__currentPos + offset) tsTo = TransformState.makePos(currentTarget + offset) sweepCollector.start() result = self.__world.sweepTestClosest( self.capsuleNP.node().getShape(0), tsFrom, tsTo, CIGlobals.WallGroup, 1e-7) sweepCollector.stop() if result.hasHit() and (type(result.getNode()) is not BulletGhostNode): if result.getNode().getCollisionResponse(): fraction -= result.getHitFraction() normal = result.getHitNormal() direction = result.getToPos() - result.getFromPos() distance = direction.length() direction.normalize() if distance != 0: reflDir = self.__computeReflectionDirection( direction, normal) reflDir.normalize() collDir = self.__parallelComponent(reflDir, normal) #if self.__spam: # lines.moveTo(result.getFromPos()) # lines.drawTo(result.getHitPos()) collisions += collDir * distance maxIter -= 1 collisions.z = 0.0 #if collisions.length() != 0 and self.__spam: # if self.currLineSegsGeom: # self.currLineSegsGeom.removeNode() # self.currLineSegsGeom = None # self.currLineSegsGeom = render.attachNewNode(lines.create()) self.__targetPos += collisions prevPeneCollector.stop()
def complete_shape(self, id_mb1, node, transform): """ create the shape then call recursive function""" #print "complete shape {}".format(node) ## construct the node self.add_node_to_shape(node, id_mb1, transform) if node.gen_type == 'piece': self.shape_building_status[node] = True elif node.gen_type() == 'link': self.link_building_status[node][1] = (id_mb1, TransformState.makeMat(transform.getMat())) self.build_link(node) ## recursive loop over the edges for face, edge in enumerate(node.edges[1:]): if edge.type() != 'empty': transform = self.change_transform(transform, face + 1, type) if edge.gen_type() == 'shape': if not self.shape_building_status[edge]: #then we have to add this node (because it #is not entirely finished self.complete_shape(id_mb1, edge, transform) elif edge.gen_type() == 'link': if self.link_building_status[edge][0][0] is None: # first time we see this link #print "hi new link" self.add_node_to_shape(edge, id_mb1, transform) self.link_building_status[edge][0] = (id_mb1, TransformState.makeMat(transform.getMat())) else: # link is complete: #print " hi end link" self.add_node_to_shape(edge, id_mb1) self.link_building_status[edge][1] = (id_mb1, TransformState.makeMat(transform.getMat())) self.build_link(edge) transform = self.change_back_transform(transform, face + 1, type)
def circle_region_detection(engine: EngineCore, position: Tuple, radius: float, detection_group: int, height=10, in_static_world=False): """ :param engine: BaseEngine class :param position: position in PGDrive :param radius: radius of the region to be detected :param detection_group: which group to detect :param height: the detect will be executed from this height to 0 :param in_static_world: execute detection in static world :return: detection result """ region_detect_start = panda_position(position, z=height) region_detect_end = panda_position(position, z=-1) tsFrom = TransformState.makePos(region_detect_start) tsTo = TransformState.makePos(region_detect_end) shape = BulletCylinderShape(radius, 5, ZUp) penetration = 0.0 physics_world = engine.physics_world.dynamic_world if not in_static_world else engine.physics_world.static_world result = physics_world.sweep_test_closest(shape, tsFrom, tsTo, detection_group, penetration) return result
def createConstraints(self,bodyA,bodyB): left_constraint = BulletGenericConstraint(bodyA,bodyB,TransformState.makeIdentity(),TransformState.makeHpr(Vec3(180,0,0)),False) right_constraint = BulletGenericConstraint(bodyA,bodyB,TransformState.makeIdentity(),TransformState.makeIdentity(),False) left_constraint.setEnabled(False) right_constraint.setEnabled(False) return (right_constraint,left_constraint)
def doCollisionSweepTestZ(self,col_mask = CollisionMasks.PLATFORM_RIGID_BODY,from_z = 0, to_z = 0): ''' doCollisionSweepTestZ(double from_z = 0, double to_z = 0) Performs a collision sweep test along z in order to determine the height at which the character's active rigid body comes into contact with an obstacle. This is useful during landing actions. @param col_mask: [optional] collision mask of the object(s) to check for collisions with. @param from_z: [optional] z value for the start position @param to_z: [optional] z value for the end position ''' pos = self.getPos() if abs(from_z - to_z) < 1e-5: height = self.getHeight() from_z = pos.getZ() + 0.5* height to_z = pos.getZ() - 0.5* height t0 = TransformState.makePos(Vec3(pos.getX(),pos.getY(),from_z)) t1 = TransformState.makePos(Vec3(pos.getX(),pos.getY(),to_z)) rigid_body = self.getRigidBody() if rigid_body.node().getNumShapes() <= 0: logging.warn("Rigid body contains no shapes, collision sweep test canceled") return aabb_shape = rigid_body.node().getShape(0) result = self.physics_world_.sweepTestClosest(aabb_shape,t0,t1,col_mask,0.0) if not result.hasHit(): logging.warn("No collision from collision sweep closest test from %s to %s "%(t0.getPos(),t1.getPos())) else: logging.debug("Found collision at point %s between p0: %s to p1 %s"%(result.getHitPos(),t0.getPos(),t1.getPos())) return result
def getCollisionShapeFromModel(model, mode='box', defaultCentered=False): #NOTE: make sure the position is relative to the center of the object minBounds, maxBounds = model.getTightBounds() offset = minBounds + (maxBounds - minBounds) / 2.0 transform = TransformState.makeIdentity() if mode == 'mesh': # Use exact triangle mesh approximation mesh = BulletTriangleMesh() geomNodes = model.findAllMatches('**/+GeomNode') for nodePath in geomNodes: geomNode = nodePath.node() for n in range(geomNode.getNumGeoms()): geom = geomNode.getGeom(n) mesh.addGeom(geom) shape = BulletTriangleMeshShape(mesh, dynamic=False) transform = model.getTransform() elif mode == "sphere": minBounds, maxBounds = model.getTightBounds() dims = maxBounds - minBounds radius = np.sqrt(np.square(dims[0]) + np.square(dims[1])) / 2.0 height = dims[2] shape = BulletCapsuleShape(radius, 2 * radius) if not defaultCentered: transform = TransformState.makePos(offset) elif mode == "hull": shape = BulletConvexHullShape() geomNodes = model.findAllMatches('**/+GeomNode') for nodePath in geomNodes: geomNode = nodePath.node() for n in range(geomNode.getNumGeoms()): geom = geomNode.getGeom(n) shape.addGeom(geom) elif mode == 'box': # Bounding box approximation minBounds, maxBounds = model.getTightBounds() dims = maxBounds - minBounds shape = BulletBoxShape(Vec3(dims.x / 2, dims.y / 2, dims.z / 2)) if not defaultCentered: transform = TransformState.makePos(offset) elif mode == 'capsule': minBounds, maxBounds = model.getTightBounds() dims = maxBounds - minBounds radius = np.sqrt(np.square(dims[0]) + np.square(dims[1])) / 2.0 height = dims[2] shape = BulletCapsuleShape(radius, height - 2 * radius) if not defaultCentered: transform = TransformState.makePos(offset) else: raise Exception( 'Unknown mode type for physic object collision shape: %s' % (mode)) return shape, transform
def step(self, action): dt = 1/self.fps self.framecount += 1 max_dist = 1.1 # Move finger finger_max_speed = 2 finger_accel = 10.0 finger_deccel = 10.0 self.action_buffer.pop(0) self.action_buffer.append(action) action = self.action_buffer[0] if action == 0: self.finger_speed_mps += dt * finger_accel if self.finger_speed_mps > finger_max_speed: self.finger_speed_mps = 2 if action == 1: if self.finger_speed_mps > 0.01: self.finger_speed_mps -= finger_deccel * dt if self.finger_speed_mps < -0.01: self.finger_speed_mps += finger_deccel * dt if action == 2: self.finger_speed_mps -= dt * finger_accel if self.finger_speed_mps < -finger_max_speed: self.finger_speed_mps = -finger_max_speed real_displacement = self.finger_speed_mps * dt self.finger_np.setY(self.finger_np.getY() + real_displacement) if self.finger_np.getY() > max_dist: self.finger_np.setY(max_dist) self.finger_speed_mps = 0 if self.finger_np.getY() < -max_dist: self.finger_np.setY(-max_dist) self.finger_speed_mps = 0 # self.world.doPhysics(dt, 5, 1.0/120.0) self.world.doPhysics(dt, 20, 1.0/240.0) self.reset_conv() self.check_teleportable(blocks_per_minute=59) # Keep the conveyor moving self.conv_np.node().setLinearVelocity(Vec3(1.0, 0.0, 0.0)) if self.human_playable is False: self.graphicsEngine.renderFrame() TransformState.garbageCollect() RenderState.garbageCollect() image = self.get_camera_image() else: image = None score = 0 score += self.check_rewards() done = False return image, score, done
def trs_transform(self): """ trs = translate rotate scale: transform for mask stage """ pos = 0.5 + self.mask_position_uv[0], 0.5 + self.mask_position_uv[1] center_shift = TransformState.make_pos2d((-pos[0], -pos[1])) scale = TransformState.make_scale2d(1/self.scale) rotate = TransformState.make_rotate2d(self.mask_angle) translate = TransformState.make_pos2d((0.5, 0.5)) return translate.compose(rotate.compose(scale.compose(center_shift)))
def _checkForStateClear(self): """ This method regulary clears the state cache """ if not hasattr(self, "lastStateClear"): self.lastStateClear = 0 if Globals.clock.getFrameTime() - self.lastStateClear > self.settings.stateCacheClearInterval: RenderState.clearCache() TransformState.clearCache() self.lastStateClear = Globals.clock.getFrameTime()
def trs_transform(self, elapsed_time): """ trs = translate rotate scale: transform for mask stage """ pos = 0.5 + self.mask_position_uv[0], 0.5 + self.mask_position_uv[1] center_shift = TransformState.make_pos2d((-pos[0], -pos[1])) scale = TransformState.make_scale2d(1/self.mask_scale) rotate = TransformState.make_rotate2d(np.mod(elapsed_time*40, 360)) translate = TransformState.make_pos2d((0.5, 0.5)) return translate.compose(rotate.compose(scale.compose(center_shift)))
def setup(self): self.worldNP = render.attachNewNode('World') # World self.debugNP = self.worldNP.attachNewNode(BulletDebugNode('Debug')) self.debugNP.show() self.debugNP.node().showWireframe(True) self.debugNP.node().showConstraints(True) self.debugNP.node().showBoundingBoxes(False) self.debugNP.node().showNormals(False) self.world = BulletWorld() self.world.setGravity(Vec3(0, 0, -9.81)) self.world.setDebugNode(self.debugNP.node()) # Box A shape = BulletBoxShape(Vec3(0.5, 0.5, 0.5)) bodyA = BulletRigidBodyNode('Box A') bodyNP = self.worldNP.attachNewNode(bodyA) bodyNP.node().addShape(shape) bodyNP.setCollideMask(BitMask32.allOn()) bodyNP.setPos(-3, 0, 4) visNP = loader.loadModel('models/box.egg') visNP.clearModelNodes() visNP.reparentTo(bodyNP) self.world.attachRigidBody(bodyA) # Box B shape = BulletBoxShape(Vec3(0.5, 0.5, 0.5)) bodyB = BulletRigidBodyNode('Box B') bodyNP = self.worldNP.attachNewNode(bodyB) bodyNP.node().addShape(shape) bodyNP.node().setMass(1.0) bodyNP.node().setDeactivationEnabled(False) bodyNP.setCollideMask(BitMask32.allOn()) bodyNP.setPos(0, 0, 0) visNP = loader.loadModel('models/box.egg') visNP.clearModelNodes() visNP.reparentTo(bodyNP) self.world.attachRigidBody(bodyB) # Slider frameA = TransformState.makePosHpr(Point3(2, 0, 0), Vec3(0, 0, 45)) frameB = TransformState.makePosHpr(Point3(0, -3, 0), Vec3(0, 0, 0)) slider = BulletSliderConstraint(bodyA, bodyB, frameA, frameB, True) slider.setDebugDrawSize(2.0) slider.setLowerLinearLimit(0) slider.setUpperLinearLimit(6) slider.setLowerAngularLimit(-60) slider.setUpperAngularLimit(60) self.world.attachConstraint(slider)
def doShoot(self, ccd): if(self.fire and self.attempts > 0 and self.gameState == 'PLAY'): self.cameraState = 'LOOK' self.fire = False self.candleThrow.play() self.attempts -= 1 #get from/to points from mouse click ## pMouse = base.mouseWatcherNode.getMouse() ## pFrom = Point3() ## pTo = Point3() ## base.camLens.extrude(pMouse, pFrom, pTo) ## pFrom = render.getRelativePoint(base.cam, pFrom) ## pTo = render.getRelativePoint(base.cam, pTo) # calculate initial velocity v = self.pTo - self.pFrom ratio = v.length() / 40 v.normalize() v *= 70.0 * ratio torqueOffset = random.random() * 10 #create bullet shape = BulletSphereShape(0.5) shape01 = BulletSphereShape(0.5) shape02 = BulletSphereShape(0.5) shape03 = BulletSphereShape(0.5) body = BulletRigidBodyNode('Candle') bodyNP = self.worldNP.attachNewNode(body) bodyNP.node().addShape(shape, TransformState.makePos(Point3(0,0,0))) bodyNP.node().addShape(shape01, TransformState.makePos(Point3(0,0.5,-0.5))) bodyNP.node().addShape(shape02,TransformState.makePos(Point3(0,1,-1))) bodyNP.node().addShape(shape03,TransformState.makePos(Point3(0,1.5,-1.5))) bodyNP.node().setMass(100) bodyNP.node().setFriction(1.0) bodyNP.node().setLinearVelocity(v) bodyNP.node().applyTorque(v*torqueOffset) bodyNP.setPos(self.pFrom) bodyNP.setCollideMask(BitMask32.allOn()) visNP = loader.loadModel('models/projectile.X') visNP.setScale(0.7) visNP.clearModelNodes() visNP.reparentTo(bodyNP) #self.bird = bodyNP.node() if ccd: bodyNP.node().setCcdMotionThreshold(1e-7) bodyNP.node().setCcdSweptSphereRadius(0.5) self.world.attachRigidBody(bodyNP.node()) #remove the bullet again after 1 sec self.bullets = bodyNP taskMgr.doMethodLater(5, self.removeBullet, 'removeBullet', extraArgs=[bodyNP], appendTask = True)
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 build_link(self, node): (id_bda, ta), (id_bdb, tb) = self.link_building_status[node] bda = self.factory.multiboxes[id_bda] bdb = self.factory.multiboxes[id_bdb] pos = bda.body.getPosition() quat = LQuaternionf(bda.body.getQuaternion()) mat = TransformState.makePosQuatScale(pos, quat, Vec3(1, 1, 1)).getMat() mat = ta.getMat() * mat print "ta", ta print "absol", TransformState.makeMat(mat) mat = LMatrix4f.translateMat(Vec3(0.5, 0, 0)) * mat anchor = TransformState.makeMat(mat).getPos() print "absol", TransformState.makeMat(mat) axis = self.quat_dict[1][1] if node.orientation == 1: t = LMatrix4f.rotateMat(*self.quat_dict[4]) * mat else: t = LMatrix4f.rotateMat(*self.quat_dict[2]) * mat row = t.getRow(0) print "rotation", t.getRow(0), type(t.getRow(0)) #axis = t.getQuat().getAxis() axis = Vec3(row.getX(), row.getY(), row.getZ()) print "axis",axis print "anchor", anchor mat = LMatrix4f.translateMat(Vec3(0.5, 0, 0)) * mat mat = tb.getInverse().getMat() * mat t = TransformState.makeMat(mat) posb = t.getPos() quatb = t.getQuat() bdb.body.setPosition(posb) bdb.body.setQuaternion(quatb) cs = OdeHingeJoint(self.physics.world, self.physics.servogroup) cs.attach(bda.body, bdb.body) cs.setAxis(axis) cs.setAnchor(anchor) #add the motor cs.setParamFMax(self.satu_cmd) cs.setParamFudgeFactor(0.5) cs.setParamCFM(11.1111) cs.setParamStopCFM(11.1111) cs.setParamStopERP(0.444444) cs.setParamLoStop(- math.pi * 0.5) cs.setParamHiStop(math.pi * 0.5) pid = PID() self.dof_motors[node] = (cs, pid) print "add constraint"
def create_colliders(root, pose_rig, joints_config): for node, parent in pose_rig.exposed_joints: if node.getName() not in joints_config: continue joint_config = joints_config[node.getName()] if "joints" not in joint_config: continue joints = joint_config["joints"] if len(joints) == 0: continue mass = joint_config["mass"] if "mass" in joint_config else 1 box_rb = BulletRigidBodyNode(node.getName()) box_rb.setMass(1.0) # box_rb.setLinearDamping(0.2) # box_rb.setAngularDamping(0.9) # box_rb.setFriction(1.0) # box_rb.setAnisotropicFriction(1.0) # box_rb.setRestitution(0.0) for joint in joints: child_node, child_parent = next( (child_node, child_parent) for child_node, child_parent in pose_rig.exposed_joints if child_node.getName() == joint ) pos = child_node.getPos(child_parent) width = pos.length() / 2.0 scale = Vec3(3, width, 3) shape = BulletBoxShape(scale) quat = Quat() lookAt(quat, child_node.getPos(child_parent), Vec3.up()) if len(joints) > 1: transform = TransformState.makePosHpr(child_node.getPos(child_parent) / 2.0, quat.getHpr()) else: transform = TransformState.makeHpr(quat.getHpr()) box_rb.addShape(shape, transform) box_np = root.attachNewNode(box_rb) if len(joints) > 1: pos = node.getPos(pose_rig.actor) hpr = node.getHpr(pose_rig.actor) box_np.setPosHpr(root, pos, hpr) else: box_np.setPos(child_parent, child_node.getPos(child_parent) / 2.0) box_np.lookAt(child_parent, child_node.getPos(child_parent)) yield box_np
def _clear_state_cache(self, task=None): """ Task which repeatedly clears the state cache to avoid storing unused states. While running once a while, this task prevents over-polluting the state-cache with unused states. This complements Panda3D's internal state garbarge collector, which does a great job, but still cannot clear up all states. """ task.delayTime = 2.0 TransformState.clear_cache() RenderState.clear_cache() return task.again
def setup(self): self.worldNP = render.attachNewNode('World') # World self.debugNP = self.worldNP.attachNewNode(BulletDebugNode('Debug')) self.debugNP.show() self.debugNP.node().showWireframe(True) self.debugNP.node().showConstraints(True) self.debugNP.node().showBoundingBoxes(False) self.debugNP.node().showNormals(False) self.world = BulletWorld() self.world.setGravity(Vec3(0, 0, -9.81)) self.world.setDebugNode(self.debugNP.node()) # Box A shape = BulletBoxShape(Vec3(0.5, 0.5, 0.5)) bodyA = BulletRigidBodyNode('Box A') bodyNP = self.worldNP.attachNewNode(bodyA) bodyNP.node().addShape(shape) bodyNP.setCollideMask(BitMask32.allOn()) bodyNP.setPos(-2, 0, 4) visNP = loader.loadModel('models/box.egg') visNP.clearModelNodes() visNP.reparentTo(bodyNP) self.world.attachRigidBody(bodyA) # Box B shape = BulletBoxShape(Vec3(0.5, 0.5, 0.5)) bodyB = BulletRigidBodyNode('Box B') bodyNP = self.worldNP.attachNewNode(bodyB) bodyNP.node().addShape(shape) bodyNP.node().setMass(1.0) bodyNP.node().setDeactivationEnabled(False) bodyNP.setCollideMask(BitMask32.allOn()) bodyNP.setPos(0, 0, 0) visNP = loader.loadModel('models/box.egg') visNP.clearModelNodes() visNP.reparentTo(bodyNP) self.world.attachRigidBody(bodyB) # Cone frameA = TransformState.makePosHpr(Point3(0, 0, -2), Vec3(0, 0, 90)) frameB = TransformState.makePosHpr(Point3(-5, 0, 0), Vec3(0, 0, 0)) cone = BulletConeTwistConstraint(bodyA, bodyB, frameA, frameB) cone.setDebugDrawSize(2.0) cone.setLimit(30, 45, 170, softness=1.0, bias=0.3, relaxation=8.0) self.world.attachConstraint(cone)
def trs_transform(self): """ trs = translate-rotate-scale transform for mask stage panda3d developer rdb contributed to this code """ pos = 0.5 + self.mask_position_uv[0], 0.5 + self.mask_position_uv[1] center_shift = TransformState.make_pos2d((-pos[0], -pos[1])) scale = TransformState.make_scale2d(1 / self.scale) rotate = TransformState.make_rotate2d( self.current_stim_params['strip_angle']) translate = TransformState.make_pos2d((0.5, 0.5)) return translate.compose(rotate.compose(scale.compose(center_shift)))
def trs_transform(self): """ trs = translate rotate scale transform for mask stage rdb contributed to this code """ #print(self.strip_angle) pos = 0.5 + self.mask_position_uv[0], 0.5 + self.mask_position_uv[1] center_shift = TransformState.make_pos2d((-pos[0], -pos[1])) scale = TransformState.make_scale2d(1 / self.scale) rotate = TransformState.make_rotate2d(self.strip_angle) translate = TransformState.make_pos2d((0.5, 0.5)) return translate.compose(rotate.compose(scale.compose(center_shift)))
def doInverseRelativeSweepTest(self, relativePoint, bitMask=None, height=0.1): globalPoint = self.scene.Base.render.getRelativePoint(self.bodyNP, relativePoint) fromT = TransformState.makePos(self.bodyNP.getPos(self.scene.Base.render) + VBase3(0, 0, height)) toT = TransformState.makePos(globalPoint + VBase3(0, 0, height)) if bitMask != None: r = self.scene.world.sweepTestClosest(self.shape, toT, fromT, bitMask) else: r = self.scene.world.sweepTestClosest(self.shape, toT, fromT) if r.getNode() == self.body: return BulletClosestHitSweepResult.empty() else: return r
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()) # Plane shape = BulletPlaneShape(Vec3(0, 0, 1), 0) np = self.worldNP.attachNewNode(BulletRigidBodyNode('Ground')) np.node().addShape(shape) np.setPos(0, 0, -1) np.setCollideMask(BitMask32.allOn()) self.world.attachRigidBody(np.node()) # Box shape = BulletBoxShape(Vec3(0.5, 0.5, 0.5)) np = self.worldNP.attachNewNode(BulletRigidBodyNode('Box')) np.node().setMass(1.0) np.node().addShape(shape) np.node().addShape(shape, TransformState.makePos(Point3(0, 1, 0))) np.node().setDeactivationEnabled(False) np.setPos(2, 0, 4) np.setCollideMask(BitMask32.allOn()) self.world.attachRigidBody(np.node()) visualNP = loader.loadModel('models/box.egg') visualNP.reparentTo(np) self.box = np.node() # Sphere shape = BulletSphereShape(0.6) np = self.worldNP.attachNewNode(BulletRigidBodyNode('Sphere')) np.node().setMass(1.0) np.node().addShape(shape) np.node().addShape(shape, TransformState.makePos(Point3(0, 1, 0))) np.setPos(-2, 0, 4) np.setCollideMask(BitMask32.allOn()) self.world.attachRigidBody(np.node()) self.sphere = np.node()
def testRenderWithModelLights(self): filename = os.path.join(TEST_SUNCG_DATA_DIR, 'metadata', 'suncgModelLights.json') info = SunCgModelLights(filename) scene = Scene() modelId = 's__1296' modelFilename = os.path.join(TEST_SUNCG_DATA_DIR, "object", str(modelId), str(modelId) + ".egg") assert os.path.exists(modelFilename) model = loadModel(modelFilename) model.setName('model-' + str(modelId)) model.show(BitMask32.allOn()) objectsNp = scene.scene.attachNewNode('objects') objNp = objectsNp.attachNewNode('object-' + str(modelId)) model.reparentTo(objNp) # Calculate the center of this object minBounds, maxBounds = model.getTightBounds() centerPos = minBounds + (maxBounds - minBounds) / 2.0 # Add offset transform to make position relative to the center model.setTransform(TransformState.makePos(-centerPos)) # Add lights to model for lightNp in info.getLightsForModel(modelId): lightNp.node().setShadowCaster(True, 512, 512) lightNp.reparentTo(model) scene.scene.setLight(lightNp) viewer = None try: viewer = Viewer(scene, interactive=False, shadowing=True) viewer.cam.setTransform( TransformState.makePos(LVector3f(0.5, 0.5, 3.0))) viewer.cam.lookAt(lightNp) for _ in range(20): viewer.step() time.sleep(1.0) finally: if viewer is not None: viewer.destroy() viewer.graphicsEngine.removeAllWindows()
def addBox(self,name,size,pos,visual): # Box (dynamic) box = NodePath(BulletRigidBodyNode(name)) box.node().setMass(1.0) box.node().addShape(BulletBoxShape(size)) box.setCollideMask(GAME_OBJECT_BITMASK) #box.node().setLinearFactor((1,0,1)) #box.node().setAngularFactor((0,1,0)) visual.instanceTo(box) box.reparentTo(self.getParent()) box.setPos(self,pos) box.setHpr(self,Vec3.zero()) self.physics_world_.attachRigidBody(box.node()) self.object_nodes_.append(box) # adding constraint motion2d_constraint = BulletGenericConstraint(self.constraint_plane_.node(),box.node(), TransformState.makeIdentity(), TransformState.makeIdentity(), False) rot_constraint = BulletGenericConstraint(self.constraint_plane_.node(),box.node(), TransformState.makeIdentity(), TransformState.makeIdentity(), False) motion2d_constraint.setLinearLimit(0,-sys.float_info.max,sys.float_info.max) motion2d_constraint.setLinearLimit(1,0,0) motion2d_constraint.setLinearLimit(2,-sys.float_info.max,sys.float_info.max) # All angular constraints must be either locked or released for the simulation to be stable #motion2d_constraint.setAngularLimit(0,-0.1,0.1) #motion2d_constraint.setAngularLimit(1,-100,100) #motion2d_constraint.setAngularLimit(2,-0.1,0.1) #motion2d_constraint.setBreakingThreshold(1000) motion2d_constraint.setDebugDrawSize(0) # for axis in range(0,6): # motion2d_constraint.setParam(BulletGenericConstraint.CP_cfm,0,axis) # motion2d_constraint.setParam(BulletGenericConstraint.CP_erp,0.4,axis) self.physics_world_.attach(motion2d_constraint) self.box_contraints_.append(motion2d_constraint) return box
def doSceneCleanup(): from panda3d.core import ModelPool, TexturePool, RenderState, RenderAttrib, TransformState, GeomCacheManager ModelPool.garbageCollect() TexturePool.garbageCollect() RenderState.clearMungerCache() RenderState.clearCache() RenderState.garbageCollect() RenderAttrib.garbageCollect() TransformState.clearCache() TransformState.garbageCollect() GeomCacheManager.getGlobalPtr().flush() base.graphicsEngine.renderFrame()
def _create_bone_node(self, bone): box_shape = panda3d.bullet.BulletBoxShape( Vec3(bone.length, bone.height, bone.width)) # ts = TransformState.makePos(Point3(bone.length, bone.height, bone.width)) ts = TransformState.makePos(Point3(0, 0, 0)) bone_node = panda3d.bullet.BulletRigidBodyNode(bone.name) bone_node.setMass(bone.mass) bone_node.setFriction(bone.friction) bone_node.addShape(box_shape, ts) bone_node.setTransform( TransformState.makePosHpr(Vec3(*bone.start_pos), Vec3(*bone.start_hpr))) self.world.attachRigidBody(bone_node) self.bones_to_nodes[bone] = bone_node
def getPhysBody(self): from panda3d.bullet import BulletRigidBodyNode, BulletBoxShape from panda3d.core import TransformState bnode = BulletRigidBodyNode('entity-phys') bnode.setMass(self.mass) bnode.setCcdMotionThreshold(1e-7) bnode.setCcdSweptSphereRadius(0.5) if self.solidType == self.SOLID_MESH: convexHull = PhysicsUtils.makeBulletConvexHullFromCollisionSolids( self.model.find("**/+CollisionNode").node()) bnode.addShape(convexHull) elif self.solidType == self.SOLID_BBOX: mins = Point3() maxs = Point3() self.calcTightBounds(mins, maxs) extents = PhysicsUtils.extentsFromMinMax(mins, maxs) tsCenter = TransformState.makePos( PhysicsUtils.centerFromMinMax(mins, maxs)) shape = BulletBoxShape(extents) bnode.addShape(shape, tsCenter) return bnode
def __init__(self, world, attach, name = '', position = Vec3(0,0,0), orientation = Vec3(0,0,0), turretPitch = 0): #Constant Relevant Instatiation Parameters self._tankSize = Vec3(1, 1.5, .5) # Actually a half-size self._tankSideLength = max(self._tankSize) friction = .3 tankMass = 800.0 # Rewrite constructor to include these? self._maxVel = 4 self._maxRotVel = 1 self._maxThrusterAccel = 5000 self._breakForce = 1000 turretRelPos = (0, 0, 0) #Relative to tank self._shape = BulletBoxShape(Vec3(1,1.5,.5)) #chassis self._transformState = TransformState.makePos(Point3(0, 0, 0)) #offset DynamicWorldObject.__init__(self, world, attach, name, position, self._shape, orientation, Vec3(0,0,0), mass = tankMass) #Initial velocity must be 0 self.__createVehicle(self._tankWorld.getPhysics()) self._collisionCounter = 0 self._taskTimer = 0 self._nodePath.node().setFriction(friction) self._nodePath.setPos(position) # Set up turret nodepath # (Nodepaths are how objects are managed in Panda3d) self.onTask = 0 # Make collide mask (What collides with what) self._nodePath.setCollideMask(0xFFFF0000) #self._nodePath.setCollideMask(BitMask32.allOff()) self.movementPoint = Point3(10,10,0)
def __init__(self, world, parent, params): self.params = params self.__world = world self.__g = world.getGravity().z # negative value self.__events = Events() self.__shape_stand = BulletCapsuleShape(params['radius'], params['height'] - 2 * params['radius'], ZUp) self.__shape_crouch = BulletCapsuleShape(params['radius'], params['crouch_height'] - 2 * params['radius'], ZUp) self.__ghost = BulletGhostNode('Capsule for ' + params['name']) self.__ghost.addShape(self.__shape_stand, TransformState.makePos((0, 0, params['height'] / 2))) self.node = parent.attachNewNode(self.__ghost) self.node.setCollideMask(BitMask32.allOn()) world.attachGhost(self.__ghost) self.__foot_contact = self.__head_contact = None self.velocity = Vec3() self.__outer_motion = Vec3() self.__motion_time_ival = 0 self.__ignore_player_motion = False self.__outer_rotation = self.__rotation_time_ival = 0 self.__ignore_player_rotation = False self.__falling = False self.__crouches = False # controls self.__want_crouch = False self.__want_fly = False
def raycast(self): # Raycast for closest hit tsFrom = TransformState.makePos(Point3(0,0,0)) tsTo = TransformState.makePos(Point3(10,0,0)) shape = BulletSphereShape(0.5) penetration = 1.0 result = self.world.sweepTestClosest(shape, tsFrom, tsTo, penetration) if result.hasHit(): torque = Vec3(10,0,0) force = Vec3(0,0,100) ## for hit in result.getHits(): ## hit.getNode().applyTorque(torque) ## hit.getNode().applyCentralForce(force) result.getNode().applyTorque(torque) result.getNode().applyCentralForce(force)
def _update_stats(self): """ Updates the stats overlay """ clock = Globals.clock self._debug_lines[0].set_text("{:3.0f} fps | {:3.1f} ms | {:3.1f} ms max".format( clock.get_average_frame_rate(), 1000.0 / max(0.001, clock.get_average_frame_rate()), clock.get_max_frame_duration() * 1000.0)) text = "{:4d} render states | {:4d} transforms" text += " | {:4d} commands | {:6d} lights | {:5d} shadow sources" self._debug_lines[1].set_text(text.format( RenderState.get_num_states(), TransformState.get_num_states(), self._pipeline.light_mgr.get_cmd_queue().get_num_processed_commands(), self._pipeline.light_mgr.get_num_lights(), self._pipeline.light_mgr.get_num_shadow_sources(), )) text = "{:3.0f} MiB VRAM usage | {:5d} images | {:5d} textures | " text += "{:5d} render targets | {:3d} plugins" tex_info = self._buffer_viewer.get_stage_information() self._debug_lines[2].set_text(text.format( tex_info["memory"] / (1024**2) , Image._NUM_IMAGES, tex_info["count"], RenderTarget._NUM_BUFFERS_ALLOCATED, self._pipeline.plugin_mgr.get_interface().get_active_plugin_count() )) text = "{} ({:1.3f}) | {:3d} active constraints" self._debug_lines[3].set_text(text.format( self._pipeline.daytime_mgr.get_time_str(), self._pipeline.daytime_mgr.get_time(), self._pipeline.daytime_mgr.get_num_constraints() ))
def __activateConstraint__(self,constraint): if self.selected_constraint_ != constraint: # disabling active constraint self.__deactivateConstraint__() if not constraint.isEnabled(): # placing actor rigid body relative to character's rigid body actorrb_np = self.animator_.getRigidBody() static = actorrb_np.node().isStatic() actorrb_np.node().setStatic(True) actorrb_np.setTransform(self,TransformState.makeIdentity()) if constraint == self.right_constraint_: actorrb_np.setH(self,0) else: actorrb_np.setH(self,180) actorrb_np.node().setStatic(static) self.node().setStatic(static) self.selected_constraint_ = constraint self.selected_constraint_.setEnabled(True) self.physics_world_.attach(self.selected_constraint_)
def __init__(self): """ Creates a new ShadowSource. After the creation, a lens can be added with setupPerspectiveLens or setupOrtographicLens. """ self.index = self._generateUID() DebugObject.__init__(self, "ShadowSource-" + str(self.index)) ShaderStructElement.__init__(self) self.valid = False self.camera = Camera("ShadowSource-" + str(self.index)) self.camera.setActive(False) self.cameraNode = NodePath(self.camera) self.cameraNode.reparentTo(Globals.render.find("RPCameraDummys")) self.cameraNode.hide() self.resolution = 512 self.atlasPos = Vec2(0) self.doesHaveAtlasPos = False self.sourceIndex = 0 self.mvp = UnalignedLMatrix4f() self.sourceIndex = -1 self.nearPlane = 0.0 self.farPlane = 1000.0 self.converterYUR = None self.transforMat = TransformState.makeMat( Mat4.convertMat( Globals.base.win.getGsg().getInternalCoordinateSystem(), CSZupRight))
def setupPhysics(self, radius=None, height=None): if not radius: radius = self.getWidth() if not height: height = self.getHeight() self.notify.debug("setupPhysics(r{0}, h{1}) hitboxData: {2}".format( radius, height, self.hitboxData)) # When the height is passed into BulletCapsuleShape, it's # talking about the height only of the cylinder part. # But what we want is the height of the entire capsule. #height -= (radius * 2) # The middle of the capsule is the origin by default. Push the capsule shape up # so the very bottom of the capsule is the origin. zOfs = (height / 2.0) + radius capsule = BulletCapsuleShape(radius, height) bodyNode = BulletRigidBodyNode('avatarBodyNode') bodyNode.addShape(capsule, TransformState.makePos(Point3(0, 0, zOfs))) bodyNode.setKinematic(True) bodyNode.setPythonTag("avatar", self) BasePhysicsObject.setupPhysics(self, bodyNode, True) self.stopWaterCheck()
def __init__(self, model, world, worldNP, pos, scale, hpr): self.worldNP = worldNP bulletWorld = world # Initialize the model. self.AIModel = loader.loadModel(model) self.AINode = BulletRigidBodyNode("AIChar") self.AIModel.setScale(scale) self.AIModel.flattenLight() # Combines all geom nodes into one geom node. # Build the triangle mesh shape and attach it with the transform. geom = self.AIModel.findAllMatches("**/+GeomNode").getPath(0).node().getGeom(0) mesh = BulletTriangleMesh() mesh.addGeom(geom) shape = BulletTriangleMeshShape(mesh, dynamic=False) self.AINode.addShape(shape, TransformState.makePosHprScale(Point3(0, 0, 0), hpr, scale)) self.AINode.setMass(0) bulletWorld.attachRigidBody(self.AINode) # Apply the same transforms on the model being rendered. self.AIModel.reparentTo(render) self.AIModel.setH(hpr.getX()) self.AIModel.setP(hpr.getY()) self.AIModel.setR(hpr.getZ()) self.AINode.setAngularFactor(Vec3(0, 0, 0)) # Attach it to the world. self.AIChar = self.worldNP.attachNewNode(self.AINode) self.AIModel.reparentTo(self.AIChar) self.AIChar.setPos(pos)
def __create2DConstraint__(self,obj): obj.setQuat(self,LQuaternion.identQuat()) obj.setY(self,0) constraint = BulletGenericConstraint(self.motion_plane_np_.node(),obj.node(), TransformState.makeIdentity(),TransformState.makeIdentity(),False) max_float = sys.float_info.max constraint.setLinearLimit(0,-max_float,max_float) constraint.setLinearLimit(1,0,0) constraint.setLinearLimit(2,-max_float,max_float) constraint.setDebugDrawSize(0) return constraint
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))
def ledgeCollisionCallback(self,action): ledge = action.game_obj2 ghost_body = self.character_obj_.getActionGhostBody() self.character_obj_.getStatus().ledge = ledge self.character_obj_.setStatic(True) # detemining position of ghost action body relative to character pos = ghost_body.node().getShapePos(0) if not self.character_obj_.isFacingRight(): # rotate about z by 180 if looking left pos.setX(-pos.getX()) # creating transform for placement of character relative to ledge ref_np = self.character_obj_.getReferenceNodePath() tf_obj_to_ghost = LMatrix4.translateMat(pos) tf_ghost_to_object = LMatrix4(tf_obj_to_ghost) tf_ghost_to_object.invertInPlace() tf_ref_to_ledge = ledge.getMat(ref_np) tf_ref_to_obj = TransformState.makeMat(tf_ref_to_ledge * tf_ghost_to_object) pos = tf_ref_to_obj.getPos() # placing character on ledge self.character_obj_.setX(ref_np,pos.getX()) self.character_obj_.setZ(ref_np,pos.getZ()) self.character_obj_.setLinearVelocity(Vec3(0,0,0)) # turning off collision ghost_body.node().setIntoCollideMask(CollisionMasks.NO_COLLISION) logging.debug(inspect.stack()[0][3] + ' invoked')
def move_city(self, task): # moves the city, using the transformation matrix # first, get the current transformation matrix # getTransform() returns a TransformState, which is a higher level # abstraction of our matrix # getMat() retrieves the inner matrix. the returned matrix is const # though oldmat = self.cityModel.getTransform().getMat() # oldmat ist a const Mat4, we need one we can manipulate newmat = Mat4(oldmat) # the matrices in Panda3d are suitable for row-vector multiplication, that is # vector * Matrix (same as opengl). the bottom row (3) is therefore the # translation in xyzt order # # replace it with a different one, we want to move the value of # time, which is the number of seconds passed since starting this task newmat.setRow(3, Vec4(1-task.time, 3, 0, 1)) # we need to create a new TransformState from the matrix, and set it # to apply the transformation self.cityModel.setTransform(TransformState.makeMat(newmat)) return Task.cont
def _createInputHandles(self): """ Defines various inputs to be used in the shader passes. Most inputs use pta-arrays, so updating them is faster than using setShaderInput all the time. """ self.cameraPosition = PTAVecBase3f.emptyArray(1) self.currentViewMat = PTALMatrix4f.emptyArray(1) self.currentProjMatInv = PTALMatrix4f.emptyArray(1) self.lastMVP = PTALMatrix4f.emptyArray(1) self.currentMVP = PTALMatrix4f.emptyArray(1) self.frameIndex = PTAInt.emptyArray(1) self.frameDelta = PTAFloat.emptyArray(1) self.renderPassManager.registerStaticVariable("lastMVP", self.lastMVP) self.renderPassManager.registerStaticVariable("currentMVP", self.currentMVP) self.renderPassManager.registerStaticVariable("frameIndex", self.frameIndex) self.renderPassManager.registerStaticVariable("cameraPosition", self.cameraPosition) self.renderPassManager.registerStaticVariable("mainCam", self.showbase.cam) self.renderPassManager.registerStaticVariable("mainRender", self.showbase.render) self.renderPassManager.registerStaticVariable("frameDelta", self.frameDelta) self.renderPassManager.registerStaticVariable("currentViewMat", self.currentViewMat) self.renderPassManager.registerStaticVariable("currentProjMatInv", self.currentProjMatInv) self.renderPassManager.registerStaticVariable("zeroVec2", Vec2(0)) self.renderPassManager.registerStaticVariable("zeroVec3", Vec3(0)) self.renderPassManager.registerStaticVariable("zeroVec4", Vec4(0)) self.transformMat = TransformState.makeMat(Mat4.convertMat(CSYupRight, CSZupRight))
def __init__(self): """ Creates a new ShadowSource. After the creation, a lens can be added with setupPerspectiveLens or setupOrtographicLens. """ self.index = self._generateUID() DebugObject.__init__(self, "ShadowSource-" + str(self.index)) ShaderStructElement.__init__(self) self.valid = False self.camera = Camera("ShadowSource-" + str(self.index)) self.camera.setActive(False) self.cameraNode = NodePath(self.camera) self.cameraNode.reparentTo(Globals.render.find("RPCameraDummys")) self.cameraNode.hide() self.resolution = 512 self.atlasPos = Vec2(0) self.doesHaveAtlasPos = False self.sourceIndex = 0 self.mvp = UnalignedLMatrix4f() self.sourceIndex = -1 self.nearPlane = 0.0 self.farPlane = 1000.0 self.converterYUR = None self.transforMat = TransformState.makeMat( Mat4.convertMat(Globals.base.win.getGsg().getInternalCoordinateSystem(), CSZupRight))
def setupVehicle(self, main): scale = 0.5 # Chassis shape = BulletBoxShape(Vec3(0.6, 1.4, 0.5)) ts = TransformState.makePos(Point3(0, 0, 0.5 * scale)) name = self.username self.chassisNode = BulletRigidBodyNode(name) self.chassisNode.setTag('username', str(name)) self.chassisNP = main.worldNP.attachNewNode(self.chassisNode) self.chassisNP.setName(str(name)) self.chassisNP.node().addShape(shape, ts) self.chassisNP.setScale(scale) self.chassisNP.setPos(self.pos) if self.isCurrentPlayer: self.chassisNP.node().notifyCollisions(True) self.chassisNP.node().setMass(800.0) else: self.chassisNP.node().notifyCollisions(True) self.chassisNP.node().setMass(400.0) self.chassisNP.node().setDeactivationEnabled(False) main.world.attachRigidBody(self.chassisNP.node()) #np.node().setCcdSweptSphereRadius(1.0) #np.node().setCcdMotionThreshold(1e-7) # Vehicle self.vehicle = BulletVehicle(main.world, self.chassisNP.node()) self.vehicle.setCoordinateSystem(ZUp) main.world.attachVehicle(self.vehicle) self.yugoNP = loader.loadModel('models/yugo/yugo.egg') self.yugoNP.reparentTo(self.chassisNP) #self.carNP = loader.loadModel('models/batmobile-chassis.egg') #self.yugoNP.setScale(.7) #self.carNP.reparentTo(self.chassisNP) # Right front wheel np = loader.loadModel('models/yugo/yugotireR.egg') np.reparentTo(main.worldNP) self.addWheel(Point3( 0.70 * scale, 1.05 * scale, 0.3), True, np) # Left front wheel np = loader.loadModel('models/yugo/yugotireL.egg') np.reparentTo(main.worldNP) self.addWheel(Point3(-0.70 * scale, 1.05 * scale, 0.3), True, np) # Right rear wheel np = loader.loadModel('models/yugo/yugotireR.egg') np.reparentTo(main.worldNP) self.addWheel(Point3( 0.70 * scale, -1.05 * scale, 0.3), False, np) # Left rear wheel np = loader.loadModel('models/yugo/yugotireL.egg') np.reparentTo(main.worldNP) self.addWheel(Point3(-0.70 * scale, -1.05 * scale, 0.3), False, np)
def draw_debugging_arrow(base, v_from, v_to): arrowModel = base.loader.loadModel('models/debuggingArrow') mat = align_to_vector(v_to-v_from) arrowModel.setTransform(TransformState.makeMat(mat)) arrowModel.setPos(*v_from) arrowModel.reparentTo(base.render) return arrowModel
def __init__(self,info): # animation base setup self.character_info_ = info size = Vec3(info.width, AnimationActor.DEFAULT_WIDTH , info.height) AnimatableObject.__init__(self,info.name,size,info.mass) self.animation_root_np_.setPos(Vec3(0,0,0)) # constraints self.left_constraint_ = None self.right_constraint_ = None self.selected_constraint_ = None # removing default shapes from rigid body shapes = self.node().getShapes() for shape in shapes: self.node().removeShape(shape) # adding capsule shape radius = 0.5*size.getX() height = size.getZ() - 2.0*radius # height of cylindrical part only height = height if height >= 0 else 0.0 bullet_shape = BulletCapsuleShape(radius, height, ZUp) bullet_shape.setMargin(GameObject.DEFAULT_COLLISION_MARGIN) self.node().addShape(bullet_shape,TransformState.makePos(Vec3(0,0,0.5*size.getZ()))) # box bottom center coincident with the origin self.node().setMass(self.character_info_.mass) self.node().setLinearFactor((1,1,1)) self.node().setAngularFactor((0,0,0)) self.setCollideMask(CollisionMasks.NO_COLLISION) # setting bounding volume min = LPoint3(-0.5*size.getX(),-0.5*size.getY(),0) max = LPoint3(0.5*size.getX(),0.5*size.getY(),size.getZ()) self.node().setBoundsType(BoundingVolume.BT_box) self.node().setBounds(BoundingBox(min,max)) # setting origin ghost nodes rel_pos = Vec3(-GameObject.ORIGIN_XOFFSET,0,info.height/2) self.left_origin_gn_ = self.attachNewNode(BulletGhostNode(self.getName() + '-left-origin')) self.left_origin_gn_.node().addShape(BulletSphereShape(GameObject.ORIGIN_SPHERE_RADIUS),TransformState.makePosHpr(rel_pos,Vec3.zero())) self.left_origin_gn_.node().setIntoCollideMask(CollisionMasks.ACTION_TRIGGER_0 if not self.isFacingRight() else CollisionMasks.NO_COLLISION) rel_pos = Vec3(GameObject.ORIGIN_XOFFSET,0,info.height/2) self.right_origin_gn_ = self.attachNewNode(BulletGhostNode(self.getName() + '-right-origin')) self.right_origin_gn_.node().addShape(BulletSphereShape(GameObject.ORIGIN_SPHERE_RADIUS),TransformState.makePosHpr(rel_pos,Vec3.zero())) self.right_origin_gn_.node().setIntoCollideMask(CollisionMasks.ACTION_TRIGGER_0 if self.isFacingRight() else CollisionMasks.NO_COLLISION) # character status self.state_data_ = CharacterStateData() # state machine self.sm_ = StateMachine() # motion commander self.motion_commander_ = MotionCommander(self) # set id self.setObjectID(self.getName())
def addMultiSphereGhost(self,rads,centT,**kw): inodenp = self.worldNP.attachNewNode(BulletGhostNode("Sphere")) for radc, posc in zip(rads, centT): shape = BulletSphereShape(radc) inodenp.node().addShape(shape, TransformState.makePos(Point3(posc[0],posc[1],posc[2])))# self.setRB(inodenp,**kw) inodenp.setCollideMask(BitMask32.allOn()) self.world.attachRigidBody(inodenp.node()) return inodenp
def __setupConstraints__(self,actor_rigid_body_np): self.__cleanupConstraints__() self.left_constraint_ = BulletGenericConstraint(self.node(), actor_rigid_body_np.node(), TransformState.makeIdentity(), TransformState.makeHpr(Vec3(180,0,0)),False) self.right_constraint_ = BulletGenericConstraint(self.node(), actor_rigid_body_np.node(), TransformState.makeIdentity(), TransformState.makeIdentity(),False) self.left_constraint_.setEnabled(False) self.right_constraint_.setEnabled(False) for axis in range(0,6): self.left_constraint_.setParam(BulletGenericConstraint.CP_cfm,0,axis) self.right_constraint_.setParam(BulletGenericConstraint.CP_cfm,0,axis)