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 makeGeom(self, points, colors, sizes): #format = GeomVertexFormat.getV3c4() array = GeomVertexArrayFormat() array.addColumn(InternalName.get_vertex(), 3, Geom.NTFloat32, Geom.CPoint) array.addColumn(InternalName.get_color(), 4, Geom.NTFloat32, Geom.CColor) array.addColumn(InternalName.get_size(), 1, Geom.NTFloat32, Geom.COther) format = GeomVertexFormat() format.addArray(array) format = GeomVertexFormat.registerFormat(format) vdata = GeomVertexData('vdata', format, Geom.UH_static) vdata.unclean_set_num_rows(len(points)) self.vwriter = GeomVertexWriter(vdata, InternalName.get_vertex()) self.colorwriter = GeomVertexWriter(vdata, InternalName.get_color()) self.sizewriter = GeomVertexWriter(vdata, InternalName.get_size()) geompoints = GeomPoints(Geom.UH_static) geompoints.reserve_num_vertices(len(points)) index = 0 for (point, color, size) in zip(points, colors, sizes): self.vwriter.addData3f(*point) self.colorwriter.addData4f(*color) self.sizewriter.addData1f(size) geompoints.addVertex(index) #geompoints.closePrimitive() index += 1 geom = Geom(vdata) geom.addPrimitive(geompoints) return geom
def 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 __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 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 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 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): 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 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): 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 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 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 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 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("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 get_render_mesh(self): array = GeomVertexArrayFormat() array.addColumn("vertex", 3, Geom.NTFloat32, Geom.CPoint) array.addColumn("barycenter", 3, Geom.NTFloat32, Geom.CPoint) vertex_format = GeomVertexFormat() vertex_format.addArray(array) vertex_format = GeomVertexFormat.registerFormat(vertex_format) v_data = GeomVertexData('mesh', vertex_format, Geom.UHStatic) v_data.setNumRows(len(self.nodes)) vertex = GeomVertexWriter(v_data, 'vertex') barycenter = GeomVertexWriter(v_data, 'barycenter') prim = GeomTriangles(Geom.UHStatic) vertex_id = 0 for elem in self.elements: def node_coords(e, i): return self.nodes[e.nodes[i]].coordinate vertex.addData3(node_coords(elem, 0).x, node_coords(elem, 0).y, 0) vertex.addData3(node_coords(elem, 1).x, node_coords(elem, 1).y, 0) vertex.addData3(node_coords(elem, 2).x, node_coords(elem, 2).y, 0) barycenter.addData3(1, 0, 0) barycenter.addData3(0, 1, 0) barycenter.addData3(0, 0, 1) prim.addVertices(vertex_id, vertex_id + 1, vertex_id + 2) vertex_id += 3 vertex.addData3(node_coords(elem, 2).x, node_coords(elem, 2).y, 0) vertex.addData3(node_coords(elem, 3).x, node_coords(elem, 3).y, 0) vertex.addData3(node_coords(elem, 0).x, node_coords(elem, 0).y, 0) barycenter.addData3(1, 0, 0) barycenter.addData3(0, 1, 0) barycenter.addData3(0, 0, 1) prim.addVertices(vertex_id, vertex_id + 1, vertex_id + 2) vertex_id += 3 geom = Geom(v_data) geom.addPrimitive(prim) return geom
def create_geometry_from_mesh(mesh): # Define the individual array formats for vertex attributes. vertex_position_format = GeomVertexArrayFormat("vertex", 3, Geom.NT_float32, Geom.C_point) vertex_normal_format = GeomVertexArrayFormat("normal", 3, Geom.NT_float32, Geom.C_normal) vertex_color_format = GeomVertexArrayFormat("color", 4, Geom.NT_uint8, Geom.C_color) # Define the vertex data format with positions and colors. vertex_format = GeomVertexFormat() vertex_format.addArray(vertex_position_format) vertex_format.addArray(vertex_normal_format) vertex_format.addArray(vertex_color_format) vertex_format = GeomVertexFormat.registerFormat(vertex_format) # Populate the vertex position and color arrays. vertex_data = GeomVertexData("mesh_vertices", vertex_format, Geom.UH_static) vertex_data.modifyArrayHandle(0).copyDataFrom( np.array(mesh.positions, dtype=np.float32)) vertex_data.modifyArrayHandle(1).copyDataFrom( np.array(mesh.normals, dtype=np.float32)) vertex_data.modifyArrayHandle(2).copyDataFrom( np.array(mesh.colors, dtype=np.uint8)) # Populate the triangle indices. triangles = GeomTriangles(Geom.UH_static) triangles.setIndexType(Geom.NT_uint32) triangles.modifyVertices().modifyHandle().copyDataFrom( np.array(mesh.triangles, dtype=np.uint32)) geometry = Geom(vertex_data) geometry.add_primitive(triangles) return geometry
def __init__(self): ShowBase.__init__(self) props = WindowProperties() props.setTitle("The Rat Cave") self.win.requestProperties(props) self.win.setClearColor((0.5, 0.5, 0.9, 1.0)) self.disableMouse() self.locked = False lens = PerspectiveLens() lens.set_fov(70) self.cam.node().setLens(lens) self.position = [30, 30, 30] self.velocity = [0, 0, 0] self.setFrameRateMeter(True) self.myFog = Fog("Fog Name") self.myFog.setColor(0.5, 0.5, 0.9) self.myFog.setExpDensity(0.005) render.setFog(self.myFog) #cool bg #b=OnscreenImage(parent=render2d, image="space.png") #base.cam.node().getDisplayRegion(0).setSort(20) render.setAntialias(AntialiasAttrib.MMultisample) debugNode = BulletDebugNode('Debug') debugNode.showWireframe(True) debugNode.showConstraints(True) debugNode.showBoundingBoxes(False) debugNode.showNormals(False) debugNP = render.attachNewNode(debugNode) debugNP.show() self.world = BulletWorld() self.world.setGravity(Vec3(0, 0, -80)) #self.world.setDebugNode(debugNP.node()) loader = Loader(self) myShader = Shader.load(Shader.SL_GLSL, vertex="vertshader.vert", fragment="fragshader.frag") floorMesh = BulletTriangleMesh() texs = [ loader.loadTexture("flatstone.png"), loader.loadTexture("flatstone2.png"), loader.loadTexture("flatgrass.png"), loader.loadTexture("flatgrass2.png"), loader.loadTexture("flatrock.png"), loader.loadTexture("flatrock2.png"), loader.loadTexture("flatsnow.png"), loader.loadTexture("flatsand.png"), loader.loadTexture("flatsand2.png") ] hmap = generator.generate(200, 200, 50, 0.01, 5) groundTypes = [[] for x in range(9)] for thing in hmap: groundTypes[thing[3]].append(thing[0:3]) for i in range(len(groundTypes)): if len(groundTypes[i]) == 0: continue format = GeomVertexFormat.get_v3n3t2() format = GeomVertexFormat.registerFormat(format) vdata = GeomVertexData('name', format, Geom.UHStatic) vdata.setNumRows(3) vertex = GeomVertexWriter(vdata, 'vertex') normal = GeomVertexWriter(vdata, 'normal') texcoord = GeomVertexWriter(vdata, 'texcoord') prim = GeomTriangles(Geom.UHStatic) for grid in groundTypes[i]: v0 = (grid[0][0], grid[0][2], grid[0][1]) vertex.addData3(v0) if grid[1][2] < 0: normal.addData3(grid[1][0], grid[1][2], grid[1][1]) else: normal.addData3(-grid[1][0], -grid[1][2], -grid[1][1]) texcoord.addData2(grid[2][0], grid[2][1]) v1 = (grid[0][3], grid[0][5], grid[0][4]) vertex.addData3(v1) if grid[1][5] < 0: normal.addData3(grid[1][3], grid[1][5], grid[1][4]) else: normal.addData3(-grid[1][3], -grid[1][5], -grid[1][4]) texcoord.addData2(grid[2][2], grid[2][3]) v2 = (grid[0][6], grid[0][8], grid[0][7]) vertex.addData3(v2) if grid[1][8] < 0: normal.addData3(grid[1][6], grid[1][8], grid[1][7]) else: normal.addData3(-grid[1][6], -grid[1][8], -grid[1][7]) texcoord.addData2(grid[2][4], grid[2][5]) floorMesh.addTriangle(v0, v1, v2) prim.add_next_vertices(3) geom = Geom(vdata) geom.addPrimitive(prim) node = GeomNode('gnode') node.addGeom(geom) nodePath = render.attachNewNode(node) nodePath.setTexture(texs[i]) nodePath.setShader(myShader) vdata2 = GeomVertexData('wata', format, Geom.UHStatic) vdata2.setNumRows(3) prim2 = GeomTriangles(Geom.UHStatic) vertex2 = GeomVertexWriter(vdata2, 'vertex') normal2 = GeomVertexWriter(vdata2, 'normal') texcoord2 = GeomVertexWriter(vdata2, 'texcoord') vertex2.addData3((0, 0, 0)) vertex2.addData3((200, 0, 0)) vertex2.addData3((0, 200, 0)) normal2.addData3((0, 0, 1)) normal2.addData3((0, 0, 1)) normal2.addData3((0, 0, 1)) texcoord2.addData2((0, 0)) texcoord2.addData2((1, 0)) texcoord2.addData2((0, 1)) prim2.addNextVertices(3) vertex2.addData3((200, 200, 0)) vertex2.addData3((0, 200, 0)) vertex2.addData3((200, 0, 0)) normal2.addData3((0, 0, 1)) normal2.addData3((0, 0, 1)) normal2.addData3((0, 0, 1)) texcoord2.addData2((1, 1)) texcoord2.addData2((0, 1)) texcoord2.addData2((1, 0)) prim2.addNextVertices(3) water = Geom(vdata2) water.addPrimitive(prim2) waterNode = GeomNode('water') waterNode.addGeom(water) waterNodePath = render.attachNewNode(waterNode) waterNodePath.setTransparency(True) waterNodePath.setTexture(loader.loadTexture("water.png")) floorMeshShape = BulletTriangleMeshShape(floorMesh, dynamic=False) fNode = BulletRigidBodyNode('floor') fNode.addShape(floorMeshShape) self.floorPhysNode = render.attachNewNode(fNode) self.world.attachRigidBody(fNode) for i in range(25): rat = loader.loadModel("deer.obj") rat.setScale((0.003, 0.003, 0.003)) rat.setHpr((0, 90, 0)) rat.setPos((0, 0, -0.8)) rat.setTexture(texs[5]) shape = BulletSphereShape(1) node = BulletRigidBodyNode('ratBox') #node.setAngularFactor((0,0,1)) node.setMass(10.0) node.addShape(shape) node.setActive(False) #node.friction = 1 np = render.attachNewNode(node) np.setPos((i % 5) * 2 + 40, int(i / 5) * 2 + 40, 50) self.world.attachRigidBody(node) rat.flattenLight() rat.reparentTo(np) #posInterval1 = rat.hprInterval(0.1, # Point3(10, 90, 0), # startHpr=Point3(-10, 90, 0)) #posInterval2 = rat.hprInterval(0.1, # Point3(-10, 90, 0), # startHpr=Point3(10,90,0)) #pandaPace = Sequence(posInterval1, posInterval2, # name="pandaPace" + str(i)) #pandaPace.loop() self.ratto = np self.deer = loader.loadModel("rat.obj") self.deer.setScale((0.15, 0.15, 0.15)) self.deer.setHpr((0, 90, 0)) self.deer.setPos((0, 0, -2)) self.deerShape = BulletBoxShape((3, 1, 3)) self.deerNode = BulletRigidBodyNode('deerBox') self.deerNode.setAngularFactor((0, 0, 1)) self.deerNode.setMass(10.0) self.deerNode.setFriction(1) self.deerNode.addShape(self.deerShape) self.deerNodePath = render.attachNewNode(self.deerNode) self.deerNodePath.setPos((30, 30, 130)) self.world.attachRigidBody(self.deerNode) self.deer.reparentTo(self.deerNodePath) self.keyMap = { "w": False, "s": False, "a": False, "d": False, "space": False, "lshift": False, "p": False, "o": False } self.accept("w", self.setKey, ["w", True]) self.accept("s", self.setKey, ["s", True]) self.accept("a", self.setKey, ["a", True]) self.accept("d", self.setKey, ["d", True]) self.accept("space", self.setKey, ["space", True]) self.accept("lshift", self.setKey, ["lshift", True]) self.accept("e", self.lockMouse) self.accept("p", self.setKey, ["p", True]) self.accept("o", self.setKey, ["o", True]) self.accept("w-up", self.setKey, ["w", False]) self.accept("s-up", self.setKey, ["s", False]) self.accept("a-up", self.setKey, ["a", False]) self.accept("d-up", self.setKey, ["d", False]) self.accept("space-up", self.setKey, ["space", False]) self.accept("lshift-up", self.setKey, ["lshift", False]) self.accept("e-up", self.setKey, ["e", False]) self.accept('escape', sys.exit) self.accept("p-up", self.setKey, ["p", False]) self.accept("o-up", self.setKey, ["o", False]) # Add the spinCameraTask procedure to the task manager. self.taskMgr.add(self.cameraControl, "CameraControl") self.camera.setPos(tuple(self.position))
def add_button(self, text, label_id, pos_x, pos_y, width=0.0, hight=0.1): if width == 0.0: for c in range(len(text)/2): width += 0.08 ls = LineSegs("lines") ls.setColor(0,1,0,1) ls.drawTo(-width/2, 0, hight/2) ls.drawTo(width/2, 0, hight/2) ls.drawTo(width/2, 0,-hight/2) ls.drawTo(-width/2, 0,-hight/2) ls.drawTo(-width/2, 0, hight/2) border = ls.create(False) border.setTag('back_ground', '1') array = GeomVertexArrayFormat() array.addColumn("vertex", 4, Geom.NTFloat32, Geom.CPoint) arr_format = GeomVertexFormat() arr_format.addArray(array) arr_format = GeomVertexFormat.registerFormat(arr_format) vdata = GeomVertexData('fill', arr_format, Geom.UHStatic) vdata.setNumRows(4) vertex = GeomVertexWriter(vdata, 'vertex') vertex.addData3f(-width/2, 0, hight/2) vertex.addData3f(width/2, 0, hight/2) vertex.addData3f(-width/2, 0,-hight/2) vertex.addData3f(width/2, 0,-hight/2) prim = GeomTristrips(Geom.UHStatic) prim.addVertex(0) prim.addVertex(1) prim.addVertex(2) prim.addVertex(3) geom = Geom(vdata) geom.addPrimitive(prim) node = GeomNode('gnode') node.addGeom(geom) nodePath = NodePath("button") nodePath.attachNewNode(node) nodePath.setPos(0,0,0) nodePath.setTag('button', '1') nodePath.setBin("unsorted", 0) nodePath.setDepthTest(False) nodePath.setColor(0,0,0,1) nodePath.attachNewNode(border) nodePath1 = NodePath("button") nodePath1.attachNewNode(node) nodePath1.setPos(0,0,0) nodePath1.setTag('button1', '1') nodePath1.setBin("unsorted", 0) nodePath1.setDepthTest(False) nodePath1.setColor(0,1,0,1) nodePath1.attachNewNode(border) button=DirectFrame( enableEdit=1, text=text, geom=nodePath, text_scale=0.05, text_fg=(0,1,0,1), borderWidth=(1,1), relief = None, text_pos=(0,-0.01,0), textMayChange=1, state=DGG.NORMAL, parent=aspect2d ) button.setPos(pos_x,0,pos_y) button.bind(DGG.B1PRESS, button_click, [button]) button.bind(DGG.WITHIN, button_hover, [button]) button.bind(DGG.WITHOUT, button_no_hover, [button]) # button.resetFrameSize() # self.button.bind(DGG.WITHIN, self.onMouseHoverInFunction, [button, some_value1]) defines.ENTITIES[defines.ENTITY_ID] = {'CATEGORY':'button', 'BUTTON':button, 'NODE':nodePath, 'LABEL':label_id,'STATUS': 0} defines.ENTITY_ID += 1
def 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
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 r += step def vector_copy(v): """Utility function to coerce a list or tuple into Vec3 format""" return Vec3(v[0], v[1], v[2]) def point_copy(p):
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
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)
def add_button(self, text, label_id, pos_x, pos_y, width=0.0, hight=0.1): if width == 0.0: for c in range(len(text) / 2): width += 0.08 ls = LineSegs("lines") ls.setColor(0, 1, 0, 1) ls.drawTo(-width / 2, 0, hight / 2) ls.drawTo(width / 2, 0, hight / 2) ls.drawTo(width / 2, 0, -hight / 2) ls.drawTo(-width / 2, 0, -hight / 2) ls.drawTo(-width / 2, 0, hight / 2) border = ls.create(False) border.setTag('back_ground', '1') array = GeomVertexArrayFormat() array.addColumn("vertex", 4, Geom.NTFloat32, Geom.CPoint) arr_format = GeomVertexFormat() arr_format.addArray(array) arr_format = GeomVertexFormat.registerFormat(arr_format) vdata = GeomVertexData('fill', arr_format, Geom.UHStatic) vdata.setNumRows(4) vertex = GeomVertexWriter(vdata, 'vertex') vertex.addData3f(-width / 2, 0, hight / 2) vertex.addData3f(width / 2, 0, hight / 2) vertex.addData3f(-width / 2, 0, -hight / 2) vertex.addData3f(width / 2, 0, -hight / 2) prim = GeomTristrips(Geom.UHStatic) prim.addVertex(0) prim.addVertex(1) prim.addVertex(2) prim.addVertex(3) geom = Geom(vdata) geom.addPrimitive(prim) node = GeomNode('gnode') node.addGeom(geom) nodePath = NodePath("button") nodePath.attachNewNode(node) nodePath.setPos(0, 0, 0) nodePath.setTag('button', '1') nodePath.setBin("unsorted", 0) nodePath.setDepthTest(False) nodePath.setColor(0, 0, 0, 1) nodePath.attachNewNode(border) nodePath1 = NodePath("button") nodePath1.attachNewNode(node) nodePath1.setPos(0, 0, 0) nodePath1.setTag('button1', '1') nodePath1.setBin("unsorted", 0) nodePath1.setDepthTest(False) nodePath1.setColor(0, 1, 0, 1) nodePath1.attachNewNode(border) button = DirectFrame(enableEdit=1, text=text, geom=nodePath, text_scale=0.05, text_fg=(0, 1, 0, 1), borderWidth=(1, 1), relief=None, text_pos=(0, -0.01, 0), textMayChange=1, state=DGG.NORMAL, parent=aspect2d) button.setPos(pos_x, 0, pos_y) button.bind(DGG.B1PRESS, button_click, [button]) button.bind(DGG.WITHIN, button_hover, [button]) button.bind(DGG.WITHOUT, button_no_hover, [button]) # button.resetFrameSize() # self.button.bind(DGG.WITHIN, self.onMouseHoverInFunction, [button, some_value1]) defines.ENTITIES[defines.ENTITY_ID] = { 'CATEGORY': 'button', 'BUTTON': button, 'NODE': nodePath, 'LABEL': label_id, 'STATUS': 0 } defines.ENTITY_ID += 1
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") colorWriter = GeomVertexWriter(vdata, "color") normalWriter = GeomVertexWriter(vdata, "normal") drawReWriter = GeomVertexRewriter(vdata, "drawFlag") texReWriter = GeomVertexRewriter(vdata, "texcoord")
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 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 generate(self, terrain, size, lod=1.0): if self.meshgentype == "marching": mesher = MarchingCubes() elif self.meshgentype == "dual": mesher = DualContour(noise=manager.get('noise')) else: mesher = Voxel() triangles = mesher.generateMesh(terrain, size, lod) #format = GeomVertexFormat.registerFormat(GeomVertexFormat.getV3n3c4t2()) format = GeomVertexFormat.registerFormat(GeomVertexFormat.getV3n3c4()) vdata = GeomVertexData('chunk_mesh', format, Geom.UHStatic) vertex = GeomVertexWriter(vdata, 'vertex') normal = GeomVertexWriter(vdata, 'normal') color = GeomVertexWriter(vdata, 'color') texcoord = GeomVertexWriter(vdata, 'texcoord') prim = GeomTriangles(Geom.UHStatic) vertexcount = 0 for triangle in triangles: for avertex in triangle: #print triangle #make vertices here shade = 0.5 vertex.addData3f(avertex[0], avertex[1], avertex[2]) #fix normals x1, y1, z1 = triangle[0][0], triangle[0][1], triangle[0][2] x2, y2, z2 = triangle[1][0], triangle[1][1], triangle[1][2] x3, y3, z3 = triangle[2][0], triangle[2][1], triangle[2][2] normx = (z1 - z2) * (y3 - y2) - (y1 - y2) * (z3 - z2) normy = (x1 - x2) * (z3 - z2) - (z1 - z2) * (x3 - x2) normz = (y1 - y2) * (x3 - x2) - (x1 - x2) * (y3 - y2) normlength = math.sqrt(normx**2 + normy**2 + normz**2) if normlength != 0: normx /= normlength normy /= normlength normz /= normlength normal.addData3f(normx, normy, normz) color.addData4f(shade, shade, shade, 1) #color.addData4f(random.randrange(0,255), random.randrange(0,255), random.randrange(0,255), 1) #texcoord.addData2f(triangle[0][0] / 16, triangle[0][1] / 16) #texcoord.addData2f(0, 1) #make triangles prim.addVertices(vertexcount, vertexcount + 1, vertexcount + 2) prim.closePrimitive() vertexcount += 3 #print prim #attach primitives and render geom = Geom(vdata) geom.addPrimitive(prim) """try: self.node.removeNode() self.bulletnode.removeShape(self.bulletshape) self.root.bulletworld.removeRigidBody(self.bulletnode) self.bulletnp.removeNode() except AttributeError: pass""" node = GeomNode("terrainmesh") node.addGeom(geom) return node #self.meshed = True """#do bullet meshing
GeomVertexFormat, GeomVertexData, GeomVertexWriter, ) from utils.colour import WHITE from utils.math import * array4 = GeomVertexArrayFormat() array4.addColumn("vertex", 4, Geom.NTFloat32, Geom.COther) array4.addColumn("normal", 4, Geom.NTFloat32, Geom.COther) array4.addColumn("colour", 4, Geom.NTFloat32, Geom.CColor) format4 = GeomVertexFormat() format4.addArray(array4) format4 = GeomVertexFormat.registerFormat(format4) class Mesh4: """ Base class for meshes in R4. Args: vertices :: array_like (N,4) A list of vertex positions in the mesh. normals :: array_like (N,4) Vectors perpendicular to the mesh at each vertex. colours :: array_like (N,4) The colour of each vertex. tetrahedra :: array_like (M,4) A list of indices that group vertices into 4-simplices.
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 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 generate(self, terrain, size, lod=1.0): if self.meshgentype == "marching": mesher = MarchingCubes() elif self.meshgentype == "dual": mesher = DualContour(noise=manager.get('noise')) else: mesher = Voxel() triangles = mesher.generateMesh(terrain, size, lod) #format = GeomVertexFormat.registerFormat(GeomVertexFormat.getV3n3c4t2()) format = GeomVertexFormat.registerFormat(GeomVertexFormat.getV3n3c4()) vdata = GeomVertexData('chunk_mesh', format, Geom.UHStatic) vertex = GeomVertexWriter(vdata, 'vertex') normal = GeomVertexWriter(vdata, 'normal') color = GeomVertexWriter(vdata, 'color') texcoord = GeomVertexWriter(vdata, 'texcoord') prim = GeomTriangles(Geom.UHStatic) vertexcount = 0 for triangle in triangles: for avertex in triangle: #print triangle #make vertices here shade = 0.5 vertex.addData3f(avertex[0], avertex[1], avertex[2]) #fix normals x1, y1, z1 = triangle[0][0], triangle[0][1], triangle[0][2] x2, y2, z2 = triangle[1][0], triangle[1][1], triangle[1][2] x3, y3, z3 = triangle[2][0], triangle[2][1], triangle[2][2] normx = (z1 - z2) * (y3 - y2) - (y1 - y2) * (z3 - z2) normy = (x1 - x2) * (z3 - z2) - (z1 - z2) * (x3 - x2) normz = (y1 - y2) * (x3 - x2) - (x1 - x2) * (y3 - y2) normlength = math.sqrt(normx ** 2 + normy ** 2 + normz ** 2) if normlength != 0: normx /= normlength normy /= normlength normz /= normlength normal.addData3f(normx, normy, normz) color.addData4f(shade, shade, shade, 1) #color.addData4f(random.randrange(0,255), random.randrange(0,255), random.randrange(0,255), 1) #texcoord.addData2f(triangle[0][0] / 16, triangle[0][1] / 16) #texcoord.addData2f(0, 1) #make triangles prim.addVertices(vertexcount, vertexcount + 1, vertexcount + 2) prim.closePrimitive() vertexcount += 3 #print prim #attach primitives and render geom = Geom(vdata) geom.addPrimitive(prim) """try: self.node.removeNode() self.bulletnode.removeShape(self.bulletshape) self.root.bulletworld.removeRigidBody(self.bulletnode) self.bulletnp.removeNode() except AttributeError: pass""" node = GeomNode("terrainmesh") node.addGeom(geom) return node #self.meshed = True """#do bullet meshing
def sample(self, segs, wrap_x=False, wrap_y=False, two_sided=False): self.comp_env.reset() x_segs, y_segs = segs array = GeomVertexArrayFormat() for column_name, column_func in self.comp_env.funcs.items(): dtype = column_func.dtype_out if issubclass(dtype, Vec2): col_type = 2 elif issubclass(dtype, Vec3): col_type = 3 elif issubclass(dtype, Vec4): col_type = 4 array.addColumn( column_name, col_type, Geom.NTFloat32, Geom.CPoint, ) vformat = GeomVertexFormat() vformat.addArray(array) vformat = GeomVertexFormat.registerFormat(vformat) vdata = GeomVertexData("Data", vformat, Geom.UHDynamic) columns = {} for column_name in self.comp_env.outputs: columns[column_name] = GeomVertexWriter(vdata, column_name) geom = Geom(vdata) # Vertices x_vertices = x_segs + 1 y_vertices = y_segs + 1 if wrap_x: x_vertices -= 1 if wrap_y: y_vertices -= 1 for x in range(x_vertices): for y in range(y_vertices): x_norm = float(x) / float(x_segs) y_norm = float(y) / float(y_segs) self.comp_env.set_value('xy', Vec2(x_norm, y_norm)) self.comp_env.compute() for column_name in self.comp_env.outputs: writer = columns[column_name] dtype = self.comp_env.funcs[column_name].dtype_out data = self.comp_env.values[column_name] if issubclass(dtype, Vec2): writer.addData2f(data) elif issubclass(dtype, Vec3): writer.addData3f(data) elif issubclass(dtype, Vec4): writer.addData4f(data) # Triangles tris = GeomTriangles(Geom.UHStatic) for x in range(x_segs): for y in range(y_segs): # v1 v3 # # v0 v2 v_0 = x * y_vertices + y v_1 = x * y_vertices + y + 1 v_2 = (x + 1) * y_vertices + y v_3 = (x + 1) * y_vertices + y + 1 if wrap_x and x == x_segs - 1: v_2 = y v_3 = y + 1 if wrap_y and y == y_segs - 1: v_1 = x * y_vertices v_3 = (x + 1) * y_vertices if wrap_x and x == x_segs - 1 and wrap_y and y == y_segs - 1: v_3 = 0 tris.addVertices(v_0, v_2, v_3) tris.addVertices(v_0, v_3, v_1) if two_sided: tris.addVertices(v_0, v_3, v_2) tris.addVertices(v_0, v_1, v_3) tris.closePrimitive() geom.addPrimitive(tris) node = GeomNode('geom_node') node.addGeom(geom) return node