def __build_Tris(self, sphere, mode): vdata = GeomVertexData("Data", self.__vformat[mode], Geom.UHStatic) _num_rows = len(sphere.pts) # Vertices. vertices = GeomVertexWriter(vdata, "vertex") vertices.reserveNumRows(_num_rows) for pt in sphere.pts: vertices.addData3f(*pt) # Map coords. if mode == "mid": mapcoords = GeomVertexWriter(vdata, "mapcoord") mapcoords.reserveNumRows(_num_rows) for mc in sphere.coords: u, v = mc[:2] mapcoords.addData2f(u,v) # Tris. prim = GeomTriangles(Geom.UHStatic) prim.reserveNumVertices(len(sphere.tris)) for tri in sphere.tris: prim.addVertices(*tri) prim.closePrimitive() # Geom. geom = Geom(vdata) geom.addPrimitive(prim) geom_node = GeomNode("geom") geom_node.addGeom(geom) geom_np = NodePath(geom_node) return geom_np
def newVertexData(self): fmt = GeomVertexFormat.getV3c4() # fmt = GeomVertexFormat.getV3n3c4() self.vertexData = GeomVertexData("path", fmt, Geom.UHStatic) self.vertexWriter = GeomVertexWriter(self.vertexData, "vertex") # self.normalWriter = GeomVertexWriter(self.vertexData, 'normal') self.colorWriter = GeomVertexWriter(self.vertexData, "color")
def _make_fullscreen_tri(self): """ Creates the oversized triangle used for rendering """ vformat = GeomVertexFormat.get_v3() vdata = GeomVertexData("vertices", vformat, Geom.UH_static) vdata.set_num_rows(3) vwriter = GeomVertexWriter(vdata, "vertex") vwriter.add_data3f(-1, 0, -1) vwriter.add_data3f(3, 0, -1) vwriter.add_data3f(-1, 0, 3) gtris = GeomTriangles(Geom.UH_static) gtris.add_next_vertices(3) geom = Geom(vdata) geom.add_primitive(gtris) geom_node = GeomNode("gn") geom_node.add_geom(geom) geom_node.set_final(True) geom_node.set_bounds(OmniBoundingVolume()) tri = NodePath(geom_node) tri.set_depth_test(False) tri.set_depth_write(False) tri.set_attrib(TransparencyAttrib.make(TransparencyAttrib.M_none), 10000) tri.set_color(Vec4(1)) tri.set_bin("unsorted", 10) tri.reparent_to(self._node) self._tri = tri
def addMeshConvexRB(self,vertices, faces,ghost=False,**kw): #step 1) create GeomVertexData and add vertex information format=GeomVertexFormat.getV3() vdata=GeomVertexData("vertices", format, Geom.UHStatic) vertexWriter=GeomVertexWriter(vdata, "vertex") [vertexWriter.addData3f(v[0],v[1],v[2]) for v in vertices] #step 2) make primitives and assign vertices to them tris=GeomTriangles(Geom.UHStatic) [self.setGeomFaces(tris,face) for face in faces] #step 3) make a Geom object to hold the primitives geom=Geom(vdata) geom.addPrimitive(tris) #step 4) create the bullet mesh and node mesh = BulletTriangleMesh() mesh.addGeom(geom) shape = BulletConvexHullShape(mesh, dynamic=not ghost)# if ghost : inodenp = self.worldNP.attachNewNode(BulletGhostNode('Mesh')) else : inodenp = self.worldNP.attachNewNode(BulletRigidBodyNode('Mesh')) inodenp.node().addShape(shape) # inodenp.setPos(0, 0, 0.1) self.setRB(inodenp,**kw) inodenp.setCollideMask(BitMask32.allOn()) self.world.attachRigidBody(inodenp.node()) return inodenp
def __modify_Model(self, field, data): geom = self.node.modifyGeom(0) vdata = geom.modifyVertexData() vwriter = GeomVertexWriter(vdata, field) vwriter.reserveNumRows(len(data)) set_data = self.set_dict[field] for datum in data: set_data(vwriter, *datum) geom.setVertexData(vdata)
def generate(self): '''(Re)generate the entire terrain erasing any current changes''' factor = self.blockSize*self.chunkSize #print "Factor:", factor for terrain in self.terrains: terrain.getRoot().removeNode() self.terrains = [] # Breaking master heightmap into subimages heightmaps = [] self.xchunks = (self.heightfield.getXSize()-1)/factor self.ychunks = (self.heightfield.getYSize()-1)/factor #print "X,Y chunks:", self.xchunks, self.ychunks n = 0 for y in range(0, self.ychunks): for x in range(0, self.xchunks): heightmap = PNMImage(factor+1, factor+1) heightmap.copySubImage(self.heightfield, 0, 0, xfrom = x*factor, yfrom = y*factor) heightmaps.append(heightmap) n += 1 # Generate GeoMipTerrains n = 0 y = self.ychunks-1 x = 0 for heightmap in heightmaps: terrain = GeoMipTerrain(str(n)) terrain.setHeightfield(heightmap) terrain.setBruteforce(self.bruteForce) terrain.setBlockSize(self.blockSize) terrain.generate() self.terrains.append(terrain) root = terrain.getRoot() root.reparentTo(self.root) root.setPos(n%self.xchunks*factor, (y)*factor, 0) # In order to texture span properly we need to reiterate through every vertex # and redefine the uv coordinates based on our size, not the subGeoMipTerrain's root = terrain.getRoot() children = root.getChildren() for child in children: geomNode = child.node() for i in range(geomNode.getNumGeoms()): geom = geomNode.modifyGeom(i) vdata = geom.modifyVertexData() texcoord = GeomVertexWriter(vdata, 'texcoord') vertex = GeomVertexReader(vdata, 'vertex') while not vertex.isAtEnd(): v = vertex.getData3f() t = texcoord.setData2f((v[0]+ self.blockSize/2 + self.blockSize*x)/(self.xsize - 1), (v[1] + self.blockSize/2 + self.blockSize*y)/(self.ysize - 1)) x += 1 if x >= self.xchunks: x = 0 y -= 1 n += 1
def buildGeom(self, meshData): prims = meshData["prims"] vertices = meshData["vertices"] normals = meshData["normals"] texcoords = meshData["texcoords"] vdata = GeomVertexData('mesh', GeomVertexFormat.getV3n3t2(), Geom.UHStatic) vwriter = GeomVertexWriter(vdata, 'vertex') nvwriter = GeomVertexWriter(vdata, 'normal') tvwriter = GeomVertexWriter(vdata, 'texcoord') for i in range(len(vertices)): v = vertices[i] n = normals[i] t = texcoords[i] vwriter.addData3f(v) nvwriter.addData3f(n) tvwriter.addData2f(t) prim = GeomTriangles(Geom.UHStatic) for i in range(len(prims)): A, B, C = prims[i] prim.addVertices(A, B, C) prim.closePrimitive() geom = Geom(vdata) geom.addPrimitive(prim) geomNode = GeomNode('trig') geomNode.addGeom(geom) geomNode.unify(1, True) return geomNode
def draw(self): if self.rendered_mesh != None: self.reset_draw() format=GeomVertexFormat.getV3n3cp() vdata=GeomVertexData('tri', format, Geom.UHDynamic) vertex=GeomVertexWriter(vdata, 'vertex') normal=GeomVertexWriter(vdata, 'normal') color=GeomVertexWriter(vdata, 'color') v_mapping = {} i=0 for v in self.verts.values(): vertex.addData3f(v.pos.x,v.pos.y,v.pos.z) normal.addData3f(v.norm.x, v.norm.y, v.norm.z) color.addData4f(v.color[0],v.color[1],v.color[2],v.color[3]) v_mapping[v.ID] = i i += 1 mesh = Geom(vdata) for f in self.faces.values(): tri = GeomTriangles(Geom.UHDynamic) tri.addVertex(v_mapping[f.v1.ID]) tri.addVertex(v_mapping[f.v2.ID]) tri.addVertex(v_mapping[f.v3.ID]) tri.closePrimitive() mesh.addPrimitive(tri) snode = GeomNode(self.name) snode.addGeom(mesh) self.rendered_mesh = render.attachNewNode(snode) self.rendered_mesh.setTwoSided(True)
def makeRotationGeomNode(): vdata = GeomVertexData('rotHandleData', GeomVertexFormat.getV3(), Geom.UHStatic) v = GeomVertexWriter(vdata, 'vertex') radius = 0.7 width = 0.08 res = 30 innerRad = radius - width for i in xrange(res): theta = i*(2*pi/res) v.addData3f(innerRad*sin(theta), innerRad*cos(theta), width/2.0) v.addData3f(innerRad*sin(theta), innerRad*cos(theta), -width/2.0) v.addData3f(radius*sin(theta), radius*cos(theta), width/2.0) v.addData3f(radius*sin(theta), radius*cos(theta), -width/2.0) circle = Geom(vdata) # Make prims for the faces of the torus faces = [GeomTristrips(Geom.UHStatic) for i in xrange(4)] for i in xrange(res): i = i*4 faces[0].addVertices(i + 1, i) faces[1].addVertices(i + 2, i + 1) faces[2].addVertices(i + 3, i + 2) faces[3].addVertices(i, i + 3) for i in xrange(4): faces[i].addVertices((i + 1) % 4, i) faces[i].closePrimitive() circle.addPrimitive(faces[i]) node = GeomNode('geomnode') node.addGeom(circle) return node
def add_plane(map_width, map_height): # Prepare the vertex format writers v_fmt = GeomVertexFormat.getV3n3c4() v_data = GeomVertexData('TerrainData', v_fmt, Geom.UHStatic) vertex = GeomVertexWriter(v_data, 'vertex') normal = GeomVertexWriter(v_data, 'normal') color = GeomVertexWriter(v_data, 'color') #texcoord = GeomVertexWriter(v_data, 'texcoord') # Create a primitive prim = GeomTrifans(Geom.UHStatic) poly_color = (uniform(0, 0.05), uniform(0, 0.5), uniform(0.5, 1), 0.5, ) for i, point in enumerate([ (-map_width/2, -map_height/2), (map_width/2, -map_height/2), (map_width/2, map_height/2), (-map_width/2, map_height/2), ]): x, y = point vertex.addData3f(x, y, 0) normal.addData3f(0, 0, 1) color.addData4f(*poly_color) #texcoord.addData2f(1, 0) prim.addVertex(i) prim.addVertex(0) prim.closePrimitive() # Add to the scene graph geom = Geom(v_data) geom.addPrimitive(prim) node = GeomNode('gnode') node.addGeom(geom) nodePath = render.attachNewNode(node) nodePath.setTwoSided(True) nodePath.setAlphaScale(0.5)
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 clearMesh(self): #if self.np: # self.np.remove() self.node.removeAllGeoms() self.vdata = GeomVertexData ('name', self.format, Geom.UHStatic) self.vWriter = GeomVertexWriter (self.vdata, 'vertex') self.cWriter = GeomVertexWriter (self.vdata, 'color') self.geom = Geom(self.vdata) #self.node = GeomNode("lines") self.node.addGeom(self.geom)
def drawBody(self, pos, quat, radius=1,UVcoord=(1,1), numVertices=_polySize): # if isRoot: # self.bodydata = GeomVertexData("body vertices", GeomVertexFormat.getV3n3t2(), Geom.UHStatic) vdata = self.bodydata circleGeom = Geom(vdata) # this was originally a copy of all previous geom in vdata... vertWriter = GeomVertexWriter(vdata, "vertex") #colorWriter = GeomVertexWriter(vdata, "color") normalWriter = GeomVertexWriter(vdata, "normal") # drawReWriter = GeomVertexRewriter(vdata, "drawFlag") texReWriter = GeomVertexRewriter(vdata, "texcoord") startRow = vdata.getNumRows() vertWriter.setRow(startRow) #colorWriter.setRow(startRow) normalWriter.setRow(startRow) texReWriter.setRow(startRow) #axisAdj=Mat4.rotateMat(45, axis)*Mat4.scaleMat(radius)*Mat4.translateMat(pos) perp1 = quat.getRight() perp2 = quat.getForward() #TODO: PROPERLY IMPLEMENT RADIAL NOISE #vertex information is written here angleSlice = 2 * pi / numVertices currAngle = 0 for i in xrange(numVertices+1): adjCircle = pos + (perp1 * cos(currAngle) + perp2 * sin(currAngle)) * radius * (.5+bNodeRadNoise*random.random()) normal = perp1 * cos(currAngle) + perp2 * sin(currAngle) normalWriter.addData3f(normal) vertWriter.addData3f(adjCircle) texReWriter.addData2f(float(UVcoord[0]*i) / numVertices,UVcoord[1]) # UV SCALE HERE! #colorWriter.addData4f(0.5, 0.5, 0.5, 1) currAngle += angleSlice #we cant draw quads directly so we use Tristrips if (startRow != 0): lines = GeomTristrips(Geom.UHStatic) for i in xrange(numVertices+1): lines.addVertex(i + startRow) lines.addVertex(i + startRow - numVertices-1) lines.addVertex(startRow) lines.addVertex(startRow - numVertices) lines.closePrimitive() #lines.decompose() circleGeom.addPrimitive(lines) circleGeomNode = GeomNode("Debug") circleGeomNode.addGeom(circleGeom) self.numPrimitives += numVertices * 2 self.bodies.attachNewNode(circleGeomNode) return circleGeomNode
def __modify_Model(self, field, data): set_dict = { 'vertex':GeomVertexWriter.setData3f, 'normal':GeomVertexWriter.setData3f, 'color':GeomVertexWriter.setData4f, 'texcoord':GeomVertexWriter.setData2f, 'info':GeomVertexWriter.setData4f, 'ref':GeomVertexWriter.setData3f, 'nbr':GeomVertexWriter.setData4i} geom = self.NP.node().modifyGeom(0) vdata = geom.modifyVertexData() vwriter = GeomVertexWriter(vdata, field) vwriter.reserveNumRows(len(data)) set_data = set_dict[field] for datum in data: set_data(vwriter, *datum) geom.setVertexData(vdata)
def makeNode(self, pointmap=(lambda x, y: (x, y, 0))): vt = tuple(self.vertices) t = Triangulator() fmt = GeomVertexFormat.getV3() vdata = GeomVertexData('name', fmt, Geom.UHStatic) vertex = GeomVertexWriter(vdata, 'vertex') for x, y in vt: t.addPolygonVertex(t.addVertex(x, y)) vertex.addData3f(pointmap(x, y)) t.triangulate() prim = GeomTriangles(Geom.UHStatic) for n in xrange(t.getNumTriangles()): prim.addVertices(t.getTriangleV0(n),t.getTriangleV1(n),t.getTriangleV2(n)) prim.closePrimitive() geom = Geom(vdata) geom.addPrimitive(prim) node = GeomNode('gnode') node.addGeom(geom) return node
def 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, name = 'Mesh'): ''' Constructor ''' self.name = name self.finished = False self.format = GeomVertexFormat.getV3n3c4() self.vertexData = GeomVertexData(name, self.format, Geom.UHStream) self.mesh = Geom(self.vertexData) self.triangles = GeomTriangles(Geom.UHStream) self.triangleData = self.triangles.modifyVertices() self.vertex = GeomVertexWriter(self.vertexData, 'vertex') self.normal = GeomVertexWriter(self.vertexData, 'normal') self.color = GeomVertexWriter(self.vertexData, 'color') #self.texcoord = GeomVertexWriter(self.vertexData, 'texcoord') self.faceCount = 0
def __init__(self, name = 'Mesh'): self.name = name self.finished = False self.format = GeomVertexFormat.getV3c4t2() #print self.format self.vertexData = GeomVertexData(name, self.format, Geom.UHStatic) self.vertexData.setNumRows(26136) self.mesh = Geom(self.vertexData) self.triangles = GeomTriangles(Geom.UHStatic) self.triangleData = self.triangles.modifyVertices() self.triangleData.setNumRows(26136) self.vertex = GeomVertexWriter(self.vertexData, 'vertex') self.normal = GeomVertexWriter(self.vertexData, 'normal') self.color = GeomVertexWriter(self.vertexData, 'color') self.texcoord = GeomVertexWriter(self.vertexData, 'texcoord') self.faceCount = 0
def __build_Star_Sphere(self, bg_stars): from panda3d.core import GeomVertexWriter, GeomVertexFormat, GeomVertexData from panda3d.core import Geom, GeomNode, GeomPoints, AmbientLight self.star_sphere_np.removeNode() # Fill GeomVertexData. vformat = GeomVertexFormat.getV3c4() vdata = GeomVertexData("Data", vformat, Geom.UHStatic) vertices = GeomVertexWriter(vdata, "vertex") colours = GeomVertexWriter(vdata, "color") for coords in bg_stars: x, y, z = coords vertices.addData3f(x, y, z) colours.addData4f(1, 1, 1, 1) # Render bg stars. bg_stars = GeomPoints(Geom.UHStatic) bg_stars.addNextVertices(_env.STAR_COUNT) bg_stars_geom = Geom(vdata) bg_stars_geom.addPrimitive(bg_stars) star_sphere = GeomNode("star_sphere") star_sphere.addGeom(bg_stars_geom) star_sphere_np = NodePath(star_sphere) star_sphere_np.reparentTo(self.NP) return star_sphere_np
def makePoints(n=1000): """ make a cloud of points that are a single node VS branching and making subnodes to control display """ #points = np.random.uniform(-10,10,(n,4)) points = np.random.randn(n,3) colors = np.random.rand(n,4) fmt = GeomVertexFormat.getV3c4() #3 component vertex, w/ 4 comp color vertexData = GeomVertexData('points', fmt, Geom.UHStatic) verts = GeomVertexWriter(vertexData, 'vertex') color = GeomVertexWriter(vertexData, 'color') for point,clr4 in zip(points,colors): #for point in points: verts.addData3f(*point) #color.addData4f(*point) color.addData4f(*clr4) #color.addData4f(.1,.1,.1,1) #pointCloud = GeomLinestrips(Geom.UHStatic) #this is f*****g cool! pointCloud = GeomTristrips(Geom.UHStatic) #this is f*****g cool! #pointCloud = GeomPoints(Geom.UHStatic) #pointCloud.addVerticies(*range(n)) pointCloud.addConsecutiveVertices(0,n) #warning may error since n-1? pointCloud.closePrimitive() cloud = Geom(vertexData) cloud.addPrimitive(pointCloud) return cloud
def makeGeom(): # Vertex data fmt = GeomVertexFormat.getV3n3t2() vdata = GeomVertexData('', fmt, Geom.UHStatic) vertex = GeomVertexWriter(vdata, InternalName.getVertex()) normal = GeomVertexWriter(vdata, InternalName.getNormal()) texcoord = GeomVertexWriter(vdata, InternalName.getTexcoord()) for (x, y, z) in vertices: vertex.addData3f(x, y, z) normal.addData3f(0, 0, 0) # Privitive prim = GeomTriangles(Geom.UHStatic) for (i1, i2, i3) in indices: prim.addVertices(i1, i2, i3) prim.closePrimitive() # Geom geom = Geom(vdata) geom.addPrimitive(prim) return geom
def makeClickableGeom(): vdata = GeomVertexData('handleData', GeomVertexFormat.getV3(), Geom.UHStatic) v = GeomVertexWriter(vdata, 'vertex') length = 1.0 cylRad = 0.10 circRes = 8 # Add vertices cylinder. for z in [length/2.0, -length/2.0]: for i in xrange(circRes): theta = i*(2*pi/circRes) v.addData3f(cylRad*sin(theta), cylRad*cos(theta), z) geom = Geom(vdata) # Make polys for the circles CCW = 1 CW = 0 for i, wind in ((0, CCW), (circRes, CW)): circle = GeomTristrips(Geom.UHStatic) l = range(i, i+circRes) for i in xrange(1-wind, (len(l)-wind)/2): l.insert(2*i+wind, l.pop()) for v in l: circle.addVertex(v) circle.closePrimitive() geom.addPrimitive(circle) # Make polys for the cylinder. cyl = GeomTristrips(Geom.UHStatic) for i in xrange(circRes): cyl.addVertex(i + circRes) cyl.addVertex(i) cyl.addVertex(circRes) cyl.addVertex(0) cyl.closePrimitive() geom.addPrimitive(cyl) node = GeomNode('geomnode') node.addGeom(geom) return node
def makeSelectRect(): ctup = (1,1,1,1) fmt = GeomVertexFormat.getV3c4() vertexData = GeomVertexData('points', fmt, Geom.UHDynamic) points = ( #makes nice for Tristrips (0,0,0), (0,0,1), (1,0,0), (1,0,1), ) verts = GeomVertexWriter(vertexData, 'vertex') color = GeomVertexWriter(vertexData, 'color') for point in points: verts.addData3f(*point) color.addData4f(*ctup) boxLines = GeomLinestrips(Geom.UHDynamic) boxLines.addVertices(0,1,3,2) boxLines.addVertex(0) boxLines.closePrimitive() boxTris = GeomTristrips(Geom.UHDynamic) boxTris.addConsecutiveVertices(0,3) boxTris.closePrimitive() box = Geom(vertexData) box.addPrimitive(boxLines) #box.addPrimitive(boxTris) return box
class VertexDataWriter (object): def __init__(self, vdata): self.count = 0 self.vertex = GeomVertexWriter(vdata, 'vertex') self.normal = GeomVertexWriter(vdata, 'normal') self.color = GeomVertexWriter(vdata, 'color') self.texcoord = GeomVertexWriter(vdata, 'texcoord') def add_vertex(self, point, normal, color, texcoord): self.vertex.add_data3f(point) self.normal.add_data3f(normal) self.color.add_data4f(*color) self.texcoord.add_data2f(*texcoord) self.count += 1
def projectVerticesToShadow(self): inVertices=self.unmodifiedVertexData modelWorldX=self.modelWorldX modelWorldY=self.modelWorldY modelWorldZ=self.modelWorldZ zRotationDegrees=self.modelRotation lightWorldX=self.lightWorldX lightWorldY=self.lightWorldY lightWorldZ=self.lightWorldZ zRotationRadians=zRotationDegrees*(math.pi/180.0) mathCosZRotationRadians=math.cos(zRotationRadians) mathSinZRotationRadians=math.sin(zRotationRadians) vdata=self.pandaVertexData vertex = GeomVertexWriter(vdata, 'vertex') for inVertex in inVertices: vertexModelX,vertexModelY,vertexModelZ=inVertex vertexModelOldX=vertexModelX vertexModelOldY=vertexModelY vertexModelX=vertexModelOldX*mathCosZRotationRadians-vertexModelOldY*mathSinZRotationRadians vertexModelY=vertexModelOldX*mathSinZRotationRadians+vertexModelOldY*mathCosZRotationRadians vertexWorldX=modelWorldX+vertexModelX vertexWorldY=modelWorldY+vertexModelY vertexWorldZ=modelWorldZ+vertexModelZ vertexLightZDiff=vertexWorldZ-lightWorldZ shadowVertexX=lightWorldX+((vertexWorldX-lightWorldX)*-lightWorldZ/vertexLightZDiff) shadowVertexY=lightWorldY+((vertexWorldY-lightWorldY)*-lightWorldZ/vertexLightZDiff) normalisedShadowVertexX=shadowVertexX-modelWorldX normalisedShadowVertexY=shadowVertexY-modelWorldY normalisedShadowVertexZ=0 vertex.setData3f(normalisedShadowVertexX,normalisedShadowVertexY,normalisedShadowVertexZ)
def line (self, start, end): # since we're doing line segments, just vertices in our geom format = GeomVertexFormat.getV3() # build our data structure and get a handle to the vertex column vdata = GeomVertexData ('', format, Geom.UHStatic) vertices = GeomVertexWriter (vdata, 'vertex') # build a linestrip vertex buffer lines = GeomLinestrips (Geom.UHStatic) vertices.addData3f (start[0], start[1], start[2]) vertices.addData3f (end[0], end[1], end[2]) lines.addVertices (0, 1) lines.closePrimitive() geom = Geom (vdata) geom.addPrimitive (lines) # Add our primitive to the geomnode #self.gnode.addGeom (geom) return geom
def makeGrid(rng = 1000, spacing = 10): #FIXME make this scale based on zoom??? ctup = (.3,.3,.3,1) xs = range(-rng,rng+1,spacing) ys = xs fmt = GeomVertexFormat.getV3c4() #3 component vertex, w/ 4 comp color #fmt = GeomVertexFormat.getV3() #3 component vertex, w/ 4 comp color vertexData = GeomVertexData('points', fmt, Geom.UHStatic) verts = GeomVertexWriter(vertexData, 'vertex') color = GeomVertexWriter(vertexData, 'color') for i,d in enumerate(xs): switch1 = (-1) ** i * rng switch2 = (-1) ** i * -rng #print(d,switch1,0) verts.addData3f(d, switch1, 0) verts.addData3f(d, switch2, 0) color.addData4f(*ctup) color.addData4f(*ctup) for i,d in enumerate(ys): switch1 = (-1) ** i * rng switch2 = (-1) ** i * -rng verts.addData3f(switch1, d, 0) verts.addData3f(switch2, d, 0) color.addData4f(*ctup) color.addData4f(*ctup) gridLines = GeomLinestrips(Geom.UHStatic) gridLines.addConsecutiveVertices(0, vertexData.getNumRows()) gridLines.closePrimitive() grid = Geom(vertexData) grid.addPrimitive(gridLines) return grid
def __init__(self, name): self.name = name self.poly_groups = [] # GeomVertexFormats # # GeomVertexFormat.getV3cpt2() - vertex, color, uv # GeomVertexFormat.getV3t2() - vertex, uv # GeomVertexFormat.getV3cp() - vertex, color # GeomVertexFormat.getV3n3t2() - vertex, normal, uv # GeomVertexFormat.getV3n3cpt2()- vertex, normal, rgba, uv # textured self.vdata = GeomVertexData(name, GeomVertexFormat.getV3n3cpt2(), Geom.UHStatic) # plain color filled polys # self.vdata = GeomVertexData(name, GeomVertexFormat.getV3cp(), Geom.UHStatic) self.vertex = GeomVertexWriter(self.vdata, 'vertex') self.vnormal = GeomVertexWriter(self.vdata, 'normal') self.color = GeomVertexWriter(self.vdata, 'color') self.texcoord = GeomVertexWriter(self.vdata, 'texcoord') self.root = NodePath(PandaNode(name+'_mesh'))
def createPlane(width,height): format=GeomVertexFormat.getV3() vdata=GeomVertexData("vertices", format, Geom.UHStatic) vertexWriter=GeomVertexWriter(vdata, "vertex") vertexWriter.addData3f(0,0,0) vertexWriter.addData3f(width,0,0) vertexWriter.addData3f(width,height,0) vertexWriter.addData3f(0,height,0) #step 2) make primitives and assign vertices to them tris=GeomTriangles(Geom.UHStatic) #have to add vertices one by one since they are not in order tris.addVertex(0) tris.addVertex(1) tris.addVertex(3) #indicates that we have finished adding vertices for the first triangle. tris.closePrimitive() #since the coordinates are in order we can use this convenience function. tris.addConsecutiveVertices(1,3) #add vertex 1, 2 and 3 tris.closePrimitive() #step 3) make a Geom object to hold the primitives squareGeom=Geom(vdata) squareGeom.addPrimitive(tris) #now put squareGeom in a GeomNode. You can now position your geometry in the scene graph. squareGN=GeomNode("square") squareGN.addGeom(squareGeom) terrainNode = NodePath("terrNode") terrainNode.reparentTo(render) terrainNode.attachNewNode(squareGN) terrainNode.setX(-width/2) texGrass = loader.loadTexture("textures/envir-ground.jpg") terrainNode.setTexture(texGrass)
def 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")
class Moon(PandaNode): def __init__(self, base_object): PandaNode.__init__(self, "Moon") self.geom = GeomNode("Moon") self.vertexData = GeomVertexData("Basis", GeomVertexFormat.getV3cpt2(), Geom.UHStatic) self.vertex = GeomVertexWriter(self.vertexData, 'vertex') self.tex_coord = GeomVertexWriter(self.vertexData, 'texcoord') self.mesh = Geom(self.vertexData) self.tris = GeomTristrips(Geom.UHStatic) size = 700 z = 1000 dx = 0 dy = 500 self.vertex.addData3f(z, size + dx, -size + dy) self.tex_coord.addData2f(1.0, 0.0) self.vertex.addData3f(z, -size + dx, -size + dy) self.tex_coord.addData2f(1.0, 1.0) self.vertex.addData3f(z, size + dx, size + dy) self.tex_coord.addData2f(0.0, 0.0) self.vertex.addData3f(z, -size + dx, size + dy) self.tex_coord.addData2f(0.0, 1.0) self.tris.add_vertices(0, 1, 2, 3) self.tris.closePrimitive() self.mesh.addPrimitive(self.tris) self.geom.addGeom(self.mesh) self.node = base_object.render.attachNewNode(self.geom) self.node.set_p(90) # self.node.set_r(-90) # self.node.set_h(90) # self.node.set_p(90) # self.node.set_scale(500) # self.node.set_pos(1.7 * self.node.get_scale()[0], # 0, # self.node.get_scale()[0] * 0.5) self.texture = base_object.loader.loadTexture( base_object.params("moon_texture")) self.node.set_texture(self.texture) self.node.setLightOff() self.node.setColorOff() self.node.setTransparency(True) self.node.set_bin('fixed', 2) self.node.set_depth_write(0) self.node.set_depth_test(0) # self.node.lookAt(0, 0, 0) def move(self, dx): self.node.set_pos(self.node.get_pos() + dx)
def gpugemsTerrain(): W, H, D = (1,1,2) noise = PerlinNoise3(1,1,1,256,0) warpNoise = PerlinNoise3(1,1,1,256,1) # noise = PerlinNoise3() # warpNoise = PerlinNoise3() def densityFunction(x, y, z): point = LVecBase3f(x, y, z) warpfactor = 0.0004 warp = warpNoise(LVecBase3f(x*warpfactor, y*warpfactor, z*warpfactor)) * 8 point.componentwiseMult(LVecBase3f(warp, warp, warp)) density = -point.z floor = 4 ω = [16.03, 8.05, 4.03, 1.96, 1.01, 0.49, 0.23, 0.097] # frequencies A = [0.25, 0.25, 0.5, 0.5, 1, 2, 8, 32] # amplitudes for i in range(len(ω)): ωVec = LVecBase3f(ω[i], ω[i], ω[i]) ωVec.componentwiseMult(point) density += noise(ωVec) * A[i] density += max(min((floor - point.z)*3, 1), 0)*40; return density def casePoint(density): if density < 0: return 0 else: return 1 g = 1 # granularity chunk = [[[ [[[densityFunction((x+32*w)/g, (y+32*h)/g, (z+32*d)/g) for x in range(33)] for y in range(33)] for z in range(33)] for w in range(W)] for h in range(H)] for d in range(D)] vdata = GeomVertexData('Land', GeomVertexFormat.get_v3n3c4(), Geom.UHStatic) vdata.setNumRows(33*33*4) vertices = GeomVertexWriter(vdata, 'vertex') normals = GeomVertexWriter(vdata, 'normal') colors = GeomVertexWriter(vdata, 'color') waterNoise = PerlinNoise2() ct = 0 for h in range(H): for w in range(W): for d in range(D): # bigger! for z in range(32): for y in range(32): for x in range(32): v0 = chunk[d][h][w][z+1][y][x] v1 = chunk[d][h][w][z][y][x] v2 = chunk[d][h][w][z][y][x+1] v3 = chunk[d][h][w][z+1][y][x+1] v4 = chunk[d][h][w][z+1][y+1][x] v5 = chunk[d][h][w][z][y+1][x] v6 = chunk[d][h][w][z][y+1][x+1] v7 = chunk[d][h][w][z+1][y+1][x+1] case = casePoint(chunk[d][h][w][z+1][y][x])\ + 2*casePoint(chunk[d][h][w][z][y][x])\ + 4*casePoint(chunk[d][h][w][z][y][x+1])\ + 8*casePoint(chunk[d][h][w][z+1][y][x+1])\ + 16*casePoint(chunk[d][h][w][z+1][y+1][x])\ + 32*casePoint(chunk[d][h][w][z][y+1][x])\ + 64*casePoint(chunk[d][h][w][z][y+1][x+1])\ + 128*casePoint(chunk[d][h][w][z+1][y+1][x+1])\ if case == 0 or case == 255: continue numpolys = TABLE['case_to_numpolys'][case][0] for polyIndex in range(numpolys): edgeConnects = TABLE['g_triTable'][case][polyIndex] currentTriangleVertices = [] currentTriangleColors = [] for edgeIndex in range(3): edge = edgeConnects[edgeIndex] X = x+32*w Y = y+32*h Z = z+32*d scale = 1 X = scale*X Y = scale*Y Z = scale*Z ph = min(1, (d*32+z)/32) # point height ph = ph*ph*ph color = None # if d == 0 and z <= 7: # v = waterNoise.noise(LVecBase2f(X, Y)) # b= 1 - v**2 # if b > 0.99: # color = [0.12, 0.29, b, 1] if edge == 0: diff = abs(v0)/(abs(v0)+abs(v1)) diff = scale * diff currentTriangleVertices.append([X, Y, Z-diff]) if color is None: color = [0.49+0.51*ph, 0.84+0.16*ph, 0.06+0.94*ph, 1] currentTriangleColors.append(color) elif edge == 1: diff = abs(v1)/(abs(v1)+abs(v2)) diff = scale * diff currentTriangleVertices.append([X+diff, Y, Z-scale]) currentTriangleColors.append([0.89, 0.17, 0.1, 1]) elif edge == 2: diff = abs(v3)/(abs(v3)+abs(v2)) diff = scale * diff currentTriangleVertices.append([X+scale, Y, Z-diff]) if color is None: color = [0.49+0.51*ph, 0.84+0.16*ph, 0.06+0.94*ph, 1] currentTriangleColors.append(color) elif edge == 3: diff = abs(v0)/(abs(v0)+abs(v3)) diff = scale * diff currentTriangleVertices.append([X+diff, Y, Z]) currentTriangleColors.append([0.89, 0.17, 0.1, 1]) elif edge == 4: diff = abs(v4)/(abs(v4)+abs(v5)) diff = scale * diff currentTriangleVertices.append([X, Y+scale, Z-diff]) if color is None: color = [0.49+0.51*ph, 0.84+0.16*ph, 0.06+0.94*ph, 1] currentTriangleColors.append(color) elif edge == 5: diff = abs(v5)/(abs(v5)+abs(v6)) diff = scale * diff currentTriangleVertices.append([X+diff, Y+scale, Z-scale]) currentTriangleColors.append([0.89, 0.17, 0.1, 1]) elif edge == 6: diff = abs(v7)/(abs(v7)+abs(v6)) diff = scale * diff currentTriangleVertices.append([X+scale, Y+scale, Z-diff]) if color is None: color = [0.49+0.51*ph, 0.84+0.16*ph, 0.06+0.94*ph, 1] currentTriangleColors.append(color) elif edge == 7: diff = abs(v4)/(abs(v4)+abs(v7)) diff = scale * diff currentTriangleVertices.append([X+diff, Y+scale, Z]) currentTriangleColors.append([0.89, 0.17, 0.1, 1]) elif edge == 8: diff = abs(v0)/(abs(v0)+abs(v4)) diff = scale * diff currentTriangleVertices.append([X, Y+diff, Z]) currentTriangleColors.append([0.89, 0.34, 0.1, 1]) elif edge == 9: diff = abs(v1)/(abs(v1)+abs(v5)) diff = scale * diff currentTriangleVertices.append([X, Y+diff, Z-scale]) currentTriangleColors.append([0.89, 0.34, 0.1, 1]) elif edge == 10: diff = abs(v2)/(abs(v2)+abs(v6)) diff = scale * diff currentTriangleVertices.append([X+scale, Y+diff, Z-scale]) currentTriangleColors.append([0.89, 0.34, 0.1, 1]) elif edge == 11: diff = abs(v3)/(abs(v3)+abs(v7)) diff = scale * diff currentTriangleVertices.append([X+scale, Y+diff, Z]) currentTriangleColors.append([0.89, 0.34, 0.1, 1]) a = currentTriangleVertices[0] b = currentTriangleVertices[1] c = currentTriangleVertices[2] ba = LVecBase3f(b[0]-a[0], b[1]-a[1], b[2]-a[2]) ca = LVecBase3f(c[0]-a[0], c[1]-a[1], c[2]-a[2]) normal = ba.cross(ca).normalized() for i in range(3): ct += 1 cv = currentTriangleVertices[i] cn = normal cc = currentTriangleColors[i] vertices.addData3f(cv[0], cv[1], cv[2]) normals.addData3f(cn[0], cn[1], cn[2]) colors.addData4f(cc[0], cc[1], cc[2], cc[3])
def create_profile(self): """ Creates the necessary rendering geometry to render the 3d rendition of an IBeam profile. """ beam = self.beam s = self.s prof = beam.profile c_1 = (0.25882353, 0.80784314, 0.95686275, 1) c_2 = (0.19607843, 0.63529412, 0.75686275, 1) fmt = GeomVertexFormat.getV3n3c4() vertexData = GeomVertexData('I prof', fmt, Geom.UHStatic) vertexData.setNumRows(108) vertices = GeomVertexWriter(vertexData, 'vertex') normals = GeomVertexWriter(vertexData, 'normal') colors = GeomVertexWriter(vertexData, 'color') T = beam.elements[0].trans_matrix[:3, :3] b_0 = np.array([beam.x[0], beam.y[0], beam.z[0]]) / s b_l = np.array([beam.x[-1], beam.y[-1], beam.z[-1]]) / s points = np.array([[0, prof.b / 2, -prof.h / 2], [0, -prof.b / 2, -prof.h / 2], [0, -prof.b / 2, -prof.h / 2 + prof.t_f], [0, -prof.t_w / 2, -prof.h / 2 + prof.t_f], [0, prof.t_w / 2, -prof.h / 2 + prof.t_f], [0, prof.b / 2, -prof.h / 2 + prof.t_f] ]) / s R = np.array([[1, 0, 0], [0, -1, 0], [0, 0, -1]]) ps = None for p in points: if ps is None: ps = np.reshape(np.dot(R, p), (1, 3)) else: ps = np.append(ps, np.reshape(np.dot(R, p), (1, 3)), axis=0) points = np.append(points, ps, axis=0) ps = None for p in points: if ps is None: ps = np.reshape(b_0 + np.dot(T.T, p), (1, 3)) else: ps = np.append(ps, np.reshape(b_0 + np.dot(T.T, p), (1, 3)), axis=0) pe = None for p in points: if pe is None: pe = np.reshape(b_l + np.dot(T.T, p), (1, 3)) else: pe = np.append(pe, np.reshape(b_l + np.dot(T.T, p), (1, 3)), axis=0) points = np.append(ps, pe, axis=0) surfs = np.array([[0, 1, 2, c_1], [0, 2, 5, c_1], # front [4, 3, 10, c_1], [4, 10, 9, c_1], [8, 11, 6, c_1], [8, 6, 7, c_1], [12, 0, 5, c_1], [12, 5, 17, c_1], # t./b. sides [1, 13, 14, c_1], [1, 14, 2, c_1], [11, 23, 18, c_1], [11, 18, 6, c_1], [20, 8, 7, c_1], [20, 7, 19, c_1], [16, 4, 9, c_2], [16, 9, 21, c_2], # Mid sides [3, 15, 22, c_2], [3, 22, 10, c_2], [13, 12, 17, c_1], [13, 17, 14, c_1], # Back [15, 16, 21, c_1], [15, 21, 22, c_1], [23, 20, 19, c_1], [23, 19, 18, c_1], [7, 6, 18, c_1], [7, 18, 19, c_1], # T. t. fl. [9, 8, 20, c_1], [9, 20, 21, c_1], # In. t. fl. l [11, 10, 22, c_1], [11, 22, 23, c_1], # In. t. fl. r [5, 4, 16, c_1], [5, 16, 17, c_1], # In. b. fl. l. [3, 2, 14, c_1], [3, 14, 15, c_1], # In. b. fl. l. [1, 0, 12, c_1], [1, 12, 13, c_1], # Bot. bot. fl. ]) prim = GeomTriangles(Geom.UHStatic) vtx_count = -1 for surf in surfs: p, n = self.mk_surface(points[surf[0]], points[surf[1]], points[surf[2]]) for i in range(p.shape[0]): vertices.addData3f(*p[i, :]) normals.addData3f(*(-n)) colors.addData4f(*surf[3]) vtx_count += 1 prim.add_vertices(vtx_count - 2, vtx_count - 1, vtx_count) geom = Geom(vertexData) geom.addPrimitive(prim) node = GeomNode('I_frame') node.addGeom(geom) return node
def generateNode(self): self.destroy() self.node = NodePath('gameobjectnode') self.node.setTwoSided(True) self.node.reparentTo(self.parent.node) if self.properties['avoidable'] == True: self.node.setTag("avoidable", 'true') else: self.node.setTag("avoidable", 'false') #setting scripting part self.node.setTag("onWalked", self.onWalked) self.node.setTag("onPicked", self.onPicked) #set unique id self.node.setTag("id", self.properties['id']) tex = loader.loadTexture(resourceManager.getResource(self.properties['url'])+'.png') tex.setWrapV(Texture.WM_clamp) tex.setWrapU(Texture.WM_clamp) #this is true pixel art #change to FTLinear for linear interpolation between pixel colors tex.setMagfilter(Texture.FTNearest) tex.setMinfilter(Texture.FTNearest) xorig = tex.getOrigFileXSize() / self.baseDimension yorig = tex.getOrigFileYSize() / self.baseDimension xscaled = (tex.getOrigFileXSize() / self.baseDimension) * self.properties['scale'] yscaled = (tex.getOrigFileYSize() / self.baseDimension) * self.properties['scale'] self.node.setTag("xscaled", str(xscaled)) self.node.setTag("yscaled", str(yscaled)) cm = CardMaker("tileobject") cm.setFrame(0,xorig,0,yorig) ts = TextureStage('ts') ts.setMode(TextureStage.MDecal) # distinguish between 3d collisions (for objects with an height and sensible self.properties['inclination']) # and 2d collisions for plain sprites if self.properties['walkable'] == 'false': if self.properties['collisionmode'] == "3d": #must handle differently objects which are small and big if xscaled < 1: self.collisionTube = CollisionBox(LPoint3f(0.5 - xscaled/2 - self.properties['offsetwidth'],0,0),LPoint3f(0.5 + xscaled/2 + self.properties['offsetwidth'],0.1,0.3 + self.properties['offsetheight'])) if xscaled >= 1: self.collisionTube = CollisionBox(LPoint3f(0 - self.properties['offsetwidth'],0,0),LPoint3f(xscaled + self.properties['offsetwidth'],0.1,0.3 + self.properties['offsetheight'])) self.collisionNode = CollisionNode('objectSphere') self.collisionNode.addSolid(self.collisionTube) self.collisionNodeNp = self.node.attachNewNode(self.collisionNode) self.collisionNodeNp.setX(self.properties['offsethorizontal']) self.collisionNodeNp.setZ(self.properties['offsetvertical']) self.collisionNodeNp.setX(self.collisionNodeNp.getX()+self.properties['offsetcollisionh']) self.collisionNodeNp.setZ(self.collisionNodeNp.getZ()+self.properties['offsetcollisionv']+0.1) if main.editormode: self.collisionNodeNp.show() elif self.properties['collisionmode'] == "2d": #must handle differently objects which are small and big if xscaled < 1: self.collisionTube = CollisionBox(LPoint3f(0.5 - xscaled/2 - self.properties['offsetwidth'],0,0),LPoint3f(0.5 + xscaled/2 + self.properties['offsetwidth'],yscaled + self.properties['offsetheight'],0.3)) if xscaled >= 1: self.collisionTube = CollisionBox(LPoint3f(0 - self.properties['offsetwidth'],0,0),LPoint3f(xscaled + self.properties['offsetwidth'],yscaled + self.properties['offsetheight'],0.3)) self.collisionNode = CollisionNode('objectSphere') self.collisionNode.addSolid(self.collisionTube) self.collisionNodeNp = self.node.attachNewNode(self.collisionNode) self.collisionNodeNp.setP(-(270-int(self.properties['inclination']))) self.collisionNodeNp.setX(self.properties['offsethorizontal']) self.collisionNodeNp.setZ(self.properties['offsetvertical']) self.collisionNodeNp.setX(self.collisionNodeNp.getX()+self.properties['offsetcollisionh']) self.collisionNodeNp.setZ(self.collisionNodeNp.getZ()+self.properties['offsetcollisionv']+0.1) if main.editormode: self.collisionNodeNp.show() geomnode = NodePath(cm.generate()) if geomnode.node().isGeomNode(): vdata = geomnode.node().modifyGeom(0).modifyVertexData() writer = GeomVertexWriter(vdata, 'vertex') reader = GeomVertexReader(vdata, 'vertex') ''' this part apply rotation flattening to the perspective view by modifying directly structure vertices ''' i = 0 #counter while not reader.isAtEnd(): v = reader.getData3f() x = v[0] y = v[1] z = v[2] newx = x newy = y newz = z if self.properties['rotation'] == -90.0: if i == 0: newx = math.fabs(math.cos(math.radians(self.properties['inclination']))) * z newz = 0 ssen = math.fabs(math.sin(math.radians(self.properties['inclination']))) * z sparsen = math.fabs(math.sin(math.radians(self.properties['inclination']))) * ssen spercos = math.fabs(math.cos(math.radians(self.properties['inclination']))) * ssen newy -= spercos newz += sparsen if i == 2: newx += math.fabs(math.cos(math.radians(self.properties['inclination']))) * z newz = 0 ssen = math.fabs(math.sin(math.radians(self.properties['inclination']))) * z sparsen = math.fabs(math.sin(math.radians(self.properties['inclination']))) * ssen spercos = math.fabs(math.cos(math.radians(self.properties['inclination']))) * ssen newy -= spercos newz += sparsen writer.setData3f(newx, newy, newz) i += 1 #increase vertex counter if xscaled >= 1: geomnode.setX(0) if xscaled < 1: geomnode.setX(0.5 - xscaled/2) geomnode.setScale(self.properties['scale']) geomnode.setX(geomnode.getX()+self.properties['offsethorizontal']) geomnode.setZ(geomnode.getZ()+self.properties['offsetvertical']) geomnode.setY(-self.properties['elevation']) geomnode.setP(int(self.properties['inclination'])-360) geomnode.setTexture(tex) geomnode.setTransparency(TransparencyAttrib.MAlpha) geomnode.reparentTo(self.node) self.node.setR(self.properties['rotation'])
def generate( self ): # call this after setting some of the variables to update it if hasattr(self, 'geomNode'): self.geomNode.removeAllGeoms() static_mode = Geom.UHStatic if self.static else Geom.UHDynamic vertex_format = Mesh._formats[(bool(self.colors), bool(self.uvs), bool(self.normals))] vdata = GeomVertexData('name', vertex_format, static_mode) vdata.setNumRows(len(self.vertices)) # for speed if not hasattr(self, 'geomNode'): self.geomNode = GeomNode('mesh') self.attachNewNode(self.geomNode) vertexwriter = GeomVertexWriter(vdata, 'vertex') for v in self.vertices: vertexwriter.addData3f(*v) if self.colors: colorwriter = GeomVertexWriter(vdata, 'color') for c in self.colors: colorwriter.addData4f(c) if self.uvs: uvwriter = GeomVertexWriter(vdata, 'texcoord') for uv in self.uvs: uvwriter.addData2f(uv[0], uv[1]) if self.normals != None: normalwriter = GeomVertexWriter(vdata, 'normal') for norm in self.normals: normalwriter.addData3f(*norm) if self.mode != 'line' or not self._triangles: self.indices = list() if self._triangles: if isinstance(self._triangles[0], int): for t in self._triangles: self.indices.append(t) elif len( self._triangles[0] ) >= 3: # if tris are tuples like this: ((0,1,2), (1,2,3)) for t in self._triangles: if len(t) == 3: self.indices.extend(t) elif len(t) == 4: # turn quad into tris self.indices.extend( [t[i] for i in (0, 1, 2, 2, 3, 0)]) else: self.indices = [i for i in range(len(self.vertices))] prim = Mesh._modes[self.mode](static_mode) self.generated_vertices = [self.vertices[i] for i in self.indices] for v in self.indices: prim.addVertex(v) prim.close_primitive() geom = Geom(vdata) geom.addPrimitive(prim) self.geomNode.addGeom(geom) else: # line with segments defined in triangles for line in self._triangles: prim = Mesh._modes[self.mode](static_mode) for e in line: prim.addVertex(e) prim.close_primitive() geom = Geom(vdata) geom.addPrimitive(prim) self.geomNode.addGeom(geom) if self.mode == 'point': self.setTexGen(TextureStage.getDefault(), TexGenAttrib.MPointSprite)
def modifyGeometryUVs(self): # Modifies the geometry vertex UVs in-place twriter = GeomVertexWriter(self.vdata, InternalName.getTexcoord()) tanwriter = GeomVertexWriter(self.vdata, InternalName.getTangent()) bwriter = GeomVertexWriter(self.vdata, InternalName.getBinormal()) for i in range(len(self.vertices)): twriter.setData2f(self.vertices[i].uv) tanwriter.setData3f(self.material.tangent) bwriter.setData3f(self.material.binormal)
def createTriangle(v1, v2, v3, is_flat=False): x1 = v1.x y1 = v1.y z1 = v1.z x2 = v2.x y2 = v2.y z2 = v2.z x3 = v3.x y3 = v3.y z3 = v3.z format=GeomVertexFormat.getV3n3cp() vdata=GeomVertexData('tri', format, Geom.UHDynamic) vertex=GeomVertexWriter(vdata, 'vertex') normal=GeomVertexWriter(vdata, 'normal') color=GeomVertexWriter(vdata, 'color') vertex.addData3f(x1, y1, z1) vertex.addData3f(x2, y2, z2) vertex.addData3f(x3, y3, z3) if is_flat: normVector = norm(Vec3( (x1 + x2 + x3)/3.0, (y1 + y2 + y3)/3.0, (z1+ z2+ z3)/3.0)) normal.addData3f(normVector) normal.addData3f(normVector) normal.addData3f(normVector) else: normal.addData3f(norm(Vec3(x1,y1,z1))) normal.addData3f(norm(Vec3(x2,y2,z2))) normal.addData3f(norm(Vec3(x3,y3,z3))) #adding different colors to the vertex for visibility color.addData4f(0.5,0.5,0.5,1.0) color.addData4f(0.5,0.5,0.5,1.0) color.addData4f(0.5,0.5,0.5,1.0) tri = GeomTriangles(Geom.UHDynamic) tri.addVertex(0) tri.addVertex(1) tri.addVertex(2) tri.closePrimitive() output_tri = Geom(vdata) output_tri.addPrimitive(tri) return output_tri
def draw(self): if self.rendered_mesh != None: self.reset_draw() format = GeomVertexFormat.getV3n3cp() vdata = GeomVertexData('tri', format, Geom.UHDynamic) vertex = GeomVertexWriter(vdata, 'vertex') normal = GeomVertexWriter(vdata, 'normal') color = GeomVertexWriter(vdata, 'color') v_mapping = {} i = 0 for v in self.verts.values(): vertex.addData3f(v.pos.x, v.pos.y, v.pos.z) normal.addData3f(v.norm.x, v.norm.y, v.norm.z) color.addData4f(v.color[0], v.color[1], v.color[2], v.color[3]) v_mapping[v.ID] = i i += 1 mesh = Geom(vdata) for f in self.faces.values(): tri = GeomTriangles(Geom.UHDynamic) tri.addVertex(v_mapping[f.v1.ID]) tri.addVertex(v_mapping[f.v2.ID]) tri.addVertex(v_mapping[f.v3.ID]) tri.closePrimitive() mesh.addPrimitive(tri) snode = GeomNode(self.name) snode.addGeom(mesh) self.rendered_mesh = render.attachNewNode(snode) self.rendered_mesh.setTwoSided(True)
def generate( self ): # call this after setting some of the variables to update it if hasattr(self, 'geomNode'): self.geomNode.removeAllGeoms() static_mode = Geom.UHStatic if self.static else Geom.UHDynamic vertex_format = Mesh._formats[(bool(self.colors), bool(self.uvs), bool(self.normals))] vdata = GeomVertexData('name', vertex_format, static_mode) vdata.setNumRows(len(self.vertices)) # for speed self.geomNode = GeomNode('mesh') self.attachNewNode(self.geomNode) vertexwriter = GeomVertexWriter(vdata, 'vertex') for v in self.vertices: vertexwriter.addData3f((v[0], v[2], v[1])) # swap y and z if self.colors: colorwriter = GeomVertexWriter(vdata, 'color') for c in self.colors: colorwriter.addData4f(c) if self.uvs: uvwriter = GeomVertexWriter(vdata, 'texcoord') for uv in self.uvs: uvwriter.addData2f(uv[0], uv[1]) if self.normals != None: normalwriter = GeomVertexWriter(vdata, 'normal') for norm in self.normals: normalwriter.addData3f((norm[0], norm[2], norm[1])) if self.mode != 'line' or not self._triangles: prim = Mesh._modes[self.mode](static_mode) if self._triangles: if isinstance(self._triangles[0], int): for t in self._triangles: prim.addVertex(t) elif len( self._triangles[0] ) >= 3: # if tris are tuples like this: ((0,1,2), (1,2,3)) for t in self._triangles: if len(t) == 3: for e in t: prim.addVertex(e) elif len(t) == 4: # turn quad into tris prim.addVertex(t[0]) prim.addVertex(t[1]) prim.addVertex(t[2]) prim.addVertex(t[2]) prim.addVertex(t[3]) prim.addVertex(t[0]) else: prim.addConsecutiveVertices(0, len(self.vertices)) prim.close_primitive() geom = Geom(vdata) geom.addPrimitive(prim) self.geomNode.addGeom(geom) else: # line with segments defined in triangles for line in self._triangles: prim = Mesh._modes[self.mode](static_mode) for e in line: prim.addVertex(e) prim.close_primitive() geom = Geom(vdata) geom.addPrimitive(prim) self.geomNode.addGeom(geom) if self.mode == 'point': self.setTexGen(TextureStage.getDefault(), TexGenAttrib.MPointSprite) # self.set_render_mode_perspective(True) self.recipe = dedent(f''' Mesh( vertices={[tuple(e) for e in self.vertices]}, triangles={self._triangles}, colors={[tuple(e) for e in self.colors]}, uvs={self.uvs}, normals={[tuple(e) for e in self.normals]}, static={self.static}, mode="{self.mode}", thickness={self.thickness} ) ''')
def addPoint(self, x, y, wheel_dir, force): """ Adds a point to the skid mark trail. The coordinates are in the world frame. The force is a number between zero and one, where one is the max force and makes the biggest and darkest skid mark. The argument 'wheel_dir' is given in degrees, where zero points toward the positive X axis. """ h = self.wheel_width * 0.5 rads = (wheel_dir - 90) * math.pi / 180.0 x0b, y0b = x + h * math.cos(rads), y + h * math.sin(rads) rads = (wheel_dir + 90) * math.pi / 180.0 x1b, y1b = x + h * math.cos(rads), y + h * math.sin(rads) x0a, y0a, x1a, y1a = self.lastpoints self.lastpoints = (x0b, y0b, x1b, y1b) if not self.havelast: self.havelast = True return indx = self.nextrect * 4 self.nextrect += 1 if self.nextrect >= self.nrects: self.nextrect = 0 vtx = GeomVertexWriter(self.vdata, "vertex") cx = GeomVertexWriter(self.vdata, "color") vtx.setRow(indx) cx.setRow(indx) c = self.forceToColor(force) vtx.addData3f(x0a, y0a, self.zpos) vtx.addData3f(x1a, y1a, self.zpos) vtx.addData3f(x0b, y0b, self.zpos) vtx.addData3f(x1b, y1b, self.zpos) cx.addData4f(*c) cx.addData4f(*c) cx.addData4f(*c) cx.addData4f(*c)
def __init__(self, nrects: int = 100, wheel_width=0.2, zpos=-0.38): """ Initalizes one track for a skid mark. The mark will be placed parallel to X-Y in world coordinates. They will be placed at the given height given by 'zpos'. The 'nrects' argument specifies how long the skid can be in input point locations. You can make the skid mark longer by increasing nrects, or spreading out the distance between input points. Once nrect points have been input, the earlier points will disappear. The 'wheel-width' parameter is the thickness of the wheel that is producing the marks. """ self.wheel_width = wheel_width # One unit = about 10 inches in current world. self.wheel_state = [ ] # Tupels of: X, Y position of wheel, While Direction in degrees, and force self.nrects = nrects self.zpos = zpos self.vdata = GeomVertexData("skid", GeomVertexFormat.getV3c4(), Geom.UHStatic) self.vdata.setNumRows(4 * nrects) vtx = GeomVertexWriter(self.vdata, "vertex") cx = GeomVertexWriter(self.vdata, "color") prim = GeomTriangles(Geom.UHStatic) c = self.forceToColor(0.0) # Here we set up all the vertexts and the primatives that use them. For each set of four vertices, a # flat rectangle is defined. Then 4 primatives are defined by splitting up the rectangle into pair of 2 # triangles -- 4 triangles per rectangle. Each pair of triangles are identical, except that their normals # are opposite, so that we don't have to worry about back culling later. Although it would be possible # to share vertics between the rectangles we don't do that here so that the chain can be cut at any point # by only operating on the vertics and not visiting the primatives. Finally, to "disable" a rectangle, # we set all the vertics to the same point in 3D space (and therefore create a zero-area rectangle). for i in range(nrects): vtx.addData3f(0.0, 0.0, 0.0) vtx.addData3f(0.0, 0.0, 0.0) vtx.addData3f(0.0, 0.0, 0.0) vtx.addData3f(0.0, 0.0, 0.0) cx.addData4f(*c) cx.addData4f(*c) cx.addData4f(*c) cx.addData4f(*c) j = i * 4 j0, j1, j2, j3 = j + 0, j + 1, j + 2, j + 3 prim.addVertices(j0, j1, j3) prim.addVertices(j3, j1, j0) prim.addVertices(j0, j3, j2) prim.addVertices(j2, j3, j0) prim.closePrimitive() geom = Geom(self.vdata) geom.addPrimitive(prim) node = GeomNode('Skid') node.addGeom(geom) self.nodepath = render.attachNewNode(node) self.nextrect = 0 self.havelast = False self.lastpoints = (0, 0, 0, 0)
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 interpolate_maps(self, task): # First, the actual interpolation t_index = self.last_time current_map = {} for x in range(0, self.sidelength): for y in range(0, self.sidelength): # calculate vertices p_1 = self.map_a[(x, y)] p_2 = self.map_b[(x, y)] v_x = p_1[0]*(1.0-t_index) + p_2[0]*t_index v_y = p_1[1]*(1.0-t_index) + p_2[1]*t_index v_z = p_1[2]*(1.0-t_index) + p_2[2]*t_index current_map[(x, y)] = (v_x, v_y, v_z) # Set up the writers vertex = GeomVertexWriter(self.vdata, 'vertex') normal = GeomVertexWriter(self.vdata, 'normal') # We don't use vertex readers as we don't care about the # current state, but if we did, it'd look like this: # vertex_reader = GeomVertexReader(self.vdata, 'vertex') # v = vertex_reader.getData3f() # Remember that all vertex readers working on a # GeomVertexData have to be created *after* the writers # working on it (due to engine internals; see the manual). for x in range(0, self.sidelength): for y in range(0, self.sidelength): v_x, v_y, v_z = current_map[(x, y)] vertex.setData3f(v_x, v_y, v_z) # Calculate the normal if x==0 and y==0: s_0 = Vec3( 0.0, 1.0, v_z - current_map[(x, y+1)][2]) s_1 = Vec3( 1.0, 0.0, v_z - current_map[(x+1, y)][2]) e_0 = s_0.cross(s_1) # Flip if necessary, then normalize if e_0[2] < 0.0: e_0 = e_0*-1.0 n = e_0 n = n/n.length() elif x==0 and y==(self.sidelength-1): # First, we calculate the vectors to the neighbors. s_1 = Vec3( 1.0, 0.0, v_z - current_map[(x+1, y)][2]) s_2 = Vec3( 0.0, -1.0, v_z - current_map[(x, y-1)][2]) e_1 = s_1.cross(s_2) # Flip if necessary, then normalize if e_1[2] < 0.0: e_1 = e_1*-1.0 n = e_1 n = n/n.length() elif x==(self.sidelength-1) and y==0: # First, we calculate the vectors to the neighbors. s_0 = Vec3( 0.0, 1.0, v_z - current_map[(x, y+1)][2]) s_3 = Vec3(-1.0, 0.0, v_z - current_map[(x-1, y)][2]) e_3 = s_3.cross(s_0) # Flip if necessary, then normalize if e_3[2] < 0.0: e_3 = e_3*-1.0 n = e_3 n = n/n.length() elif x==(self.sidelength-1) or y==(self.sidelength-1): # First, we calculate the vectors to the neighbors. s_2 = Vec3( 0.0, -1.0, v_z - current_map[(x, y-1)][2]) s_3 = Vec3(-1.0, 0.0, v_z - current_map[(x-1, y)][2]) e_2 = s_2.cross(s_3) # Flip if necessary, then normalize if e_2[2] < 0.0: e_2 = e_2*-1.0 n = e_2 n = n/n.length() elif x==0: # First, we calculate the vectors to the neighbors. s_0 = Vec3( 0.0, 1.0, v_z - current_map[(x, y+1)][2]) s_1 = Vec3( 1.0, 0.0, v_z - current_map[(x+1, y)][2]) s_2 = Vec3( 0.0, -1.0, v_z - current_map[(x, y-1)][2]) e_0 = s_0.cross(s_1) e_1 = s_1.cross(s_2) # Flip if necessary, then normalize if e_0[2] < 0.0: e_0 = e_0*-1.0 if e_1[2] < 0.0: e_1 = e_1*-1.0 n = e_0 + e_1 n = n/n.length() elif y==0: # First, we calculate the vectors to the neighbors. s_0 = Vec3( 0.0, 1.0, v_z - current_map[(x, y+1)][2]) s_1 = Vec3( 1.0, 0.0, v_z - current_map[(x+1, y)][2]) s_3 = Vec3(-1.0, 0.0, v_z - current_map[(x-1, y)][2]) e_0 = s_0.cross(s_1) e_3 = s_3.cross(s_0) # Flip if necessary, then normalize if e_0[2] < 0.0: e_0 = e_0*-1.0 if e_3[2] < 0.0: e_3 = e_3*-1.0 n = e_0 + e_3 n = n/n.length() elif x==(self.sidelength-1): # First, we calculate the vectors to the neighbors. s_1 = Vec3( 1.0, 0.0, v_z - current_map[(x+1, y)][2]) s_2 = Vec3( 0.0, -1.0, v_z - current_map[(x, y-1)][2]) s_3 = Vec3(-1.0, 0.0, v_z - current_map[(x-1, y)][2]) e_1 = s_1.cross(s_2) e_2 = s_2.cross(s_3) # Flip if necessary, then normalize if e_1[2] < 0.0: e_1 = e_1*-1.0 if e_2[2] < 0.0: e_2 = e_2*-1.0 n = e_1 + e_2 n = n/n.length() elif y==(self.sidelength-1): # First, we calculate the vectors to the neighbors. s_1 = Vec3( 1.0, 0.0, v_z - current_map[(x+1, y)][2]) s_2 = Vec3( 0.0, -1.0, v_z - current_map[(x, y-1)][2]) s_3 = Vec3(-1.0, 0.0, v_z - current_map[(x-1, y)][2]) e_1 = s_1.cross(s_2) e_2 = s_2.cross(s_3) # Flip if necessary, then normalize if e_1[2] < 0.0: e_1 = e_1*-1.0 if e_2[2] < 0.0: e_2 = e_2*-1.0 n = e_1 + e_2 n = n/n.length() else: # This is a normal case, not an edge or corner. # First, we calculate the vectors to the neighbors. s_0 = Vec3( 0.0, 1.0, v_z - current_map[(x, y+1)][2]) s_1 = Vec3( 1.0, 0.0, v_z - current_map[(x+1, y)][2]) s_2 = Vec3( 0.0, -1.0, v_z - current_map[(x, y-1)][2]) s_3 = Vec3(-1.0, 0.0, v_z - current_map[(x-1, y)][2]) e_0 = s_0.cross(s_1) e_1 = s_1.cross(s_2) e_2 = s_2.cross(s_3) e_3 = s_3.cross(s_0) # Flip if necessary, then normalize if e_0[2] < 0.0: e_0 = e_0*-1.0 if e_1[2] < 0.0: e_1 = e_1*-1.0 if e_2[2] < 0.0: e_2 = e_2*-1.0 if e_3[2] < 0.0: e_3 = e_3*-1.0 n = e_0 + e_1 + e_2 + e_3 n = n/n.length() normal.setData3f(n[0], n[1], n[2]) return Task.cont
def create_geom(self, sidelength): # Set up the vertex arrays vformat = GeomVertexFormat.getV3n3c4() vdata = GeomVertexData("Data", vformat, Geom.UHDynamic) vertex = GeomVertexWriter(vdata, 'vertex') normal = GeomVertexWriter(vdata, 'normal') color = GeomVertexWriter(vdata, 'color') geom = Geom(vdata) # Write vertex data for x in range(0, sidelength): for y in range(0, sidelength): # vertex_number = x * sidelength + y v_x, v_y, v_z = self.map_b[(x, y)] n_x, n_y, n_z = 0.0, 0.0, 1.0 c_r, c_g, c_b, c_a = 0.5, 0.5, 0.5, 0.5 vertex.addData3f(v_x, v_y, v_z) normal.addData3f(n_x, n_y, n_z) color.addData4f(c_r, c_g, c_b, c_a) # Add triangles for x in range(0, sidelength - 1): for y in range(0, sidelength - 1): # The vertex arrangement (y up, x right) # 2 3 # 0 1 v_0 = x * sidelength + y v_1 = x * sidelength + (y + 1) v_2 = (x + 1) * sidelength + y v_3 = (x + 1) * sidelength + (y + 1) if (x+y)%1 == 0: # An even square tris = GeomTriangles(Geom.UHStatic) tris.addVertices(v_0, v_2, v_3) tris.closePrimitive() geom.addPrimitive(tris) tris = GeomTriangles(Geom.UHStatic) tris.addVertices(v_3, v_1, v_0) tris.closePrimitive() geom.addPrimitive(tris) else: # An odd square tris = GeomTriangles(Geom.UHStatic) tris.addVertices(v_1, v_0, v_2) tris.closePrimitive() geom.addPrimitive(tris) tris = GeomTriangles(Geom.UHStatic) tris.addVertices(v_2, v_3, v_1) tris.closePrimitive() geom.addPrimitive(tris) # Create the actual node node = GeomNode('geom_node') node.addGeom(geom) # Remember GeomVertexWriters to adjust vertex data later #self.vertex_writer = vertex #self.color_writer = color self.vdata = vdata return node
def __build_Tris(self, sphere, mode): vdata = GeomVertexData("Data", self.__vformat[mode], Geom.UHStatic) _num_rows = len(sphere.pts) # Vertices. vertices = GeomVertexWriter(vdata, "vertex") vertices.reserveNumRows(_num_rows) for pt in sphere.pts: vertices.addData3f(*pt) # Map coords. if mode == "mid": mapcoords = GeomVertexWriter(vdata, "mapcoord") mapcoords.reserveNumRows(_num_rows) for mc in sphere.coords: u, v = mc[:2] mapcoords.addData2f(u, v) # Tris. prim = GeomTriangles(Geom.UHStatic) prim.reserveNumVertices(len(sphere.tris)) for tri in sphere.tris: prim.addVertices(*tri) prim.closePrimitive() # Geom. geom = Geom(vdata) geom.addPrimitive(prim) geom_node = GeomNode("geom") geom_node.addGeom(geom) geom_np = NodePath(geom_node) return geom_np
def regenerateGeometry(self): # # Generate vertex data # numVerts = len(self.vertices) vdata = GeomVertexData("SolidFace", getFaceFormat(), GeomEnums.UHStatic) vdata.uncleanSetNumRows(len(self.vertices)) vwriter = GeomVertexWriter(vdata, InternalName.getVertex()) twriter = GeomVertexWriter(vdata, InternalName.getTexcoord()) nwriter = GeomVertexWriter(vdata, InternalName.getNormal()) tanwriter = GeomVertexWriter(vdata, InternalName.getTangent()) bwriter = GeomVertexWriter(vdata, InternalName.getBinormal()) for i in range(len(self.vertices)): vert = self.vertices[i] vwriter.setData3f(vert.pos) twriter.setData2f(vert.uv) nwriter.setData3f(self.plane.getNormal()) tanwriter.setData3f(self.material.tangent) bwriter.setData3f(self.material.binormal) # # Generate indices # # Triangles in 3D view prim3D = GeomTriangles(GeomEnums.UHStatic) prim3D.reserveNumVertices((numVerts - 2) * 3) for i in range(1, numVerts - 1): prim3D.addVertices(i + 1, i, 0) prim3D.closePrimitive() # Line loop in 2D view.. using line strips prim2D = GeomLinestrips(GeomEnums.UHStatic) prim2D.reserveNumVertices(numVerts + 1) for i in range(numVerts): prim2D.addVertex(i) # Close off the line strip with the first vertex.. creating a line loop prim2D.addVertex(0) prim2D.closePrimitive() # # Generate mesh objects # geom3D = SolidFaceGeom(vdata) geom3D.setDrawMask(VIEWPORT_3D_MASK) geom3D.setPlaneCulled(True) geom3D.setPlane(self.plane) geom3D.addPrimitive(prim3D) self.index3D = self.solid.addFaceGeom(geom3D, self.state3D) geom3DLines = SolidFaceGeom(vdata) geom3DLines.addPrimitive(prim2D) geom3DLines.setDrawMask(VIEWPORT_3D_MASK) geom3DLines.setDraw(False) self.index3DLines = self.solid.addFaceGeom(geom3DLines, self.state3DLines) geom2D = SolidFaceGeom(vdata) geom2D.addPrimitive(prim2D) geom2D.setDrawMask(VIEWPORT_2D_MASK) self.index2D = self.solid.addFaceGeom(geom2D, self.state2D) self.geom3D = geom3D self.geom3DLines = geom3DLines self.geom2D = geom2D self.vdata = vdata self.hasGeometry = True
def __build_Patches(self, sphere): vdata = GeomVertexData("Data", self.__vformat['high'], Geom.UHStatic) vertices = GeomVertexWriter(vdata, "vertex") mapcoords = GeomVertexWriter(vdata, "mapcoord") texcoords = GeomVertexWriter(vdata, "texcoord") _num_rows = len(sphere.pts) vertices.reserveNumRows(_num_rows) mapcoords.reserveNumRows(_num_rows) texcoords.reserveNumRows(_num_rows) # Pts. for pt, uv, coords, in zip(sphere.pts, sphere.uvs, sphere.coords): vertices.addData3f(*pt) mapcoords.addData2f(*coords) texcoords.addData2f(*uv) ## *.99+.01) # Patches. prim = GeomPatches(3, Geom.UHStatic) prim.reserveNumVertices(len(sphere.tris)) for tri in sphere.tris: prim.addVertices(*tri) prim.closePrimitive() # Geom. geom = Geom(vdata) geom.addPrimitive(prim) geom_node = GeomNode("geom") geom_node.addGeom(geom) geom_np = NodePath(geom_node) return geom_np
def __init__(self, position, gridshape): self.geomnode = GeomNode("rhomdo") super().__init__(self.geomnode) z, y, x = position depth, height, width = gridshape self.color = (x / width), (y / height), (z / depth), 1 format = GeomVertexFormat.getV3c4() vdata = GeomVertexData("vertices", format, Geom.UHStatic) vdata.setNumRows(14) vertexWriter = GeomVertexWriter(vdata, "vertex") colorWriter = GeomVertexWriter(vdata, "color") for i in range(14): colorWriter.addData4f(*self.color) self.color = max(self.color[0] - .03, 0), max(self.color[1] - .03, 0), max(self.color[2] - .03, 0), 1 realX = x * 2 - width realY = y * 2 - height realZ = z * SR2 - SR2 * .5 * depth odd = z % 2 == 1 if odd: realX += 1 realY += 1 vertexWriter.addData3f(realX, realY, realZ + SR2) vertexWriter.addData3f(realX - 1, realY, realZ + (SR2 / 2)) vertexWriter.addData3f(realX, realY - 1, realZ + (SR2 / 2)) vertexWriter.addData3f(realX + 1, realY, realZ + (SR2 / 2)) vertexWriter.addData3f(realX, realY + 1, realZ + (SR2 / 2)) vertexWriter.addData3f(realX - 1, realY - 1, realZ) vertexWriter.addData3f(realX + 1, realY - 1, realZ) vertexWriter.addData3f(realX + 1, realY + 1, realZ) vertexWriter.addData3f(realX - 1, realY + 1, realZ) vertexWriter.addData3f(realX - 1, realY, realZ - (SR2 / 2)) vertexWriter.addData3f(realX, realY - 1, realZ - (SR2 / 2)) vertexWriter.addData3f(realX + 1, realY, realZ - (SR2 / 2)) vertexWriter.addData3f(realX, realY + 1, realZ - (SR2 / 2)) vertexWriter.addData3f(realX, realY, realZ - SR2) # step 2) make primitives and assign vertices to them tris = GeomTriangles(Geom.UHStatic) # top tris.addVertex(0) tris.addVertex(1) tris.addVertex(2) tris.closePrimitive() tris.addVertex(0) tris.addVertex(2) tris.addVertex(3) tris.closePrimitive() tris.addVertex(0) tris.addVertex(3) tris.addVertex(4) tris.closePrimitive() tris.addVertex(0) tris.addVertex(4) tris.addVertex(1) tris.closePrimitive() tris.addVertex(1) tris.addVertex(5) tris.addVertex(2) tris.closePrimitive() tris.addVertex(2) tris.addVertex(6) tris.addVertex(3) tris.closePrimitive() tris.addVertex(3) tris.addVertex(7) tris.addVertex(4) tris.closePrimitive() tris.addVertex(4) tris.addVertex(8) tris.addVertex(1) tris.closePrimitive() # middle tris.addVertex(1) tris.addVertex(8) tris.addVertex(9) tris.closePrimitive() tris.addVertex(1) tris.addVertex(9) tris.addVertex(5) tris.closePrimitive() tris.addVertex(2) tris.addVertex(5) tris.addVertex(10) tris.closePrimitive() tris.addVertex(2) tris.addVertex(10) tris.addVertex(6) tris.closePrimitive() tris.addVertex(3) tris.addVertex(6) tris.addVertex(11) tris.closePrimitive() tris.addVertex(3) tris.addVertex(11) tris.addVertex(7) tris.closePrimitive() tris.addVertex(4) tris.addVertex(7) tris.addVertex(12) tris.closePrimitive() tris.addVertex(4) tris.addVertex(12) tris.addVertex(8) tris.closePrimitive() # bottom tris.addVertex(5) tris.addVertex(9) tris.addVertex(10) tris.closePrimitive() tris.addVertex(6) tris.addVertex(10) tris.addVertex(11) tris.closePrimitive() tris.addVertex(7) tris.addVertex(11) tris.addVertex(12) tris.closePrimitive() tris.addVertex(8) tris.addVertex(12) tris.addVertex(9) tris.closePrimitive() tris.addVertex(9) tris.addVertex(13) tris.addVertex(10) tris.closePrimitive() tris.addVertex(10) tris.addVertex(13) tris.addVertex(11) tris.closePrimitive() tris.addVertex(11) tris.addVertex(13) tris.addVertex(12) tris.closePrimitive() tris.addVertex(12) tris.addVertex(13) tris.addVertex(9) tris.closePrimitive() rhomGeom = Geom(vdata) rhomGeom.addPrimitive(tris) self.geomnode.addGeom(rhomGeom)
def __init__(self): ShowBase.__init__(self) self.cols = 100 self.rows = 100 base.disableMouse() base.setFrameRateMeter(True) self.cameraHeight = 13 self.camera.set_pos(self.cols / 2, -30, self.cameraHeight) self.camera.look_at(self.cols / 2, 300, 0) plights = [] for i in range(0, int(self.cols / 5), 2): plight = PointLight("plight") plight.setColor(VBase4(1, 1, 1, 1)) plights.append(plight) plights[i] = self.render.attachNewNode(plight) x, y, z = self.camera.get_pos() plights[i].setPos(self.cols / 2 + ((i - int(i / 2)) * 10), y + 20, 5) self.render.set_light(plights[i]) plight = PointLight("plight") plight.setColor(VBase4(1, 1, 1, 1)) plights.append(plight) plights[i + 1] = self.render.attachNewNode(plight) x, y, z = self.camera.get_pos() plights[i + 1].setPos(self.cols / 2 + ((i - int(i / 2)) * 10), y + 20, 10) self.render.set_light(plights[i + 1]) self.plights = plights format = GeomVertexFormat.getV3c4() vdata = GeomVertexData('name', format, Geom.UHStatic) vdata.setNumRows(self.cols * self.rows) self.vertex = GeomVertexWriter(vdata, 'vertex') self.color = GeomVertexWriter(vdata, 'color') pz = [random.uniform(-1, 1)] for i in range(self.rows): pz.append(random.uniform(pz[i - 1] - 1, pz[i] + 1)) for y in range(0, self.rows): for x in range(0, self.cols): nz1 = random.uniform(pz[x] - 1, pz[x] + 1) nz2 = random.uniform(pz[x - 1] - 1, pz[x - 1] + 1) nz3 = random.uniform(pz[x + 1] - 1, pz[x + 1] + 1) nz = (nz1 + nz2 + nz3) / 3 self.vertex.add_data3f((x, y + 1, nz)) self.vertex.add_data3f((x, y, pz[x])) if nz < -5: self.color.add_data4f(0.2, 0.1, 0, 1) elif nz < -3: self.color.add_data4f(0, 0.2, 0.1, 1) elif nz < 0: self.color.add_data4f(0, 0.4, 0.2, 1) elif nz < 2: self.color.add_data4f(0.4, 0.4, 0.4, 1) else: self.color.add_data4f(1, 1, 1, 1) if nz < -5: self.color.add_data4f(0.2, 0.1, 0, 1) elif nz < -3: self.color.add_data4f(0, 0.2, 0.1, 1) elif pz[x] < 0: self.color.add_data4f(0, 0.4, 0.2, 1) elif pz[x] < 2: self.color.add_data4f(0.4, 0.4, 0.4, 1) else: self.color.add_data4f(1, 1, 1, 1) pz[x] = nz #print (nz) self.pz = pz geom = Geom(vdata) for y in range(0, self.rows): prim = GeomTristrips(Geom.UH_static) prim.addVertex(y * self.cols * 2) prim.add_next_vertices((self.cols * 2) - 1) prim.close_primitive() geom.addPrimitive(prim) nodeTris = GeomNode("TriStrips") nodeTris.addGeom(geom) self.nodeTrisPath = self.render.attachNewNode(nodeTris) self.task_mgr.add(self.moveForwardTask, "moveForwardTask") self.vdata = vdata self.newNodePath = [] self.counter = 0 self.rows1 = self.rows skybox = self.loader.loadModel("models/skybox.bam") skybox.reparent_to(self.render) skybox.set_scale(20000) skybox_texture = self.loader.loadTexture("textures/dayfair.jpg") skybox_texture.set_minfilter(SamplerState.FT_linear) skybox_texture.set_magfilter(SamplerState.FT_linear) skybox_texture.set_wrap_u(SamplerState.WM_repeat) skybox_texture.set_wrap_v(SamplerState.WM_mirror) skybox_texture.set_anisotropic_degree(16) skybox.set_texture(skybox_texture) skybox_shader = Shader.load(Shader.SL_GLSL, "skybox.vert.glsl", "skybox.frag.glsl") skybox.set_shader(skybox_shader)
def create_profile(self): """ Creates the necessary rendering geometry to render the 3d rendition of a CHS. """ beam = self.beam s = self.s prof = beam.profile color = (0.25882353, 0.80784314, 0.95686275, 1) fmt = GeomVertexFormat.getV3n3c4() vertexData = GeomVertexData('something', fmt, Geom.UHStatic) vertexData.setNumRows(2304) vertices = GeomVertexWriter(vertexData, 'vertex') normals = GeomVertexWriter(vertexData, 'normal') colors = GeomVertexWriter(vertexData, 'color') T = beam.elements[0].trans_matrix[:3, :3] b_0 = np.array([beam.x[0], beam.y[0], beam.z[0]]) / s b_l = np.array([beam.x[-1], beam.y[-1], beam.z[-1]]) / s s_ang = 49 wall = [] for in_out in ((prof.D / 2) / s, (prof.D / 2 - prof.t) / s): for b in [b_0, b_l]: layer = [] for j in range(s_ang): ang = j * (2 * np.pi / (s_ang-1)) p = b + np.dot(T.T, np.array([0, in_out * np.sin(ang), in_out * np.cos(ang)])) layer.append(p) if layer: wall.append(layer) prim = GeomTriangles(Geom.UHStatic) vtx_count = -1 for io in (0, 1): for l in range(2): for a in range(s_ang-1): if io == 0: p, n = self.mk_surface(wall[l][a], wall[l+1][a+1], wall[l][a+1]) else: p, n = self.mk_surface(wall[l+io][a], wall[l+io][a+1], wall[l+1+io][a+1]) for i in range(p.shape[0]): vertices.addData3f(*p[i, :]) normals.addData3f(*(-n)) colors.addData4f(*color) vtx_count += 1 prim.add_vertices(vtx_count - 2, vtx_count - 1, vtx_count) if io == 0: p, n = self.mk_surface(wall[l+io][a], wall[l+1+io][a], wall[l+1+io][a+1]) else: p, n = self.mk_surface(wall[l+io][a], wall[l+1+io][a+1], wall[l+1+io][a]) for i in range(p.shape[0]): vertices.addData3f(*p[i, :]) normals.addData3f(*(-n)) colors.addData4f(*color) vtx_count += 1 prim.add_vertices(vtx_count - 2, vtx_count - 1, vtx_count) for io in (0, 2): for a in range(s_ang-1): if io == 0: p, n = self.mk_surface(wall[0][a], wall[-2][a+1], wall[-2][a]) else: p, n = self.mk_surface(wall[1][a], wall[-1][a], wall[-1][a+1]) for i in range(p.shape[0]): vertices.addData3f(*p[i, :]) normals.addData3f(*(-n)) colors.addData4f(*color) vtx_count += 1 prim.add_vertices(vtx_count - 2, vtx_count - 1, vtx_count) if io == 0: p, n = self.mk_surface(wall[0][a], wall[0][a+1], wall[-2][a+1]) else: p, n = self.mk_surface(wall[1][a], wall[-1][a+1], wall[1][a+1]) for i in range(p.shape[0]): vertices.addData3f(*p[i, :]) normals.addData3f(*(-n)) colors.addData4f(*color) vtx_count += 1 prim.add_vertices(vtx_count - 2, vtx_count - 1, vtx_count) geom = Geom(vertexData) geom.addPrimitive(prim) node = GeomNode('CHS') node.addGeom(geom) return node
def visualize(centers, corners, edges): from meshtool.filters.panda_filters.pandacore import getVertexData, attachLights, ensureCameraAt from meshtool.filters.panda_filters.pandacontrols import KeyboardMovement, MouseDrag, MouseScaleZoom, MouseCamera from panda3d.core import GeomPoints, GeomTriangles, Geom, GeomNode, GeomVertexFormat, GeomVertexData, GeomVertexWriter, LineSegs, VBase3 from direct.showbase.ShowBase import ShowBase format = GeomVertexFormat.getV3c4() vdata = GeomVertexData('pts', format, Geom.UHDynamic) vertex = GeomVertexWriter(vdata, 'vertex') color = GeomVertexWriter(vdata, 'color') vertex_index = 0 center_vertex_indices = {} corner_vertex_indices = {} for key, center in centers.iteritems(): vertex.addData3f(center.x * X_SCALE, center.y * Y_SCALE, center.elevation * Z_SCALE) curcolor = hex2rgb(COLORS[center.biome]) color.addData4f(curcolor[0], curcolor[1], curcolor[2], 1) center_vertex_indices[key] = vertex_index vertex_index += 1 for corner in center.corners: vertex.addData3f(corner.x * X_SCALE, corner.y * Y_SCALE, corner.elevation * Z_SCALE) color.addData4f(curcolor[0], curcolor[1], curcolor[2], 1) corner_vertex_indices[corner.id] = vertex_index vertex_index += 1 tris = GeomTriangles(Geom.UHDynamic) for edge in edges.itervalues(): corner0 = edge.corner0 corner1 = edge.corner1 center0 = edge.center0 center1 = edge.center1 if corner0 is None or corner1 is None: continue tris.addVertices(corner_vertex_indices[corner1.id], corner_vertex_indices[corner0.id], center_vertex_indices[center0.id]) tris.addVertices(center_vertex_indices[center1.id], corner_vertex_indices[corner0.id], corner_vertex_indices[corner1.id]) tris.closePrimitive() pgeom = Geom(vdata) pgeom.addPrimitive(tris) node = GeomNode("primitive") node.addGeom(pgeom) p3dApp = ShowBase() attachLights(render) geomPath = render.attachNewNode(node) #geomPath.setRenderModeThickness(6.0) #geomPath.setRenderModeWireframe() ensureCameraAt(geomPath, base.cam) boundingSphere = geomPath.getBounds() base.cam.setPos(boundingSphere.getCenter() + boundingSphere.getRadius()) base.cam.lookAt(boundingSphere.getCenter()) geomPath.setScale(VBase3(50, 50, 50)) KeyboardMovement() #MouseDrag(geomPath) MouseCamera() MouseScaleZoom(geomPath) #render.setShaderAuto() p3dApp.run()
class Mesh(): def __init__(self, name): self.name = name self.poly_groups = [] # GeomVertexFormats # # GeomVertexFormat.getV3cpt2() - vertex, color, uv # GeomVertexFormat.getV3t2() - vertex, uv # GeomVertexFormat.getV3cp() - vertex, color # GeomVertexFormat.getV3n3t2() - vertex, normal, uv # GeomVertexFormat.getV3n3cpt2()- vertex, normal, rgba, uv # textured self.vdata = GeomVertexData(name, GeomVertexFormat.getV3n3cpt2(), Geom.UHStatic) # plain color filled polys # self.vdata = GeomVertexData(name, GeomVertexFormat.getV3cp(), Geom.UHStatic) self.vertex = GeomVertexWriter(self.vdata, 'vertex') self.vnormal = GeomVertexWriter(self.vdata, 'normal') self.color = GeomVertexWriter(self.vdata, 'color') self.texcoord = GeomVertexWriter(self.vdata, 'texcoord') self.root = NodePath(PandaNode(name + '_mesh')) # f is a 0x36 mesh fragment (see fragment.py for reference) def buildFromFragment(self, f, wld_container, debug=False): # write vertex coordinates for v in f.vertexList: self.vertex.addData3f(v[0], v[1], v[2]) # write vertex colors for rgba in f.vertexColorsList: ''' r = (rgba & 0xff000000) >> 24 g = (rgba & 0x00ff0000) >> 16 b = (rgba & 0x0000ff00) >> 8 a = (rgba & 0x000000ff) if a != 0: print 'vertex color has alpha component, r:0x%x g:0x%x b:0x%x a:0x%x ' % (r, g, b, a) ''' self.color.addData1f(rgba) # write vertex normals for v in f.vertexNormalsList: self.vnormal.addData3f(v[0], v[1], v[2]) # write texture uv for uv in f.uvList: self.texcoord.addData2f(uv[0], uv[1]) # Build PolyGroups # each polyTexList is a tuple containing a polygon count and the texture index for those polys # we create a PolyGroup for each of these # the PolyGroup creates all Polygons sharing a texture and adds them under a NodePath poly_idx = 0 for pt in f.polyTexList: n_polys = pt[0] tex_idx = pt[1] if debug: print(" Bulding a poly group with tex_id " + str(tex_idx)) pg = PolyGroup(self.vdata, tex_idx) # pass fragment so that it can access the SPRITES if pg.build(wld_container, f, poly_idx, n_polys, tex_idx, debug) == 1: self.poly_groups.append(pg) pg.nodePath.reparentTo(self.root) poly_idx += n_polys if poly_idx != f.polyCount or poly_idx != len(f.polyList): print 'ERROR: polycount mismatch'
class Orbit(VisibleObject): ignore_light = True default_shown = False selected_color = LColor(1.0, 0.0, 0.0, 1.0) def __init__(self, body): VisibleObject.__init__(self, body.get_ascii_name() + '-orbit') self.body = body self.nbOfPoints = 360 self.orbit = self.find_orbit(self.body) self.color = None self.fade = 0.0 if not self.orbit: print("No orbit for", self.get_name()) self.visible = False self.check_settings() def check_settings(self): if self.body.body_class is None: print("No class for", self.body.get_name()) return self.set_shown(settings.show_orbits and bodyClasses.get_show_orbit(self.body.body_class)) def find_orbit(self, body): if body != None: if not isinstance(body.orbit, FixedOrbit): return body.orbit else: return None, None else: return None, None def set_selected(self, selected): if selected: self.color = self.selected_color else: self.color = self.parent.get_orbit_color() if self.instance: self.instance.setColor(self.color * self.fade) def create_instance(self): if not self.orbit: return self.vertexData = GeomVertexData('vertexData', GeomVertexFormat.getV3(), Geom.UHStatic) self.vertexWriter = GeomVertexWriter(self.vertexData, 'vertex') delta = self.body.parent.get_local_position() for i in range(self.nbOfPoints): time = self.orbit.period / self.nbOfPoints * i pos = self.orbit.get_position_at(time) rot = self.orbit.get_rotation_at(time) pos = self.orbit.frame.get_local_position(rot.xform(pos)) - delta self.vertexWriter.addData3f(*pos) self.lines = GeomLines(Geom.UHStatic) for i in range(self.nbOfPoints - 1): self.lines.addVertex(i) self.lines.addVertex(i + 1) self.lines.closePrimitive() self.lines.addVertex(self.nbOfPoints - 1) self.lines.addVertex(0) self.lines.closePrimitive() self.geom = Geom(self.vertexData) self.geom.addPrimitive(self.lines) self.node = GeomNode(self.body.get_ascii_name() + '-orbit') self.node.addGeom(self.geom) self.instance = NodePath(self.node) self.instance.setRenderModeThickness(settings.orbit_thickness) self.instance.setCollideMask(GeomNode.getDefaultCollideMask()) self.instance.node().setPythonTag('owner', self) self.instance.reparentTo(self.context.annotation_shader) if self.color is None: self.color = self.parent.get_orbit_color() self.instance.setColor(self.color * self.fade) self.instance.setAntialias(AntialiasAttrib.MMultisample) self.appearance = ModelAppearance(attribute_color=True) if settings.use_inv_scaling: vertex_control = LargeObjectVertexControl() else: vertex_control = None self.instance_ready = True self.shader = BasicShader(lighting_model=FlatLightingModel(), vertex_control=vertex_control) self.shader.apply(self, self.appearance) self.shader.update(self, self.appearance) def check_visibility(self, pixel_size): if self.parent.shown and self.orbit: distance_to_obs = self.parent.distance_to_obs if distance_to_obs > 0.0: size = self.orbit.get_apparent_radius() / (distance_to_obs * pixel_size) else: size = 0.0 self.visible = size > settings.orbit_fade self.fade = min( 1.0, max(0.0, (size - settings.orbit_fade) / settings.orbit_fade)) if self.color is not None and self.instance is not None: self.instance.setColor(self.color * self.fade) else: self.visible = False def update_instance(self, camera_pos, orientation): if self.instance: self.place_instance_params(self.instance, self.body.parent.scene_position, self.body.parent.scene_scale_factor, LQuaternion()) self.shader.update(self, self.appearance)
def makeSquare(x1, y1, z1, x2, y2, z2, colorInfo): format = GeomVertexFormat.getV3n3cpt2() vdata = GeomVertexData('square', format, Geom.UHDynamic) vertex = GeomVertexWriter(vdata, 'vertex') normal = GeomVertexWriter(vdata, 'normal') color = GeomVertexWriter(vdata, 'color') texcoord = GeomVertexWriter(vdata, 'texcoord') # make sure we draw the sqaure in the right plane if x1 != x2: vertex.addData3(x1, y1, z1) vertex.addData3(x2, y1, z1) vertex.addData3(x2, y2, z2) vertex.addData3(x1, y2, z2) normal.addData3(normalized(2 * x1 - 1, 2 * y1 - 1, 2 * z1 - 1)) normal.addData3(normalized(2 * x2 - 1, 2 * y1 - 1, 2 * z1 - 1)) normal.addData3(normalized(2 * x2 - 1, 2 * y2 - 1, 2 * z2 - 1)) normal.addData3(normalized(2 * x1 - 1, 2 * y2 - 1, 2 * z2 - 1)) else: vertex.addData3(x1, y1, z1) vertex.addData3(x2, y2, z1) vertex.addData3(x2, y2, z2) vertex.addData3(x1, y1, z2) normal.addData3(normalized(2 * x1 - 1, 2 * y1 - 1, 2 * z1 - 1)) normal.addData3(normalized(2 * x2 - 1, 2 * y2 - 1, 2 * z1 - 1)) normal.addData3(normalized(2 * x2 - 1, 2 * y2 - 1, 2 * z2 - 1)) normal.addData3(normalized(2 * x1 - 1, 2 * y1 - 1, 2 * z2 - 1)) # adding different colors to the vertex for visibility color.addData4f(colorInfo[0], colorInfo[1], colorInfo[2], colorInfo[3]) color.addData4f(colorInfo[0], colorInfo[1], colorInfo[2], colorInfo[3]) color.addData4f(colorInfo[0], colorInfo[1], colorInfo[2], colorInfo[3]) color.addData4f(colorInfo[0], colorInfo[1], colorInfo[2], colorInfo[3]) texcoord.addData2f(0.0, 1.0) texcoord.addData2f(0.0, 0.0) texcoord.addData2f(1.0, 0.0) texcoord.addData2f(1.0, 1.0) # Quads aren't directly supported by the Geom interface # you might be interested in the CardMaker class if you are # interested in rectangle though tris = GeomTriangles(Geom.UHDynamic) tris.addVertices(0, 1, 3) tris.addVertices(1, 2, 3) square = Geom(vdata) square.addPrimitive(tris) return square
def __init__(self, mp): vdata = GeomVertexData('name_me', GeomVertexFormat.getV3c4(), Geom.UHStatic) vertex = GeomVertexWriter(vdata, 'vertex') color = GeomVertexWriter(vdata, 'color') primitive = GeomTristrips(Geom.UHStatic) film_size = base.cam.node().getLens().getFilmSize() x = film_size.getX() / 2.0 z = x * 256.0 / 240.0 vertex.addData3f(x, 90, z) vertex.addData3f(-x, 90, z) vertex.addData3f(x, 90, -z) vertex.addData3f(-x, 90, -z) color.addData4f(VBase4(*mp['backgroundcolor1'])) color.addData4f(VBase4(*mp['backgroundcolor1'])) color.addData4f(VBase4(*mp['backgroundcolor2'])) color.addData4f(VBase4(*mp['backgroundcolor2'])) primitive.addNextVertices(4) primitive.closePrimitive() geom = Geom(vdata) geom.addPrimitive(primitive) self.node = GeomNode('sky') self.node.addGeom(geom) base.camera.attachNewNode(self.node)
def create_instance(self): self.vertexData = GeomVertexData('vertexData', GeomVertexFormat.getV3c4(), Geom.UHStatic) self.vertexWriter = GeomVertexWriter(self.vertexData, 'vertex') self.colorwriter = GeomVertexWriter(self.vertexData, 'color') for r in range(1, self.nbOfRings + 1): for i in range(self.nbOfPoints): angle = 2 * pi / self.nbOfPoints * i x = cos(angle) * sin(pi * r / (self.nbOfRings + 1)) y = sin(angle) * sin(pi * r / (self.nbOfRings + 1)) z = sin(-pi / 2 + pi * r / (self.nbOfRings + 1)) self.vertexWriter.addData3f( (self.context.observer.infinity * x, self.context.observer.infinity * y, self.context.observer.infinity * z)) if r == self.nbOfRings / 2 + 1: self.colorwriter.addData4f(self.color.x * 1.5, 0, 0, 1) else: self.colorwriter.addData4f(*self.color) for s in range(self.nbOfSectors): for i in range(self.points_to_remove, self.nbOfPoints // 2 - self.points_to_remove + 1): angle = 2 * pi / self.nbOfPoints * i x = cos(2 * pi * s / self.nbOfSectors) * sin(angle) y = sin(2 * pi * s / self.nbOfSectors) * sin(angle) z = cos(angle) self.vertexWriter.addData3f( (self.context.observer.infinity * x, self.context.observer.infinity * y, self.context.observer.infinity * z)) if s == 0: self.colorwriter.addData4f(self.color.x * 1.5, 0, 0, 1) else: self.colorwriter.addData4f(*self.color) self.lines = GeomLines(Geom.UHStatic) index = 0 for r in range(self.nbOfRings): for i in range(self.nbOfPoints - 1): self.lines.addVertex(index) self.lines.addVertex(index + 1) self.lines.closePrimitive() index += 1 self.lines.addVertex(index) self.lines.addVertex(index - self.nbOfPoints + 1) self.lines.closePrimitive() index += 1 for r in range(self.nbOfSectors): for i in range(self.nbOfPoints // 2 - self.points_to_remove * 2): self.lines.addVertex(index) self.lines.addVertex(index + 1) self.lines.closePrimitive() index += 1 index += 1 self.geom = Geom(self.vertexData) self.geom.addPrimitive(self.lines) self.node = GeomNode("grid") self.node.addGeom(self.geom) self.instance = NodePath(self.node) self.instance.setRenderModeThickness(settings.grid_thickness) #myMaterial = Material() #myMaterial.setEmission((1.0, 1.0, 1.0, 1)) #self.instance.setMaterial(myMaterial) self.instance.reparentTo(self.context.annotation) self.instance.setQuat(LQuaternion(*self.orientation))
class Asterism(VisibleObject): def __init__(self, name): VisibleObject.__init__(self, name) self.visible = True self.color = bodyClasses.get_orbit_color('constellation') self.position = LPoint3d(0, 0, 0) self.segments = [] self.position = None def check_settings(self): self.set_shown(settings.show_asterisms) def set_segments_list(self, segments): self.segments = segments ra_sin = 0 ra_cos = 0 decl = 0 if len(self.segments) > 0 and len(self.segments[0]) > 0: for star in self.segments[0]: asc = star.orbit.get_right_asc() ra_sin += sin(asc) ra_cos += cos(asc) decl += star.orbit.get_declination() ra = atan2(ra_sin, ra_cos) decl /= len(self.segments[0]) self.position = InfinitePosition(right_asc=ra, right_asc_unit=units.Rad, declination=decl, declination_unit=units.Rad) def create_instance(self): self.vertexData = GeomVertexData('vertexData', GeomVertexFormat.getV3c4(), Geom.UHStatic) self.vertexWriter = GeomVertexWriter(self.vertexData, 'vertex') self.colorwriter = GeomVertexWriter(self.vertexData, 'color') #TODO: Ugly hack to calculate star position from the sun... old_cam_pos = self.context.observer.camera_global_pos self.context.observer.camera_global_pos = LPoint3d() center = LPoint3d() for segment in self.segments: if len(segment) < 2: continue for star in segment: #TODO: Temporary workaround to have star pos star.update(0) star.update_obs(self.context.observer) position, distance, scale_factor = self.get_real_pos_rel( star.rel_position, star.distance_to_obs, star.vector_to_obs) self.vertexWriter.addData3f(*position) self.colorwriter.addData4f(*self.color) self.context.observer.camera_global_pos = old_cam_pos self.lines = GeomLines(Geom.UHStatic) index = 0 for segment in self.segments: if len(segment) < 2: continue for i in range(len(segment) - 1): self.lines.addVertex(index) self.lines.addVertex(index + 1) self.lines.closePrimitive() index += 1 index += 1 self.geom = Geom(self.vertexData) self.geom.addPrimitive(self.lines) self.node = GeomNode("asterism") self.node.addGeom(self.geom) self.instance = NodePath(self.node) self.instance.setRenderModeThickness(settings.asterism_thickness) self.instance.reparentTo(self.context.annotation) self.instance.setBin('background', settings.asterisms_depth) self.instance.set_depth_write(False)
def _generate_mesh(radius: float, count: int) -> Geom: """Generate mesh for the ground plane.""" vertex_data = GeomVertexData('ground', VERTEX_FORMAT, Geom.UH_static) vertex_data.set_num_rows(count**2) vertex_writer = GeomVertexWriter(vertex_data, 'vertex') normal_writer = GeomVertexWriter(vertex_data, 'normal') texcoord_writer = GeomVertexWriter(vertex_data, 'texcoord') step = 2 * radius / count for i, j in product(range(count + 1), repeat=2): vertex_writer.add_data3f(i * step - radius, j * step - radius, 0.0) normal_writer.add_data3f(0.0, 0.0, 1.0) texcoord_writer.add_data2f(i * 512, j * 512) geom = Geom(vertex_data) primitive = GeomTristrips(Geom.UH_static) for j in range(count): rows = range(count + 1) if j % 2 else reversed(range(count + 1)) for i in rows: primitive.add_vertex((j + (j + 1) % 2) * (count + 1) + i) primitive.add_vertex((j + j % 2) * (count + 1) + i) primitive.close_primitive() geom.add_primitive(primitive) return geom
class Sun(PandaNode): def __init__(self, base_object): PandaNode.__init__(self, "Sun") self.geom = GeomNode("Sun") self.vertexData = GeomVertexData("Basis", GeomVertexFormat.getV3cpt2(), Geom.UHStatic) self.vertex = GeomVertexWriter(self.vertexData, 'vertex') self.tex_coord = GeomVertexWriter(self.vertexData, 'texcoord') self.mesh = Geom(self.vertexData) self.tris = GeomTristrips(Geom.UHStatic) self.vertex.addData3f(0.0, 0.0, 0.0) self.tex_coord.addData2f(1.0, 0.0) self.vertex.addData3f(1.0, 0.0, 0.0) self.tex_coord.addData2f(1.0, 1.0) self.vertex.addData3f(0.0, 1.0, 0.0) self.tex_coord.addData2f(0.0, 0.0) self.vertex.addData3f(1.0, 1.0, 0.0) self.tex_coord.addData2f(0.0, 1.0) self.tris.add_vertices(0, 1, 2, 3) self.tris.closePrimitive() self.mesh.addPrimitive(self.tris) self.geom.addGeom(self.mesh) self.node = base_object.render.attachNewNode(self.geom) self.node.set_r(-90) self.node.set_h(90) self.node.set_scale(40) self.node.set_pos(0, 500, 0) self.texture = base_object.loader.loadTexture( base_object.params("sun_texture")) self.node.set_texture(self.texture) self.node.setLightOff() self.node.setColorOff() self.node.setTransparency(True) self.node.set_bin('fixed', 1) self.node.set_depth_write(0) self.node.set_depth_test(0) self.node.setBillboardPointEye() def move(self, dx): self.node.set_pos(self.node.get_pos() + dx)