def make_node_from_mesh(points: np.ndarray, faces: np.ndarray, normals: np.ndarray, rgba: np.ndarray = np.asarray([1, 1, 1, 1])): vertex_normal_format = GeomVertexFormat.get_v3n3c4() v_data = GeomVertexData('sphere', vertex_normal_format, Geom.UHStatic) num_rows = np.max([points.shape[0], faces.shape[0]]) v_data.setNumRows(int(num_rows)) vertex_data = GeomVertexWriter(v_data, 'vertex') normal_data = GeomVertexWriter(v_data, 'normal') color_data = GeomVertexWriter(v_data, 'color') for point, normal in zip(points, normals): vertex_data.addData3(point[0], point[1], point[2]) normal_data.addData3(normal[0], normal[1], normal[2]) color_data.addData4(rgba[0], rgba[1], rgba[2], rgba[3]) geom = Geom(v_data) for face in faces: tri = GeomTriangles(Geom.UHStatic) p_1 = points[face[0], :] p_2 = points[face[1], :] p_3 = points[face[2], :] norm = normals[face[0], :] if np.dot(np.cross(p_2 - p_1, p_3 - p_2), norm) < 0: tri.add_vertices(face[2], face[1], face[0]) else: tri.add_vertices(face[0], face[1], face[2]) geom.addPrimitive(tri) node = GeomNode('gnode') node.addGeom(geom) return node
def makeSimpleGeomBuffer(array, color, geomType=GeomPoints): """ massively faster than the nonbuffer version """ full = [tuple(d) for d in np.hstack((array,color))] fmt = GeomVertexFormat.getV3c4() vertexData = GeomVertexData('points', fmt, Geom.UHDynamic) #FIXME use the index for these too? with setPythonTag, will have to 'reserve' some cloudGeom = Geom(vertexData) cloudNode = GeomNode('just some points') vertexData.setNumRows(len(array)) mem_array = vertexData.modifyArray(0) view = memoryview(mem_array) arr = np.asarray(view) arr[:] = full points = geomType(Geom.UHDynamic) points.addConsecutiveVertices(0,len(array)) points.closePrimitive() cloudGeom.addPrimitive(points) cloudNode.addGeom(cloudGeom) return cloudNode
def _CreateOneSynapse(self, presynCell, synapsesType): presynCell.setPresynapticFocus() # highlight presynaptic cells form = GeomVertexFormat.getV3() vdata = GeomVertexData("SynapseLine", form, Geom.UHStatic) vdata.setNumRows(1) vertex = GeomVertexWriter(vdata, "vertex") vertex.addData3f(presynCell.getNode().getPos(self._node)) vertex.addData3f(0, 0, 0) prim = GeomLines(Geom.UHStatic) prim.addVertices(0, 1) geom = Geom(vdata) geom.addPrimitive(prim) node = GeomNode("Synapse_" + str(synapsesType)) node.addGeom(geom) nodePath = self._node.attachNewNode(node) nodePath.setRenderModeThickness(2) # color of the line if presynCell.active: nodePath.setColor(COL_DISTAL_SYNAPSES_ACTIVE) else: nodePath.setColor(COL_DISTAL_SYNAPSES_INACTIVE)
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 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
class PointMaker(): def __init__(self, name): self.name = name self.new() def new(self): self.point = 0 self.vdata = GeomVertexData( self.name, GeomVertexFormat.get_v3c4(), Geom.UHStatic) self.vdata.set_num_rows(2) self.vertex = GeomVertexWriter(self.vdata, 'vertex') self.color = GeomVertexWriter(self.vdata, 'color') self.prim = GeomPoints(Geom.UHStatic) def add(self, pos=(0,0,0), color=(1,1,1,1)): self.vertex.add_data3(pos[0],pos[1],pos[2]+0.02) self.color.add_data4(color) self.prim.add_vertex(self.point) self.point += 1 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 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 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 make_axes(): """Make an axes geometry. Returns: Geom -- p3d geometry """ vformat = GeomVertexFormat.get_v3c4() vdata = GeomVertexData('vdata', vformat, Geom.UHStatic) vdata.uncleanSetNumRows(6) vertex = GeomVertexWriter(vdata, 'vertex') color = GeomVertexWriter(vdata, 'color') for x, y, z in np.eye(3): vertex.addData3(0, 0, 0) color.addData4(x, y, z, 1) vertex.addData3(x, y, z) color.addData4(x, y, z, 1) prim = GeomLines(Geom.UHStatic) prim.addNextVertices(6) geom = Geom(vdata) geom.addPrimitive(prim) return geom
def __init__(self, name, format = GeomVertexFormat.getV3()): self.views = [] self.vertexBuffer = GeomVertexData(name + "-vdata", format, GeomEnums.UHDynamic) self.np = NodePath(name) self.np.node().setBounds(OmniBoundingVolume()) self.np.node().setFinal(1)
def _CreateOneSynapse(self, presynCell, synapsesType): form = GeomVertexFormat.getV3() vdata = GeomVertexData("SynapseLine", form, Geom.UHStatic) vdata.setNumRows(1) vertex = GeomVertexWriter(vdata, "vertex") vertex.addData3f(presynCell.getNode().getPos(self.__node)) vertex.addData3f(0, 0, 0) # vertex.addData3f(self.__node.getPos()) # printLog("inputObj:"+str(i)+"bits:"+str(y)) # printLog(inputObj[i].inputBits[y].getNode().getPos(self.__node)) prim = GeomLines(Geom.UHStatic) prim.addVertices(0, 1) geom = Geom(vdata) geom.addPrimitive(prim) node = GeomNode("Synapse_" + str(synapsesType)) node.addGeom(geom) nodePath = self.__cellsNodePath.attachNewNode(node) nodePath.setRenderModeThickness(2) # color of the line if presynCell.active: nodePath.setColor(COL_PROXIMAL_SYNAPSES_ACTIVE) else: nodePath.setColor(COL_PROXIMAL_SYNAPSES_INACTIVE)
def make_grid(num_ticks=10, step=1.0): """Make a grid geometry. Keyword Arguments: step {float} -- step in meters (default: {1.0}) num_ticks {int} -- ticks number per axis (default: {5}) Returns: Geom -- p3d geometry """ ticks = np.arange(-num_ticks // 2, num_ticks // 2 + 1) * step vformat = GeomVertexFormat.get_v3() vdata = GeomVertexData('vdata', vformat, Geom.UHStatic) vdata.uncleanSetNumRows(len(ticks) * 4) vertex = GeomVertexWriter(vdata, 'vertex') for t in ticks: vertex.addData3(t, ticks[0], 0) vertex.addData3(t, ticks[-1], 0) vertex.addData3(ticks[0], t, 0) vertex.addData3(ticks[-1], t, 0) prim = GeomLines(Geom.UHStatic) prim.addNextVertices(len(ticks) * 4) geom = Geom(vdata) geom.addPrimitive(prim) return geom
def _create_geom(self): color = ConfigVariableColor('grid-color', DEFAULT_GRID_COLOR) radius = floor(self.size / (2 * self.spacing)) diameter = (2 * radius + 1) start = -radius * self.spacing vertex_format = GeomVertexFormat.get_v3c4() vertex_data = GeomVertexData('grid', vertex_format, Geom.UH_static) vertex_data.set_num_rows(diameter * 4) vertex_writer = GeomVertexWriter(vertex_data, 'vertex') color_writer = GeomVertexWriter(vertex_data, 'color') for i, j in product(range(diameter), repeat=2): vertex_writer.add_data3f(start + i * self.spacing, start + j * self.spacing, 0.0) alpha = GRID_ALPHA - GRID_ALPHA * ( Vector(i - radius, j - radius).norm() / radius) color_writer.add_data4f(color[0], color[1], color[2], alpha) primitive = GeomLinestrips(Geom.UH_static) for vertex in vertex_indexes(diameter): primitive.add_vertex(vertex) primitive.close_primitive() self.geom = Geom(vertex_data) self.geom.add_primitive(primitive)
def makeGeom(self, points, colors, sizes): #format = GeomVertexFormat.getV3c4() array = GeomVertexArrayFormat() array.addColumn(InternalName.get_vertex(), 3, Geom.NTFloat32, Geom.CPoint) array.addColumn(InternalName.get_color(), 4, Geom.NTFloat32, Geom.CColor) array.addColumn(InternalName.get_size(), 1, Geom.NTFloat32, Geom.COther) format = GeomVertexFormat() format.addArray(array) format = GeomVertexFormat.registerFormat(format) vdata = GeomVertexData('vdata', format, Geom.UH_static) vdata.unclean_set_num_rows(len(points)) self.vwriter = GeomVertexWriter(vdata, InternalName.get_vertex()) self.colorwriter = GeomVertexWriter(vdata, InternalName.get_color()) self.sizewriter = GeomVertexWriter(vdata, InternalName.get_size()) geompoints = GeomPoints(Geom.UH_static) geompoints.reserve_num_vertices(len(points)) index = 0 for (point, color, size) in zip(points, colors, sizes): self.vwriter.addData3f(*point) self.colorwriter.addData4f(*color) self.sizewriter.addData1f(size) geompoints.addVertex(index) #geompoints.closePrimitive() index += 1 geom = Geom(vdata) geom.addPrimitive(geompoints) return geom
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 createColoredUnitDisk(color_vec4=Vec4(0., 0., 1., 1.), num_of_verts=10, origin_point=Vec3(0., 0., 0.), radius=1.): # Own Geometry # format = GeomVertexFormat.getV3c4t2() format = GeomVertexFormat.getV3c4() vdata = GeomVertexData("colored_circle", format, Geom.UHStatic) vdata.setNumRows(4) vertexPosWriter = GeomVertexWriter(vdata, "vertex") # num_of_verts = 10 # phi = 0. r = radius # origin_point_x = 0. # origin_point_z = 0. vertexPosWriter.addData3f(origin_point[0], origin_point[1], origin_point[2]) circle_points = math_utils.get_circle_vertices(num_of_verts=num_of_verts, radius=r) circle_points[:,0] += origin_point[0] circle_points[:,1] += origin_point[1] circle_points[:,2] += origin_point[2] _normal_vector_info = Vec3(0., 1., 0.) # this is returned just as info about the normal vector of the generated geometry for p in circle_points: vertexPosWriter.addData3f(p[0], 0, p[1]) # for i in range(num_of_verts): # phi += 2. * np.pi / num_of_verts # x = r * np.cos(phi) # z = r * np.sin(phi) # vertexPosWriter.addData3f(x, 0, z) # let's also add color to each vertex colorWriter = GeomVertexWriter(vdata, "color") colorWriter.addData4f(color_vec4) # origin point for i in range(num_of_verts): 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 = GeomTrifans(Geom.UHStatic) # the first vertex is a vertex that all triangles share tris.add_consecutive_vertices(0, num_of_verts+1) tris.addVertex(1) tris.closePrimitive() # the 1st primitive is finished # make a Geom object to hold the primitives geom = Geom(vdata) geom.addPrimitive(tris) geom_node = GeomNode("colored_circle_node") geom_node.addGeom(geom) return geom_node, _normal_vector_info
def draw_rain_mesh(self): _format = GeomVertexFormat.get_v3cp() self.rain_vdata = GeomVertexData('rain', _format, Geom.UHDynamic) self.rain_vdata.setNumRows(self.n_points**2) vertex = GeomVertexWriter(self.rain_vdata, 'vertex') color = GeomVertexWriter(self.rain_vdata, 'color') for j in range(self.n_points): for i in range(self.n_points): # Rain Vertices vertex.addData3f(self.x[j][i], self.y[j][i], self.n_points) # Rain Colors color.addData4f(0.3, 0.3, 1, 0) # Rain Primitive prim = GeomPoints(Geom.UHDynamic) for j in range(self.n_points): for i in range(self.n_points): prim.add_vertices(j * (self.n_points) + i, j * (self.n_points) + i, j * (self.n_points) + i) geom = Geom(self.rain_vdata) prim.closePrimitive() geom.addPrimitive(prim) node = GeomNode('gnode') node.addGeom(geom) rain_nodePath = render.attachNewNode(node) rain_nodePath.setTransparency(TransparencyAttrib.MAlpha) rain_nodePath.setAntialias(AntialiasAttrib.MAuto) rain_nodePath.setRenderModeThickness(2) rain_nodePath.setPos(-50, -50, 0)
def makeSimpleGeomBuffer(array, color, geomType=GeomPoints): """ massively faster than the nonbuffer version """ full = [tuple(d) for d in np.hstack((array, color))] fmt = GeomVertexFormat.getV3c4() vertexData = GeomVertexData( 'points', fmt, Geom.UHDynamic ) #FIXME use the index for these too? with setPythonTag, will have to 'reserve' some cloudGeom = Geom(vertexData) cloudNode = GeomNode('just some points') vertexData.setNumRows(len(array)) mem_array = vertexData.modifyArray(0) view = memoryview(mem_array) arr = np.asarray(view) arr[:] = full points = geomType(Geom.UHDynamic) points.addConsecutiveVertices(0, len(array)) points.closePrimitive() cloudGeom.addPrimitive(points) cloudNode.addGeom(cloudGeom) return cloudNode
def _get_geom_vertex_data(cls, layer: Layer, nozzle_diam: float, height: float, name: str) -> GeomVertexData: """Generate GeomVertexData for the provided Layer. Parameters ---------- layer : Layer Layer for which the data should be generated and written. nozzle_diam : float Nozzle diameter. height : float Layer height, thickness. name : str Name for generated GeomVertexData Returns ------- GeomVertexData Generated GeomVertexData. """ geom_vertex_count = sum([len(path) * 4 for path in layer.paths]) geom_data = GeomVertexData(name, cls._GEOM_VERTEX_FORMAT, Geom.UHStatic) geom_data.setNumRows(geom_vertex_count) cls._write_geom_data(geom_data=geom_data, layer=layer, width=nozzle_diam, height=height) return geom_data
def create_GeomNode_Single_Point(color_vec4=Vec4(1., 1., 1., 1.)): # ---- step 1: create point at (0,0,0) and close the primitive format = GeomVertexFormat.getV3c4() vdata = GeomVertexData("colored_point", format, Geom.UHStatic) vdata.setNumRows(4) # add color to each vertex colorWriter = GeomVertexWriter(vdata, "color") # add a vertex position to each vertex vertexPosWriter = GeomVertexWriter(vdata, "vertex") # just one origin point vertex, it gets transformed later # to it's intended position vertexPosWriter.addData3f(0., 0., 0.) colorWriter.addData4f(color_vec4) # build the primitive pointsprimitive = GeomPoints(Geom.UHStatic) pointsprimitive.addVertex(0) pointsprimitive.closePrimitive() # this resets all the data contained in the vertexPosWriter and colorWriter # ----- step 3: make a GeomNode out of the Geom (to which the Primitives have been added) # make a Geom object to hold the primitives geom = Geom(vdata) geom.addPrimitive(pointsprimitive) geom_node = GeomNode("colored_point_node") geom_node.addGeom(geom) return geom_node
def _get_geom_data_plate(build_plate_size: LVector2d, name: str = "") -> GeomVertexData: """Generate build plate GeomVertexData. Parameters ---------- build_plate_size : LVector2d Build plate size. name : str Name for the generated GeomVertexData. """ # noinspection PyArgumentList geom_data = GeomVertexData(name, GeomVertexFormat.get_v3t2(), Geom.UHStatic) geom_data.setNumRows(4) writer_vertex = GeomVertexWriter(geom_data, "vertex") writer_texture = GeomVertexWriter(geom_data, "texcoord") # Add build plate vertices writer_vertex.addData3d(0, 0, 0) writer_vertex.addData3d(build_plate_size.x, 0, 0) writer_vertex.addData3d(build_plate_size.x, build_plate_size.y, 0) writer_vertex.addData3d(0, build_plate_size.y, 0) for uv in [(0, 0), (1, 0), (1, 1), (0, 1)]: writer_texture.addData2(*uv) return geom_data
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 pandageom_from_vfnf(vertices, face_normals, triangles, name='auto'): """ :param vertices: nx3 nparray, each row is vertex :param face_normals: nx3 nparray, each row is the normal of a face :param triangles: nx3 nparray, each row is three idx to the vertices :param name: :return: a geom model that is ready to be used to define a nodepath author: weiwei date: 20160613, 20210109 """ # expand vertices to let each triangle refer to a different vert+normal # vertices and normals vertformat = GeomVertexFormat.getV3n3() vertexdata = GeomVertexData(name, vertformat, Geom.UHStatic) vertids = triangles.flatten() multiplied_verticies = np.empty((len(vertids), 3), dtype=np.float32) multiplied_verticies[:] = vertices[vertids] vertex_normals = np.repeat(face_normals.astype(np.float32), repeats=3, axis=0) npstr = np.hstack((multiplied_verticies, vertex_normals)).tobytes() vertexdata.modifyArrayHandle(0).setData(npstr) # triangles primitive = GeomTriangles(Geom.UHStatic) primitive.setIndexType(GeomEnums.NTUint32) multiplied_triangles = np.arange(len(vertids), dtype=np.uint32).reshape(-1, 3) primitive.modifyVertices(-1).modifyHandle().setData( multiplied_triangles.tobytes()) # make geom geom = Geom(vertexdata) geom.addPrimitive(primitive) return geom
def __init__(self, vertices, normals, colours, tetrahedra): super().__init__() self.n_vertices = len(vertices) self.n_tetrahedra = len(tetrahedra) self.data = GeomVertexData(repr(self), format4, Geom.UHDynamic) self.data.setNumRows(self.n_vertices) self.prim = GeomLinesAdjacency(Geom.UHDynamic) vertex_writer = GeomVertexWriter(self.data, "vertex") normal_writer = GeomVertexWriter(self.data, "normal") colour_writer = GeomVertexWriter(self.data, "colour") for vertex in vertices: vertex_writer.addData4(*vertex) for normal in normals: normal_writer.addData4(*normal) for colour in colours: colour_writer.addData4(*colour) for tetra in tetrahedra: self.prim.addVertices(*tetra) self.prim.closePrimitive() self.geom = Geom(self.data) self.geom.addPrimitive(self.prim) self.node = GeomNode(repr(self)) self.node.addGeom(self.geom)
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 new(self): self.point = 0 self.vdata = GeomVertexData( self.name, GeomVertexFormat.get_v3c4(), Geom.UHStatic) self.vdata.set_num_rows(2) self.vertex = GeomVertexWriter(self.vdata, 'vertex') self.color = GeomVertexWriter(self.vdata, 'color') self.prim = GeomPoints(Geom.UHStatic)
def empty_geom(prefix, nb_data, nb_vertices, points=False, normal=True, texture=True, color=False, tanbin=False): array = GeomVertexArrayFormat() array.addColumn(InternalName.make('vertex'), 3, Geom.NTFloat32, Geom.CPoint) if color: array.addColumn(InternalName.make('color'), 4, Geom.NTFloat32, Geom.CColor) if texture: array.addColumn(InternalName.make('texcoord'), 2, Geom.NTFloat32, Geom.CTexcoord) if normal: array.addColumn(InternalName.make('normal'), 3, Geom.NTFloat32, Geom.CVector) if tanbin: array.addColumn(InternalName.make('binormal'), 3, Geom.NTFloat32, Geom.CVector) array.addColumn(InternalName.make('tangent'), 3, Geom.NTFloat32, Geom.CVector) format = GeomVertexFormat() format.addArray(array) format = GeomVertexFormat.registerFormat(format) gvd = GeomVertexData('gvd', format, Geom.UHStatic) if nb_data != 0: gvd.unclean_set_num_rows(nb_data) geom = Geom(gvd) gvw = GeomVertexWriter(gvd, 'vertex') if color: gcw = GeomVertexWriter(gvd, 'color') else: gcw = None if texture: gtw = GeomVertexWriter(gvd, 'texcoord') else: gtw = None if normal: gnw = GeomVertexWriter(gvd, 'normal') else: gnw = None if tanbin: gtanw = GeomVertexWriter(gvd, 'tangent') gbiw = GeomVertexWriter(gvd, 'binormal') else: gtanw = None gbiw = None if points: prim = GeomPoints(Geom.UHStatic) else: prim = GeomTriangles(Geom.UHStatic) if nb_vertices != 0: prim.reserve_num_vertices(nb_vertices) return (gvw, gcw, gtw, gnw, gtanw, gbiw, prim, geom)
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 __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, size, translation, rotation, color, text): self._visible = False wy, wx, wz = size[0], size[1], size[2] format = GeomVertexFormat.getV3c4() vdata = GeomVertexData('cu_points', format, Geom.UHStatic) vdata.setNumRows(8) self._pos_writer = GeomVertexWriter(vdata, 'vertex') self._color_writer = GeomVertexWriter(vdata, 'color') self._pos_writer.set_row(0) self._color_writer.set_row(0) self._pos_writer.addData3f(-0.5 * wx, -0.5 * wy, 0.) self._pos_writer.addData3f(-0.5 * wx, -0.5 * wy, wz) self._pos_writer.addData3f(0.5 * wx, -0.5 * wy, wz) self._pos_writer.addData3f(0.5 * wx, -0.5 * wy, 0.) self._pos_writer.addData3f(-0.5 * wx, 0.5 * wy, 0.) self._pos_writer.addData3f(-0.5 * wx, 0.5 * wy, wz) self._pos_writer.addData3f(0.5 * wx, 0.5 * wy, wz) self._pos_writer.addData3f(0.5 * wx, 0.5 * wy, 0.) for i in range(8): self._color_writer.addData4f(color[0], color[1], color[2], color[3]) lines = GeomLines(Geom.UHStatic) lines.addVertices(0, 1) lines.addVertices(1, 2) lines.addVertices(2, 3) lines.addVertices(3, 0) lines.addVertices(4, 5) lines.addVertices(5, 6) lines.addVertices(6, 7) lines.addVertices(7, 4) lines.addVertices(0, 4) lines.addVertices(1, 5) lines.addVertices(2, 6) lines.addVertices(3, 7) cuboid = Geom(vdata) cuboid.addPrimitive(lines) node = GeomNode('cuboid') node.addGeom(cuboid) self._node_path = NodePath(node) # self.title = OnscreenText(text=text, style=1, fg=(1, 1, 1, 1), pos=(-0.1, 0.1), scale=.05, # parent=self._node_path, align=TextNode.ARight) self._txt_node = TextNode('id') self._txt_node.setText(text) self._txt_node.setTextScale(0.2) self._txt_node.setCardColor(0, 0, 1, 1) self._txt_node.setCardAsMargin(0, 0, 0, 0) self._txt_node.setCardDecal(True) self._txt_node.set_align(2) text_geom = GeomNode('text') text_geom.addChild(self._txt_node) self._txt_np = NodePath(text_geom) self._txt_np.reparentTo(self._node_path) self.show() self.update_values(size, translation, rotation, color, text)
def makeGrid(rng = 1000, spacing = 10): #FIXME make this scale based on zoom??? ctup = (.3,.3,.3,1) xs = range(-rng,rng+1,spacing) ys = xs fmt = GeomVertexFormat.getV3c4() #3 component vertex, w/ 4 comp color #fmt = GeomVertexFormat.getV3() #3 component vertex, w/ 4 comp color vertexData = GeomVertexData('points', fmt, Geom.UHStatic) verts = GeomVertexWriter(vertexData, 'vertex') color = GeomVertexWriter(vertexData, 'color') for i,d in enumerate(xs): switch1 = (-1) ** i * rng switch2 = (-1) ** i * -rng #print(d,switch1,0) verts.addData3f(d, switch1, 0) verts.addData3f(d, switch2, 0) color.addData4f(*ctup) color.addData4f(*ctup) for i,d in enumerate(ys): switch1 = (-1) ** i * rng switch2 = (-1) ** i * -rng verts.addData3f(switch1, d, 0) verts.addData3f(switch2, d, 0) color.addData4f(*ctup) color.addData4f(*ctup) gridLines = GeomLinestrips(Geom.UHStatic) gridLines.addConsecutiveVertices(0, vertexData.getNumRows()) gridLines.closePrimitive() grid = Geom(vertexData) grid.addPrimitive(gridLines) return grid
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 createBox(self): """ Create the skybox GeomNode :return: """ obj = '' obj += "# Skybox\n" obj += 'mtllib skybox.mtl\n' mtl = '# material for skybox\n' fmt = GeomVertexFormat.getV3n3t2() vdata = GeomVertexData('skybox', fmt, Geom.UHStatic) vdata.setNumRows(24) vertex = GeomVertexWriter(vdata, 'vertex') normals = GeomVertexWriter(vdata, 'normal') texcoord = GeomVertexWriter(vdata, 'texcoord') node = GeomNode('skybox') for normal in self.normals: geom = Geom(vdata) prim = GeomTriangles(Geom.UHStatic) idx = vertex.getWriteRow() verts = self.vertMappings[normal] tcs = self.getFaceMapping(normal) for v, t in zip(verts, tcs): vertex.addData3f(v[0]*2, v[1]*2, v[2]*2) normals.addData3f(normal) texcoord.addData2f(t) obj += 'v {0} {1} {2}\n'.format(v[0]*2, v[1]*2, v[2]*2) obj += 'vn {0} {1} {2}\n'.format(*normal) obj += 'vt {0} {1}\n'.format(*t) tex = self.getFaceTexture(normal) prim.addVertices(idx, idx + 1, idx + 3) prim.closePrimitive() obj += "usemtl {0}\n".format(tex.getName()) obj += 'f {0}/{0} {1}/{1} {2}/{2}\n'.format(1+idx, 1+idx+1, 1+idx+3) prim.addVertices(idx + 1, idx + 2, idx + 3) prim.closePrimitive() obj += "usemtl {0}\n".format(tex.getName()) obj += 'f {0}/{0} {1}/{1} {2}/{2}\n'.format(1+idx+1, 1+idx+2, 1+idx+3) geom.addPrimitive(prim) tex.setWrapU(Texture.WMMirror) tex.setWrapV(Texture.WMMirror) node.addGeom(geom, RenderState.make(TextureAttrib.make(tex))) mtl += "newmtl {0}\n".format(tex.getName()) mtl += "Ka 1 1 1\n" mtl += "Kd 1 1 1\n" mtl += "map_Kd {0}\n".format(tex.getFilename().toOsSpecific()) return node
def add_button(self, text, label_id, pos_x, pos_y, width=0.0, hight=0.1): if width == 0.0: for c in range(len(text)/2): width += 0.08 ls = LineSegs("lines") ls.setColor(0,1,0,1) ls.drawTo(-width/2, 0, hight/2) ls.drawTo(width/2, 0, hight/2) ls.drawTo(width/2, 0,-hight/2) ls.drawTo(-width/2, 0,-hight/2) ls.drawTo(-width/2, 0, hight/2) border = ls.create(False) border.setTag('back_ground', '1') array = GeomVertexArrayFormat() array.addColumn("vertex", 4, Geom.NTFloat32, Geom.CPoint) arr_format = GeomVertexFormat() arr_format.addArray(array) arr_format = GeomVertexFormat.registerFormat(arr_format) vdata = GeomVertexData('fill', arr_format, Geom.UHStatic) vdata.setNumRows(4) vertex = GeomVertexWriter(vdata, 'vertex') vertex.addData3f(-width/2, 0, hight/2) vertex.addData3f(width/2, 0, hight/2) vertex.addData3f(-width/2, 0,-hight/2) vertex.addData3f(width/2, 0,-hight/2) prim = GeomTristrips(Geom.UHStatic) prim.addVertex(0) prim.addVertex(1) prim.addVertex(2) prim.addVertex(3) geom = Geom(vdata) geom.addPrimitive(prim) node = GeomNode('gnode') node.addGeom(geom) nodePath = NodePath("button") nodePath.attachNewNode(node) nodePath.setPos(0,0,0) nodePath.setTag('button', '1') nodePath.setBin("unsorted", 0) nodePath.setDepthTest(False) nodePath.setColor(0,0,0,1) nodePath.attachNewNode(border) nodePath1 = NodePath("button") nodePath1.attachNewNode(node) nodePath1.setPos(0,0,0) nodePath1.setTag('button1', '1') nodePath1.setBin("unsorted", 0) nodePath1.setDepthTest(False) nodePath1.setColor(0,1,0,1) nodePath1.attachNewNode(border) button=DirectFrame( enableEdit=1, text=text, geom=nodePath, text_scale=0.05, text_fg=(0,1,0,1), borderWidth=(1,1), relief = None, text_pos=(0,-0.01,0), textMayChange=1, state=DGG.NORMAL, parent=aspect2d ) button.setPos(pos_x,0,pos_y) button.bind(DGG.B1PRESS, button_click, [button]) button.bind(DGG.WITHIN, button_hover, [button]) button.bind(DGG.WITHOUT, button_no_hover, [button]) # button.resetFrameSize() # self.button.bind(DGG.WITHIN, self.onMouseHoverInFunction, [button, some_value1]) defines.ENTITIES[defines.ENTITY_ID] = {'CATEGORY':'button', 'BUTTON':button, 'NODE':nodePath, 'LABEL':label_id,'STATUS': 0} defines.ENTITY_ID += 1
def getVertexData(vertex, vertex_index, normal=None, normal_index=None, texcoordset=(), texcoord_indexset=(), textangentset=(), textangent_indexset=(), texbinormalset=(), texbinormal_indexset=()): format = GeomVertexFormat() formatArray = GeomVertexArrayFormat() indices2stack = [vertex_index.reshape(-1, 1)] alldata = [vertex] formatArray.addColumn(InternalName.make("vertex"), 3, Geom.NTFloat32, Geom.CPoint) if normal is not None: indices2stack.append(normal_index.reshape(-1, 1)) alldata.append(collada.util.normalize_v3(numpy.copy(normal))) formatArray.addColumn(InternalName.make("normal"), 3, Geom.NTFloat32, Geom.CVector) if len(texcoordset) > 0: indices2stack.append(texcoord_indexset[0].reshape(-1, 1)) alldata.append(texcoordset[0]) formatArray.addColumn(InternalName.make("texcoord"), 2, Geom.NTFloat32, Geom.CTexcoord) if len(textangentset) > 0: indices2stack.append(textangent_indexset[0].reshape(-1, 1)) alldata.append(textangentset[0]) formatArray.addColumn(InternalName.make("tangent"), 3, Geom.NTFloat32, Geom.CVector) if len(texbinormalset) > 0: indices2stack.append(texbinormal_indexset[0].reshape(-1, 1)) alldata.append(texbinormalset[0]) formatArray.addColumn(InternalName.make("binormal"), 3, Geom.NTFloat32, Geom.CVector) #have to flatten and reshape like this so that it's contiguous stacked_indices = numpy.hstack(indices2stack).flatten().reshape((-1, len(indices2stack))) #index_map - maps each unique value back to a location in the original array it came from # eg. stacked_indices[index_map] == unique_stacked_indices #inverse_map - maps original array locations to their location in the unique array # e.g. unique_stacked_indices[inverse_map] == stacked_indices unique_stacked_indices, index_map, inverse_map = numpy.unique(stacked_indices.view([('',stacked_indices.dtype)]*stacked_indices.shape[1]), return_index=True, return_inverse=True) unique_stacked_indices = unique_stacked_indices.view(stacked_indices.dtype).reshape(-1,stacked_indices.shape[1]) #unique returns as int64, so cast back index_map = numpy.cast['uint32'](index_map) inverse_map = numpy.cast['uint32'](inverse_map) #sort the index map to get a list of the index of the first time each value was encountered sorted_map = numpy.cast['uint32'](numpy.argsort(index_map)) #since we're sorting the unique values, we have to map the inverse_map to the new index locations backwards_map = numpy.zeros_like(sorted_map) backwards_map[sorted_map] = numpy.arange(len(sorted_map), dtype=numpy.uint32) #now this is the new unique values and their indices unique_stacked_indices = unique_stacked_indices[sorted_map] inverse_map = backwards_map[inverse_map] #combine the unique stacked indices into unique stacked data data2stack = [] for idx, data in enumerate(alldata): data2stack.append(data[unique_stacked_indices[:,idx]]) unique_stacked_data = numpy.hstack(data2stack).flatten() unique_stacked_data.shape = (-1) all_data = unique_stacked_data.tostring() format.addArray(formatArray) format = GeomVertexFormat.registerFormat(format) vdata = GeomVertexData("dataname", format, Geom.UHStatic) arr = GeomVertexArrayData(format.getArray(0), GeomEnums.UHStream) datahandle = arr.modifyHandle() datahandle.setData(all_data) all_data = None vdata.setArray(0, arr) datahandle = None arr = None indexFormat = GeomVertexArrayFormat() indexFormat.addColumn(InternalName.make("index"), 1, Geom.NTUint32, Geom.CIndex) indexFormat = GeomVertexArrayFormat.registerFormat(indexFormat) indexArray = GeomVertexArrayData(indexFormat, GeomEnums.UHStream) indexHandle = indexArray.modifyHandle() indexData = inverse_map.tostring() indexHandle.setData(indexData) return vdata, indexArray
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 getNodeFromController(controller, controlled_prim): if type(controlled_prim) is collada.controller.BoundSkinPrimitive: ch = Character('simplechar') bundle = ch.getBundle(0) skeleton = PartGroup(bundle, '<skeleton>') character_joints = {} for (name, joint_matrix) in controller.joint_matrices.iteritems(): joint_matrix.shape = (-1) character_joints[name] = CharacterJoint(ch, bundle, skeleton, name, Mat4(*joint_matrix)) tbtable = TransformBlendTable() for influence in controller.index: blend = TransformBlend() for (joint_index, weight_index) in influence: char_joint = character_joints[controller.getJoint(joint_index)] weight = controller.getWeight(weight_index)[0] blend.addTransform(JointVertexTransform(char_joint), weight) tbtable.addBlend(blend) array = GeomVertexArrayFormat() array.addColumn(InternalName.make('vertex'), 3, Geom.NTFloat32, Geom.CPoint) array.addColumn(InternalName.make('normal'), 3, Geom.NTFloat32, Geom.CPoint) array.addColumn(InternalName.make('texcoord'), 2, Geom.NTFloat32, Geom.CTexcoord) blendarr = GeomVertexArrayFormat() blendarr.addColumn(InternalName.make('transform_blend'), 1, Geom.NTUint16, Geom.CIndex) format = GeomVertexFormat() format.addArray(array) format.addArray(blendarr) aspec = GeomVertexAnimationSpec() aspec.setPanda() format.setAnimation(aspec) format = GeomVertexFormat.registerFormat(format) dataname = controller.id + '-' + controlled_prim.primitive.material.id vdata = GeomVertexData(dataname, format, Geom.UHStatic) vertex = GeomVertexWriter(vdata, 'vertex') normal = GeomVertexWriter(vdata, 'normal') texcoord = GeomVertexWriter(vdata, 'texcoord') transform = GeomVertexWriter(vdata, 'transform_blend') numtris = 0 if type(controlled_prim.primitive) is collada.polylist.BoundPolylist: for poly in controlled_prim.primitive.polygons(): for tri in poly.triangles(): for tri_pt in range(3): vertex.addData3f(tri.vertices[tri_pt][0], tri.vertices[tri_pt][1], tri.vertices[tri_pt][2]) normal.addData3f(tri.normals[tri_pt][0], tri.normals[tri_pt][1], tri.normals[tri_pt][2]) if len(controlled_prim.primitive._texcoordset) > 0: texcoord.addData2f(tri.texcoords[0][tri_pt][0], tri.texcoords[0][tri_pt][1]) transform.addData1i(tri.indices[tri_pt]) numtris+=1 elif type(controlled_prim.primitive) is collada.triangleset.BoundTriangleSet: for tri in controlled_prim.primitive.triangles(): for tri_pt in range(3): vertex.addData3f(tri.vertices[tri_pt][0], tri.vertices[tri_pt][1], tri.vertices[tri_pt][2]) normal.addData3f(tri.normals[tri_pt][0], tri.normals[tri_pt][1], tri.normals[tri_pt][2]) if len(controlled_prim.primitive._texcoordset) > 0: texcoord.addData2f(tri.texcoords[0][tri_pt][0], tri.texcoords[0][tri_pt][1]) transform.addData1i(tri.indices[tri_pt]) numtris+=1 tbtable.setRows(SparseArray.lowerOn(vdata.getNumRows())) gprim = GeomTriangles(Geom.UHStatic) for i in range(numtris): gprim.addVertices(i*3, i*3+1, i*3+2) gprim.closePrimitive() pgeom = Geom(vdata) pgeom.addPrimitive(gprim) render_state = getStateFromMaterial(controlled_prim.primitive.material) control_node = GeomNode("ctrlnode") control_node.addGeom(pgeom, render_state) ch.addChild(control_node) bundle = AnimBundle('simplechar', 5.0, 2) skeleton = AnimGroup(bundle, '<skeleton>') root = AnimChannelMatrixXfmTable(skeleton, 'root') #hjoint = AnimChannelMatrixXfmTable(root, 'joint1') #table = [10, 11, 12, 13, 14, 15, 14, 13, 12, 11] #data = PTAFloat.emptyArray(len(table)) #for i in range(len(table)): # data.setElement(i, table[i]) #hjoint.setTable(ord('i'), CPTAFloat(data)) #vjoint = AnimChannelMatrixXfmTable(hjoint, 'joint2') #table = [10, 9, 8, 7, 6, 5, 6, 7, 8, 9] #data = PTAFloat.emptyArray(len(table)) #for i in range(len(table)): # data.setElement(i, table[i]) #vjoint.setTable(ord('j'), CPTAFloat(data)) wiggle = AnimBundleNode('wiggle', bundle) np = NodePath(ch) anim = NodePath(wiggle) a = Actor(np, {'simplechar' : anim}) a.loop('simplechar') return a #a.setPos(0, 0, 0) else: raise Exception("Error: unsupported controller type")
import numpy as np from panda3d.core import Geom, GeomVertexFormat, GeomVertexData from .util.ipython import embed size = 1000 data = np.random.randint(0,1000,(size,3)) #color = np.random.randint(0,255,(size,4)) color = np.repeat(np.random.randint(0,255,(1,4)), size, 0) #full = np.hstack((data,color)) full = [tuple(d) for d in np.hstack((data,color))] #full = [tuple(*d,*color) for d in data] geom = GeomVertexData('points', GeomVertexFormat.getV3c4(), Geom.UHDynamic) geom.setNumRows(len(full)) array = geom.modifyArray(0) # need a writeable version handle = array.modifyHandle() #options are then the following: view = memoryview(array) arr = np.asarray(view) arr[:] = full embed() #OR #handle.copyDataFrom('some other handle to a GVDA') #handle.copySubataFrom(to_start, to_size, buffer, from_start, from_size)
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)