def close_world(self): self.taskMgr.stop() # It will report a warning said AsynTaskChain is created when taskMgr.destroy() is called but a new showbase is # created. logging.debug( "Before del taskMgr: task_chain_num={}, all_tasks={}".format( self.taskMgr.mgr.getNumTaskChains(), self.taskMgr.getAllTasks() ) ) self.taskMgr.destroy() logging.debug( "After del taskMgr: task_chain_num={}, all_tasks={}".format( self.taskMgr.mgr.getNumTaskChains(), self.taskMgr.getAllTasks() ) ) # while self.taskMgr.getAllTasks(): # time.sleep(0.1) self.physics_world.destroy() self.destroy() AssetLoader.destroy() import sys if sys.version_info >= (3, 0): import builtins else: import __builtin__ as builtins if hasattr(builtins, 'base'): del builtins.base
def __init__(self, block_index: int, pre_block_socket: BlockSocket, global_network: RoadNetwork, random_seed): super(Block, self).__init__(random_seed) # block information assert self.ID is not None, "Each Block must has its unique ID When define Block" assert self.SOCKET_NUM is not None, "The number of Socket should be specified when define a new block" if block_index == 0: from pgdrive.scene_creator.blocks import FirstBlock assert isinstance(self, FirstBlock), "only first block can use block index 0" elif block_index < 0: logging.debug("It is recommended that block index should > 1") self._block_name = str(block_index) + self.ID self.block_index = block_index self.number_of_sample_trial = 0 # each block contains its own road network and a global network self._global_network = global_network self.block_network = RoadNetwork() # used to spawn npc self._reborn_roads = [] # own sockets, one block derives from a socket, but will have more sockets to connect other blocks self._sockets = [] # used to connect previous blocks, save its info here self._pre_block_socket = pre_block_socket self.pre_block_socket_index = pre_block_socket.index # a bounding box used to improve efficiency x_min, x_max, y_min, y_max self.bounding_box = None # used to create this block, but for first block it is nonsense if block_index != 0: self.positive_lanes = self._pre_block_socket.positive_road.get_lanes(self._global_network) self.negative_lanes = self._pre_block_socket.negative_road.get_lanes(self._global_network) self.positive_lane_num = len(self.positive_lanes) self.negative_lane_num = len(self.negative_lanes) self.positive_basic_lane = self.positive_lanes[-1] # most right or outside lane is the basic lane self.negative_basic_lane = self.negative_lanes[-1] # most right or outside lane is the basic lane self.lane_width = self.positive_basic_lane.width_at(0) if self.render: # render pre-load self.road_texture = self.loader.loadTexture(AssetLoader.file_path("textures", "sci", "color.jpg")) self.road_texture.setMinfilter(SamplerState.FT_linear_mipmap_linear) self.road_texture.setAnisotropicDegree(8) self.road_normal = self.loader.loadTexture(AssetLoader.file_path("textures", "sci", "normal.jpg")) self.ts_color = TextureStage("color") self.ts_normal = TextureStage("normal") self.side_texture = self.loader.loadTexture(AssetLoader.file_path("textures", "side_walk", "color.png")) self.side_texture.setMinfilter(SamplerState.FT_linear_mipmap_linear) self.side_texture.setAnisotropicDegree(8) self.side_normal = self.loader.loadTexture(AssetLoader.file_path("textures", "side_walk", "normal.png")) self.side_walk = self.loader.loadModel(AssetLoader.file_path("models", "box.bam"))
def __init__(self, pg_world, show_navi_point: False): """ It now only support from first block start to the end node, but can be extended easily """ self.map = None self.final_road = None self.checkpoints = None self.final_lane = None self.target_checkpoints_index = None self.navi_info = None # navi information res self.current_ref_lanes = None # Vis self.showing = True # store the state of navigation mark self.show_navi_point = pg_world.mode == RENDER_MODE_ONSCREEN and not pg_world.pg_config[ "debug_physics_world"] self.goal_node_path = pg_world.render.attachNewNode( "target") if self.show_navi_point else None self.arrow_node_path = pg_world.aspect2d.attachNewNode( "arrow") if self.show_navi_point else None if self.show_navi_point: navi_arrow_model = AssetLoader.loader.loadModel( AssetLoader.file_path("models", "navi_arrow.gltf")) navi_arrow_model.setScale(0.1, 0.12, 0.2) navi_arrow_model.setPos(2, 1.15, -0.221) self.left_arrow = self.arrow_node_path.attachNewNode("left arrow") self.left_arrow.setP(180) self.right_arrow = self.arrow_node_path.attachNewNode( "right arrow") self.left_arrow.setColor(self.MARK_COLOR) self.right_arrow.setColor(self.MARK_COLOR) navi_arrow_model.instanceTo(self.left_arrow) navi_arrow_model.instanceTo(self.right_arrow) self.arrow_node_path.setPos(0, 0, 0.08) self.arrow_node_path.hide(BitMask32.allOn()) self.arrow_node_path.show(CamMask.MainCam) self.arrow_node_path.setQuat( LQuaternionf(np.cos(-np.pi / 4), 0, 0, np.sin(-np.pi / 4))) # the transparency attribute of gltf model is invalid on windows # self.arrow_node_path.setTransparency(TransparencyAttrib.M_alpha) if show_navi_point: navi_point_model = AssetLoader.loader.loadModel( AssetLoader.file_path("models", "box.egg")) navi_point_model.reparentTo(self.goal_node_path) self.goal_node_path.setTransparency(TransparencyAttrib.M_alpha) self.goal_node_path.setColor(0.6, 0.8, 0.5, 0.7) self.goal_node_path.hide(BitMask32.allOn()) self.goal_node_path.show(CamMask.MainCam) logging.debug("Load Vehicle Module: {}".format( self.__class__.__name__))
def _add_wheel(self, pos: Vec3, radius: float, front: bool, left): wheel_np = self.node_path.attachNewNode("wheel") if self.render: # TODO something wrong with the wheel render model_path = 'models/yugo/yugotireR.egg' if left else 'models/yugo/yugotireL.egg' wheel_model = self.loader.loadModel( AssetLoader.file_path(model_path)) wheel_model.reparentTo(wheel_np) wheel_model.set_scale(1.4, radius / 0.25, radius / 0.25) wheel = self.system.create_wheel() wheel.setNode(wheel_np.node()) wheel.setChassisConnectionPointCs(pos) wheel.setFrontWheel(front) wheel.setWheelDirectionCs(Vec3(0, 0, -1)) wheel.setWheelAxleCs(Vec3(1, 0, 0)) # TODO add them to PGConfig in the future wheel.setWheelRadius(radius) wheel.setMaxSuspensionTravelCm(40) wheel.setSuspensionStiffness(30) wheel.setWheelsDampingRelaxation(4.8) wheel.setWheelsDampingCompression(1.2) wheel.setFrictionSlip(self.vehicle_config["wheel_friction"]) wheel.setRollInfluence(1.5) return wheel
def __init__(self, random_seed=None, name=None): """ Config is a static conception, which specified the parameters of one element. There parameters doesn't change, such as length of straight road, max speed of one vehicle, etc. """ self.name = random_string() if name is None else name assert isinstance( self.PARAMETER_SPACE, PGSpace ) or random_seed is None, "Using PGSpace to define parameter spaces of " + self.class_name self._config = PGConfig( {k: None for k in self.PARAMETER_SPACE.parameters}) self.random_seed = 0 if random_seed is None else random_seed if self.PARAMETER_SPACE is not None: self.PARAMETER_SPACE.seed(self.random_seed) self.render = False if AssetLoader.loader is None else True # each element has its node_path to render, physics node are child nodes of it self.node_path = None # Temporally store bullet nodes that have to place in bullet world (not NodePath) self.dynamic_nodes = PhysicsNodeList() # Nodes in this tuple didn't interact with other nodes! they only used to do rayTest or sweepTest self.static_nodes = PhysicsNodeList() if self.render: self.loader = AssetLoader.get_loader() if not hasattr(self.loader, "loader"): # It is closed before! self.loader.__init__()
def _load_shader_str(shaderpath, defines=None): shader_dir = AssetLoader.file_path("shaders", "pbr_shaders", shaderpath) with open(shader_dir) as shaderfile: shaderstr = shaderfile.read() if defines is not None: shaderstr = _add_shader_defines(shaderstr, defines) return shaderstr
def _add_lane_line2bullet(self, lane_start, lane_end, middle, parent_np: NodePath, color: Vec4, line_type: LineType, straight_stripe=False): length = norm(lane_end[0] - lane_start[0], lane_end[1] - lane_start[1]) if length <= 0: return if LineType.prohibit(line_type): node_name = BodyName.White_continuous_line if color == LineColor.GREY else BodyName.Yellow_continuous_line else: node_name = BodyName.Broken_line # add bullet body for it if straight_stripe: body_np = parent_np.attachNewNode(node_name) else: 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) # its scale will change by setScale body_height = Block.LANE_LINE_GHOST_HEIGHT shape = BulletBoxShape( Vec3(length / 2 if line_type != LineType.BROKEN else length, Block.LANE_LINE_WIDTH / 2, body_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()) # position and heading 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))) if self.render: # For visualization lane_line = self.loader.loadModel( AssetLoader.file_path("models", "box.bam")) lane_line.setScale(length, Block.LANE_LINE_WIDTH, Block.LANE_LINE_THICKNESS) lane_line.setPos(Vec3(0, 0 - Block.LANE_LINE_GHOST_HEIGHT / 2)) lane_line.reparentTo(body_np) body_np.set_color(color)
def test_asset_loader(): default_config = PGDriveEnv.default_config() world_config = default_config["pg_world_config"] world_config.update({"use_render": False, "use_image": False, "debug": False}) world = PGWorld(config=world_config) try: world.clear_world() initialize_asset_loader(world) print(AssetLoader.asset_path) print(AssetLoader.file_path("aaa")) # print(AssetLoader.get_loader()) finally: world.close_world()
def __init__(self, index: int, kinematic_model: IDMVehicle, enable_respawn: bool = False, np_random=None): """ A traffic vehicle class. :param index: Each Traffic vehicle has an unique index, and the name of this vehicle will contain this index :param kinematic_model: IDM Model or other models :param enable_respawn: It will be generated at the spawn place again when arriving at the destination :param np_random: Random Engine """ kinematic_model.LENGTH = self.LENGTH kinematic_model.WIDTH = self.WIDTH super(PGTrafficVehicle, self).__init__() self.vehicle_node = TrafficVehicleNode( BodyName.Traffic_vehicle, IDMVehicle.create_from(kinematic_model)) chassis_shape = BulletBoxShape( Vec3(self.LENGTH / 2, self.WIDTH / 2, self.HEIGHT / 2)) self.index = index self.vehicle_node.addShape( chassis_shape, TransformState.makePos(Point3(0, 0, self.HEIGHT / 2))) self.vehicle_node.setMass(800.0) self.vehicle_node.setIntoCollideMask(BitMask32.bit( self.COLLISION_MASK)) self.vehicle_node.setKinematic(False) self.vehicle_node.setStatic(True) self.enable_respawn = enable_respawn self._initial_state = kinematic_model if enable_respawn else None self.dynamic_nodes.append(self.vehicle_node) self.node_path = NodePath(self.vehicle_node) self.out_of_road = False np_random = np_random or get_np_random() [path, scale, x_y_z_offset, H] = self.path[np_random.randint(0, len(self.path))] if self.render: if path not in PGTrafficVehicle.model_collection: carNP = self.loader.loadModel( AssetLoader.file_path("models", path)) PGTrafficVehicle.model_collection[path] = carNP else: carNP = PGTrafficVehicle.model_collection[path] carNP.setScale(scale) carNP.setH(H) carNP.setPos(x_y_z_offset) carNP.instanceTo(self.node_path) self.step(1e-1)
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)
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)
def _add_lane_line2bullet( self, lane_start, lane_end, middle, parent_np: NodePath, color: Vec4, line_type: LineType, straight_stripe=False ): length = norm(lane_end[0] - lane_start[0], lane_end[1] - lane_start[1]) if length <= 0: return if LineType.prohibit(line_type): node_name = BodyName.Continuous_line else: node_name = BodyName.Stripped_line # add bullet body for it if straight_stripe: body_np = parent_np.attachNewNode(node_name) else: scale = 2 if line_type == LineType.STRIPED else 1 body_node = BulletRigidBodyNode(node_name) body_node.setActive(False) body_node.setKinematic(False) body_node.setStatic(True) body_np = parent_np.attachNewNode(body_node) shape = BulletBoxShape(Vec3(scale / 2, Block.LANE_LINE_WIDTH / 2, Block.LANE_LINE_THICKNESS)) body_np.node().addShape(shape) body_np.node().setIntoCollideMask(BitMask32.bit(Block.LANE_LINE_COLLISION_MASK)) self.dynamic_nodes.append(body_np.node()) # position and heading body_np.setPos(panda_position(middle, 0)) 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))) if self.render: # For visualization lane_line = self.loader.loadModel(AssetLoader.file_path("models", "box.bam")) lane_line.getChildren().reparentTo(body_np) body_np.setScale(length, Block.LANE_LINE_WIDTH, Block.LANE_LINE_THICKNESS) body_np.set_color(color)
def __init__(self, lane, lane_index: LaneIndex, position: Sequence[float], heading: float = 0.): super(TrafficCone, self).__init__(lane, lane_index, position, heading) self.body_node = ObjectNode(self.NAME) self.body_node.addShape(BulletCylinderShape(self.RADIUS, self.HEIGHT)) self.node_path: NodePath = NodePath(self.body_node) self.node_path.setPos(panda_position(self.position, self.HEIGHT / 2)) self.dynamic_nodes.append(self.body_node) self.node_path.setH(panda_heading(self.heading)) if self.render: model = self.loader.loadModel( AssetLoader.file_path("models", "traffic_cone", "scene.gltf")) model.setScale(0.02) model.setPos(0, 0, -self.HEIGHT / 2) model.reparentTo(self.node_path)
def __init__(self, parent_node_np: NodePath, num_lasers: int = 16, distance: float = 50, enable_show=False): # properties assert num_lasers > 0 show = enable_show and (AssetLoader.loader is not None) self.dim = num_lasers self.num_lasers = num_lasers self.perceive_distance = distance self.height = self.DEFAULT_HEIGHT self.radian_unit = 2 * np.pi / num_lasers self.start_phase_offset = 0 self.node_path = parent_node_np.attachNewNode("Could_points") self._lidar_range = np.arange( 0, self.num_lasers) * self.radian_unit + self.start_phase_offset # detection result self.cloud_points = np.ones((self.num_lasers, ), dtype=float) self.detected_objects = [] # override these properties to decide which elements to detect and show self.node_path.hide(CamMask.RgbCam | CamMask.Shadow | CamMask.Shadow | CamMask.DepthCam) self.mask = BitMask32.bit(CollisionGroup.BrokenLaneLine) self.cloud_points_vis = [] if show else None logging.debug("Load Vehicle Module: {}".format( self.__class__.__name__)) if show: for laser_debug in range(self.num_lasers): ball = AssetLoader.loader.loadModel( AssetLoader.file_path("models", "box.bam")) ball.setScale(0.001) ball.setColor(0., 0.5, 0.5, 1) shape = BulletSphereShape(0.1) ghost = BulletGhostNode('Lidar Point') ghost.setIntoCollideMask(BitMask32.allOff()) ghost.addShape(shape) laser_np = self.node_path.attachNewNode(ghost) self.cloud_points_vis.append(laser_np) ball.getChildren().reparentTo(laser_np)
def __init__(self, pure_background: bool = False): super(SkyBox, self).__init__() self._accumulate = 0 self.f = 1 if not self.render or pure_background: self.node_path = NodePath("pure_background") return skybox = self.loader.loadModel( AssetLoader.file_path("models", "skybox.bam")) skybox.hide(CamMask.MiniMap | CamMask.RgbCam | CamMask.Shadow | CamMask.ScreenshotCam) skybox.set_scale(20000) skybox_texture = self.loader.loadTexture( AssetLoader.file_path("textures", "skybox.jpg")) skybox_texture.set_minfilter(SamplerState.FT_linear) skybox_texture.set_magfilter(SamplerState.FT_linear) skybox_texture.set_wrap_u(SamplerState.WM_repeat) skybox_texture.set_wrap_v(SamplerState.WM_mirror) skybox_texture.set_anisotropic_degree(16) skybox.set_texture(skybox_texture) gles = ConfigVariableString("load-display").getValue() if gles == "pandagles2": skybox_shader = Shader.load( Shader.SL_GLSL, AssetLoader.file_path("shaders", "skybox_gles.vert.glsl"), # FIXME a potential bug here? AssetLoader.file_path("shaders", "skybox_gles.frag.glsl")) else: if is_mac(): vert_file = "skybox_mac.vert.glsl" frag_file = "skybox_mac.frag.glsl" else: vert_file = "skybox.vert.glsl" frag_file = "skybox.frag.glsl" skybox_shader = Shader.load( Shader.SL_GLSL, AssetLoader.file_path("shaders", vert_file), # FIXME a potential bug here? AssetLoader.file_path("shaders", frag_file)) skybox.set_shader(skybox_shader) self.node_path = skybox skybox.setZ(-4400) skybox.setH(30)
def __init__(self, parent_node_np: NodePath, laser_num: int = 240, distance: float = 50): show = self.enable_show and (AssetLoader.loader is not None) self.Lidar_point_cloud_obs_dim = laser_num self.laser_num = laser_num self.perceive_distance = distance self.radian_unit = 2 * np.pi / laser_num self.detection_results = [] self.node_path = parent_node_np.attachNewNode("cloudPoints") self.node_path.hide(CamMask.RgbCam | CamMask.Shadow) self.cloud_points = [] if show else None logging.debug("Load Vehicle Module: {}".format(self.__class__.__name__)) if show: for laser_debug in range(self.laser_num): ball = AssetLoader.loader.loadModel(AssetLoader.file_path("models", "box.egg")) ball.setScale(0.001) ball.setColor(0., 0.5, 0.5, 1) shape = BulletSphereShape(0.1) ghost = BulletGhostNode('Lidar Point') ghost.setIntoCollideMask(BitMask32.allOff()) ghost.addShape(shape) laser_np = self.node_path.attachNewNode(ghost) self.cloud_points.append(laser_np) ball.getChildren().reparentTo(laser_np)
def __init__(self): super(Terrain, self).__init__() shape = BulletPlaneShape(Vec3(0, 0, 1), 0) node = BulletRigidBodyNode(BodyName.Ground) node.setFriction(.9) node.addShape(shape) node.setIntoCollideMask(BitMask32.bit(self.COLLISION_MASK)) self.dynamic_nodes.append(node) self.node_path = NodePath(node) if self.render: self.node_path.hide(CamMask.MiniMap | CamMask.Shadow | CamMask.DepthCam | CamMask.ScreenshotCam) # self.terrain_normal = self.loader.loadTexture( # AssetLoader.file_path( "textures", "grass2", "normal.jpg") # ) self.terrain_texture = self.loader.loadTexture(AssetLoader.file_path("textures", "ground.png")) self.terrain_texture.setWrapU(Texture.WM_repeat) self.terrain_texture.setWrapV(Texture.WM_repeat) self.ts_color = TextureStage("color") self.ts_normal = TextureStage("normal") self.ts_normal.set_mode(TextureStage.M_normal) self.node_path.setPos(0, 0, self.HEIGHT) cm = CardMaker('card') scale = 20000 cm.setUvRange((0, 0), (scale / 10, scale / 10)) card = self.node_path.attachNewNode(cm.generate()) # scale = 1 if self.use_hollow else 20000 card.set_scale(scale) card.setPos(-scale / 2, -scale / 2, -0.1) card.setZ(-.05) card.setTexture(self.ts_color, self.terrain_texture) # card.setTexture(self.ts_normal, self.terrain_normal) self.terrain_texture.setMinfilter(SamplerState.FT_linear_mipmap_linear) self.terrain_texture.setAnisotropicDegree(8) card.setQuat(LQuaternionf(numpy.cos(-numpy.pi / 4), numpy.sin(-numpy.pi / 4), 0, 0))
def __init__(self, config: dict = None): # Setup config and Panda3d self.pg_config = self.default_config() if config is not None: self.pg_config.update(config) if self.pg_config["pstats"]: # pstats debug provided by panda3d loadPrcFileData("", "want-pstats 1") loadPrcFileData("", "win-size {} {}".format(*self.pg_config["window_size"])) # Setup onscreen render if self.pg_config["use_render"]: self.mode = RENDER_MODE_ONSCREEN # Warning it may cause memory leak, Pand3d Official has fixed this in their master branch. # You can enable it if your panda version is latest. loadPrcFileData("", "threading-model Cull/Draw") # multi-thread render, accelerate simulation when evaluate else: if self.pg_config["use_image"]: self.mode = RENDER_MODE_OFFSCREEN else: self.mode = RENDER_MODE_NONE if is_mac() and (self.mode == RENDER_MODE_OFFSCREEN): # Mac don't support offscreen rendering self.mode = RENDER_MODE_ONSCREEN # Setup some debug options if self.pg_config["headless_image"]: # headless machine support loadPrcFileData("", "load-display pandagles2") if self.pg_config["debug"]: # debug setting PGWorld.DEBUG = True _free_warning() setup_logger(debug=True) self.accept('1', self.toggleDebug) self.accept('2', self.toggleWireframe) self.accept('3', self.toggleTexture) self.accept('4', self.toggleAnalyze) else: # only report fatal error when debug is False _suppress_warning() # a special debug mode if self.pg_config["debug_physics_world"]: self.accept('1', self.toggleDebug) super(PGWorld, self).__init__(windowType=self.mode) # Change window size at runtime if screen too small assert int(self.pg_config["use_topdown"]) + int(self.pg_config["use_image"]) <= 1, ( "Only one of use_topdown and use_image options can be selected." ) main_window_position = (0, 0) if self.mode == RENDER_MODE_ONSCREEN: loadPrcFileData("", "compressed-textures 1") # Default to compress h = self.pipe.getDisplayHeight() w = self.pipe.getDisplayWidth() if self.pg_config["window_size"][0] > 0.9 * w or self.pg_config["window_size"][1] > 0.9 * h: old_scale = self.pg_config["window_size"][0] / self.pg_config["window_size"][1] new_w = int(min(0.9 * w, 0.9 * h * old_scale)) new_h = int(min(0.9 * h, 0.9 * w / old_scale)) self.pg_config["window_size"] = tuple([new_w, new_h]) from panda3d.core import WindowProperties props = WindowProperties() props.setSize(self.pg_config["window_size"][0], self.pg_config["window_size"][1]) self.win.requestProperties(props) logging.warning( "Since your screen is too small ({}, {}), we resize the window to {}.".format( w, h, self.pg_config["window_size"] ) ) main_window_position = ( (w - self.pg_config["window_size"][0]) / 2, (h - self.pg_config["window_size"][1]) / 2 ) self.highway_render = None if self.pg_config["use_topdown"]: self.highway_render = HighwayRender(self.pg_config["use_render"], main_window_position) # screen scale factor self.w_scale = max(self.pg_config["window_size"][0] / self.pg_config["window_size"][1], 1) self.h_scale = max(self.pg_config["window_size"][1] / self.pg_config["window_size"][0], 1) if self.mode == RENDER_MODE_ONSCREEN: self.disableMouse() if not self.pg_config["debug_physics_world"] and (self.mode in [RENDER_MODE_ONSCREEN, RENDER_MODE_OFFSCREEN]): initialize_asset_loader(self) gltf.patch_loader(self.loader) # Display logo if self.mode == RENDER_MODE_ONSCREEN: self._loading_logo = OnscreenImage( image=AssetLoader.file_path("PGDrive-large.png"), pos=(0, 0, 0), scale=(self.w_scale, 1, self.h_scale) ) self._loading_logo.setTransparency(True) for i in range(20): self.graphicsEngine.renderFrame() self.taskMgr.add(self.remove_logo, "remove _loading_logo in first frame") self.closed = False # add element to render and pbr render, if is exists all the time. # these element will not be removed when clear_world() is called self.pbr_render = self.render.attachNewNode("pbrNP") # attach node to this root root whose children nodes will be clear after calling clear_world() self.worldNP = self.render.attachNewNode("world_np") # same as worldNP, but this node is only used for render gltf model with pbr material self.pbr_worldNP = self.pbr_render.attachNewNode("pbrNP") self.debug_node = None # some render attr self.pbrpipe = None self.light = None self.collision_info_np = None # physics world self.physics_world = PGPhysicsWorld() # for real time simulation self.force_fps = ForceFPS(self, start=False) # init terrain self.terrain = Terrain() self.terrain.attach_to_pg_world(self.render, self.physics_world) # init other world elements if self.mode != RENDER_MODE_NONE: from pgdrive.world.our_pbr import OurPipeline self.pbrpipe = OurPipeline( render_node=None, window=None, camera_node=None, msaa_samples=4, max_lights=8, use_normal_maps=False, use_emission_maps=True, exposure=1.0, enable_shadows=False, enable_fog=False, use_occlusion_maps=False ) self.pbrpipe.render_node = self.pbr_render self.pbrpipe.render_node.set_antialias(AntialiasAttrib.M_auto) self.pbrpipe._recompile_pbr() self.pbrpipe.manager.cleanup() # set main cam self.cam.node().setCameraMask(CamMask.MainCam) self.cam.node().getDisplayRegion(0).setClearColorActive(True) self.cam.node().getDisplayRegion(0).setClearColor(ImageBuffer.BKG_COLOR) lens = self.cam.node().getLens() lens.setFov(70) lens.setAspectRatio(1.2) self.sky_box = SkyBox() self.sky_box.attach_to_pg_world(self.render, self.physics_world) self.light = Light(self.pg_config) self.light.attach_to_pg_world(self.render, self.physics_world) self.render.setLight(self.light.direction_np) self.render.setLight(self.light.ambient_np) self.render.setShaderAuto() self.render.setAntialias(AntialiasAttrib.MAuto) # ui and render property if self.pg_config["show_fps"]: self.setFrameRateMeter(True) # onscreen message self.on_screen_message = PGOnScreenMessage( debug=self.DEBUG ) if self.mode == RENDER_MODE_ONSCREEN and self.pg_config["onscreen_message"] else None self._show_help_message = False self._episode_start_time = time.time() self.accept("h", self.toggle_help_message) self.accept("f", self.force_fps.toggle) else: self.on_screen_message = None # task manager self.taskMgr.remove('audioLoop')
def __init__(self, pg_world, show_navi_mark: bool = False, random_navi_mark_color=False, show_dest_mark=False, show_line_to_dest=False): """ This class define a helper for localizing vehicles and retrieving navigation information. It now only support from first block start to the end node, but can be extended easily. """ self.map = None self.final_road = None self.checkpoints = None self.final_lane = None self.current_ref_lanes = None self.current_road = None self._target_checkpoints_index = None self._navi_info = np.zeros( (self.navigation_info_dim, )) # navi information res self.navi_mark_color = ( 0.6, 0.8, 0.5) if not random_navi_mark_color else get_np_random().rand(3) # Vis self._is_showing = True # store the state of navigation mark self._show_navi_info = ( pg_world.mode == RENDER_MODE_ONSCREEN and not pg_world.world_config["debug_physics_world"]) self._dest_node_path = None self._goal_node_path = None self._arrow_node_path = None self._line_to_dest = None self._show_line_to_dest = show_line_to_dest if self._show_navi_info: # nodepath self._line_to_dest = pg_world.render.attachNewNode("line") self._goal_node_path = pg_world.render.attachNewNode("target") self._dest_node_path = pg_world.render.attachNewNode("dest") self._arrow_node_path = pg_world.aspect2d.attachNewNode("arrow") navi_arrow_model = AssetLoader.loader.loadModel( AssetLoader.file_path("models", "navi_arrow.gltf")) navi_arrow_model.setScale(0.1, 0.12, 0.2) navi_arrow_model.setPos(2, 1.15, -0.221) self._left_arrow = self._arrow_node_path.attachNewNode( "left arrow") self._left_arrow.setP(180) self._right_arrow = self._arrow_node_path.attachNewNode( "right arrow") self._left_arrow.setColor(self.MARK_COLOR) self._right_arrow.setColor(self.MARK_COLOR) navi_arrow_model.instanceTo(self._left_arrow) navi_arrow_model.instanceTo(self._right_arrow) self._arrow_node_path.setPos(0, 0, 0.08) self._arrow_node_path.hide(BitMask32.allOn()) self._arrow_node_path.show(CamMask.MainCam) self._arrow_node_path.setQuat( LQuaternionf(np.cos(-np.pi / 4), 0, 0, np.sin(-np.pi / 4))) # the transparency attribute of gltf model is invalid on windows # self._arrow_node_path.setTransparency(TransparencyAttrib.M_alpha) if show_navi_mark: navi_point_model = AssetLoader.loader.loadModel( AssetLoader.file_path("models", "box.bam")) navi_point_model.reparentTo(self._goal_node_path) if show_dest_mark: dest_point_model = AssetLoader.loader.loadModel( AssetLoader.file_path("models", "box.bam")) dest_point_model.reparentTo(self._dest_node_path) if show_line_to_dest: line_seg = LineSegs("line_to_dest") line_seg.setColor(self.navi_mark_color[0], self.navi_mark_color[1], self.navi_mark_color[2], 0.7) line_seg.setThickness(2) self._dynamic_line_np = NodePath(line_seg.create(True)) self._dynamic_line_np.reparentTo(pg_world.render) self._line_to_dest = line_seg self._goal_node_path.setTransparency(TransparencyAttrib.M_alpha) self._dest_node_path.setTransparency(TransparencyAttrib.M_alpha) self._goal_node_path.setColor(self.navi_mark_color[0], self.navi_mark_color[1], self.navi_mark_color[2], 0.7) self._dest_node_path.setColor(self.navi_mark_color[0], self.navi_mark_color[1], self.navi_mark_color[2], 0.7) self._goal_node_path.hide(BitMask32.allOn()) self._dest_node_path.hide(BitMask32.allOn()) self._goal_node_path.show(CamMask.MainCam) self._dest_node_path.show(CamMask.MainCam) logging.debug("Load Vehicle Module: {}".format( self.__class__.__name__))
def __init__(self, length: int, width: int, view_ground: bool, chassis_np: NodePath, pg_world: PGWorld): """ :param length: Control resolution of this sensor :param width: Control resolution of this sensor :param view_ground: Lane line will be invisible when set to True :param chassis_np: The vehicle chassis to place this sensor :param pg_world: PG-World """ self.view_ground = view_ground self.BUFFER_W = length self.BUFFER_H = width super(DepthCamera, self).__init__(self.BUFFER_W, self.BUFFER_H, Vec3(0.0, 0.8, 1.5), self.BKG_COLOR, pg_world=pg_world, parent_node=chassis_np) self.add_to_display(pg_world, self.default_region) self.cam.lookAt(0, 2.4, 1.3) self.lens.setFov(60) self.lens.setAspectRatio(2.0) # add shader for it if pg_world.world_config["headless_image"]: vert_path = AssetLoader.file_path("shaders", "depth_cam_gles.vert.glsl") frag_path = AssetLoader.file_path("shaders", "depth_cam_gles.frag.glsl") else: if is_mac(): vert_path = AssetLoader.file_path("shaders", "depth_cam_mac.vert.glsl") frag_path = AssetLoader.file_path("shaders", "depth_cam_mac.frag.glsl") else: vert_path = AssetLoader.file_path("shaders", "depth_cam.vert.glsl") frag_path = AssetLoader.file_path("shaders", "depth_cam.frag.glsl") custom_shader = Shader.load(Shader.SL_GLSL, vertex=vert_path, fragment=frag_path) self.cam.node().setInitialState( RenderState.make(ShaderAttrib.make(custom_shader, 1))) if self.view_ground: self.ground = GeoMipTerrain("mySimpleTerrain") self.ground.setHeightfield( AssetLoader.file_path("textures", "height_map.png")) # terrain.setBruteforce(True) # # Since the terrain is a texture, shader will not calculate the depth information, we add a moving terrain # # model to enable the depth information of terrain self.ground_model = self.ground.getRoot() self.ground_model.reparentTo(chassis_np) self.ground_model.setPos(-128, 0, self.GROUND) self.ground_model.hide(BitMask32.allOn()) self.ground_model.show(CamMask.DepthCam) self.ground.generate() pg_world.taskMgr.add(self.renew_pos_of_ground_mode, self.TASK_NAME, extraArgs=[chassis_np], appendTask=True)