def makeGeom(): # Vertex data fmt = GeomVertexFormat.getV3n3t2() vdata = GeomVertexData('', fmt, Geom.UHStatic) vertex = GeomVertexWriter(vdata, InternalName.getVertex()) normal = GeomVertexWriter(vdata, InternalName.getNormal()) texcoord = GeomVertexWriter(vdata, InternalName.getTexcoord()) for (x, y, z) in vertices: vertex.addData3f(x, y, z) normal.addData3f(0, 0, 0) # Privitive prim = GeomTriangles(Geom.UHStatic) for (i1, i2, i3) in indices: prim.addVertices(i1, i2, i3) prim.closePrimitive() # Geom geom = Geom(vdata) geom.addPrimitive(prim) return geom
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 buildGeom(self, meshData): prims = meshData["prims"] vertices = meshData["vertices"] normals = meshData["normals"] texcoords = meshData["texcoords"] vdata = GeomVertexData('mesh', GeomVertexFormat.getV3n3t2(), Geom.UHStatic) vwriter = GeomVertexWriter(vdata, 'vertex') nvwriter = GeomVertexWriter(vdata, 'normal') tvwriter = GeomVertexWriter(vdata, 'texcoord') for i in range(len(vertices)): v = vertices[i] n = normals[i] t = texcoords[i] vwriter.addData3f(v) nvwriter.addData3f(n) tvwriter.addData2f(t) prim = GeomTriangles(Geom.UHStatic) for i in range(len(prims)): A, B, C = prims[i] prim.addVertices(A, B, C) prim.closePrimitive() geom = Geom(vdata) geom.addPrimitive(prim) geomNode = GeomNode('trig') geomNode.addGeom(geom) geomNode.unify(1, True) return geomNode
def make_plane(size=(1.0, 1.0)): """Make a plane geometry. Arguments: size {tuple} -- plane size x,y Returns: Geom -- p3d geometry """ vformat = GeomVertexFormat.get_v3n3t2() vdata = GeomVertexData('vdata', vformat, Geom.UHStatic) vdata.uncleanSetNumRows(4) vertex = GeomVertexWriter(vdata, 'vertex') normal = GeomVertexWriter(vdata, 'normal') tcoord = GeomVertexWriter(vdata, 'texcoord') quad = ((0, 0), (1, 0), (0, 1), (1, 1)) for u, v in quad: vertex.addData3((u - 0.5) * size[0], (v - 0.5) * size[1], 0) normal.addData3(0, 0, 1) tcoord.addData2(u, v) prim = GeomTriangles(Geom.UHStatic) prim.addVertices(0, 1, 2) prim.addVertices(2, 1, 3) geom = Geom(vdata) geom.addPrimitive(prim) return geom
def load(self): if panda3d is None: raise ImportError("Cannot locate Panda3D") #KLUDGE if self.material is not None and self.colors is None: col = self.material.getAmbient() col = (col[0] / col[3], col[1] / col[3], col[2] / col[3], 1.0) self.colors = (col,) * len(self.vertices) #/KLUDGE geom = make_geom(self.vertices, self.normals, self.colors, self.texcoords) prim = GeomTriangles(Geom.UHStatic) for face in self.faces: #TODO: proper tesselation! the current one only works for convex faces first = face[0] curr = face[1] for v in face[2:]: prim.addVertex(curr) prim.addVertex(v) prim.addVertex(first) curr = v prim.closePrimitive() geom.addPrimitive(prim) node = GeomNode(self.name) node.addGeom(geom) self.node = NodePath(node) self.node.setTwoSided(True) if self.material is not None: self.node.setMaterial(self.material, priority=1) self.loaded = True
def pg_draw_tris(pg, render): format = GeomVertexFormat.getV3c4() vdata = GeomVertexData('pgtris', format, Geom.UHStatic) vdata.setNumRows(len(pg.nodes)) vertex = GeomVertexWriter(vdata, 'vertex') color = GeomVertexWriter(vdata, 'color') prim = GeomTriangles(Geom.UHStatic) for pt in pg.nodes: vertex.addData3f(pt.x, pt.y, pt.z) color.addData4f(random.random(), random.random(), random.random(), 1.0) for pt in pg.nodes: if len(pt.conn) > 0: for i, cpt in enumerate(pt.conn): next_cpt = pt.conn[(i + 1) % len(pt.conn)] prim.addVertices(pt.idx, cpt.idx, next_cpt.idx) print("%d - %d - %d" % (pt.idx, cpt.idx, next_cpt.idx)) geom = Geom(vdata) geom.addPrimitive(prim) node = GeomNode('TheTris') node.addGeom(geom) nodePath = render.attachNewNode(node) nodePath.setPos(0, 10, 0)
def make_box(): """Make a uniform box geometry. Returns: Geom -- p3d geometry """ vformat = GeomVertexFormat.get_v3n3t2() vdata = GeomVertexData('vdata', vformat, Geom.UHStatic) vdata.uncleanSetNumRows(24) vertex = GeomVertexWriter(vdata, 'vertex') normal = GeomVertexWriter(vdata, 'normal') tcoord = GeomVertexWriter(vdata, 'texcoord') axes = itertools.permutations(np.eye(3), r=2) quad = ((0, 0), (1, 0), (0, 1), (1, 1)) for x, y in axes: z = np.cross(x, y) for u, v in quad: vertex.addData3(*(x * (u - 0.5) + y * (v - 0.5) + z * 0.5)) normal.addData3(*z) tcoord.addData2(u, v) prim = GeomTriangles(Geom.UHStatic) for i in range(0, 24, 4): prim.addVertices(i + 0, i + 1, i + 2) prim.addVertices(i + 2, i + 1, i + 3) geom = Geom(vdata) geom.addPrimitive(prim) return geom
def create_colored_rect(x, z, width, height, colors=None): _format = GeomVertexFormat.getV3c4() vdata = GeomVertexData('square', _format, Geom.UHDynamic) vertex = GeomVertexWriter(vdata, 'vertex') color = GeomVertexWriter(vdata, 'color') vertex.addData3(x, 0, z) vertex.addData3(x + width, 0, z) vertex.addData3(x + width, 0, z + height) vertex.addData3(x, 0, z + height) if colors: if len(colors) < 4: colors = (1.0, 1.0, 1.0, 1.0) color.addData4f(colors) color.addData4f(colors) color.addData4f(colors) color.addData4f(colors) else: color.addData4f(1.0, 0.0, 0.0, 1.0) color.addData4f(0.0, 1.0, 0.0, 1.0) color.addData4f(0.0, 0.0, 1.0, 1.0) color.addData4f(1.0, 1.0, 1.0, 1.0) tris = GeomTriangles(Geom.UHDynamic) tris.addVertices(0, 1, 2) tris.addVertices(2, 3, 0) square = Geom(vdata) square.addPrimitive(tris) return square
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 __init__(self, wheel_pos, radius, heading): self.radius = radius v_f = GeomVertexFormat.getV3() self.vdata = GeomVertexData('skid', v_f, Geom.UHDynamic) self.vdata.setNumRows(1) self.vertex = GeomVertexWriter(self.vdata, 'vertex') self.prim = GeomTriangles(Geom.UHStatic) self.cnt = 1 self.last_pos = wheel_pos geom = Geom(self.vdata) geom.addPrimitive(self.prim) node = GeomNode('gnode') node.addGeom(geom) nodePath = render.attachNewNode(node) nodePath.setTransparency(True) nodePath.setDepthOffset(1) self.__set_material(nodePath) nodePath.node().setBounds(OmniBoundingVolume()) self.add_vertices(radius, heading) self.add_vertices(radius, heading) self.remove_seq = Sequence( Wait(8), LerpFunc(nodePath.setAlphaScale, 8, 1, 0, 'easeInOut'), Func(nodePath.remove_node)) self.remove_seq.start()
def make_square(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4, tex_len=None, tex_width=None): format = GeomVertexFormat.getV3n3cpt2() vdata = GeomVertexData('square', format, Geom.UHDynamic) vertex = GeomVertexWriter(vdata, 'vertex') normal = GeomVertexWriter(vdata, 'normal') texcoord = GeomVertexWriter(vdata, 'texcoord') vertex.addData3(x1, y1, z1) vertex.addData3(x2, y2, z2) vertex.addData3(x3, y3, z3) vertex.addData3(x4, y4, z4) D = Vec3(x1, y1, z1) C = Vec3(x2, y2, z2) B = Vec3(x3, y3, z3) A = Vec3(x4, y4, z4) normal_vec = (C - A).cross(D - B).normalize() normal.addData3(normal_vec) normal.addData3(normal_vec) normal.addData3(normal_vec) normal.addData3(normal_vec) side_len = math.sqrt((x3 - x1)**2 + (y3 - y1)**2) start_width = math.sqrt((x2 - x1)**2 + (y2 - y1)**2) end_width = math.sqrt((x4 - x3)**2 + (y4 - y3)**2) texcoord.addData2f(0.0, (start_width / tex_width) if tex_width is not None else 1.0) texcoord.addData2f(0.0, 0.0) texcoord.addData2f((side_len / tex_len) if tex_len is not None else 1.0, 0.0) texcoord.addData2f( (side_len / tex_len) if tex_len is not None else 1.0, (end_width / tex_width) if tex_width is not None else 1.0) # Quads aren't directly supported by the Geom interface # you might be interested in the CardMaker class if you are # interested in rectangle though tris = GeomTriangles(Geom.UHDynamic) tris.addVertices(0, 1, 2) tris.addVertices(0, 2, 3) square = Geom(vdata) square.addPrimitive(tris) return square
def makeSquare(x1, y1, z1, x2, y2, z2): format = GeomVertexFormat.getV3n3cpt2() vdata = GeomVertexData('square', format, Geom.UHDynamic) vertex = GeomVertexWriter(vdata, 'vertex') normal = GeomVertexWriter(vdata, 'normal') color = GeomVertexWriter(vdata, 'color') texcoord = GeomVertexWriter(vdata, 'texcoord') # make sure we draw the sqaure in the right plane if x1 != x2: vertex.addData3(x1, y1, z1) vertex.addData3(x2, y1, z1) vertex.addData3(x2, y2, z2) vertex.addData3(x1, y2, z2) normal.addData3(normalized(2 * x1 - 1, 2 * y1 - 1, 2 * z1 - 1)) normal.addData3(normalized(2 * x2 - 1, 2 * y1 - 1, 2 * z1 - 1)) normal.addData3(normalized(2 * x2 - 1, 2 * y2 - 1, 2 * z2 - 1)) normal.addData3(normalized(2 * x1 - 1, 2 * y2 - 1, 2 * z2 - 1)) else: vertex.addData3(x1, y1, z1) vertex.addData3(x2, y2, z1) vertex.addData3(x2, y2, z2) vertex.addData3(x1, y1, z2) normal.addData3(normalized(2 * x1 - 1, 2 * y1 - 1, 2 * z1 - 1)) normal.addData3(normalized(2 * x2 - 1, 2 * y2 - 1, 2 * z1 - 1)) normal.addData3(normalized(2 * x2 - 1, 2 * y2 - 1, 2 * z2 - 1)) normal.addData3(normalized(2 * x1 - 1, 2 * y1 - 1, 2 * z2 - 1)) # adding different colors to the vertex for visibility # color.addData4f(1.0, 0.0, 0.0, 1.0) # color.addData4f(0.0, 1.0, 0.0, 1.0) # color.addData4f(0.0, 0.0, 1.0, 1.0) # color.addData4f(1.0, 0.0, 1.0, 1.0) color.addData4f(1.0, 1.0, 1.0, 1.0) color.addData4f(1.0, 1.0, 1.0, 1.0) color.addData4f(1.0, 1.0, 1.0, 1.0) color.addData4f(1.0, 1.0, 1.0, 1.0) texcoord.addData2f(0.0, 1.0) texcoord.addData2f(0.0, 0.0) texcoord.addData2f(1.0, 0.0) texcoord.addData2f(1.0, 1.0) # Quads aren't directly supported by the Geom interface # you might be interested in the CardMaker class if you are # interested in rectangle though tris = GeomTriangles(Geom.UHDynamic) tris.addVertices(0, 1, 3) tris.addVertices(1, 2, 3) square = Geom(vdata) square.addPrimitive(tris) return square
def __init__(self): self.vformat = GeomVertexFormat.getV3n3c4() self.vdata = GeomVertexData("Data", self.vformat, Geom.UHStatic) self.vdata.setNumRows(3) self.vertex = GeomVertexWriter(self.vdata, 'vertex') self.normal = GeomVertexWriter(self.vdata, 'normal') self.color = GeomVertexWriter(self.vdata, 'color') self.prim = GeomTriangles(Geom.UHStatic) self.idx = 0
def __init__(self, vdata, tex_idx): self.vdata = vdata # vertex data, passed in from parent mesh self.name = 'PolyGroup_' + str(tex_idx) self.geom = Geom(self.vdata) self.primitives = GeomTriangles(Geom.UHStatic) self.geom.addPrimitive(self.primitives) self.sprite_list_index = 0 self.nodePath = None
def resetWriters(self): ''' ''' self.vdata = GeomVertexData('street', GeomVertexFormat.getV3n3c4t2(), Geom.UHStatic) self.vertex = GeomVertexWriter(self.vdata, 'vertex') self.normal = GeomVertexWriter(self.vdata, 'normal') self.color = GeomVertexWriter(self.vdata, 'color') self.texcoord = GeomVertexWriter(self.vdata, 'texcoord') self.prim = GeomTriangles(Geom.UHStatic)
def makeSquare(x1, y1, z1, x2, y2, z2): format = GeomVertexFormat.getV3n3cpt2() vdata = GeomVertexData('square', format, Geom.UHDynamic) #initializing variables vertex = GeomVertexWriter(vdata, 'vertex') normal = GeomVertexWriter(vdata, 'normal') color = GeomVertexWriter(vdata, 'color') texcoord = GeomVertexWriter(vdata, 'texcoord') #gotta draw the sqaure in the right plane #aligning vertexes to the right planes if x1 != x2: vertex.addData3(x1, y1, z1) vertex.addData3(x2, y1, z1) vertex.addData3(x2, y2, z2) vertex.addData3(x1, y2, z2) normal.addData3(normalized(2 * x1 - 1, 2 * y1 - 1, 2 * z1 - 1)) normal.addData3(normalized(2 * x2 - 1, 2 * y1 - 1, 2 * z1 - 1)) normal.addData3(normalized(2 * x2 - 1, 2 * y2 - 1, 2 * z2 - 1)) normal.addData3(normalized(2 * x1 - 1, 2 * y2 - 1, 2 * z2 - 1)) else: #adding vertexes vertex.addData3(x1, y1, z1) vertex.addData3(x2, y2, z1) vertex.addData3(x2, y2, z2) vertex.addData3(x1, y1, z2) normal.addData3(normalized(2 * x1 - 1, 2 * y1 - 1, 2 * z1 - 1)) normal.addData3(normalized(2 * x2 - 1, 2 * y2 - 1, 2 * z1 - 1)) normal.addData3(normalized(2 * x2 - 1, 2 * y2 - 1, 2 * z2 - 1)) normal.addData3(normalized(2 * x1 - 1, 2 * y1 - 1, 2 * z2 - 1)) #adding different colors to the vertex for visibility color.addData4f(1.0, 0.0, 0.0, 1.0) color.addData4f(0.0, 1.0, 0.0, 1.0) color.addData4f(0.0, 0.0, 1.0, 1.0) color.addData4f(1.0, 0.0, 1.0, 1.0) texcoord.addData2f(0.0, 1.0) texcoord.addData2f(0.0, 0.0) texcoord.addData2f(1.0, 0.0) texcoord.addData2f(1.0, 1.0) #quads aren't directly supported by the geom interface tris = GeomTriangles(Geom.UHDynamic) tris.addVertices(0, 1, 3) tris.addVertices(1, 2, 3) #initialize surface square = Geom(vdata) square.addPrimitive(tris) return square
class Skidmark: def __init__(self, wheel_pos, radius, heading): self.radius = radius v_f = GeomVertexFormat.getV3() self.vdata = GeomVertexData('skid', v_f, Geom.UHDynamic) self.vdata.setNumRows(1) self.vertex = GeomVertexWriter(self.vdata, 'vertex') self.prim = GeomTriangles(Geom.UHStatic) self.cnt = 1 self.last_pos = wheel_pos geom = Geom(self.vdata) geom.addPrimitive(self.prim) node = GeomNode('gnode') node.addGeom(geom) nodePath = render.attachNewNode(node) nodePath.setTransparency(True) nodePath.setDepthOffset(1) self.__set_material(nodePath) nodePath.node().setBounds(OmniBoundingVolume()) self.add_vertices(radius, heading) self.add_vertices(radius, heading) self.remove_seq = Sequence( Wait(8), LerpFunc(nodePath.setAlphaScale, 8, 1, 0, 'easeInOut'), Func(nodePath.remove_node)) self.remove_seq.start() def __set_material(self, nodePath): mat = Material() mat.setAmbient((.35, .35, .35, .5)) mat.setDiffuse((.35, .35, .35, .5)) mat.setSpecular((.35, .35, .35, .5)) mat.setShininess(12.5) nodePath.set_material(mat, 1) def add_vertices(self, radius, heading): base_pos = self.last_pos + (0, 0, -radius + .05) rot_mat = Mat4() rot_mat.setRotateMat(heading, (0, 0, 1)) self.vertex.addData3f(base_pos + rot_mat.xformVec((-.12, 0, 0))) self.vertex.addData3f(base_pos + rot_mat.xformVec((.12, 0, 0))) if self.cnt >= 3: self.prim.addVertices(self.cnt - 3, self.cnt - 2, self.cnt - 1) self.prim.addVertices(self.cnt - 2, self.cnt, self.cnt - 1) self.cnt += 2 def update(self, pos, heading): if (pos - self.last_pos).length() > .2: self.last_pos = pos self.add_vertices(self.radius, heading) def destroy(self): self.remove_seq = self.remove_seq.finish()
def __init__(self, voxel_unit_size): self.voxel_unit_size = voxel_unit_size self.triangles = GeomTriangles(Geom.UHStatic) self.format = GeomVertexFormat.getV3n3c4() self.v_data = GeomVertexData('square', self.format, Geom.UHStatic) self.vertex = GeomVertexWriter(self.v_data, 'vertex') self.normal = GeomVertexWriter(self.v_data, 'normal') self.color = GeomVertexWriter(self.v_data, 'color')
def makeSquare(x1, y1, z1, x2, y2, z2): format = GeomVertexFormat.getV3n3cpt2() vdata = GeomVertexData('square', format, Geom.UHDynamic) vertex = GeomVertexWriter(vdata, 'vertex') normal = GeomVertexWriter(vdata, 'normal') # color = GeomVertexWriter(vdata, 'color') texcoord = GeomVertexWriter(vdata, 'texcoord') # make sure we draw the sqaure in the right plane if x1 != x2: vertex.addData3(x1, y1, z1) vertex.addData3(x2, y1, z1) vertex.addData3(x2, y2, z2) vertex.addData3(x1, y2, z2) normal.addData3(normalized(2 * x1 - 1, 2 * y1 - 1, 2 * z1 - 1)) normal.addData3(normalized(2 * x2 - 1, 2 * y1 - 1, 2 * z1 - 1)) normal.addData3(normalized(2 * x2 - 1, 2 * y2 - 1, 2 * z2 - 1)) normal.addData3(normalized(2 * x1 - 1, 2 * y2 - 1, 2 * z2 - 1)) else: vertex.addData3(x1, y1, z1) vertex.addData3(x2, y2, z1) vertex.addData3(x2, y2, z2) vertex.addData3(x1, y1, z2) normal.addData3(normalized(2 * x1 - 1, 2 * y1 - 1, 2 * z1 - 1)) normal.addData3(normalized(2 * x2 - 1, 2 * y2 - 1, 2 * z1 - 1)) normal.addData3(normalized(2 * x2 - 1, 2 * y2 - 1, 2 * z2 - 1)) normal.addData3(normalized(2 * x1 - 1, 2 * y1 - 1, 2 * z2 - 1)) # adding different colors to the vertex for visibility # color.addData4f(1.0, 0.0, 0.0, 1.0) # color.addData4f(0.0, 1.0, 0.0, 1.0) # color.addData4f(0.0, 0.0, 1.0, 1.0) # color.addData4f(1.0, 0.0, 1.0, 1.0) texcoord.addData2f(0.0, 1.0) texcoord.addData2f(0.0, 0.0) texcoord.addData2f(1.0, 0.0) texcoord.addData2f(1.0, 1.0) # Quads aren't directly supported by the Geom interface # you might be interested in the CardMaker class if you are # interested in rectangle though tris = GeomTriangles(Geom.UHDynamic) tris.addVertices(0, 1, 3) tris.addVertices(1, 2, 3) square = Geom(vdata) square.addPrimitive(tris) return square
def __init__(self, name: str = 'cube_mesh', wireframe_thickness: float = 5) -> None: self.name = name self.__vertex_data_format = GeomVertexFormat.getV3n3() self.__vertex_data = GeomVertexData(name, self.__vertex_data_format, Geom.UHStatic) self.geom = Geom(self.__vertex_data) self.__triangles = GeomTriangles(Geom.UHStatic) self.__triangle_data = self.__triangles.modifyVertices() self.__vertex = GeomVertexWriter(self.__vertex_data, 'vertex') self.__normal = GeomVertexWriter(self.__vertex_data, 'normal') self.__face_count = 0 def add_face(face: Face) -> None: self.__make_face(face) self.__make_face(Face.LEFT) self.__make_face(Face.RIGHT) self.__make_face(Face.BACK) self.__make_face(Face.FRONT) self.__make_face(Face.BOTTOM) self.__make_face(Face.TOP) self.__triangles.close_primitive() self.geom.add_primitive(self.__triangles) def is_connected(x, y, z, x1, y1, z1): return (abs(x - x1) == 1 and abs(y - y1) != 1 and abs(z - z1) != 1) or \ (abs(x - x1) != 1 and abs(y - y1) == 1 and abs(z - z1) != 1) or \ (abs(x - x1) != 1 and abs(y - y1) != 1 and abs(z - z1) == 1) ls = LineSegs() ls.set_thickness(wireframe_thickness) arr_x = [0, 0, 0, 0, 1, 1, 1, 1] arr_y = [0, 0, 1, 1, 1, 1, 0, 0] arr_z = [0, -1, -1, 0, 0, -1, -1, 0] for pos1 in range(len(arr_x) - 1): for pos2 in range(pos1, len(arr_x)): x = arr_x[pos1] y = arr_y[pos1] z = arr_z[pos1] x1 = arr_x[pos2] y1 = arr_y[pos2] z1 = arr_z[pos2] if (is_connected(x, y, z, x1, y1, z1)): ls.move_to(x, y, z) ls.draw_to(x1, y1, z1) self.__wireframe_node = ls.create()
def Square(self): format = GeomVertexFormat.getV3n3cpt2() vdata = GeomVertexData('cube', format, Geom.UHDynamic) vertex = GeomVertexWriter(vdata, 'vertex') ################################ # # FACE 1 # ################################ vert1 = LVector3(self.pos.getX(), self.pos.getY(), self.pos.getZ()) vert2 = LVector3(vert1.getX() + self.len, vert1.getY(), vert1.getZ()) vert3 = LVector3(vert2.getX(), vert2.getY() + self.wid, vert2.getZ()) vert4 = LVector3(vert1.getX(), vert1.getY() + self.wid, vert1.getZ()) vertex.addData3(vert1) vertex.addData3(vert2) vertex.addData3(vert3) vertex.addData3(vert4) normal = GeomVertexWriter(vdata, 'normal') norm = (vert4 - vert1).cross(vert2 - vert1) norm.normalize() normal.addData3(norm) normal.addData3(norm) normal.addData3(norm) normal.addData3(norm) color = GeomVertexWriter(vdata, 'color') color.addData4f(self.color) color.addData4f(self.color) color.addData4f(self.color) color.addData4f(self.color) texcoord = GeomVertexWriter(vdata, 'texcoord') texcoord.addData2f(1, 0) texcoord.addData2f(1, 1) texcoord.addData2f(0, 1) texcoord.addData2f(0, 0) tris = GeomTriangles(Geom.UHDynamic) tris.addVertices(0, 3, 1) tris.addVertices(1, 3, 2) square = Geom(vdata) square.addPrimitive(tris) self.prim = square self.model = GeomNode(self.name) self.model.addGeom(self.prim)
def createTexturedUnitQuadGeomNode(): # Own Geometry # format = GeomVertexFormat.getV3c4t2() format = GeomVertexFormat.getV3t2() vdata = GeomVertexData("textured_quad", format, Geom.UHStatic) vdata.setNumRows(4) vertexPosWriter = GeomVertexWriter(vdata, "vertex") vertexPosWriter.addData3f(0, 0, 0) vertexPosWriter.addData3f(1, 0, 0) vertexPosWriter.addData3f(1, 0, 1) vertexPosWriter.addData3f(0, 0, 1) # let's also add color to each vertex # colorWriter = GeomVertexWriter(vdata, "color") # colorWriter.addData4f(0,0,1,1) # colorWriter.addData4f(0,0,1,1) # colorWriter.addData4f(0,0,1,1) # colorWriter.addData4f(0,0,1,1) # let's add texture coordinates (u,v) texcoordWriter = GeomVertexWriter(vdata, "texcoord") texcoordWriter.addData2f(0, 0) texcoordWriter.addData2f(1, 0) texcoordWriter.addData2f(1, 1) texcoordWriter.addData2f(0, 1) # make primitives and assign vertices to them (primitives and primitive # groups can be made independently from vdata, and are later assigned # to vdata) tris = GeomTriangles(Geom.UHStatic) # 1st triangle tris.addVertices(0, 1, 3) tris.closePrimitive() # the 1st primitive is finished # 2nd triangle tris.addVertices(1, 2, 3) tris.closePrimitive() # make a Geom object to hold the primitives quadGeom = Geom(vdata) quadGeom.addPrimitive(tris) # now put quadGeom in a GeomNode. You can now position your geometry # in the scene graph. quadGeomNode = GeomNode("quad") quadGeomNode.addGeom(quadGeom) return quadGeomNode
def createColoredUnitQuadGeomNode(color_vec4=Vec4(0., 0., 1., 1.), center_it=False): # Own Geometry # format = GeomVertexFormat.getV3c4t2() format = GeomVertexFormat.getV3c4() vdata = GeomVertexData("colored_quad", format, Geom.UHStatic) vdata.setNumRows(4) vertexPosWriter = GeomVertexWriter(vdata, "vertex") if center_it == False: vertexPosWriter.addData3f(0, 0, 0) vertexPosWriter.addData3f(1, 0, 0) vertexPosWriter.addData3f(1, 0, 1) vertexPosWriter.addData3f(0, 0, 1) else: vertexPosWriter.addData3f(0 - 0.5, 0, 0 - 0.5) vertexPosWriter.addData3f(1 - 0.5, 0, 0 - 0.5) vertexPosWriter.addData3f(1 - 0.5, 0, 1 - 0.5) vertexPosWriter.addData3f(0 - 0.5, 0, 1 - 0.5) # let's also add color to each vertex colorWriter = GeomVertexWriter(vdata, "color") colorWriter.addData4f(color_vec4) colorWriter.addData4f(color_vec4) colorWriter.addData4f(color_vec4) colorWriter.addData4f(color_vec4) # make primitives and assign vertices to them (primitives and primitive # groups can be made independently from vdata, and are later assigned # to vdata) tris = GeomTriangles(Geom.UHStatic) # 1st triangle tris.addVertices(0, 1, 3) tris.closePrimitive() # the 1st primitive is finished # 2nd triangle tris.addVertices(1, 2, 3) tris.closePrimitive() # make a Geom object to hold the primitives quadGeom = Geom(vdata) quadGeom.addPrimitive(tris) # now put quadGeom in a GeomNode. You can now position your geometry # in the scene graph. quadGeomNode = GeomNode("colored_quad_node") quadGeomNode.addGeom(quadGeom) return quadGeomNode
def __build_Tris(self, sphere, mode): vdata = GeomVertexData("Data", self.__vformat[mode], Geom.UHStatic) _num_rows = len(sphere.pts) # Vertices. vertices = GeomVertexWriter(vdata, "vertex") vertices.reserveNumRows(_num_rows) for pt in sphere.pts: vertices.addData3f(*pt) # Map coords. if mode == "mid": mapcoords = GeomVertexWriter(vdata, "mapcoord") mapcoords.reserveNumRows(_num_rows) for mc in sphere.coords: u, v = mc[:2] mapcoords.addData2f(u, v) # Tris. prim = GeomTriangles(Geom.UHStatic) prim.reserveNumVertices(len(sphere.tris)) for tri in sphere.tris: prim.addVertices(*tri) prim.closePrimitive() # Geom. geom = Geom(vdata) geom.addPrimitive(prim) geom_node = GeomNode("geom") geom_node.addGeom(geom) geom_np = NodePath(geom_node) return geom_np
def __init__(self, name='Unnamed Shape'): self._name = name self._vert_data = GeomVertexData( self._name, GeomVertexFormat.get_v3n3c4t2(), Geom.UH_static ) self._vert_writer = GeomVertexWriter(self._vert_data, 'vertex') self._norm_writer = GeomVertexWriter(self._vert_data, 'normal') self._color_writer = GeomVertexWriter(self._vert_data, 'color') self._tex_writer = GeomVertexWriter(self._vert_data, 'texcoord') self._prim = GeomTriangles(Geom.UH_static) self._v_id = 0
def draw(self): if self.rendered_mesh != None: self.reset_draw() format = GeomVertexFormat.getV3n3cp() vdata = GeomVertexData('tri', format, Geom.UHDynamic) vertex = GeomVertexWriter(vdata, 'vertex') normal = GeomVertexWriter(vdata, 'normal') color = GeomVertexWriter(vdata, 'color') v_mapping = {} i = 0 for v in self.verts.values(): vertex.addData3f(v.pos.x, v.pos.y, v.pos.z) normal.addData3f(v.norm.x, v.norm.y, v.norm.z) color.addData4f(v.color[0], v.color[1], v.color[2], v.color[3]) v_mapping[v.ID] = i i += 1 mesh = Geom(vdata) for f in self.faces.values(): tri = GeomTriangles(Geom.UHDynamic) tri.addVertex(v_mapping[f.v1.ID]) tri.addVertex(v_mapping[f.v2.ID]) tri.addVertex(v_mapping[f.v3.ID]) tri.closePrimitive() mesh.addPrimitive(tri) snode = GeomNode(self.name) snode.addGeom(mesh) self.rendered_mesh = render.attachNewNode(snode) self.rendered_mesh.setTwoSided(True)
def draw_face(self, f, f_color): #add normal format = GeomVertexFormat.getV3n3cp() vdata = GeomVertexData('vert', format, Geom.UHDynamic) vertex = GeomVertexWriter(vdata, 'vertex') color = GeomVertexWriter(vdata, 'color') normal = GeomVertexWriter(vdata, 'normal') vertex.addData3f(f.v1.pos) normal.addData3f(f.v1.norm.x, f.v1.norm.y, f.v1.norm.z) color.addData4f(f_color) vertex.addData3f(f.v2.pos) normal.addData3f(f.v2.norm.x, f.v2.norm.y, f.v2.norm.z) color.addData4f(f_color) vertex.addData3f(f.v3.pos) normal.addData3f(f.v3.norm.x, f.v3.norm.y, f.v3.norm.z) color.addData4f(f_color) mesh = Geom(vdata) tri = GeomTriangles(Geom.UHDynamic) tri.addVertex(0) tri.addVertex(1) tri.addVertex(2) tri.closePrimitive() mesh.addPrimitive(tri) face_node = GeomNode(self.mesh.name + '_face_' + str(f.ID)) face_node.addGeom(mesh) face_node.setTag('ID', str(f.ID)) rendered_face = self.render_root.attachNewNode(face_node) rendered_face.setTwoSided(True) self.render_nodes['face_' + str(f.ID)] = rendered_face
def create_model(self): # Set up the vertex arrays vformat = GeomVertexFormat.get_v3c4() vdata = GeomVertexData("Data", vformat, Geom.UHStatic) vertex = GeomVertexWriter(vdata, 'vertex') color = GeomVertexWriter(vdata, 'color') geom = Geom(vdata) # Vertex data vertex.addData3f(1.5, 0, -1) color.addData4f(1, 0, 0, 1) vertex.addData3f(-1.5, 0, -1) color.addData4f(0, 1, 0, 1) vertex.addData3f(0, 0, 1) color.addData4f(0, 0, 1, 1) # Primitive tri = GeomTriangles(Geom.UHStatic) tri.add_vertex(2) tri.add_vertex(1) tri.add_vertex(0) tri.close_primitive() geom.addPrimitive(tri) # Create the actual node node = GeomNode('geom_node') node.addGeom(geom) np = NodePath(node) # Shader and initial shader vars np.set_shader( Shader.load(Shader.SL_GLSL, "shader/shader.vert", "shader/shader.frag")) np.set_shader_input("time", 0.0) # No instancing necessary #np.set_instance_count(27) # return np np.reparent_to(base.render) self.model = np
def getPrimAndDataFromTri(triset, matstate): if triset.normal is None: triset.generateNormals() needsTanAndBin = False if matstate is not None and matstate.hasAttrib(TextureAttrib): texattr = matstate.getAttrib(TextureAttrib) for i in range(texattr.getNumOnStages()): if texattr.getOnStage(i).getMode() == TextureStage.MNormal: needsTanAndBin = True if needsTanAndBin and isinstance(triset, collada.triangleset.TriangleSet) and \ len(triset.texcoordset) > 0 and len(triset.textangentset) == 0: triset.generateTexTangentsAndBinormals() vdata, indexdata = getVertexData( triset.vertex, triset.vertex_index, triset.normal, triset.normal_index, triset.texcoordset, triset.texcoord_indexset, triset.textangentset, triset.textangent_indexset, triset.texbinormalset, triset.texbinormal_indexset) gprim = GeomTriangles(Geom.UHStatic) gprim.setIndexType(Geom.NTUint32) gprim.setVertices(indexdata) gprim.closePrimitive() return (vdata, gprim)
def __init__(self): ShowBase.__init__(self) PanditorDisableMouseFunc() camera.setPos(0.0, 0.0, 50.0) camera.lookAt(0.0) PanditorEnableMouseFunc() # 1) create GeomVertexData frmt = GeomVertexFormat.getV3n3cp() vdata = GeomVertexData('triangle', frmt, Geom.UHDynamic) # 2) create Writers/Rewriters (must all be created before any readers and readers are one-pass-temporary) vertex = GeomVertexRewriter(vdata, 'vertex') normal = GeomVertexRewriter(vdata, 'normal') color = GeomVertexRewriter(vdata, 'color') zUp = Vec3(0, 0, 1) wt = Vec4(1.0, 1.0, 1.0, 1.0) gr = Vec4(0.5, 0.5, 0.5, 1.0) # 3) write each column on the vertex data object (for speed, have a different writer for each column) def addPoint(x, y, z): vertex.addData3f(x, y, z) normal.addData3f(zUp) color.addData4f(wt) addPoint(0.0, 0.0, 0.0) addPoint(5.0, 0.0, 0.0) addPoint(0.0, 5.0, 0.0) addPoint(5.0, 5.0, 0.0) # 4) create a primitive and add the vertices via index (not truely associated with the actual vertex table, yet) tris = GeomTriangles(Geom.UHDynamic) tris.addVertices(0, 1, 2) tris.closePrimitive( ) # exception thrown if verts added != 3, other types inform Panda how many verts/primitive tris.addVertices(2, 1, 3) print "vdataPoints", vdata.getArrays()[0] # 5.1) (adding to scene) create a Geom and add primitives of like base-type i.e. triangles and triangle strips geom = Geom(vdata) geom.addPrimitive(tris) # 5.2) create a GeomNode to hold the Geom(s) and add the Geom(s) gn = GeomNode('gnode') gn.addGeom(geom) # 5.3) attache the node to the scene gnNodePath = render.attachNewNode(gn) geomPts = Geom(vdata) pts = GeomPoints(Geom.UHStatic) pts.addVertices(0, 1, 2) pts.closePrimitive() geomPts.addPrimitive(pts) pointsNode = GeomNode('points_node') pointsNode.addGeom(geomPts) pointsNP = render.attachNewNode(pointsNode) pointsNP.setZ(0.5) render.ls()
def make_cube_geom(self, pos=(0, 0, 0), geom_color=(1, 1, 1, 0.5), faces_no_draw=(0, 0, 0, 0, 0, 0)): format = GeomVertexFormat.getV3n3cpt2() shift_x, shift_y, shift_z = pos cube_vertex_list = deepcopy(cube_data["vertexPositions"]) for vert in cube_vertex_list: vert[0] += shift_x vert[1] += shift_y vert[2] += shift_z vdata = GeomVertexData('square', format, Geom.UHDynamic) vertex = GeomVertexWriter(vdata, 'vertex') normal = GeomVertexWriter(vdata, 'normal') color = GeomVertexWriter(vdata, 'color') texcoord = GeomVertexWriter(vdata, 'texcoord') test_textcoords = [] # define available vertexes here [vertex.addData3(*v) for v in cube_vertex_list] [normal.addData3(*n) for n in cube_data["vertexNormals"]] [color.addData4f(*geom_color) for _ in cube_vertex_list] [texcoord.addData2f(*t) for t in texture_mapping] """ CREATE A NEW PRIMITIVE """ prim = GeomTriangles(Geom.UHStatic) # convert from numpy arr mapping to normal faces mapping... excluded_normals = [ normal_face_mapping[self.dict_mapping[i]] for i in range(len(faces_no_draw)) if faces_no_draw[i] == 1 ] # only use acceptable indices indices = [ ind for ind in cube_data['indices'] if cube_data['vertexNormals'][ind] not in excluded_normals ] [prim.addVertex(v) for v in indices] # N.B: this must correspond to a vertex defined in vdata geom = Geom(vdata) # create a new geometry geom.addPrimitive(prim) # add the primitive to the geometry return geom
def addMeshConvexRB(self,vertices, faces,ghost=False,**kw): #step 1) create GeomVertexData and add vertex information format=GeomVertexFormat.getV3() vdata=GeomVertexData("vertices", format, Geom.UHStatic) vertexWriter=GeomVertexWriter(vdata, "vertex") [vertexWriter.addData3f(v[0],v[1],v[2]) for v in vertices] #step 2) make primitives and assign vertices to them tris=GeomTriangles(Geom.UHStatic) [self.setGeomFaces(tris,face) for face in faces] #step 3) make a Geom object to hold the primitives geom=Geom(vdata) geom.addPrimitive(tris) #step 4) create the bullet mesh and node mesh = BulletTriangleMesh() mesh.addGeom(geom) shape = BulletConvexHullShape(mesh, dynamic=not ghost)# if ghost : inodenp = self.worldNP.attachNewNode(BulletGhostNode('Mesh')) else : inodenp = self.worldNP.attachNewNode(BulletRigidBodyNode('Mesh')) inodenp.node().addShape(shape) # inodenp.setPos(0, 0, 0.1) self.setRB(inodenp,**kw) inodenp.setCollideMask(BitMask32.allOn()) self.world.attachRigidBody(inodenp.node()) return inodenp
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()
def draw(self): if self.rendered_mesh != None: self.reset_draw() format=GeomVertexFormat.getV3n3cp() vdata=GeomVertexData('tri', format, Geom.UHDynamic) vertex=GeomVertexWriter(vdata, 'vertex') normal=GeomVertexWriter(vdata, 'normal') color=GeomVertexWriter(vdata, 'color') v_mapping = {} i=0 for v in self.verts.values(): vertex.addData3f(v.pos.x,v.pos.y,v.pos.z) normal.addData3f(v.norm.x, v.norm.y, v.norm.z) color.addData4f(v.color[0],v.color[1],v.color[2],v.color[3]) v_mapping[v.ID] = i i += 1 mesh = Geom(vdata) for f in self.faces.values(): tri = GeomTriangles(Geom.UHDynamic) tri.addVertex(v_mapping[f.v1.ID]) tri.addVertex(v_mapping[f.v2.ID]) tri.addVertex(v_mapping[f.v3.ID]) tri.closePrimitive() mesh.addPrimitive(tri) snode = GeomNode(self.name) snode.addGeom(mesh) self.rendered_mesh = render.attachNewNode(snode) self.rendered_mesh.setTwoSided(True)
def getPrimAndDataFromTri(triset, matstate): if triset.normal is None: triset.generateNormals() needsTanAndBin = False if matstate is not None and matstate.hasAttrib(TextureAttrib): texattr = matstate.getAttrib(TextureAttrib) for i in range(texattr.getNumOnStages()): if texattr.getOnStage(i).getMode() == TextureStage.MNormal: needsTanAndBin = True if needsTanAndBin and isinstance(triset, collada.triangleset.TriangleSet) and \ len(triset.texcoordset) > 0 and len(triset.textangentset) == 0: triset.generateTexTangentsAndBinormals() vdata, indexdata = getVertexData(triset.vertex, triset.vertex_index, triset.normal, triset.normal_index, triset.texcoordset, triset.texcoord_indexset, triset.textangentset, triset.textangent_indexset, triset.texbinormalset, triset.texbinormal_indexset) gprim = GeomTriangles(Geom.UHStatic) gprim.setIndexType(Geom.NTUint32) gprim.setVertices(indexdata) gprim.closePrimitive() return (vdata, gprim)
def __build_Tris(self, sphere, mode): vdata = GeomVertexData("Data", self.__vformat[mode], Geom.UHStatic) _num_rows = len(sphere.pts) # Vertices. vertices = GeomVertexWriter(vdata, "vertex") vertices.reserveNumRows(_num_rows) for pt in sphere.pts: vertices.addData3f(*pt) # Map coords. if mode == "mid": mapcoords = GeomVertexWriter(vdata, "mapcoord") mapcoords.reserveNumRows(_num_rows) for mc in sphere.coords: u, v = mc[:2] mapcoords.addData2f(u,v) # Tris. prim = GeomTriangles(Geom.UHStatic) prim.reserveNumVertices(len(sphere.tris)) for tri in sphere.tris: prim.addVertices(*tri) prim.closePrimitive() # Geom. geom = Geom(vdata) geom.addPrimitive(prim) geom_node = GeomNode("geom") geom_node.addGeom(geom) geom_np = NodePath(geom_node) return geom_np
def create_model(self): # Set up the vertex arrays vformat = GeomVertexFormat.get_v3c4() vdata = GeomVertexData("Data", vformat, Geom.UHStatic) vertex = GeomVertexWriter(vdata, 'vertex') color = GeomVertexWriter(vdata, 'color') geom = Geom(vdata) # Vertex data vertex.addData3f(1.5, 0, -1) color.addData4f(1, 0, 0, 1) vertex.addData3f(-1.5, 0, -1) color.addData4f(0, 1, 0, 1) vertex.addData3f(0, 0, 1) color.addData4f(0, 0, 1, 1) # Primitive tri = GeomTriangles(Geom.UHStatic) tri.add_vertex(2) tri.add_vertex(1) tri.add_vertex(0) tri.close_primitive() geom.addPrimitive(tri) # Create the actual node node = GeomNode('geom_node') node.addGeom(geom) np = NodePath(node) # Shader and initial shader vars np.set_shader(Shader.load(Shader.SL_GLSL, "shader/shader.vert", "shader/shader.frag")) np.set_shader_input("time", 0.0) # No instancing necessary #np.set_instance_count(27) # return np np.reparent_to(base.render) self.model = np
def draw_face(self,f,f_color): #add normal format = GeomVertexFormat.getV3n3cp() vdata=GeomVertexData('vert', format, Geom.UHDynamic) vertex=GeomVertexWriter(vdata, 'vertex') color=GeomVertexWriter(vdata, 'color') normal=GeomVertexWriter(vdata, 'normal') vertex.addData3f(f.v1.pos) normal.addData3f(f.v1.norm.x, f.v1.norm.y, f.v1.norm.z) color.addData4f(f_color) vertex.addData3f(f.v2.pos) normal.addData3f(f.v2.norm.x, f.v2.norm.y, f.v2.norm.z) color.addData4f(f_color) vertex.addData3f(f.v3.pos) normal.addData3f(f.v3.norm.x, f.v3.norm.y, f.v3.norm.z) color.addData4f(f_color) mesh = Geom(vdata) tri = GeomTriangles(Geom.UHDynamic) tri.addVertex(0) tri.addVertex(1) tri.addVertex(2) tri.closePrimitive() mesh.addPrimitive(tri) face_node = GeomNode(self.mesh.name+'_face_'+str(f.ID)) face_node.addGeom(mesh) face_node.setTag('ID',str(f.ID)) rendered_face = self.render_root.attachNewNode(face_node) rendered_face.setTwoSided(True) self.render_nodes['face_'+str(f.ID)] = rendered_face
def __init__(self): ShowBase.__init__(self) PanditorDisableMouseFunc() camera.setPos(0.0, 0.0, 50.0) camera.lookAt(0.0) PanditorEnableMouseFunc() # 1) create GeomVertexData frmt = GeomVertexFormat.getV3n3cp() vdata = GeomVertexData('triangle', frmt, Geom.UHDynamic) # 2) create Writers/Rewriters (must all be created before any readers and readers are one-pass-temporary) vertex = GeomVertexRewriter(vdata, 'vertex') normal = GeomVertexRewriter(vdata, 'normal') color = GeomVertexRewriter(vdata, 'color') zUp = Vec3(0, 0, 1) wt = Vec4(1.0, 1.0, 1.0, 1.0) gr = Vec4(0.5, 0.5, 0.5, 1.0) # 3) write each column on the vertex data object (for speed, have a different writer for each column) def addPoint(x, y, z): vertex.addData3f(x, y, z) normal.addData3f(zUp) color.addData4f(wt) addPoint(0.0, 0.0, 0.0) addPoint(5.0, 0.0, 0.0) addPoint(0.0, 5.0, 0.0) addPoint(5.0, 5.0, 0.0) # 4) create a primitive and add the vertices via index (not truely associated with the actual vertex table, yet) tris = GeomTriangles(Geom.UHDynamic) tris.addVertices(0, 1, 2) tris.closePrimitive() # exception thrown if verts added != 3, other types inform Panda how many verts/primitive tris.addVertices(2, 1, 3) print "vdataPoints", vdata.getArrays()[0] # 5.1) (adding to scene) create a Geom and add primitives of like base-type i.e. triangles and triangle strips geom = Geom(vdata) geom.addPrimitive(tris) # 5.2) create a GeomNode to hold the Geom(s) and add the Geom(s) gn = GeomNode('gnode') gn.addGeom(geom) # 5.3) attache the node to the scene gnNodePath = render.attachNewNode(gn) geomPts = Geom(vdata) pts = GeomPoints(Geom.UHStatic) pts.addVertices(0, 1, 2) pts.closePrimitive() geomPts.addPrimitive(pts) pointsNode = GeomNode('points_node') pointsNode.addGeom(geomPts) pointsNP = render.attachNewNode(pointsNode) pointsNP.setZ(0.5) render.ls()
def makeNode(self, pointmap=(lambda x, y: (x, y, 0))): vt = tuple(self.vertices) t = Triangulator() fmt = GeomVertexFormat.getV3() vdata = GeomVertexData('name', fmt, Geom.UHStatic) vertex = GeomVertexWriter(vdata, 'vertex') for x, y in vt: t.addPolygonVertex(t.addVertex(x, y)) vertex.addData3f(pointmap(x, y)) t.triangulate() prim = GeomTriangles(Geom.UHStatic) for n in xrange(t.getNumTriangles()): prim.addVertices(t.getTriangleV0(n),t.getTriangleV1(n),t.getTriangleV2(n)) prim.closePrimitive() geom = Geom(vdata) geom.addPrimitive(prim) node = GeomNode('gnode') node.addGeom(geom) return node
def __init__(self, vdata, tex_idx): self.vdata = vdata # vertex data, passed in from parent mesh self.name = 'PolyGroup_'+str(tex_idx) self.geom = Geom(self.vdata) self.primitives = GeomTriangles(Geom.UHStatic) self.geom.addPrimitive(self.primitives) self.sprite_list_index = 0 self.nodePath = None
def makeSquare(face, rhs=True): format=GeomVertexFormat.getV3n3cpt2() format=GeomVertexFormat.getV3n3t2() vdata=GeomVertexData('square', format, Geom.UHStatic) vertex=GeomVertexWriter(vdata, 'vertex') normal=GeomVertexWriter(vdata, 'normal') #color=GeomVertexWriter(vdata, 'color') texcoord=GeomVertexWriter(vdata, 'texcoord') if not rhs: face = list(reversed(face)) normalvec = (face[1]-face[0]).cross(face[2]-face[0]) normalvec.normalize() f = 0.9 if rhs else 0.8 f = 1.0 for ver in face: vertex.addData3f(ver*f) normal.addData3f(normalvec) #color.addData3f((ver+1.0+2.0)*0.25) #color.addData3f(ver*0.0+1.0) if not normalvec.z: texcoord.addData2f(0.0, 0.0) texcoord.addData2f(1.0, 0.0) texcoord.addData2f(1.0, 1.0) texcoord.addData2f(0.0, 1.0) tri=GeomTriangles(Geom.UHStatic) tri.addVertices(0, 1, 2) tri.addVertices(2, 3, 0) tri.closePrimitive() square=Geom(vdata) square.addPrimitive(tri) return square
def reconstruct(self): trianglator = Triangulator() #Add vertices to the trianglator for vertex in self.vertices: trianglator.addPolygonVertex(trianglator.addVertex(vertex)) trianglator.triangulate() #Prepare to create the primative self.vdata = GeomVertexData('floor', GeomVertexFormat.getV3n3cpt2(), Geom.UHStatic) vertexW = GeomVertexWriter(self.vdata, 'vertex') normalW = GeomVertexWriter(self.vdata, 'normal') colorW = GeomVertexWriter(self.vdata, 'color') texcoordW = GeomVertexWriter(self.vdata, 'texcoord') #Add vertices to the primative i = 0 while i < trianglator.getNumVertices(): vertex = trianglator.getVertex(i) vertexW.addData3f(vertex.x,vertex.y,0.0) normalW.addData3f(0,0,1) colorW.addData4f(0.1,0.1,0.1,0.5) texcoordW.addData2f(0.0, 1.0) i+=1 self.geom = Geom(self.vdata) #Add triangles to the primative i = 0 print(trianglator.getNumTriangles()) while i < trianglator.getNumTriangles(): tri = GeomTriangles(Geom.UHStatic) tri.addVertices(trianglator.getTriangleV0(i),trianglator.getTriangleV1(i),trianglator.getTriangleV2(i)) tri.closePrimitive() self.geom.addPrimitive(tri) i+=1 self.addGeom(self.geom)
def createTriangle(v1, v2, v3, is_flat=False): x1 = v1.x y1 = v1.y z1 = v1.z x2 = v2.x y2 = v2.y z2 = v2.z x3 = v3.x y3 = v3.y z3 = v3.z format=GeomVertexFormat.getV3n3cp() vdata=GeomVertexData('tri', format, Geom.UHDynamic) vertex=GeomVertexWriter(vdata, 'vertex') normal=GeomVertexWriter(vdata, 'normal') color=GeomVertexWriter(vdata, 'color') vertex.addData3f(x1, y1, z1) vertex.addData3f(x2, y2, z2) vertex.addData3f(x3, y3, z3) if is_flat: normVector = norm(Vec3( (x1 + x2 + x3)/3.0, (y1 + y2 + y3)/3.0, (z1+ z2+ z3)/3.0)) normal.addData3f(normVector) normal.addData3f(normVector) normal.addData3f(normVector) else: normal.addData3f(norm(Vec3(x1,y1,z1))) normal.addData3f(norm(Vec3(x2,y2,z2))) normal.addData3f(norm(Vec3(x3,y3,z3))) #adding different colors to the vertex for visibility color.addData4f(0.5,0.5,0.5,1.0) color.addData4f(0.5,0.5,0.5,1.0) color.addData4f(0.5,0.5,0.5,1.0) tri = GeomTriangles(Geom.UHDynamic) tri.addVertex(0) tri.addVertex(1) tri.addVertex(2) tri.closePrimitive() output_tri = Geom(vdata) output_tri.addPrimitive(tri) return output_tri
def createTetraeder(self, iterations): ''' Note that the first and the last node of the Thetha_Range should be 0 and 180 Degrees because this will be just one time added to verticies ''' #Format format = GeomVertexFormat.getV3n3cpt2() #VertexData vdata = GeomVertexData('name', format, Geom.UHDynamic) ##VertexWriter vertex = GeomVertexWriter(vdata, 'vertex') normal = GeomVertexWriter(vdata, 'normal') color = GeomVertexWriter(vdata, 'color') texcoord = GeomVertexWriter(vdata, 'texcoord') vertex.addData3f(0,1.434,-0.507) vertex.addData3f(-1.242,-0.717,-0.507) vertex.addData3f(1.242,-0.717,-0.507) vertex.addData3f(0,0,1.521) color.addData4f(1,1,1,1) color.addData4f(1,1,1,1) color.addData4f(1,1,1,1) color.addData4f(1,1,1,1) normal.addData3f(0,1.434,-0.507) normal.addData3f(-1.242,-0.717,-0.507) normal.addData3f(1.242,-0.717,-0.507) normal.addData3f(0,0,1.521) ### Create Geom geom = Geom(vdata) ### Create Primitives prim = GeomTriangles(Geom.UHStatic) prim.addVertices(0, 1, 2) prim.addVertices(0, 1, 3) prim.addVertices(1, 2, 3) prim.addVertices(2, 0, 3) prim.closePrimitive() geom.addPrimitive(prim) node = GeomNode('gnode') node.addGeom(geom) return node
def __init__(self, name = 'Mesh'): ''' Constructor ''' self.name = name self.finished = False self.format = GeomVertexFormat.getV3n3c4() self.vertexData = GeomVertexData(name, self.format, Geom.UHStream) self.mesh = Geom(self.vertexData) self.triangles = GeomTriangles(Geom.UHStream) self.triangleData = self.triangles.modifyVertices() self.vertex = GeomVertexWriter(self.vertexData, 'vertex') self.normal = GeomVertexWriter(self.vertexData, 'normal') self.color = GeomVertexWriter(self.vertexData, 'color') #self.texcoord = GeomVertexWriter(self.vertexData, 'texcoord') self.faceCount = 0
def __init__(self, name = 'Mesh'): self.name = name self.finished = False self.format = GeomVertexFormat.getV3c4t2() #print self.format self.vertexData = GeomVertexData(name, self.format, Geom.UHStatic) self.vertexData.setNumRows(26136) self.mesh = Geom(self.vertexData) self.triangles = GeomTriangles(Geom.UHStatic) self.triangleData = self.triangles.modifyVertices() self.triangleData.setNumRows(26136) self.vertex = GeomVertexWriter(self.vertexData, 'vertex') self.normal = GeomVertexWriter(self.vertexData, 'normal') self.color = GeomVertexWriter(self.vertexData, 'color') self.texcoord = GeomVertexWriter(self.vertexData, 'texcoord') self.faceCount = 0
def load(self): if panda3d is None: raise ImportError("Cannot locate Panda3D") node = GeomNode(self.name) for n in range(len(self.faces)): facevertices = self.faces[n] vertices = [self.vertices[v] for v in facevertices] normals = None if self.normals is not None: normals = (self.normals[n],) * len(facevertices) colors = None if self.facecolors is not None: colors = (self.facecolors[n],) * len(facevertices) elif self.fvcolors is not None: colors = self.fvcolors[n] texcoords = None if self.texcoords is not None: texcoords = self.texcoords[n] #KLUDGE if self.material is not None and colors is None: col = self.material.getAmbient() col = (col[0] / col[3], col[1] / col[3], col[2] / col[3], 1.0) colors = (col,) * len(vertices) #/KLUDGE geom = make_geom(vertices, normals, colors, texcoords) prim = GeomTriangles(Geom.UHStatic) #TODO: proper tesselation! the current one only works for convex faces curr = 1 for v in range(2, len(facevertices)): prim.addVertex(curr) prim.addVertex(v) prim.addVertex(0) curr = v prim.closePrimitive() geom.addPrimitive(prim) node.addGeom(geom) self.node = NodePath(node) self.node.setTwoSided(True) if self.material is not None: self.node.setMaterial(self.material, priority=1) self.loaded = True
def renderVerts(verts, idx): from meshtool.filters.panda_filters.pandacore import getVertexData, attachLights, ensureCameraAt from meshtool.filters.panda_filters.pandacontrols import KeyboardMovement, MouseDrag, MouseScaleZoom from panda3d.core import GeomTriangles, Geom, GeomNode from direct.showbase.ShowBase import ShowBase vdata, indexdata = getVertexData(verts, idx) gprim = GeomTriangles(Geom.UHStatic) gprim.setIndexType(Geom.NTUint32) gprim.setVertices(indexdata) gprim.closePrimitive() pgeom = Geom(vdata) pgeom.addPrimitive(gprim) node = GeomNode("primitive") node.addGeom(pgeom) p3dApp = ShowBase() #attachLights(render) geomPath = render.attachNewNode(node) geomPath.setRenderModeWireframe() ensureCameraAt(geomPath, base.camera) KeyboardMovement() #render.setShaderAuto() p3dApp.run()
def renderCharts(facegraph, verts, vert_indices, lineset=None): from meshtool.filters.panda_filters.pandacore import getVertexData, attachLights, ensureCameraAt from meshtool.filters.panda_filters.pandacontrols import KeyboardMovement, MouseDrag, MouseScaleZoom, ButtonUtils from panda3d.core import GeomTriangles, Geom, GeomNode, GeomVertexFormat, GeomVertexData, GeomVertexWriter, LineSegs from direct.showbase.ShowBase import ShowBase vformat = GeomVertexFormat.getV3c4() vdata=GeomVertexData('tris', vformat, Geom.UHDynamic) vertex=GeomVertexWriter(vdata, 'vertex') color=GeomVertexWriter(vdata, 'color') colors = gen_color3(len(facegraph)) numtris = 0 for chart, data in facegraph.nodes_iter(data=True): curcolor = next(colors) for tri in data['tris']: triv = verts[vert_indices[tri]] vertex.addData3f(triv[0][0], triv[0][1], triv[0][2]) vertex.addData3f(triv[1][0], triv[1][1], triv[1][2]) vertex.addData3f(triv[2][0], triv[2][1], triv[2][2]) color.addData4f(curcolor[0],curcolor[1], curcolor[2], 1) color.addData4f(curcolor[0],curcolor[1], curcolor[2], 1) color.addData4f(curcolor[0],curcolor[1], curcolor[2], 1) numtris += 1 tris=GeomTriangles(Geom.UHDynamic) tris.addConsecutiveVertices(0, 3*numtris) tris.closePrimitive() linenodes = [] if lineset: for lines in lineset: ls = LineSegs() ls.setThickness(4) curcolor = next(colors) ls.setColor(curcolor[0]/256.0, curcolor[1]/256.0, curcolor[2]/256.0, 1) tuples = False for blah in lines: if isinstance(blah, tuple): tuples = True break if tuples: for i, j in lines: frompt = verts[i] topt = verts[j] ls.moveTo(frompt[0], frompt[1], frompt[2]) ls.drawTo(topt[0], topt[1], topt[2]) else: for i in range(len(lines)-1): frompt = verts[lines[i]] topt = verts[lines[i+1]] ls.moveTo(frompt[0], frompt[1], frompt[2]) ls.drawTo(topt[0], topt[1], topt[2]) linenodes.append(ls.create()) pgeom = Geom(vdata) pgeom.addPrimitive(tris) node = GeomNode("primitive") node.addGeom(pgeom) p3dApp = ShowBase() #attachLights(render) geomPath = render.attachNewNode(node) for linenode in linenodes: geomPath.attachNewNode(linenode) #geomPath.setRenderModeWireframe() ensureCameraAt(geomPath, base.cam) boundingSphere = geomPath.getBounds() base.cam.setPos(boundingSphere.getCenter() + boundingSphere.getRadius()) base.cam.lookAt(boundingSphere.getCenter()) KeyboardMovement() ButtonUtils(geomPath) MouseDrag(geomPath) MouseScaleZoom(geomPath) #render.setShaderAuto() p3dApp.run()
class Chunk2GeomDecoder: """ Chunk decoder that decodes chunks to Panda3D Geoms/Nodes """ def __init__(self): self.textures={} for k in texMap: v=texMap[k] tex=loader.loadTexture("gfx/%s"%v) tex.setWrapU(Texture.WM_clamp) tex.setWrapV(Texture.WM_clamp) self.textures[k]=tex self.viewPoint=(0,0,0) self.cubeVtxSrc=[ # 14 vertices per cube mapped # so that UV coords utilize # the typical cube unwrap: # # #### <-- square texture # ##U# # BLFR # ##D# #=unused # # This form uses 14 vertices per cube since # the extra (worldspace overlapped) vertices # map different U,V coordinates at the same # worldspace coordinates, depending on face # # x y z u v (1.00,1.00,1.00,0.00,0.50), # A (1.00,1.00,0.00,0.00,0.25), # B (0.00,1.00,1.00,0.25,0.50), # C (0.00,1.00,0.00,0.25,0.25), # D (0.00,0.00,1.00,0.50,0.50), # E (0.00,0.00,0.00,0.50,0.25), # F (1.00,0.00,1.00,0.75,0.50), # G (1.00,0.00,0.00,0.75,0.25), # H (1.00,1.00,1.00,1.00,0.50), # I (1.00,1.00,0.00,1.00,0.25), # J (0.00,1.00,1.00,0.50,0.75), # K (1.00,1.00,1.00,0.75,0.75), # L (0.00,1.00,0.00,0.50,0.00), # M (1.00,1.00,0.00,0.75,0.00) # N ] self.triSrc=[ # # Faces (QUAD/TRIPAIR) # using RHR vertex ordering for # correct face surface normals # # front: EFHG/EFH+HGE # rear: CABD/CAB+BDC # left: CDFE/CDF+FEC # right: GHJI/GHJ+JIG # upper: KEGL/KEG+GLK # lower: FMNH/FMN+NHF # "EFH","HGE", "CAB","BDC", "CDF","FEC", "GHJ","JIG", "KEG","GLK", "FMN","NHF" ] # # setup cube # # one cube node will be generated per non-air block # since different block id's potentially refer to # different textures and thus must be separate nodes # of the scene graph. # # 1. vertices self.cubeVtx=GeomVertexData('blockCube',GeomVertexFormat.getV3t2(),Geom.UHStatic) self.cubeVtx.setNumRows(len(self.cubeVtxSrc)) vtxW=GeomVertexWriter(self.cubeVtx,'vertex') txcW=GeomVertexWriter(self.cubeVtx,'texcoord') for vertex in self.cubeVtxSrc: vtxW.addData3f(*vertex[0:3]) txcW.addData2f(*vertex[3:5]) # 2. mesh self.cubeMesh=GeomTriangles(Geom.UHStatic) for tri in self.triSrc: for triV in tri: triVtxId=ord(triV)-65 # changea 'A'-'N' to 0-13 self.cubeMesh.addVertex(triVtxId) self.cubeMesh.close_primitive() # 3. geometry (primitive+vertex pair) self.cubeGeom=Geom(self.cubeVtx) self.cubeGeom.addPrimitive(self.cubeMesh) def setViewpoint(x,y,z): self.viewPoint=(x,y,z) @decompress def Chunk2Geom(self,sChunk,origin): """ Decodes chunk into Panda3D geometry format @param sChunk: encoded chunk origin: chunk location in world as 3-tuple @return A panda3D Node object translated appropriately to place the decoded chunk correctly within the world. """ # determine where chunk should be placed in world space orgX=origin[0] orgY=origin[1] orgZ=origin[2] # determine chunk's coordinate chunkX=orgX/16 chunkY=orgY/16 # generate name tags for the various parts chunkId="%s_%s" % (chunkX,chunkY) vtxName="vtx_%s" % chunkId nodeName="chunk_%s" % chunkId # create empty node for entire chunk chunkNode=render.attachNewNode(nodeName) # convert string chunk to numeric chunk=[ord(c) for c in sChunk] # TODO: read chunk data and generate cube nodes flags=chunk[0]+(chunk[1]<<8)+(chunk[2]<<16)+(chunk[3]<<24) chunk=chunk[4:] # remove biome/flagbits for cY in range(16): for cX in range(16): for cZ in range(256): cell=cZ+(cX<<8)+(cY<<12) # lookup neighbours me=chunk[cell] if me>0: n_up=chunk[cell-1] if cZ>0 else 0 n_dn=chunk[cell+1] if cZ<255 else 0 n_lt=chunk[cell-256] if cX>0 else 0 n_rt=chunk[cell+256] if cX<15 else 0 n_bk=chunk[cell-4096] if cY>0 else 0 n_fd=chunk[cell+4096] if cY<15 else 0 if n_up==0 or n_dn==0 or \ n_lt==0 or n_rt==0 or \ n_bk==0 or n_fd==0: # for any non-obscured block # generate a cube block=GeomNode("%s_block_%s_%s_%s"%(nodeName,cX,cY,cZ)) block.addGeom(self.cubeGeom) blockNode=chunkNode.attachNewNode(block) blockNode.setTexture(self.textures[me]) blockNode.setPos(cX,cY,cZ) chunkNode.setPos(chunkX*16,chunkY*16,-64) return chunkNode
def __init__(self): self.textures={} for k in texMap: v=texMap[k] tex=loader.loadTexture("gfx/%s"%v) tex.setWrapU(Texture.WM_clamp) tex.setWrapV(Texture.WM_clamp) self.textures[k]=tex self.viewPoint=(0,0,0) self.cubeVtxSrc=[ # 14 vertices per cube mapped # so that UV coords utilize # the typical cube unwrap: # # #### <-- square texture # ##U# # BLFR # ##D# #=unused # # This form uses 14 vertices per cube since # the extra (worldspace overlapped) vertices # map different U,V coordinates at the same # worldspace coordinates, depending on face # # x y z u v (1.00,1.00,1.00,0.00,0.50), # A (1.00,1.00,0.00,0.00,0.25), # B (0.00,1.00,1.00,0.25,0.50), # C (0.00,1.00,0.00,0.25,0.25), # D (0.00,0.00,1.00,0.50,0.50), # E (0.00,0.00,0.00,0.50,0.25), # F (1.00,0.00,1.00,0.75,0.50), # G (1.00,0.00,0.00,0.75,0.25), # H (1.00,1.00,1.00,1.00,0.50), # I (1.00,1.00,0.00,1.00,0.25), # J (0.00,1.00,1.00,0.50,0.75), # K (1.00,1.00,1.00,0.75,0.75), # L (0.00,1.00,0.00,0.50,0.00), # M (1.00,1.00,0.00,0.75,0.00) # N ] self.triSrc=[ # # Faces (QUAD/TRIPAIR) # using RHR vertex ordering for # correct face surface normals # # front: EFHG/EFH+HGE # rear: CABD/CAB+BDC # left: CDFE/CDF+FEC # right: GHJI/GHJ+JIG # upper: KEGL/KEG+GLK # lower: FMNH/FMN+NHF # "EFH","HGE", "CAB","BDC", "CDF","FEC", "GHJ","JIG", "KEG","GLK", "FMN","NHF" ] # # setup cube # # one cube node will be generated per non-air block # since different block id's potentially refer to # different textures and thus must be separate nodes # of the scene graph. # # 1. vertices self.cubeVtx=GeomVertexData('blockCube',GeomVertexFormat.getV3t2(),Geom.UHStatic) self.cubeVtx.setNumRows(len(self.cubeVtxSrc)) vtxW=GeomVertexWriter(self.cubeVtx,'vertex') txcW=GeomVertexWriter(self.cubeVtx,'texcoord') for vertex in self.cubeVtxSrc: vtxW.addData3f(*vertex[0:3]) txcW.addData2f(*vertex[3:5]) # 2. mesh self.cubeMesh=GeomTriangles(Geom.UHStatic) for tri in self.triSrc: for triV in tri: triVtxId=ord(triV)-65 # changea 'A'-'N' to 0-13 self.cubeMesh.addVertex(triVtxId) self.cubeMesh.close_primitive() # 3. geometry (primitive+vertex pair) self.cubeGeom=Geom(self.cubeVtx) self.cubeGeom.addPrimitive(self.cubeMesh)
class MeshGenerator(): def __init__(self, name = 'Mesh'): self.name = name self.finished = False self.format = GeomVertexFormat.getV3c4t2() #print self.format self.vertexData = GeomVertexData(name, self.format, Geom.UHStatic) self.vertexData.setNumRows(26136) self.mesh = Geom(self.vertexData) self.triangles = GeomTriangles(Geom.UHStatic) self.triangleData = self.triangles.modifyVertices() self.triangleData.setNumRows(26136) self.vertex = GeomVertexWriter(self.vertexData, 'vertex') self.normal = GeomVertexWriter(self.vertexData, 'normal') self.color = GeomVertexWriter(self.vertexData, 'color') self.texcoord = GeomVertexWriter(self.vertexData, 'texcoord') self.faceCount = 0 def makeFace(self, x1, y1, z1, x2, y2, z2, id, color): if x1 != x2: self.vertex.addData3f(x1, y1, z1) self.vertex.addData3f(x2, y1, z1) self.vertex.addData3f(x2, y2, z2) self.vertex.addData3f(x1, y2, z2) else: self.vertex.addData3f(x1, y1, z1) self.vertex.addData3f(x2, y2, z1) self.vertex.addData3f(x2, y2, z2) self.vertex.addData3f(x1, y1, z2) self.color.addData4f(color, color, color, 1.0) self.color.addData4f(color, color, color, 1.0) self.color.addData4f(color, color, color, 1.0) self.color.addData4f(color, color, color, 1.0) if id == 1: self.texcoord.addData2f(0.0, 0.5) self.texcoord.addData2f(0.0, 0.0) self.texcoord.addData2f(0.25, 0.0) self.texcoord.addData2f(0.25, 0.5) elif id == 2: self.texcoord.addData2f(0.25, 0.5) self.texcoord.addData2f(0.25, 0.0) self.texcoord.addData2f(0.5, 0.0) self.texcoord.addData2f(0.5, 0.5) elif id == 3: self.texcoord.addData2f(0.5, 0.5) self.texcoord.addData2f(0.5, 0.0) self.texcoord.addData2f(0.75, 0.0) self.texcoord.addData2f(0.75, 0.5) elif id == 4: self.texcoord.addData2f(0.75, 0.5) self.texcoord.addData2f(0.75, 0.0) self.texcoord.addData2f(1.0, 0.0) self.texcoord.addData2f(1.0, 0.5) elif id == 5: self.texcoord.addData2f(0.0, 1.0) self.texcoord.addData2f(0.0, 0.5) self.texcoord.addData2f(0.25, 0.5) self.texcoord.addData2f(0.25, 1.0) elif id == 6: self.texcoord.addData2f(0.25, 1.0) self.texcoord.addData2f(0.25, 0.5) self.texcoord.addData2f(0.5, 0.5) self.texcoord.addData2f(0.5, 1.0) vertexId = self.faceCount * 4 self.triangles.addVertices(vertexId, vertexId + 1, vertexId + 3) self.triangles.addVertices(vertexId + 1, vertexId + 2, vertexId + 3) self.faceCount += 1 def makeFrontFace(self, x, y, z, id): self.makeFace(x + 1, y + 1, z - 1, x, y + 1, z, id, 0.6) def makeBackFace(self, x, y, z, id): self.makeFace(x, y, z - 1, x + 1, y, z, id, 0.85) def makeRightFace(self, x, y, z, id): self.makeFace(x + 1, y, z - 1, x + 1, y + 1, z, id, 1.0) def makeLeftFace(self, x, y, z, id): self.makeFace(x, y + 1, z - 1, x, y, z, id, 0.9) def makeTopFace(self, x, y, z, id): self.makeFace(x + 1, y + 1, z, x, y, z, id, 1.0) def makeBottomFace(self, x, y, z, id): self.makeFace(x, y + 1, z - 1, x + 1, y, z - 1, id, 0.70) def getMesh(self): return self.mesh def getGeomNode(self): if self.finished == False: self.triangles.closePrimitive() self.mesh.addPrimitive(self.triangles) self.finished = True geomNode = GeomNode(self.name) geomNode.addGeom(self.mesh) return geomNode
def create_mesh(parentnp, debug=False, invert=False): """This creates a simple 17x17 grid mesh for the sides of our cube. The ultimate goal is to use a LOD system, probably based on quadtrees. If debug is true then we get a color gradiant on our vertexes.""" x = -1.0 y = -1.0 vertex_count = 0 u = 0.0 v = 0.0 WIDTH_STEP = 2 / 16.0 while y <= 1.0: while x <= 1.0: vertex.addData3f(x, y, 0) if invert: normal.addData3f(myNormalize((Vec3(2 * x + 1, 2 * y + 1, 2 * 0 - 1)))) else: normal.addData3f(myNormalize((Vec3(2 * x - 1, 2 * y - 1, 2 * 0 - 1)))) if debug: color.addData4f(1.0, u, v, 1.0) texcoord.addData2f(u, v) vertex_count += 1 x += WIDTH_STEP u += WIDTH_STEP / 2.0 x = -1.0 u = 0 y += WIDTH_STEP v += WIDTH_STEP / 2.0 print vertex_count triangles = [] for y in range(0, 16): for x in range(0, 16): v = 17 * y + x tri = GeomTriangles(Geom.UHDynamic) tri.addVertex(v) tri.addVertex(v + 1) tri.addVertex(v + 17) tri.closePrimitive() triangles.append(tri) tri = GeomTriangles(Geom.UHDynamic) tri.addVertex(v + 1) tri.addVertex(v + 18) tri.addVertex(v + 17) tri.closePrimitive() triangles.append(tri) mesh = Geom(vdata) for t in triangles: mesh.addPrimitive(t) mnode = GeomNode("quadface") mnode.addGeom(mesh) nodePath = parentnp.attachNewNode(mnode) return nodePath
def make_square(sq_color): # sq_color is a list of tuples, describing each vertex: # (r, g, b, a) for [bl, br, tr, tl] x1 = -1 y1 = -1 z1 = -1 x2 = 1 y2 = -1 z2 = 1 v_format = GeomVertexFormat.getV3n3cpt2() v_data = GeomVertexData('square', v_format, Geom.UHDynamic) vertex = GeomVertexWriter(v_data, 'vertex') normal = GeomVertexWriter(v_data, 'normal') color = GeomVertexWriter(v_data, 'color') tex_coord = GeomVertexWriter(v_data, 'texcoord') # make sure we draw the sqaure in the right plane if x1 != x2: vertex.addData3(x1, y1, z1) vertex.addData3(x2, y1, z1) vertex.addData3(x2, y2, z2) vertex.addData3(x1, y2, z2) normal.addData3(normalized(2 * x1 - 1, 2 * y1 - 1, 2 * z1 - 1)) normal.addData3(normalized(2 * x2 - 1, 2 * y1 - 1, 2 * z1 - 1)) normal.addData3(normalized(2 * x2 - 1, 2 * y2 - 1, 2 * z2 - 1)) normal.addData3(normalized(2 * x1 - 1, 2 * y2 - 1, 2 * z2 - 1)) else: vertex.addData3(x1, y1, z1) vertex.addData3(x2, y2, z1) vertex.addData3(x2, y2, z2) vertex.addData3(x1, y1, z2) normal.addData3(normalized(2 * x1 - 1, 2 * y1 - 1, 2 * z1 - 1)) normal.addData3(normalized(2 * x2 - 1, 2 * y2 - 1, 2 * z1 - 1)) normal.addData3(normalized(2 * x2 - 1, 2 * y2 - 1, 2 * z2 - 1)) normal.addData3(normalized(2 * x1 - 1, 2 * y1 - 1, 2 * z2 - 1)) # adding different colors to the vertex for visibility # color.addData4f(1.0, 0.0, 0.0, 1.0) # color.addData4f(0.0, 1.0, 0.0, 1.0) # color.addData4f(0.0, 0.0, 1.0, 1.0) # color.addData4f(1.0, 0.0, 1.0, 1.0) color.addData4f(sq_color[0]) # (0, 0) bottom left color.addData4f(sq_color[1]) # (0.5, 0) bottom right color.addData4f(sq_color[2]) # (0.5, 0.5) top right color.addData4f(sq_color[3]) # (0, 0.5) top left tex_coord.addData2f(0.0, 1.0) tex_coord.addData2f(0.0, 0.0) tex_coord.addData2f(1.0, 0.0) tex_coord.addData2f(1.0, 1.0) # Quads aren't directly supported by the Geom interface # you might be interested in the CardMaker class if you are # interested in rectangle though tris = GeomTriangles(Geom.UHDynamic) tris.addVertices(0, 1, 3) tris.addVertices(1, 2, 3) square = Geom(v_data) square.addPrimitive(tris) return square
def createModelClone(self,modelFilename): newVisualCar = loader.loadModel(modelFilename) geomNodeCollection = newVisualCar.findAllMatches('**/+GeomNode') simpleTris=[] self.unmodifiedVertexData=[] for nodePath in geomNodeCollection: geomNode = nodePath.node() for i in range(geomNode.getNumGeoms()): geom = geomNode.getGeom(i) vdata = geom.getVertexData() vertex = GeomVertexReader(vdata, 'vertex') while not vertex.isAtEnd(): v=vertex.getData3f() vertexModelX,vertexModelY,vertexModelZ=v self.unmodifiedVertexData.append([vertexModelX,vertexModelY,vertexModelZ]) for primitiveIndex in range(geom.getNumPrimitives()): prim=geom.getPrimitive(primitiveIndex) prim=prim.decompose() for p in range(prim.getNumPrimitives()): s = prim.getPrimitiveStart(p) e = prim.getPrimitiveEnd(p) singleTriData=[] for i in range(s, e): vertex.setRow(prim.getVertex(s)) vi = prim.getVertex(i) singleTriData.append(vi) simpleTris.append(singleTriData) simpleVertices=self.unmodifiedVertexData format=GeomVertexFormat.getV3() vdata=GeomVertexData('shadow', format, Geom.UHDynamic) self.pandaVertexData=vdata vertex=GeomVertexWriter(vdata, 'vertex') for vertexIndex in range(len(simpleVertices)): simpleVertex=simpleVertices[vertexIndex] vertex.addData3f(0,0,0) tris=GeomTriangles(Geom.UHStatic) for index in range(len(simpleTris)): simpleTri=simpleTris[index] tris.addVertex(simpleTri[0]) tris.addVertex(simpleTri[1]) tris.addVertex(simpleTri[2]) tris.closePrimitive() shadow=Geom(vdata) shadow.addPrimitive(tris) snode=GeomNode('shadow') snode.addGeom(shadow) self.snode=snode
def createPlane(width,height): format=GeomVertexFormat.getV3() vdata=GeomVertexData("vertices", format, Geom.UHStatic) vertexWriter=GeomVertexWriter(vdata, "vertex") vertexWriter.addData3f(0,0,0) vertexWriter.addData3f(width,0,0) vertexWriter.addData3f(width,height,0) vertexWriter.addData3f(0,height,0) #step 2) make primitives and assign vertices to them tris=GeomTriangles(Geom.UHStatic) #have to add vertices one by one since they are not in order tris.addVertex(0) tris.addVertex(1) tris.addVertex(3) #indicates that we have finished adding vertices for the first triangle. tris.closePrimitive() #since the coordinates are in order we can use this convenience function. tris.addConsecutiveVertices(1,3) #add vertex 1, 2 and 3 tris.closePrimitive() #step 3) make a Geom object to hold the primitives squareGeom=Geom(vdata) squareGeom.addPrimitive(tris) #now put squareGeom in a GeomNode. You can now position your geometry in the scene graph. squareGN=GeomNode("square") squareGN.addGeom(squareGeom) terrainNode = NodePath("terrNode") terrainNode.reparentTo(render) terrainNode.attachNewNode(squareGN) terrainNode.setX(-width/2) texGrass = loader.loadTexture("textures/envir-ground.jpg") terrainNode.setTexture(texGrass)
def create_geom(self, sidelength): # Set up the vertex arrays vformat = GeomVertexFormat.getV3n3c4() vdata = GeomVertexData("Data", vformat, Geom.UHDynamic) vertex = GeomVertexWriter(vdata, 'vertex') normal = GeomVertexWriter(vdata, 'normal') color = GeomVertexWriter(vdata, 'color') geom = Geom(vdata) # Write vertex data for x in range(0, sidelength): for y in range(0, sidelength): # vertex_number = x * sidelength + y v_x, v_y, v_z = self.map_b[(x, y)] n_x, n_y, n_z = 0.0, 0.0, 1.0 c_r, c_g, c_b, c_a = 0.5, 0.5, 0.5, 0.5 vertex.addData3f(v_x, v_y, v_z) normal.addData3f(n_x, n_y, n_z) color.addData4f(c_r, c_g, c_b, c_a) # Add triangles for x in range(0, sidelength - 1): for y in range(0, sidelength - 1): # The vertex arrangement (y up, x right) # 2 3 # 0 1 v_0 = x * sidelength + y v_1 = x * sidelength + (y + 1) v_2 = (x + 1) * sidelength + y v_3 = (x + 1) * sidelength + (y + 1) if (x+y)%1 == 0: # An even square tris = GeomTriangles(Geom.UHStatic) tris.addVertices(v_0, v_2, v_3) tris.closePrimitive() geom.addPrimitive(tris) tris = GeomTriangles(Geom.UHStatic) tris.addVertices(v_3, v_1, v_0) tris.closePrimitive() geom.addPrimitive(tris) else: # An odd square tris = GeomTriangles(Geom.UHStatic) tris.addVertices(v_1, v_0, v_2) tris.closePrimitive() geom.addPrimitive(tris) tris = GeomTriangles(Geom.UHStatic) tris.addVertices(v_2, v_3, v_1) tris.closePrimitive() geom.addPrimitive(tris) # Create the actual node node = GeomNode('geom_node') node.addGeom(geom) # Remember GeomVertexWriters to adjust vertex data later #self.vertex_writer = vertex #self.color_writer = color self.vdata = vdata return node