def _make_fullscreen_tri(self): """ Creates the oversized triangle used for rendering """ vformat = GeomVertexFormat.get_v3() vdata = GeomVertexData("vertices", vformat, Geom.UH_static) vdata.set_num_rows(3) vwriter = GeomVertexWriter(vdata, "vertex") vwriter.add_data3f(-1, 0, -1) vwriter.add_data3f(3, 0, -1) vwriter.add_data3f(-1, 0, 3) gtris = GeomTriangles(Geom.UH_static) gtris.add_next_vertices(3) geom = Geom(vdata) geom.add_primitive(gtris) geom_node = GeomNode("gn") geom_node.add_geom(geom) geom_node.set_final(True) geom_node.set_bounds(OmniBoundingVolume()) tri = NodePath(geom_node) tri.set_depth_test(False) tri.set_depth_write(False) tri.set_attrib(TransparencyAttrib.make(TransparencyAttrib.M_none), 10000) tri.set_color(Vec4(1)) tri.set_bin("unsorted", 10) tri.reparent_to(self._node) self._tri = tri
def geom_node(): array = GeomVertexArrayFormat() array.add_column("vertex", 3, Geom.NT_float32, Geom.C_point) array.add_column("normal", 3, Geom.NT_float32, Geom.C_normal) array.add_column("color", 3, Geom.NT_float32, Geom.C_color) array.add_column("texcoord", 3, Geom.NT_float32, Geom.C_texcoord) format = GeomVertexFormat() format.add_array(array) format = GeomVertexFormat.register_format(format) vdata = GeomVertexData("test", format, Geom.UH_static) vdata.set_num_rows(4) vertex = GeomVertexWriter(vdata, 'vertex') normal = GeomVertexWriter(vdata, 'normal') color = GeomVertexWriter(vdata, 'color') texcoord = GeomVertexWriter(vdata, 'texcoord') vertex.add_data3f(1, 0, 0) normal.add_data3f(0, 0, 1) color.add_data4f(0, 0, 1, 1) texcoord.add_data2f(1, 0) vertex.add_data3f(1, 1, 0) normal.add_data3f(0, 1, 1) color.add_data4f(1, 0, 1, 1) texcoord.add_data2f(1, 1) geom = Geom(vdata) node = GeomNode('gnode') node.add_geom(geom) return node
def get_p3d_geom_node(self, name='UnnamedGeom'): # type: (Optional[str]) -> GeomNode """Returns a Panda3D GeomNode object""" vertex_data = GeomVertexData(name, GeomVertexFormat.get_v3c4(), Geom.UH_static) total_triangles = len(self.__triangles__) # Every triangle gets its unique set of vertices for flat shading num_rows = total_triangles * 3 vertex_data.set_num_rows(num_rows) vertex_writer = GeomVertexWriter(vertex_data, 'vertex') color_writer = GeomVertexWriter(vertex_data, 'color') for i in range(total_triangles): triangle = self.vertices[self.triangles[i]] vertex_writer.add_data3f(*triangle[0]) vertex_writer.add_data3f(*triangle[1]) vertex_writer.add_data3f(*triangle[2]) triangle_color = self.colors[self.triangles[i]].sum(axis=0) / 3 for _ in [0, 0, 0]: color_writer.add_data4f(*triangle_color) geom = Geom(vertex_data) for i in range(total_triangles): triangle = GeomTriangles(Geom.UH_static) first = i * 3 triangle.add_vertex(first) triangle.add_vertex(first + 1) triangle.add_vertex(first + 2) geom.add_primitive(triangle) node = GeomNode(name) node.add_geom(geom) return node
def make_SB(pos, hpr): #use this to construct a torus geom. #import torus #geom = torus.make_geom() geom = (loader.load_model('models/torus.egg').find_all_matches( '**/+GeomNode').get_path(0).node().modify_geom(0)) geomNode = GeomNode('') geomNode.add_geom(geom) node = BulletSoftBodyNode.make_tri_mesh(info, geom) node.link_geom(geomNode.modify_geom(0)) node.generate_bending_constraints(2) node.get_cfg().set_positions_solver_iterations(2) node.get_cfg().set_collision_flag( BulletSoftBodyConfig.CF_vertex_face_soft_soft, True) node.randomize_constraints() node.set_total_mass(50, True) softNP = self.worldNP.attach_new_node(node) softNP.set_pos(pos) softNP.set_hpr(hpr) self.world.attach(node) geomNP = softNP.attach_new_node(geomNode)
def wrap_up(self): self.prim.close_primitive() geom = Geom(self.vdata) geom.add_primitive(self.prim) node = GeomNode('point') node.add_geom(geom) return NodePath(node)
def mesh(vertices, normals, colours, triangles): # TODO: Make this name meaningful in some way name = 'test' v3n3c4 = GeomVertexFormat.get_v3n3c4() data = GeomVertexData(name, v3n3c4, Geom.UHStatic) data.set_num_rows(len(vertices)) vertex_writer = GeomVertexWriter(data, 'vertex') normal_writer = GeomVertexWriter(data, 'normal') colour_writer = GeomVertexWriter(data, 'color') for vertex in vertices: vertex_writer.add_data3(*vertex) for normal in normals: normal_writer.add_data3(*normal) for colour in colours: colour_writer.add_data4(*colour) prim = GeomTriangles(Geom.UHStatic) for triangle in triangles: prim.add_vertices(*triangle) geom = Geom(data) geom.add_primitive(prim) node = GeomNode(name) node.add_geom(geom) return node
def create(parent: NodePath, way: Way) -> NodePath: """Create node for given way and attach it to the parent.""" geom = _generate_mesh(way) node = GeomNode(str(way.id)) node.add_geom(geom) node.adjust_draw_mask(0x00000000, 0x00010000, 0xfffeffff) node_path = parent.attach_new_node(node) node_path.set_texture(textures.get('road'), 1) return node_path
def create(parent: NodePath, node: Node) -> NodePath: """Create node for given node and attach it to the parent.""" geom = _generate_mesh(node) node_ = GeomNode(str(node.id)) node_.add_geom(geom) node_.adjust_draw_mask(0x00000000, 0x00010000, 0xfffeffff) node_path = parent.attach_new_node(node_) node_path.set_texture(textures.get('intersection')) return node_path
def _make_grid(self): model = GeomNode('grid') model.add_geom(geometry.make_grid()) node = self.render.attach_new_node(model) node.set_light_off() node.set_render_mode_wireframe() node.set_antialias(AntialiasAttrib.MLine) node.hide(self.LightMask) return node
def create(parent: NodePath, radius: float, count: int) -> NodePath: """Create and add the ground plane to the scene.""" geom = _generate_mesh(radius, count) node = GeomNode('world') node.add_geom(geom) node_path = parent.attach_new_node(node) node_path.set_texture(textures.get('ground')) node_path.set_effect(DecalEffect.make()) return node_path
def _make_floor(self): model = GeomNode('floor') model.add_geom(geometry.make_plane(size=(10, 10))) node = self.render.attach_new_node(model) node.set_color(Vec4(0.3, 0.3, 0.3, 1)) material = Material() material.set_ambient(Vec4(0, 0, 0, 1)) material.set_diffuse(Vec4(0.3, 0.3, 0.3, 1)) material.set_specular(Vec3(1, 1, 1)) material.set_roughness(0.8) node.set_material(material, 1) return node
def make_light(self): d_light = DirectionalLight('dlight') d_light.setColor((0.3, 0.3, 0.3, 1)) d_light_np = self.app.render.attachNewNode(d_light) self.app.render.setLight(d_light_np) cam_cube_node = GeomNode('cam_cube') cam_cube_node.add_geom(make_cube_geom(geom_color=(1, 1, 0, 1))) cam_cube_path = self.app.render.attachNewNode(cam_cube_node) cam_cube_path.reparentTo(d_light_np) d_light_np.setPos(self.ref_node.getPos()) d_light_np.setHpr(self.ref_node.getHpr())
def __init__(self, spacing: float, size: float, parent: NodePath, focus: NodePath): self.spacing = spacing self.size = size self.focus = focus self._create_geom() node = GeomNode('grid') node.add_geom(self.geom) self.node_path = parent.attach_new_node(node) self.node_path.set_z(0.1) self.node_path.set_transparency(TransparencyAttrib.M_alpha) self.node_path.set_light_off() self.node_path.set_shader_off()
def append_capsule(self, root_path, name, radius, length, frame=None): """Append a capsule primitive node to the group. Arguments: root_path {str} -- path to the group's root node name {str} -- node name within a group radius {float} -- capsule radius length {float} -- capsule length Keyword Arguments: frame {tuple} -- local frame position and quaternion (default: {None}) """ geom_node = GeomNode('capsule') geom_node.add_geom(geometry.make_capsule(radius, length)) node = NodePath(geom_node) self.append_node(root_path, name, node, frame)
def append_sphere(self, root_path, name, radius, frame=None): """Append a sphere primitive node to the group. Arguments: root_path {str} -- path to the group's root node name {str} -- node name within a group radius {float} -- sphere radius Keyword Arguments: frame {tuple} -- local frame position and quaternion (default: {None}) """ geom_node = GeomNode('sphere') geom_node.add_geom(geometry.make_sphere()) node = NodePath(geom_node) node.set_scale(Vec3(radius, radius, radius)) self.append_node(root_path, name, node, frame)
def append_box(self, root_path, name, size, frame=None): """Append a box primitive node to the group. Arguments: root_path {str} -- path to the group's root node name {str} -- node name within a group size {Vec3} -- box size Keyword Arguments: frame {tuple} -- local frame position and quaternion (default: {None}) """ geom_node = GeomNode('box') geom_node.add_geom(geometry.make_box()) node = NodePath(geom_node) node.set_scale(Vec3(*size)) self.append_node(root_path, name, node, frame)
def draw_circle_filled(self, p: Point, nsteps=16, radius: float = 0.06, colour: Colour = WHITE) -> None: gn = GeomNode("circle") exists: bool = False for cn, cr, cg in self.__circles: if cn == nsteps and cr == radius: exists = True gn.add_geom(cg) break if not exists: self.__circles.append((nsteps, radius, BuildGeometry.addCircle(gn, nsteps, radius, colour))) np = self.root.attach_new_node(gn) np.set_pos(*p) np.set_color(*colour)
def append_plane(self, root_path, name, size, frame=None): """Append a plane primitive node to the group. Arguments: root_path {str} -- path to the group's root node name {str} -- node name within a group size {Vec2} -- plane x,y size Keyword Arguments: frame {tuple} -- local frame position and quaternion (default: {None}) """ geom_node = GeomNode('plane') geom_node.add_geom(geometry.make_plane()) node = NodePath(geom_node) node.set_scale(Vec3(size[0], size[1], 1.0)) self.append_node(root_path, name, node, frame)
def create_hidden_area_mesh(self, mask): """ Using the provided mask configuration, create the mesh that will cover the area not visible from the HMD """ gvf = GeomVertexFormat.get_v3() gvd = GeomVertexData('gvd', gvf, Geom.UH_static) geom = Geom(gvd) gvw = GeomVertexWriter(gvd, InternalName.get_vertex()) for i in range(mask.unTriangleCount * 3): vertex = mask.pVertexData[i] # The clip space in Panda3D has [-1, 1] coordinates, the received coordinates are in [0, 1] gvw.add_data3(vertex[0] * 2 - 1, vertex[1] * 2 - 1, -1) prim = GeomTriangles(Geom.UH_static) for i in range(mask.unTriangleCount): prim.add_vertices(i * 3, i * 3 + 1, i * 3 + 2) geom.add_primitive(prim) node = GeomNode('hidden-area-mesh') node.add_geom(geom) return node
def create(parent: NodePath, path: Path) -> NodePath: """Create node for given path and attach it to the parent.""" points = path.oriented_points() if len(points) >= 2: geom = _generate_mesh(points) node = GeomNode('path') node.add_geom(geom) node.adjust_draw_mask(0x00000000, 0x00010000, 0xfffeffff) node_path = parent.attach_new_node(node) node_path.set_light_off() # Setting depth write to false solves the problem of this big flat # polygon obscuring other semi-transparent things (like the lane # connections card) depending on the camera angle. See: # https://docs.panda3d.org/1.10/python/programming/texturing/transparency-and-blending node_path.set_depth_write(False) node_path.set_transparency(TransparencyAttrib.M_alpha) else: node_path = None return node_path
def get_geom_node(self): node = GeomNode(self.name) node.add_geom(self.get_geom()) return node
class Skidmark(GameObject): def __init__(self, whl_pos, whl_radius, car_h): GameObject.__init__(self) self.radius = whl_radius v_f = GeomVertexFormat.getV3() vdata = GeomVertexData('skid', v_f, Geom.UHDynamic) prim = GeomTriangles(Geom.UHStatic) self.vtx_cnt = 1 self.last_pos = whl_pos geom = Geom(vdata) geom.add_primitive(prim) self.node = GeomNode('gnode') self.node.add_geom(geom) nodepath = self.eng.gfx.root.attach_node(self.node) nodepath.set_transparency(True) nodepath.set_depth_offset(1) nodepath.node.set_two_sided(True) # for self-shadowing issues self.__set_material(nodepath) nodepath.p3dnode.set_bounds(OmniBoundingVolume()) self.add_vertices(whl_radius, car_h) self.add_vertices(whl_radius, car_h) def alpha(time, n_p): if not n_p.is_empty: n_p.node.set_shader_input('alpha', time) # this if seems necessary since, if there are skidmarks and you # exit from the race (e.g. back to the menu), then alpha is being # called from the interval manager even if the interval manager # correctly says that there are 0 intervals. self.remove_seq = Sequence( Wait(8), LerpFunc(alpha, 8, .5, 0, 'easeInOut', [nodepath]), Func(nodepath.remove_node)) self.remove_seq.start() @staticmethod def __set_material(nodepath): # mat = Material() # mat.set_ambient((.35, .35, .35, .5)) # mat.set_diffuse((.35, .35, .35, .5)) # mat.set_specular((.35, .35, .35, .5)) # mat.set_shininess(12.5) # nodepath.set_material(mat) nodepath.node.set_shader(Shader.make(Shader.SL_GLSL, vert, frag)) nodepath.node.set_shader_input('alpha', .5) def add_vertices(self, whl_radius, car_h): base_pos = self.last_pos + (0, 0, -whl_radius + .05) rot_mat = Mat4() rot_mat.set_rotate_mat(car_h, (0, 0, 1)) vdata = self.node.modify_geom(0).modify_vertex_data() vwriter = GeomVertexWriter(vdata, 'vertex') vwriter.set_row(vdata.get_num_rows()) vwriter.add_data3f(base_pos + rot_mat.xform_vec((-.12, 0, 0))) vwriter.add_data3f(base_pos + rot_mat.xform_vec((.12, 0, 0))) cnt = self.vtx_cnt prim = self.node.modify_geom(0).modify_primitive(0) if cnt >= 3: prim.add_vertices(cnt - 3, cnt - 2, cnt - 1) prim.add_vertices(cnt - 2, cnt, cnt - 1) self.vtx_cnt += 2 def update(self, whl_pos, car_h): if (whl_pos - self.last_pos).length() > .2: self.last_pos = whl_pos self.add_vertices(self.radius, car_h) def destroy(self): self.remove_seq = self.remove_seq.finish() GameObject.destroy(self)
class PointCloud(): name: str node_path: NodePath geom_node: GeomNode def __init__(self, name='point_cloud', thickness: float = 3) -> None: self.name = name self.geom_node = GeomNode(self.name) self.node_path = NodePath(self.geom_node) self.node_path.set_render_mode_wireframe() self.node_path.set_render_mode_thickness(thickness) self.node_path.set_antialias(AntialiasAttrib.MPoint) @staticmethod def __make_points(vertices, colours=None, geom: Geom = None) -> Geom: """ This function is largely inspired by panda3d_viewer's implementation. Copyright (c) 2020, Igor Kalevatykh Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ if not isinstance(vertices, np.ndarray): vertices = np.asarray(vertices, dtype=np.float32) if colours is not None: if not isinstance(colours, np.ndarray): colours = np.asarray(colours) if colours.dtype != np.uint8: colours = np.uint8(colours * 255) vertices = np.column_stack((vertices.view(dtype=np.uint32).reshape(-1, 3), colours.view(dtype=np.uint32))) data = vertices.tostring() if geom is None: if vertices.strides[0] == 12: vformat = GeomVertexFormat.get_v3() elif vertices.strides[0] == 16: vformat = GeomVertexFormat.get_v3c4() else: raise ValueError('Incompatible point clout format: {},{}'.format(vertices.dtype, vertices.shape)) vdata = GeomVertexData('vdata', vformat, Geom.UHDynamic) vdata.unclean_set_num_rows(len(vertices)) vdata.modify_array_handle(0).set_subdata(0, len(data), data) prim = GeomPoints(Geom.UHDynamic) prim.clear_vertices() prim.add_consecutive_vertices(0, len(vertices)) prim.close_primitive() geom = Geom(vdata) geom.add_primitive(prim) else: vdata = geom.modify_vertex_data() vdata.unclean_set_num_rows(len(vertices)) vdata.modify_array_handle(0).set_subdata(0, len(data), data) prim = geom.modify_primitive(0) prim.clear_vertices() prim.add_consecutive_vertices(0, len(vertices)) prim.close_primitive() return geom def update(self, vertices, colours=None) -> None: if self.geom_node.get_num_geoms() == 0: self.geom = self.__make_points(vertices, colours) self.geom_node.add_geom(self.geom) else: self.geom = self.geom_node.modify_geom(0) self.__make_points(vertices, colours, self.geom)
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.show_tight_bounds() #self.debugNP.show_bounds() self.world = BulletWorld() self.world.set_gravity(LVector3(0, 0, -9.81)) self.world.set_debug_node(self.debugNP.node()) # Ground p0 = LPoint3(-20, -20, 0) p1 = LPoint3(-20, 20, 0) p2 = LPoint3(20, -20, 0) p3 = LPoint3(20, 20, 0) mesh = BulletTriangleMesh() mesh.add_triangle(p0, p1, p2) mesh.add_triangle(p1, p2, p3) shape = BulletTriangleMeshShape(mesh, dynamic=False) np = self.worldNP.attach_new_node(BulletRigidBodyNode('Mesh')) np.node().add_shape(shape) np.set_pos(0, 0, -2) np.set_collide_mask(BitMask32.all_on()) self.world.attach(np.node()) # Stair origin = LPoint3(0, 0, 0) size = LVector3(2, 10, 1) shape = BulletBoxShape(size * 0.5) for i in range(10): pos = origin + size * i pos.setY(0) np = self.worldNP.attach_new_node( BulletRigidBodyNode('Stair{}'.format(i))) np.node().add_shape(shape) np.set_pos(pos) np.set_collide_mask(BitMask32.all_on()) npV = loader.load_model('models/box.egg') npV.reparent_to(np) npV.set_scale(size) self.world.attach(np.node()) # Soft body world information info = self.world.get_world_info() info.set_air_density(1.2) info.set_water_density(0) info.set_water_offset(0) info.set_water_normal(LVector3(0, 0, 0)) # Softbody center = LPoint3(0, 0, 0) radius = LVector3(1, 1, 1) * 1.5 node = BulletSoftBodyNode.make_ellipsoid(info, center, radius, 128) node.set_name('Ellipsoid') node.get_material(0).set_linear_stiffness(0.1) node.get_cfg().set_dynamic_friction_coefficient(1) node.get_cfg().set_damping_coefficient(0.001) node.get_cfg().set_pressure_coefficient(1500) node.set_total_mass(30, True) node.set_pose(True, False) np = self.worldNP.attach_new_node(node) np.set_pos(15, 0, 12) #np.setH(90.0) #np.show_bounds() #np.show_tight_bounds() self.world.attach(np.node()) geom = BulletHelper.make_geom_from_faces(node) node.link_geom(geom) nodeV = GeomNode('EllipsoidVisual') nodeV.add_geom(geom) npV = np.attach_new_node(nodeV)
def setup(self): self.worldNP = render.attach_new_node('World') # World self.debugNP = self.worldNP.attach_new_node(BulletDebugNode('Debug')) self.debugNP.show() self.world = BulletWorld() self.world.set_gravity(LVector3(0, 0, -9.81)) self.world.set_debug_node(self.debugNP.node()) # Ground p0 = LPoint3(-20, -20, 0) p1 = LPoint3(-20, 20, 0) p2 = LPoint3(20, -20, 0) p3 = LPoint3(20, 20, 0) mesh = BulletTriangleMesh() mesh.add_triangle(p0, p1, p2) mesh.add_triangle(p1, p2, p3) shape = BulletTriangleMeshShape(mesh, dynamic=False) np = self.worldNP.attach_new_node(BulletRigidBodyNode('Mesh')) np.node().add_shape(shape) np.set_pos(0, 0, -2) np.set_collide_mask(BitMask32.all_on()) self.world.attach(np.node()) # Soft body world information info = self.world.get_world_info() info.set_air_density(1.2) info.set_water_density(0) info.set_water_offset(0) info.set_water_normal(LVector3(0, 0, 0)) # Softbody for i in range(50): p00 = LPoint3(-2, -2, 0) p10 = LPoint3(2, -2, 0) p01 = LPoint3(-2, 2, 0) p11 = LPoint3(2, 2, 0) node = BulletSoftBodyNode.make_patch(info, p00, p10, p01, p11, 6, 6, 0, True) node.generate_bending_constraints(2) node.get_cfg().set_lift_coefficient(0.004) node.get_cfg().set_dynamic_friction_coefficient(0.0003) node.get_cfg().set_aero_model( BulletSoftBodyConfig.AM_vertex_two_sided) node.set_total_mass(0.1) node.add_force(LVector3(0, 2, 0), 0) np = self.worldNP.attach_new_node(node) np.set_pos(self.LVector3_rand() * 10 + LVector3(0, 0, 20)) np.set_hpr(self.LVector3_rand() * 16) self.world.attach(node) fmt = GeomVertexFormat.get_v3n3t2() geom = BulletHelper.make_geom_from_faces(node, fmt, True) node.link_geom(geom) nodeV = GeomNode('') nodeV.add_geom(geom) npV = np.attach_new_node(nodeV) tex = loader.load_texture('models/panda.jpg') npV.set_texture(tex) BulletHelper.make_texcoords_for_patch(geom, 6, 6)
def get_node(self): geom = Geom(self._vert_data) geom.add_primitive(self._prim) node = GeomNode(self._name) node.add_geom(geom) return node
class Simulator(ShowBase): def __init__(self, textboxes=({}), default_text_scale=.07, graph_objs={}): ShowBase.__init__(self) self.joys = self.devices.getDevices(InputDevice.DeviceClass.gamepad) #Attaches input devices to base for ind, joy in enumerate(self.joys): self.attachInputDevice(joy, prefix=str(ind)) #Joystick reading variable self.joystick_readings = [] #Add panda and background self.scene = self.loader.loadModel("models/environment") self.scene.reparentTo(self.render) self.scene.setScale(0.25, 0.25, 0.25) #Sets the scene position self.scene.setPos(-8, 48, 0) self.camera.setPos(-8, 48, -4) self.pandaActor = Actor("models/panda-model", {"walk": "models/panda-walk4"}) self.pandaActor.setScale(0.005, 0.005, 0.005) self.pandaActor.reparentTo(self.render) self.pandaLocation = [0, 0, 0] self.setPandaToLocation() #Lines to be rendered on the next frame self.lines = [] self.lineNodes = [] self.lineNodePaths = [] #Text boxes which will be rendered every frame #Key is a node name, value is a dict with #arguments such as text, location, and scale #Hack to keep default argument immutable and prevent bugs if type(textboxes) == tuple: self.textboxes = textboxes[0] else: self.textboxes = textboxes self.textNodes = {} self.textNodePaths = {} self.default_text_scale = default_text_scale #Geometry drawing node self.geom_node = GeomNode("drawer") self.aspect2d.attach_new_node(self.geom_node) self.text_is_active = True #If the text toggle button has been up for more than one frame self.text_button_lifted = True #If changes that need to be made on text have taken place self.text_toggled = True #Loop the animation to the one loaded in the dictionary self.pandaActor.loop("walk") #Intantiates physics engine self.physics = physics.Swerve() self.taskMgr.add(self.updateJoysticks, "updateJoysticks") self.taskMgr.add(self.walkPandaToPhysics, "walkPandaToPhysics") self.taskMgr.add(self.update2dDisplay, "update2dDisplay") self.taskMgr.add(self.toggleText, "toggleText") #Creates a graph of y vectors self.graphs = graph_objs #Adds dummy value to graph to prevent crash self.graphs["y_graph"].update(0) self.graphs["vector_graph"].update(0, 0) def walkPanda(self, task): x = self.joystick_readings[0]["axes"]["left_x"] y = self.joystick_readings[0]["axes"]["left_y"] magnitude = sqrt(x**2 + y**2) self.pandaLocation[0] += x / 7 self.pandaLocation[1] += y / 7 angle = atan2(y, x) * (180 / pi) self.setPandaToLocation() self.pandaActor.setHpr(angle + 90, 0, 0) if not self.pandaActor.getCurrentAnim() == "walk": self.pandaActor.loop("walk") else: self.pandaActor.setPlayRate(magnitude * 2, "walk") return Task.cont def walkPandaToPhysics(self, task): """ Makes panda walk based on inputs from physics enigne """ x = self.joystick_readings[0]["axes"]["left_x"] y = self.joystick_readings[0]["axes"]["left_y"] z = self.joystick_readings[0]["axes"]["right_x"] self.physics.sendControls(x, y, z) self.physics.update() self.pandaLocation[0] = self.physics.position[0] self.pandaLocation[1] = self.physics.position[1] angle = self.physics.position[2] * (180 / pi) self.setPandaToLocation() self.pandaActor.setHpr(angle + 180, 0, 0) self.graphs["y_graph"].update(self.physics.velocities["frame"][1]) magnitude = sqrt(x**2 + y**2) direction = atan2(y, x) self.graphs["vector_graph"].update(magnitude, direction) return Task.cont def setPandaToLocation(self): self.pandaActor.setPos(self.pandaLocation[0], self.pandaLocation[1], self.pandaLocation[2]) def updateJoysticks(self, task): joystick_readings = [] for joystick in self.joys: joystick_readings.append(joy.readJoystickValues(joystick)) self.joystick_readings = joystick_readings return Task.cont def update2dDisplay(self, task): """ Updates the 2d heads-up overlay """ #Removes all lines from the geometry node self.geom_node.removeAllGeoms() if self.text_is_active: frvector = "Mag: {}\nDir: {}\nTheta_acc: {}\nVel_x: {}\nVel_y: {}\nVel_t: {}\nPos: {}, {}\nRot: {}".format( round(self.physics.vectors["frame"].magnitude, 4), round(self.physics.vectors["frame"].direction, 4), round(self.physics.z_acceleration, 4), round(self.physics.velocities["frame"][0], 4), round(self.physics.velocities["frame"][1], 4), round(self.physics.z_velocity, 4), round(self.physics.position[0], 4), round(self.physics.position[1], 4), round(self.physics.position[2], 4)) self.textboxes["frvector_value"]["text"] = frvector self.lines = [] for graph_name in self.graphs: lines, strings = self.graphs[graph_name].render() #Splits the lines into pairs of points and assigns them to self.lines for line in lines: self.lines += pairPoints(line) #Clears all graph generated strings from textboxes deleted = [] for key in self.textboxes: if graph_name in key: deleted.append(key) for key in deleted: self.textboxes.pop(key) #Processes strings into textboxes for ind, val in enumerate(strings): location, string = val self.textboxes["{}_{}".format(graph_name, str(ind))] = { "location": location, "text": string } self.manageTextNodes() self.renderText() self.manageGeometry() return Task.cont def manageGeometry(self): """ Manages geometry generation """ #(Re)Renders all the lines which are in self.lines for line in self.lines: self.addLine(line) def addLine(self, points): """ Adds a line to class GeomNode from a pair of points """ #Creates objects needed to draw a geometry on the HUD #The vertex data which will define the rendered geometry vertex_data = GeomVertexData("graph", GeomVertexFormat.getV3(), Geom.UHStatic) #The object that writes vertexes the vertex data writer = GeomVertexWriter(vertex_data, "vertex") for point in points: writer.add_data3f(point[0], 0, point[1]) #Defines that this geometry represents a polyline primitive = GeomLinestrips(Geom.UHStatic) #Tells geometry how many verticies will be added(?) primitive.add_consecutive_vertices(0, 2) primitive.close_primitive() geometry = Geom(vertex_data) geometry.add_primitive(primitive) #Draws a graph on the HUD self.geom_node.add_geom(geometry) def manageTextNodes(self): deleted = [] for name in self.textboxes: if name not in self.textNodes: #If the name has not been given a textNode object, set it up self.textNodes[name] = TextNode(name) self.textNodePaths[name] = self.aspect2d.attachNewNode( self.textNodes[name]) #Checks if any textNodes no longer have their respective textbox object and should be deleted for name in self.textNodes: if name not in self.textboxes: deleted.append(name) for node in deleted: self.textNodePaths[node].removeNode() self.textNodePaths.pop(node) self.textNodes.pop(node) def renderText(self): for name in self.textboxes: if "location" in self.textboxes[name]: location = self.textboxes[name]["location"] else: location = (0, 0) if "scale" in self.textboxes[name]: scale = self.textboxes[name]["scale"] else: scale = self.default_text_scale if "text" in self.textboxes[name]: self.textNodes[name].setText(self.textboxes[name]["text"]) self.textNodePaths[name].setScale(scale) self.textNodePaths[name].setPos(location[0], 0, location[1]) def toggleText(self, task): if self.joystick_readings[0]["axes"][ "right_trigger"] >= .05 and self.text_button_lifted: self.text_is_active = not self.text_is_active self.text_toggled = False self.text_button_lifted = False elif not self.joystick_readings[0]["axes"]["right_trigger"] >= .05: self.text_button_lifted = True if not self.text_toggled: if not self.text_is_active: for path in self.textNodePaths: self.textNodePaths[path].detachNode() for path in self.lineNodePaths: path.detachNode() else: for node in self.textNodes: self.textNodePaths[node] = self.aspect2d.attachNewNode( self.textNodes[node]) for node in self.lineNodes: self.aspect2d.attachNewNode(node) return Task.cont