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 __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 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 __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 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 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 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 __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 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")
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 __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 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
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)
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")
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
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