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 makeGeom(self, points, colors, sizes): #format = GeomVertexFormat.getV3c4() array = GeomVertexArrayFormat() array.addColumn(InternalName.make('vertex'), 3, Geom.NTFloat32, Geom.CPoint) array.addColumn(InternalName.make('color'), 4, Geom.NTFloat32, Geom.CColor) array.addColumn(InternalName.make('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, 'vertex') self.colorwriter = GeomVertexWriter(vdata, 'color') self.sizewriter = GeomVertexWriter(vdata, '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 __init__(self, base, obj, **kwargs): super(GalaxyView, self).__init__(base, obj, **kwargs) array = GeomVertexArrayFormat() array.addColumn(InternalName.make('vertex'), 3, Geom.NTFloat32, Geom.CPoint) array.addColumn(InternalName.make('color'), 4, Geom.NTFloat32, Geom.CColor) array.addColumn(InternalName.make('size'), 1, Geom.NTFloat32, Geom.COther) gmformat = GeomVertexFormat() gmformat.addArray(array) gmformat = GeomVertexFormat.registerFormat(gmformat) vdata = GeomVertexData('points', gmformat, Geom.UHDynamic) vertex = GeomVertexWriter(vdata, 'vertex') color = GeomVertexWriter(vdata, 'color') size = GeomVertexWriter(vdata, 'size') self.node = NodePath('galaxy') self.node.reparentTo(self.base.render) self.node.setTransparency(TransparencyAttrib.MAlpha) lumsort = sorted([star.luminosity for star in self.obj.stars]) #highest_luminosity = lumsort[-1] median_luminosity = lumsort[len(lumsort) / 2] for star in self.obj.stars: vertex.addData3f(star.galpos.x, star.galpos.y, star.galpos.z) color.addData4f(star.red, star.green, star.blue, 1.0) #size.addData1f(min(100, max(5, 10-star.magnitude/2))) sizeval = 10 + log(star.luminosity) size.addData1f(min(30, max(10, sizeval))) prim = GeomPoints(Geom.UHStatic) prim.addConsecutiveVertices(0, len(self.obj.stars)) prim.closePrimitive() geom = Geom(vdata) geom.addPrimitive(prim) node = GeomNode('gnode') node.addGeom(geom) galaxy_node = self.node.attachNewNode(node) galaxy_node.setRenderModeThickness(1) ts = TextureStage.getDefault() #TextureStage('ts') #ts.setMode(TextureStage.MGlow) galaxy_node.setTexGen(ts, TexGenAttrib.MPointSprite) galaxy_node.setTexture( ts, self.base.loader.loadTexture('texture/flare.png')) #galaxy_node.setRenderModePerspective(True) galaxy_node.setBin("unsorted", 1) galaxy_node.setDepthWrite(0) galaxy_node.setTransparency(1) self.setup_glow_shader() """
def create_model(self): # Set up the vertex arrays vformatArray = GeomVertexArrayFormat() # Panda3D implicitly generates a bounding volume from a # column named "vertex", so you either # * have a column of that name, or # * add a bounding volume yourself. vformatArray.addColumn(InternalName.make("vertex"), 3, Geom.NTFloat32, Geom.CPoint) vformatArray.addColumn(InternalName.make("color"), 4, Geom.NTFloat32, Geom.CColor) vformat = GeomVertexFormat() vformat.addArray(vformatArray) vformat = GeomVertexFormat.registerFormat(vformat) 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 = GeomPatches(3, 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, initial shader vars, number of instances np.set_shader( Shader.load(Shader.SL_GLSL, vertex="shader.vert", tess_control="shader.tesc", tess_evaluation="shader.tese", geometry="shader.geom", fragment="shader.frag")) np.set_shader_input("time", 0.0) np.set_shader_input("tess_level", 32.0) np.set_instance_count(num_instances) np.set_shader_input("numInstances", num_instances) return np
def begin(self, numVerts): self.vertexBuffer.uncleanSetNumRows(numVerts) for view in self.views: view.clear() self.vwriter = GeomVertexWriter(self.vertexBuffer, InternalName.getVertex()) self.twriter = GeomVertexWriter(self.vertexBuffer, InternalName.getTexcoord()) self.nwriter = GeomVertexWriter(self.vertexBuffer, InternalName.getNormal())
def modifyGeometryUVs(self): # Modifies the geometry vertex UVs in-place twriter = GeomVertexWriter(self.vdata, InternalName.getTexcoord()) tanwriter = GeomVertexWriter(self.vdata, InternalName.getTangent()) bwriter = GeomVertexWriter(self.vdata, InternalName.getBinormal()) for i in range(len(self.vertices)): twriter.setData2f(self.vertices[i].uv) tanwriter.setData3f(self.material.tangent) bwriter.setData3f(self.material.binormal)
def update_geom(self, points, colors, sizes): geom = self.instance.children[0].node().modify_geom(0) vdata = geom.modify_vertex_data() vdata.unclean_set_num_rows(len(points)) vwriter = GeomVertexRewriter(vdata, InternalName.get_vertex()) colorwriter = GeomVertexWriter(vdata, InternalName.get_color()) sizewriter = GeomVertexWriter(vdata, InternalName.get_size()) for (point, color, size) in zip(points, colors, sizes): vwriter.addData3f(*point) colorwriter.addData4f(*color) sizewriter.addData1f(size)
def getFaceFormat(): global FaceFormat if not FaceFormat: arr = GeomVertexArrayFormat() arr.addColumn(InternalName.getVertex(), 3, GeomEnums.NTStdfloat, GeomEnums.CPoint) arr.addColumn(InternalName.getNormal(), 3, GeomEnums.NTStdfloat, GeomEnums.CNormal) arr.addColumn(InternalName.getTangent(), 3, GeomEnums.NTStdfloat, GeomEnums.CVector) arr.addColumn(InternalName.getBinormal(), 3, GeomEnums.NTStdfloat, GeomEnums.CVector) arr.addColumn(InternalName.getTexcoord(), 2, GeomEnums.NTStdfloat, GeomEnums.CTexcoord) FaceFormat = GeomVertexFormat.registerFormat(arr) return FaceFormat
def __init__(self, __occupying_unit = None, __occupiable = True, x = 0, z = 0, r = 5, tag = 0): self.__occupying_unit = __occupying_unit self.__occupiable = __occupiable self.__r = r self.__x = x self.__z = z self.__tag = tag #Procedurally creating a hex! geometry_array = GeomVertexArrayFormat() geometry_array.addColumn(InternalName.make('vertex'), 3, Geom.NTFloat32, Geom.CPoint) geometry_array.addColumn(InternalName.make('normal'), 3, Geom.NTFloat32, Geom.CPoint) format = GeomVertexFormat() format.addArray(geometry_array) format = GeomVertexFormat.registerFormat(format) self.__vdata = GeomVertexData('Hex', format, Geom.UHStatic) self.__vertex = GeomVertexWriter(self.__vdata, 'vertex') self.__normal = GeomVertexWriter(self.__vdata, 'normal') #Vertex 1 self.__vertex.addData3f(self.__x, self.__z+self.__r, 0) self.__normal.addData3f(1, 0, 0) #Vertex 2 self.__vertex.addData3f(self.__x+self.__r*sin(pi/3), self.__z+self.__r*cos(pi/3), 0) self.__normal.addData3f(1, 0, 0) #Vertex 3 self.__vertex.addData3f(self.__x+self.__r*sin(pi/3), self.__z-self.__r*cos(pi/3), 0) self.__normal.addData3f(1, 0, 0) #Vertex 4 self.__vertex.addData3f(self.__x, self.__z-self.__r, 0) self.__normal.addData3f(1, 0, 0) #Vertex 5 self.__vertex.addData3f(self.__x-self.__r*sin(pi/3), self.__z-self.__r*cos(pi/3), 0) self.__normal.addData3f(1, 0, 0) #Vertex 6 self.__vertex.addData3f(self.__x-self.__r*sin(pi/3), self.__z+self.__r*cos(pi/3), 0) self.__normal.addData3f(1, 0, 0) self.__hex_primitive = GeomTrifans(Geom.UHStatic) self.__hex_primitive.addVertices(5, 4) self.__hex_primitive.addVertices(3, 2) self.__hex_primitive.addVertices(1, 0) self.__hex_primitive.closePrimitive() self.__hex_geometry = Geom(self.__vdata) self.__hex_geometry.addPrimitive(self.__hex_primitive) self.__hex_node = GeomNode('HexNode') self.__hex_node.addGeom(self.__hex_geometry) nodePath = render.attachNewNode(self.__hex_node) nodePath.setTag( "hex", str(tag) ) nodePath.node().setIntoCollideMask(BitMask32.bit(1)) nodePath.hide()
def create_model(self): # Set up the vertex arrays vformatArray = GeomVertexArrayFormat() # Panda3D implicitly generates a bounding volume from a # column named "vertex", so you either # * have a column of that name, or # * add a bounding volume yourself. vformatArray.addColumn(InternalName.make("vertex"), 3, Geom.NTFloat32, Geom.CPoint) vformatArray.addColumn(InternalName.make("color"), 4, Geom.NTFloat32, Geom.CColor) vformat = GeomVertexFormat() vformat.addArray(vformatArray) vformat = GeomVertexFormat.registerFormat(vformat) 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 = GeomPatches(3, 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, initial shader vars, number of instances np.set_shader(Shader.load(Shader.SL_GLSL, vertex = "shader.vert", tess_control = "shader.tesc", tess_evaluation = "shader.tese", geometry = "shader.geom", fragment = "shader.frag")) np.set_shader_input("time", 0.0) np.set_shader_input("tess_level", 32.0) np.set_instance_count(num_instances) np.set_shader_input("numInstances", num_instances) return np
def __generate_Vformats(self): vformat_dict = {} # Simple. array = GeomVertexArrayFormat() array.addColumn(InternalName.make("vertex"), 3, Geom.NTFloat32, Geom.CPoint) vformat = GeomVertexFormat() vformat.addArray(array) vformat_dict['simp'] = GeomVertexFormat.registerFormat(vformat) # Low. array = GeomVertexArrayFormat() array.addColumn(InternalName.make("vertex"), 3, Geom.NTFloat32, Geom.CPoint) array.addColumn(InternalName.make("color"), 4, Geom.NTFloat32, Geom.CColor) vformat = GeomVertexFormat() vformat.addArray(array) vformat_dict['low'] = GeomVertexFormat.registerFormat(vformat) # Mid. array = GeomVertexArrayFormat() array.addColumn(InternalName.make("vertex"), 3, Geom.NTFloat32, Geom.CPoint) array.addColumn(InternalName.make("mapcoord"), 2, Geom.NTFloat32, Geom.CTexcoord) vformat = GeomVertexFormat() vformat.addArray(array) vformat_dict['mid'] = GeomVertexFormat.registerFormat(vformat) # High (patches). array = GeomVertexArrayFormat() array.addColumn(InternalName.make("vertex"), 3, Geom.NTFloat32, Geom.CPoint) array.addColumn(InternalName.make("mapcoord"), 2, Geom.NTFloat32, Geom.CTexcoord) array.addColumn(InternalName.make("texcoord"), 2, Geom.NTFloat32, Geom.CTexcoord) vformat = GeomVertexFormat() vformat.addArray(array) vformat_dict['high'] = GeomVertexFormat.registerFormat(vformat) return vformat_dict
def makeSprite(name, texture, scale, add = False): from panda3d.core import (GeomVertexFormat, GeomVertexData, GeomEnums, InternalName, GeomVertexWriter, GeomPoints, Geom, GeomNode, NodePath, TextureStage, TexGenAttrib, BoundingSphere) format = GeomVertexFormat.getV3() data = GeomVertexData(name + "_data", format, GeomEnums.UHStatic) writer = GeomVertexWriter(data, InternalName.getVertex()) writer.addData3f((0, 0, 0)) primitive = GeomPoints(GeomEnums.UHStatic) primitive.addVertex(0) primitive.closePrimitive() geom = Geom(data) geom.addPrimitive(primitive) geomNode = GeomNode(name) geomNode.addGeom(geom) np = NodePath(geomNode) np.setLightOff(1) np.setMaterialOff(1) np.setRenderModePerspective(True) ts = TextureStage('sprite') if add: ts.setMode(TextureStage.MAdd) np.setTexture(ts, texture) np.setTexGen(ts, TexGenAttrib.MPointSprite) np.setDepthWrite(False) np.setDepthOffset(1) np.setTransparency(True) np.node().setBounds(BoundingSphere((0, 0, 0), 1)) np.node().setFinal(True) np.flattenStrong() np.setScale(scale) return np
def pandageom_from_points(vertices, rgba=None, name=''): """ pack the vertices into a panda3d point cloud geom :param vertices: :param rgba: rgba color for each vertex, can be list or nparray (rgb is also acceptable) :param name: :return: author: weiwei date: 20170328, 20210116, 20220721 """ if rgba is None: # default vertex_rgbas = np.asarray([[0, 0, 0, 255]] * len(vertices), dtype=np.uint8) if isinstance(rgba, list): rgba = np.array(rgba) if not isinstance(rgba, np.array): raise ValueError('rgba must be a list or an nparray!') if len(rgba) == 1: vertex_rgbas = np.tile((rgba * 255).astype(np.uint8), (len(vertices), 1)) elif len(rgba) == len(vertices): vertex_rgbas = (rgba * 255).astype(np.uint8) n_color_bit = rgba.shape[1] vertformat = GeomVertexFormat() arrayformat = GeomVertexArrayFormat() arrayformat.addColumn(InternalName.getVertex(), 3, GeomEnums.NTFloat32, GeomEnums.CPoint) vertformat.addArray(arrayformat) arrayformat = GeomVertexArrayFormat() arrayformat.addColumn(InternalName.getColor(), n_color_bit, GeomEnums.NTUint8, GeomEnums.CColor) vertformat.addArray(arrayformat) vertformat = GeomVertexFormat.registerFormat(vertformat) vertexdata = GeomVertexData(name, vertformat, Geom.UHStatic) vertexdata.modifyArrayHandle(0).copyDataFrom( np.ascontiguousarray(vertices, dtype=np.float32)) vertexdata.modifyArrayHandle(1).copyDataFrom(vertex_rgbas) primitive = GeomPoints(Geom.UHStatic) primitive.setIndexType(GeomEnums.NTUint32) primitive.modifyVertices(-1).modifyHandle().copyDataFrom( np.arange(len(vertices), dtype=np.uint32)) geom = Geom(vertexdata) geom.addPrimitive(primitive) return geom
def pandageom_from_points(vertices, rgba_list=None, name=''): """ pack the vertices into a panda3d point cloud geom :param vertices: :param rgba_list: a list with a single 1x4 nparray or with len(vertices) 1x4 nparray :param name: :return: author: weiwei date: 20170328, 20210116 """ if rgba_list is None: # default vertex_rgbas = np.array([[0, 0, 0, 255]] * len(vertices), dtype=np.uint8) elif type(rgba_list) is not list: raise Exception('rgba\_list must be a list!') elif len(rgba_list) == 1: vertex_rgbas = np.tile((np.array(rgba_list[0]) * 255).astype(np.uint8), (len(vertices), 1)) elif len(rgba_list) == len(vertices): vertex_rgbas = (np.array(rgba_list) * 255).astype(np.uint8) else: raise ValueError( 'rgba_list must be a list of one or len(vertices) 1x4 nparray!') vertformat = GeomVertexFormat() arrayformat = GeomVertexArrayFormat() arrayformat.addColumn(InternalName.getVertex(), 3, GeomEnums.NTFloat32, GeomEnums.CPoint) vertformat.addArray(arrayformat) arrayformat = GeomVertexArrayFormat() arrayformat.addColumn(InternalName.getColor(), 4, GeomEnums.NTUint8, GeomEnums.CColor) vertformat.addArray(arrayformat) vertformat = GeomVertexFormat.registerFormat(vertformat) vertexdata = GeomVertexData(name, vertformat, Geom.UHStatic) vertexdata.modifyArrayHandle(0).copyDataFrom( np.ascontiguousarray(vertices, dtype=np.float32)) vertexdata.modifyArrayHandle(1).copyDataFrom(vertex_rgbas) primitive = GeomPoints(Geom.UHStatic) primitive.setIndexType(GeomEnums.NTUint32) primitive.modifyVertices(-1).modifyHandle().copyDataFrom( np.arange(len(vertices), dtype=np.uint32)) geom = Geom(vertexdata) geom.addPrimitive(primitive) return geom
def load_pcd_content(content, w=2, color_mode="intensity", intensity_filter=50): pc = pypcd.PointCloud.from_buffer(content) fmt = GeomVertexFormat() #3 component vertex, w/ 4 comp color fmt_arr = GeomVertexArrayFormat() fmt_arr.addColumn(InternalName.make('vertex'), 3, Geom.NTFloat32, Geom.CPoint) fmt_color_arr = GeomVertexArrayFormat() fmt_color_arr.addColumn(InternalName.make('color'), 4, Geom.NTUint8, Geom.CColor) fmt.addArray(fmt_arr) fmt.addArray(fmt_color_arr) fmt = GeomVertexFormat.registerFormat(fmt) vertexData = GeomVertexData('points', fmt, Geom.UHStatic) pointCloud = GeomPoints(Geom.UHStatic) pc.pc_data.dtype = numpy.dtype("<f4") v, c = arrayfilter.vertices_filter(pc.pc_data.reshape((pc.points, 4))) for i in xrange(len(v)): pointCloud.addVertex(i) pointCloud.closePrimitive() arr = GeomVertexArrayData(fmt.getArray(0), GeomEnums.UHStream) datahandle = arr.modifyHandle() datahandle.copyDataFrom(v) vertexData.setArray(0, arr) arr = GeomVertexArrayData(fmt.getArray(1), GeomEnums.UHStream) datahandle = arr.modifyHandle() datahandle.copyDataFrom(c) vertexData.setArray(1, arr) cloud = Geom(vertexData) cloud.addPrimitive(pointCloud) cloudNode = GeomNode('points') cloudNode.addGeom(cloud) cloudNodePath = NodePath(cloudNode) cloudNodePath.setRenderModeThickness(w) cloudNodePath.setRenderModePerspective(True) return cloudNode
def __init__(self): formatArray = GeomVertexArrayFormat() formatArray.addColumn( InternalName.make("drawFlag"), 1, Geom.NTUint8, Geom.COther) format = GeomVertexFormat(GeomVertexFormat.getV3n3cpt2()) format.addArray(formatArray) self.format = GeomVertexFormat.registerFormat(format) # bodydata = GeomVertexData("body vertices", format, Geom.UHStatic) self.barkTexture = loader.loadTexture("../asset/TreeGenerator/barkTexture.jpg")
def makeVertexFormat(color=True, normal=False, texcoord=False, tan_binorm=False): myArray = GeomVertexArrayFormat() myArray.addColumn(InternalName.make('vertex'), 3, Geom.NTFloat32, Geom.CPoint) if color: myArray.addColumn(InternalName.make('color'), 4, Geom.NTFloat32, Geom.CColor) if normal: myArray.addColumn(InternalName.make('normal'), 3, Geom.NTFloat32, Geom.CVector) if texcoord: myArray.addColumn(InternalName.make('texcoord'), 2, Geom.NTFloat32, Geom.CTexcoord) if tan_binorm: myArray.addColumn(InternalName.make('tangent'), 3, Geom.NTFloat32, Geom.CVector) myArray.addColumn(InternalName.make('binormal'), 3, Geom.NTFloat32, Geom.CVector) myFormat = GeomVertexFormat() myFormat.addArray(myArray) myFormat = GeomVertexFormat.registerFormat(myFormat) return myFormat
def __init__(self): array_format = GeomVertexArrayFormat() array_format.addColumn( InternalName.make(ArrayFormatColunm.Vertex.value), 3, Geom.NT_float32, Geom.C_point) array_format.addColumn( InternalName.make(ArrayFormatColunm.Color.value), 4, Geom.NT_uint8, Geom.C_color) array_format.addColumn( InternalName.make(ArrayFormatColunm.Normal.value), 3, Geom.NT_float32, Geom.C_normal) array_format.addColumn( InternalName.make(ArrayFormatColunm.Tangent.value), 3, Geom.NT_float32, Geom.C_vector) array_format.addColumn( InternalName.make(ArrayFormatColunm.Binormal.value), 3, Geom.NT_float32, Geom.C_vector) array_format.addColumn( InternalName.make(ArrayFormatColunm.UVMap.value), 2, Geom.NT_float32, Geom.C_texcoord) self.vertex_format = GeomVertexFormat() self.vertex_format.addArray(array_format) self.vertex_format = GeomVertexFormat.registerFormat( self.vertex_format)
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): formatArray = GeomVertexArrayFormat() formatArray.addColumn(InternalName.make("drawFlag"), 1, Geom.NTUint8, Geom.COther) format = GeomVertexFormat(GeomVertexFormat.getV3n3cpt2()) format.addArray(formatArray) self.format = GeomVertexFormat.registerFormat(format) bodydata = GeomVertexData("body vertices", format, Geom.UHStatic) self.barkTexture = loader.loadTexture("barkTexture.jpg") treeNodePath = NodePath("Tree Holder") makeFractalTree(bodydata, treeNodePath, LVector3(4, 4, 7)) treeNodePath.setTexture(self.barkTexture, 1) treeNodePath.reparentTo(render) self.accept("q", self.regenTree) self.accept("w", self.addTree) self.accept("arrow_up", self.upIterations) self.accept("arrow_down", self.downIterations) self.accept("arrow_right", self.upCopies) self.accept("arrow_left", self.downCopies) self.numIterations = 11 self.numCopies = 4 self.upDownEvent = OnscreenText( text="Up/Down: Increase/Decrease the number of iterations (" + str(self.numIterations) + ")", parent=base.a2dTopLeft, align=TextNode.ALeft, style=1, fg=(1, 1, 1, 1), pos=(0.06, -0.22), scale=.05, mayChange=True) self.leftRightEvent = OnscreenText( text="Left/Right: Increase/Decrease branching (" + str(self.numCopies) + ")", parent=base.a2dTopLeft, align=TextNode.ALeft, style=1, fg=(1, 1, 1, 1), pos=(0.06, -0.28), scale=.05, mayChange=True)
def __build_Writers(self): # Build Vdata. array = GeomVertexArrayFormat() for field_name, field_spec_name in list(self.field_types.items()): field_specs = self._data_types[field_spec_name][:-1] array.addColumn(InternalName.make(field_name), *field_specs) vformat = GeomVertexFormat() vformat.addArray(array) vformat = GeomVertexFormat.registerFormat(vformat) vdata = GeomVertexData("data", vformat, Geom.UHStatic) # Build GeomVertexWriters. writers = {} for field_name in list(self.field_types.keys()): writers[field_name] = GeomVertexWriter(vdata, field_name) return vdata, writers
def update_geom(self): geom = self.node.modify_geom(0) vdata = geom.modify_vertex_data() vwriter = GeomVertexRewriter(vdata, InternalName.get_vertex()) #TODO: refactor with above code !!! delta = self.body.parent.get_local_position() if self.orbit.is_periodic(): epoch = self.context.time.time_full - self.orbit.period step = self.orbit.period / (self.nbOfPoints - 1) else: #TODO: Properly calculate orbit start and end time epoch = self.orbit.get_time_of_perihelion() - self.orbit.period * 5.0 step = self.orbit.period * 10.0 / (self.nbOfPoints - 1) for i in range(self.nbOfPoints): time = epoch + step * i pos = self.orbit.get_position_at(time) - delta vwriter.setData3f(*pos)
def registerObject(self, obj): """ Registers a new dynamic object, this will store an index for every vertex, which can be used to read and store last position data in order to compute the velocity. This method also assigns the standard animated shader to the node """ self.debug("Registering dynamic object") # Find all GeomNodes for node in obj.findAllMatches("**/+GeomNode"): geomNode = node.node() geomCount = geomNode.getNumGeoms() # Find all Geoms for i in xrange(geomCount): # Modify vertex data geom = geomNode.modifyGeom(i) geomVertexData = geom.modifyVertexData() # Add a new column named "dovindex" to the vertex data formatArray = GeomVertexArrayFormat() formatArray.addColumn(InternalName.make("dovindex"), 1, GeomEnums.NTUint32, GeomEnums.CIndex) newArrayFormat = GeomVertexFormat(geomVertexData.getFormat()) newArrayFormat.addArray(formatArray) newArrayFormat = GeomVertexFormat.registerFormat( newArrayFormat) # Convert the old vertex data and assign the new vertex data convertedVertexData = geomVertexData.convertTo(newArrayFormat) geom.setVertexData(convertedVertexData) # Write the per-vertex indices the dovindex column newVertexData = geom.modifyVertexData() vtxReader = GeomVertexReader(newVertexData, "vertex") indexWriter = GeomVertexWriter(newVertexData, "dovindex") while not vtxReader.isAtEnd(): data = vtxReader.getData3f() indexWriter.setData1i(self.currentIndex) self.currentIndex += 1 if self.currentIndex > self.maxVertexCount: self.error("Max dynamic vertex count of", self.maxVertexCount, "reached!")
def registerObject(self, obj): """ Registers a new dynamic object, this will store an index for every vertex, which can be used to read and store last position data in order to compute the velocity. This method also assigns the standard animated shader to the node """ self.debug("Registering dynamic object") # Find all GeomNodes for node in obj.findAllMatches("**/+GeomNode"): geomNode = node.node() geomCount = geomNode.getNumGeoms() # Find all Geoms for i in xrange(geomCount): # Modify vertex data geom = geomNode.modifyGeom(i) geomVertexData = geom.modifyVertexData() # Add a new column named "dovindex" to the vertex data formatArray = GeomVertexArrayFormat() formatArray.addColumn(InternalName.make("dovindex"), 1, GeomEnums.NTUint32, GeomEnums.CIndex) newArrayFormat = GeomVertexFormat(geomVertexData.getFormat()) newArrayFormat.addArray(formatArray) newArrayFormat = GeomVertexFormat.registerFormat(newArrayFormat) # Convert the old vertex data and assign the new vertex data convertedVertexData = geomVertexData.convertTo(newArrayFormat) geom.setVertexData(convertedVertexData) # Write the per-vertex indices the dovindex column newVertexData = geom.modifyVertexData() vtxReader = GeomVertexReader(newVertexData, "vertex") indexWriter = GeomVertexWriter(newVertexData, "dovindex") while not vtxReader.isAtEnd(): data = vtxReader.getData3f() indexWriter.setData1i(self.currentIndex) self.currentIndex += 1 if self.currentIndex > self.maxVertexCount: self.error("Max dynamic vertex count of", self.maxVertexCount, "reached!")
def create_hidden_area_mesh(self, mask): """ Using the provided mask configuration, create the mesh that will cover the area not visible from the HMD """ gvf = GeomVertexFormat.get_v3() gvd = GeomVertexData('gvd', gvf, Geom.UH_static) geom = Geom(gvd) gvw = GeomVertexWriter(gvd, InternalName.get_vertex()) for i in range(mask.unTriangleCount * 3): vertex = mask.pVertexData[i] # The clip space in Panda3D has [-1, 1] coordinates, the received coordinates are in [0, 1] gvw.add_data3(vertex[0] * 2 - 1, vertex[1] * 2 - 1, -1) prim = GeomTriangles(Geom.UH_static) for i in range(mask.unTriangleCount): prim.add_vertices(i * 3, i * 3 + 1, i * 3 + 2) geom.add_primitive(prim) node = GeomNode('hidden-area-mesh') node.add_geom(geom) return node
def __init__(self): formatArray = GeomVertexArrayFormat() formatArray.addColumn( InternalName.make("drawFlag"), 1, Geom.NTUint8, Geom.COther) format = GeomVertexFormat(GeomVertexFormat.getV3n3cpt2()) format.addArray(formatArray) self.format = GeomVertexFormat.registerFormat(format) bodydata = GeomVertexData("body vertices", format, Geom.UHStatic) self.barkTexture = loader.loadTexture("barkTexture.jpg") treeNodePath = NodePath("Tree Holder") makeFractalTree(bodydata, treeNodePath, LVector3(4, 4, 7)) treeNodePath.setTexture(self.barkTexture, 1) treeNodePath.reparentTo(render) self.accept("q", self.regenTree) self.accept("w", self.addTree) self.accept("arrow_up", self.upIterations) self.accept("arrow_down", self.downIterations) self.accept("arrow_right", self.upCopies) self.accept("arrow_left", self.downCopies) self.numIterations = 11 self.numCopies = 4 self.upDownEvent = OnscreenText( text="Up/Down: Increase/Decrease the number of iterations (" + str( self.numIterations) + ")", parent=base.a2dTopLeft, align=TextNode.ALeft, style=1, fg=(1, 1, 1, 1), pos=(0.06, -0.22), scale=.05, mayChange=True) self.leftRightEvent = OnscreenText( text="Left/Right: Increase/Decrease branching (" + str( self.numCopies) + ")", parent=base.a2dTopLeft, align=TextNode.ALeft, style=1, fg=(1, 1, 1, 1), pos=(0.06, -0.28), scale=.05, mayChange=True)
def makeVertexFormat(color = True, normal = False, texcoord = False, tan_binorm = False): myArray = GeomVertexArrayFormat() myArray.addColumn(InternalName.make('vertex'), 3, Geom.NTFloat32, Geom.CPoint) if color: myArray.addColumn(InternalName.make('color'), 4, Geom.NTFloat32, Geom.CColor) if normal: myArray.addColumn(InternalName.make('normal'), 3, Geom.NTFloat32, Geom.CVector) if texcoord: myArray.addColumn(InternalName.make('texcoord'), 2, Geom.NTFloat32, Geom.CTexcoord) if tan_binorm: myArray.addColumn(InternalName.make('tangent'), 3, Geom.NTFloat32, Geom.CVector) myArray.addColumn(InternalName.make('binormal'), 3, Geom.NTFloat32, Geom.CVector) myFormat = GeomVertexFormat() myFormat.addArray(myArray) myFormat = GeomVertexFormat.registerFormat(myFormat) return myFormat
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
def __init__(self, __occupying_unit=None, __occupiable=True, x=0, z=0, r=5, tag=0): self.__occupying_unit = __occupying_unit self.__occupiable = __occupiable self.__r = r self.__x = x self.__z = z self.__tag = tag #Procedurally creating a hex! geometry_array = GeomVertexArrayFormat() geometry_array.addColumn(InternalName.make('vertex'), 3, Geom.NTFloat32, Geom.CPoint) geometry_array.addColumn(InternalName.make('normal'), 3, Geom.NTFloat32, Geom.CPoint) format = GeomVertexFormat() format.addArray(geometry_array) format = GeomVertexFormat.registerFormat(format) self.__vdata = GeomVertexData('Hex', format, Geom.UHStatic) self.__vertex = GeomVertexWriter(self.__vdata, 'vertex') self.__normal = GeomVertexWriter(self.__vdata, 'normal') #Vertex 1 self.__vertex.addData3f(self.__x, self.__z + self.__r, 0) self.__normal.addData3f(1, 0, 0) #Vertex 2 self.__vertex.addData3f(self.__x + self.__r * sin(pi / 3), self.__z + self.__r * cos(pi / 3), 0) self.__normal.addData3f(1, 0, 0) #Vertex 3 self.__vertex.addData3f(self.__x + self.__r * sin(pi / 3), self.__z - self.__r * cos(pi / 3), 0) self.__normal.addData3f(1, 0, 0) #Vertex 4 self.__vertex.addData3f(self.__x, self.__z - self.__r, 0) self.__normal.addData3f(1, 0, 0) #Vertex 5 self.__vertex.addData3f(self.__x - self.__r * sin(pi / 3), self.__z - self.__r * cos(pi / 3), 0) self.__normal.addData3f(1, 0, 0) #Vertex 6 self.__vertex.addData3f(self.__x - self.__r * sin(pi / 3), self.__z + self.__r * cos(pi / 3), 0) self.__normal.addData3f(1, 0, 0) self.__hex_primitive = GeomTrifans(Geom.UHStatic) self.__hex_primitive.addVertices(5, 4) self.__hex_primitive.addVertices(3, 2) self.__hex_primitive.addVertices(1, 0) self.__hex_primitive.closePrimitive() self.__hex_geometry = Geom(self.__vdata) self.__hex_geometry.addPrimitive(self.__hex_primitive) self.__hex_node = GeomNode('HexNode') self.__hex_node.addGeom(self.__hex_geometry) nodePath = render.attachNewNode(self.__hex_node) nodePath.setTag("hex", str(tag)) nodePath.node().setIntoCollideMask(BitMask32.bit(1)) nodePath.hide()
def __init__(self, mainReference): self.mainRef = mainReference # fog experiment myFog = Fog("Mist") myFog.setColor(0.6, 0.6, 0.6) myFog.setExpDensity(0.0007) render.setFog(myFog) # loading H_Block self.H_Block = loader.loadModel("../../models/H_Block/H_Block") self.H_Block.reparentTo(self.mainRef.render) # loading H_Block's colision mesh self.H_Block_col = loader.loadModel("../../models/H_Block/H_Block_collision") self.H_Block_col.ls() # creating triangle meshes for all static nodes self.hBlockRoomGeom = self.H_Block_col.getChild(0).getNode(0).getGeom(0) self.hBlockBulletMesh = BulletTriangleMesh() self.hBlockBulletMesh.addGeom(self.hBlockRoomGeom) self.hBlockBulletShape = BulletTriangleMeshShape(self.hBlockBulletMesh, dynamic=False) self.bulletHBlockNode = BulletRigidBodyNode('hBlockNode') self.bulletHBlockNode.addShape(self.hBlockBulletShape) self.mainRef.world.attachRigidBody(self.bulletHBlockNode) self.mainRef.render.attachNewNode(self.bulletHBlockNode).setCollideMask(BitMask32.allOn()) # arrays containing all regions and portals dividing those regions self.convexRegions = [] self.portals = [] self.convexRegionsGeometry = loader.loadModel("../../models/H_Block/ConvexRegions2") self.portalsGeometry = loader.loadModel("../../models/H_Block/Portals2") # self.portalsGeometry.reparentTo(self.mainRef.render) # Regions self.convexRegions.append( Region(0) ) # Just making the access to convexRegions easier for convexRegion in self.convexRegionsGeometry.getChild(0).getChildren(): regionNode = convexRegion.getNode(0) regionID = int( regionNode.getTag("prop") ) self.convexRegions.append( Region(regionID) ) # Get vertices that define the convex region vertexReader = GeomVertexReader(regionNode.getGeom(0).getVertexData(), InternalName.getVertex()) while( not(vertexReader.isAtEnd() ) ): data = vertexReader.getData3() X = data.getX() Y = data.getY() Z = data.getZ() self.convexRegions[-1].vertices.append(Vec3(X,Y,Z)) self.convexRegions = sorted(self.convexRegions, key=lambda convexRegion: convexRegion.regionID) # Debug # for cr in self.convexRegions: # print cr.regionID # Portals for portal in self.portalsGeometry.getChild(0).getChildren(): portalNode = portal.getNode(0) # Get vertices that define the portal frontiers = [] vertexReader = GeomVertexReader(portalNode.getGeom(0).getVertexData(), InternalName.getVertex()) for i in range(2): # We got 2 vertices per portal data = vertexReader.getData3() X = data.getX() Y = data.getY() frontiers.append(Vec2(X,Y)) connectedRegionsIDs = map(int, portalNode.getTag("prop").split(',')) self.portals.append( Portal(connectedRegionsIDs, frontiers) ) self.convexRegions[ connectedRegionsIDs[0] ].portalEntrancesList.append( PortalEntrance( self.portals[-1], connectedRegionsIDs[1] ) ) self.convexRegions[ connectedRegionsIDs[1] ].portalEntrancesList.append( PortalEntrance( self.portals[-1], connectedRegionsIDs[0] ) )
if not res.has_key(tree): res[tree] = [] x = random.randint(sx, ex) y = random.randint(sy, ey) z = self.world.map3d[x, y] if 0 < z < self.config.low_mount_level[1]: res[tree].append((x, y, z)) self[item] = res return res # Shit for f*****g trees formatArray = GeomVertexArrayFormat() formatArray.addColumn(InternalName.make("drawFlag"), 1, Geom.NTUint8, Geom.COther) treeform = GeomVertexFormat(GeomVertexFormat.getV3n3cpt2()) treeform.addArray(formatArray) treeform = GeomVertexFormat.registerFormat(treeform) #this draws the body of the tree. This draws a ring of vertices and connects the rings with #triangles to form the body. #this keepDrawing paramter tells the function wheter or not we're at an end #if the vertices before you were an end, dont draw branches to it def draw_body(nodePath, vdata, pos, vecList,
def regenerateGeometry(self): # # Generate vertex data # numVerts = len(self.vertices) vdata = GeomVertexData("SolidFace", getFaceFormat(), GeomEnums.UHStatic) vdata.uncleanSetNumRows(len(self.vertices)) vwriter = GeomVertexWriter(vdata, InternalName.getVertex()) twriter = GeomVertexWriter(vdata, InternalName.getTexcoord()) nwriter = GeomVertexWriter(vdata, InternalName.getNormal()) tanwriter = GeomVertexWriter(vdata, InternalName.getTangent()) bwriter = GeomVertexWriter(vdata, InternalName.getBinormal()) for i in range(len(self.vertices)): vert = self.vertices[i] vwriter.setData3f(vert.pos) twriter.setData2f(vert.uv) nwriter.setData3f(self.plane.getNormal()) tanwriter.setData3f(self.material.tangent) bwriter.setData3f(self.material.binormal) # # Generate indices # # Triangles in 3D view prim3D = GeomTriangles(GeomEnums.UHStatic) prim3D.reserveNumVertices((numVerts - 2) * 3) for i in range(1, numVerts - 1): prim3D.addVertices(i + 1, i, 0) prim3D.closePrimitive() # Line loop in 2D view.. using line strips prim2D = GeomLinestrips(GeomEnums.UHStatic) prim2D.reserveNumVertices(numVerts + 1) for i in range(numVerts): prim2D.addVertex(i) # Close off the line strip with the first vertex.. creating a line loop prim2D.addVertex(0) prim2D.closePrimitive() # # Generate mesh objects # geom3D = SolidFaceGeom(vdata) geom3D.setDrawMask(VIEWPORT_3D_MASK) geom3D.setPlaneCulled(True) geom3D.setPlane(self.plane) geom3D.addPrimitive(prim3D) self.index3D = self.solid.addFaceGeom(geom3D, self.state3D) geom3DLines = SolidFaceGeom(vdata) geom3DLines.addPrimitive(prim2D) geom3DLines.setDrawMask(VIEWPORT_3D_MASK) geom3DLines.setDraw(False) self.index3DLines = self.solid.addFaceGeom(geom3DLines, self.state3DLines) geom2D = SolidFaceGeom(vdata) geom2D.addPrimitive(prim2D) geom2D.setDrawMask(VIEWPORT_2D_MASK) self.index2D = self.solid.addFaceGeom(geom2D, self.state2D) self.geom3D = geom3D self.geom3DLines = geom3DLines self.geom2D = geom2D self.vdata = vdata self.hasGeometry = True
def processModel(path): scene = loadModel(path) if scene.isEmpty(): print("Error converting `{0}`!".format(path)) return fPath = Filename.fromOsSpecific(path) outputPath = Filename.toOsSpecific( Filename("bam2smd/" + fPath.getDirname() + "/" + fPath.getBasenameWoExtension() + "/")) if not os.path.exists(outputPath): os.makedirs(outputPath) isCharacter = not scene.find("**/+Character").isEmpty() isAnimation = not scene.find("**/+AnimBundleNode").isEmpty() if not isAnimation: if isCharacter: nodes = Skeleton(scene.findAllMatches("**/+Character")) else: nodes = Skeleton(None) names = {} for geomNp in scene.findAllMatches("**/+GeomNode"): smd = "version 1\n" smd += str(nodes) smd += "skeleton\n" smd += "time 0\n" if isCharacter: boneIds = sorted(nodes.bones.keys()) for iBone in range(len(boneIds)): boneId = boneIds[iBone] bone = nodes.bones[boneId] if isinstance(bone, CharacterJoint): boneTform = bone.getTransformState() pos = boneTform.getPos() boneMat = boneTform.getMat().getUpper3() #boneMat.transposeInPlace() rot = mat3NormalizedToEulO(boneMat) else: pos = Vec3() rot = Vec3() smd += boneFrameString(boneId, pos, rot) else: smd += "0 0 0 0 0 0 0\n" smd += "end\n" smd += "triangles\n" for geom in geomNp.node().getGeoms(): geom = geom.decompose() vdata = geom.getVertexData() blendTable = vdata.getTransformBlendTable() for prim in geom.getPrimitives(): numTris = prim.getNumPrimitives() for nTri in range(numTris): start = prim.getPrimitiveStart(nTri) end = prim.getPrimitiveEnd(nTri) smd += "no_material\n" for primVert in range(start, end): vertIdx = prim.getVertex(primVert) reader = GeomVertexReader(vdata) reader.setColumn(InternalName.getVertex()) reader.setRow(vertIdx) pos = reader.getData3f() uv = Vec2(0, 0) if vdata.hasColumn(InternalName.getTexcoord()): reader.setColumn(InternalName.getTexcoord()) reader.setRow(vertIdx) uv = reader.getData2f() norm = Vec3.forward() if vdata.hasColumn(InternalName.getNormal()): reader.setColumn(InternalName.getNormal()) reader.setRow(vertIdx) norm = reader.getData3f() smd += "0 {0:.6f} {1:.6f} {2:.6f} {3:.6f} {4:.6f} {5:.6f} {6:.6f} {7:.6f} ".format( pos[0], pos[1], pos[2], norm[0], norm[1], norm[2], uv[0], uv[1]) if (isCharacter and blendTable and vdata.getNumArrays() > 1 and vdata.getArray(1).hasColumn( InternalName.getTransformBlend())): reader.setColumn( 1, vdata.getArray( 1).getArrayFormat().getColumn( InternalName.getTransformBlend())) reader.setRow(vertIdx) nBlend = reader.getData1i() blend = blendTable.getBlend(nBlend) numTransforms = blend.getNumTransforms() smd += "{0} ".format(numTransforms) for nTransform in range(numTransforms): transform = blend.getTransform(nTransform) if isinstance(transform, JointVertexTransform): boneId = nodes.getBoneId( transform.getJoint()) smd += "{0} {1:.6f} ".format( boneId, blend.getWeight(nTransform)) else: smd += "1 0 1.0" smd += "\n" smd += "end\n" smdFile = geomNp.getName() if len(smdFile) == 0: smdFile = getUnknownName() elif names.get(smdFile, 0) > 0: smdFile = smdFile + "_{0}".format(names[smdFile]) names[smdFile] += 1 else: names[smdFile] = 1 smdFile += ".smd" outFile = open(outputPath + "\\" + smdFile, "w") outFile.write(smd) outFile.flush() outFile.close() else: bundles = scene.findAllMatches("**/+AnimBundleNode") bundle = bundles[0].node().getBundle() nodes = Skeleton(bundles) smd = "version 1\n" smd += str(nodes) smd += "skeleton\n" numFrames = bundle.getNumFrames() boneIds = sorted(nodes.bones.keys()) for iFrame in range(numFrames): smd += "time {0}\n".format(iFrame) for iBone in range(len(boneIds)): bone = nodes.getBone(boneIds[iBone]) if isinstance(bone, AnimChannelACMatrixSwitchType): boneFrameMat = Mat4() bone.getValueNoScaleShear(iFrame, boneFrameMat) boneFrameTransform = TransformState.makeMat(boneFrameMat) pos = boneFrameTransform.getPos() rotMat = boneFrameMat.getUpper3() #rotMat.transposeInPlace() rot = mat3NormalizedToEulO(rotMat) smd += boneFrameString(boneIds[iBone], pos, rot) smd += "end\n" smdFile = fPath.getBasenameWoExtension() + ".smd" outFile = open(outputPath + "\\" + smdFile, "w") outFile.write(smd) outFile.flush() outFile.close()
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")
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
def __init__(self, size, pos, depth, mask, spec = WaterSpec()): NodePath.__init__(self, 'waterNode') self.setPos(pos) self.spec = spec self.pos = pos self.depth = depth self.size = size self.mask = mask self.height = pos[2] normal = (0, 0, 1) tangent = (normal[0], normal[2], -normal[1]) binormal = (normal[2], normal[1], -normal[0]) # Build array for new format. array = GeomVertexArrayFormat() array.addColumn(InternalName.make('vertex'), 3, Geom.NTFloat32, Geom.CPoint) array.addColumn(InternalName.make('texcoord'), 2, Geom.NTFloat32, Geom.CTexcoord) array.addColumn(InternalName.make('normal'), 3, Geom.NTFloat32, Geom.CVector) array.addColumn(InternalName.make('binormal'), 3, Geom.NTFloat32, Geom.CVector) array.addColumn(InternalName.make('tangent'), 3, Geom.NTFloat32, Geom.CVector) # Create and register format. format = GeomVertexFormat() format.addArray(array) format = GeomVertexFormat.registerFormat(format) vdata = GeomVertexData('waterPlanes', format, Geom.UHStatic) vdata.setNumRows(4) vtxWriter = GeomVertexWriter(vdata, 'vertex') tcWriter = GeomVertexWriter(vdata, 'texcoord') tnWriter = GeomVertexWriter(vdata, 'tangent') bnWriter = GeomVertexWriter(vdata, 'binormal') normWriter = GeomVertexWriter(vdata, 'normal') # top left corner vtxWriter.addData3f(size[0], size[3], 0) tcWriter.addData2f(0, 1) normWriter.addData3f(*normal) tnWriter.addData3f(*tangent) bnWriter.addData3f(*binormal) # bottom left corner vtxWriter.addData3f(size[0], size[2], 0) tcWriter.addData2f(0, 0) normWriter.addData3f(*normal) tnWriter.addData3f(*tangent) bnWriter.addData3f(*binormal) # top right corner vtxWriter.addData3f(size[1], size[3], 0) tcWriter.addData2f(1, 1) normWriter.addData3f(*normal) tnWriter.addData3f(*tangent) bnWriter.addData3f(*binormal) # bottom right corner vtxWriter.addData3f(size[1], size[2], 0) tcWriter.addData2f(1, 0) normWriter.addData3f(*normal) tnWriter.addData3f(*tangent) bnWriter.addData3f(*binormal) topTris = GeomTriangles(Geom.UHStatic) topTris.addVertices(0, 1, 2) topTris.addVertices(3, 2, 1) topGeom = Geom(vdata) topGeom.addPrimitive(topTris) self.topNP = self.attachNewNode(GeomNode('waterTop')) self.topNP.node().addGeom(topGeom) # Reverse the winding for the bottom water plane botTris = GeomTriangles(Geom.UHStatic) botTris.addVertices(2, 1, 0) botTris.addVertices(1, 2, 3) botGeom = Geom(vdata) botGeom.addPrimitive(botTris) self.botNP = self.attachNewNode(GeomNode('waterBot')) self.botNP.node().addGeom(botGeom) # Create an AABB which defines the volume of this water. self.aabb = BoundingBox(Point3(size[0], size[2], -depth), Point3(size[1], size[3], 0)) self.aabb.xform(self.getMat(render)) self.cubemap = base.bspLoader.getClosestCubemapTexture(self.getPos(render)) self.dudvFrame = 0
if not res.has_key(tree): res[tree] = [] x = random.randint(sx, ex) y = random.randint(sy, ey) z = self.world.map3d[x, y] if 0 < z < self.config.low_mount_level[1]: res[tree].append((x, y, z)) self[item] = res return res # Shit for f*****g trees formatArray = GeomVertexArrayFormat() formatArray.addColumn(InternalName.make("drawFlag"), 1, Geom.NTUint8, Geom.COther) treeform = GeomVertexFormat(GeomVertexFormat.getV3n3cpt2()) treeform.addArray(formatArray) treeform = GeomVertexFormat.registerFormat(treeform) # this draws the body of the tree. This draws a ring of vertices and connects the rings with # triangles to form the body. # this keepDrawing paramter tells the function wheter or not we're at an end # if the vertices before you were an end, dont draw branches to it def draw_body(nodePath, vdata, pos, vecList, radius=1, keepDrawing=True, numVertices=3): circleGeom = Geom(vdata) vertWriter = GeomVertexWriter(vdata, "vertex")
from panda3d.core import Material, NodePath, PerlinNoise3, PNMImage, Point3 from panda3d.core import Shader, Texture, TextureStage from panda3d.core import VBase4, Vec3 from utils import convertToPatches, shape_generator_advanced #you cant normalize in-place so this is a helper function def normalize(vec): vec.normalize() return vec # Build array for new format. array = GeomVertexArrayFormat() array.addColumn(InternalName.make(b'vertex'), 3, Geom.NTFloat32, Geom.CPoint) array.addColumn(InternalName.make(b'texcoord'), 2, Geom.NTFloat32, Geom.CTexcoord) array.addColumn(InternalName.make(b'normal'), 3, Geom.NTFloat32, Geom.CVector) array.addColumn(InternalName.make(b'binormal'), 3, Geom.NTFloat32, Geom.CVector) array.addColumn(InternalName.make(b'tangent'), 3, Geom.NTFloat32, Geom.CVector) # Create and register format. format = GeomVertexFormat() format.addArray(array) format = GeomVertexFormat.registerFormat(format) def frange(start, stop, step): r = start while r < stop: yield r
def build(self): # http://www.panda3d.org/forums/viewtopic.php?t=11528 """Create the geometry from the submitted arrays""" verts = self.verts polys = self.polys self.geomnode = GeomNode('geometry') self.color_lookup = [] if not self.vnorms: self.getNormals() if not self.uvs: self.getUVMapping() if self.use_tangents: self.getTangents() # Build array for new format. array = GeomVertexArrayFormat() array.addColumn(InternalName.make(b'vertex'), 3, Geom.NTFloat32, Geom.CPoint) array.addColumn(InternalName.make(b'texcoord'), 2, Geom.NTFloat32, Geom.CTexcoord) array.addColumn(InternalName.make(b'normal'), 3, Geom.NTFloat32, Geom.CVector) if self.use_tangents: array.addColumn(InternalName.make(b'binormal'), 3, Geom.NTFloat32, Geom.CVector) array.addColumn(InternalName.make(b'tangent'), 3, Geom.NTFloat32, Geom.CVector) # Create and register format. format = GeomVertexFormat() format.addArray(array) format = GeomVertexFormat.registerFormat(format) geoms = [] for i in range(len(self.colors)): vdata = GeomVertexData('ngon', format, Geom.UHStatic) geom = Geom(vdata) tri = GeomTriangles(Geom.UHStatic) vertex = GeomVertexWriter(vdata, b'vertex') normal = GeomVertexWriter(vdata, b'normal') texcoord = GeomVertexWriter(vdata, b'texcoord') geoms.append({'geom':geom, 'tri':tri, 'vertex':vertex, 'texcoord':texcoord, 'normal':normal, 'index':0, 'vdata':vdata, 'color':i}) if self.use_tangents: tangent = GeomVertexWriter(vdata, b'tangent') binormal = GeomVertexWriter(vdata, b'binormal') geoms[i]['tangent'] = tangent geoms[i]['binormal'] = binormal for poly_index in range(len(polys)): color_index = self.colors.index(self.mats[poly_index]) vertcount = geoms[color_index]['index'] p = polys[poly_index] poly = [verts[i] for i in p] uvs = self.uvs[poly_index] norm = [self.vnorms[i] for i in p] if self.use_tangents: binorm = [self.binorms[i] for i in p] tan = [self.tans[i] for i in p] reindexed = [] # New vertex indices per-poly for v in poly: geoms[color_index]['vertex'].addData3f(v[0], v[1], v[2]) reindexed.append(vertcount) vertcount += 1 geoms[color_index]['index'] = vertcount for i in range(len(poly)): geoms[color_index]['normal'].addData3f(Vec3(norm[i][0], norm[i][1], norm[i][2])) if self.use_tangents: geoms[color_index]['binormal'].addData3f(Vec3(binorm[i][0], binorm[i][1], binorm[i][2])) geoms[color_index]['tangent'].addData3f(Vec3(tan[i][0], tan[i][1], tan[i][2])) for tvert in uvs: geoms[color_index]['texcoord'].addData2f(tvert[0], tvert[1]) triangulated = self.getFanning(reindexed) # Use new vertex indices for tri_index in range(len(triangulated)): t = triangulated[tri_index] tri = geoms[color_index]['tri'] tri.addVertices(t[0], t[1], t[2]) for color_index in range(len(self.colors)): geom = geoms[color_index]['geom'] tri = geoms[color_index]['tri'] tri.closePrimitive() geom.addPrimitive(tri) self.geomnode.addGeom(geom) self.color_lookup.append(color_index)
def scan_model(self, instance): stages = instance.findAllTextureStages() stages.sort() #TODO: We assume all the geom have the same texture stage (which is obviously wrong) #Should be done like transparency for all the geoms and create a shader per geom... has_surface = False has_normal = False has_glow = False has_gloss = False for stage in stages: tex = instance.find_texture(stage) if tex: mode = stage.get_mode() #print("FOUND STAGE", stage.name, stage.sort, mode, tex) if mode in (TextureStage.M_modulate, TextureStage.M_modulate_glow, TextureStage.M_modulate_gloss): if not has_surface: self.texture = WrapperTexture(tex) self.texture_index = self.nb_textures self.has_specular_mask = mode == TextureStage.M_modulate_gloss if self.srgb: tex_format = tex.getFormat() if tex_format == Texture.F_rgb: tex.set_format(Texture.F_srgb) elif tex_format == Texture.F_rgba: tex.set_format(Texture.F_srgb_alpha) self.nb_textures += 1 has_surface = True #print("SURFACE", self.texture_index, self.texture) elif mode in (TextureStage.M_normal, TextureStage.M_normal_height, TextureStage.M_normal_gloss): if not has_normal: self.normal_map = WrapperTexture(tex) self.normal_map_index = self.nb_textures self.nb_textures += 1 has_normal = True #print("NORMAL", self.normal_map_index, self.normal_map) elif mode in (TextureStage.M_glow, ): if not has_glow: self.emission_texture = WrapperTexture(tex) self.emission_texture_index = self.nb_textures self.nb_textures += 1 has_glow = True #print("GLOW", self.emission_texture_index, self.emission_texture) elif mode in (TextureStage.M_gloss, ): if not has_gloss: self.gloss_map = WrapperTexture(tex) self.gloss_map_texture_index = self.nb_textures self.nb_textures += 1 has_gloss = True #print("GLOSS", self.gloss_map_texture_index, self.gloss_map) else: print("Unsupported mode %d" % mode) transparency_mode = TransparencyAttrib.M_none for np in instance.find_all_matches('**'): if np.has_transparency(): if transparency_mode != TransparencyAttrib.M_none: print("Overriding transparency config") transparency_mode = np.get_transparency() node = np.node() attrib = node.get_attrib(TransparencyAttrib) if attrib is not None: transparency_mode = attrib.get_mode() if isinstance(node, GeomNode): for geom in node.get_geoms(): vdata = geom.getVertexData() has_tangent = vdata.has_column(InternalName.get_tangent()) has_binormal = vdata.has_column( InternalName.get_binormal()) self.generate_binormal = has_tangent and not has_binormal for state in node.get_geom_states(): attrib = state.get_attrib(TransparencyAttrib) if attrib is not None: transparency_mode = attrib.get_mode() if transparency_mode == TransparencyAttrib.M_none: self.transparency = False self.transparency_blend = TransparencyBlend.TB_None elif transparency_mode == TransparencyAttrib.M_alpha: self.transparency = True self.transparency_level = 0.0 self.transparency_blend = TransparencyBlend.TB_Alpha elif transparency_mode == TransparencyAttrib.M_premultiplied_alpha: self.transparency = True self.transparency_level = 0.0 self.transparency_blend = TransparencyBlend.TB_PremultipliedAlpha elif transparency_mode == TransparencyAttrib.M_binary: self.transparency = True self.transparency_level = 0.5 self.transparency_blend = TransparencyBlend.TB_None else: print("Unsupported transparency mode", transparency_mode) #Activate transparency anyway self.transparency = True self.transparency_level = 0.0 self.transparency_blend = TransparencyBlend.TB_Alpha self.nb_textures_coord = 1
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")