Пример #1
0
 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
Пример #2
0
    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
Пример #3
0
    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
Пример #4
0
 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
Пример #5
0
    def __build_ocean_mesh(self):
        vdata = GeomVertexData('data', GeomVertexFormat.getV3n3c4t2(),
                               Geom.UHStatic)
        vertex = GeomVertexWriter(vdata, 'vertex')
        normal = GeomVertexWriter(vdata, 'normal')
        texcoord = GeomVertexWriter(vdata, 'texcoord')
        color = GeomVertexWriter(vdata, 'color')

        axes = [Vec3.unitX(), Vec3.unitY(), Vec3.unitZ()]
        face = 0

        for x in range(3):
            for s in [-1, 1]:
                for i in range(self.__n + 1):
                    for j in range(self.__n + 1):
                        a = (i * 1.0 / self.__n) * (pi / 2) - (pi / 4)
                        b = (j * 1.0 / self.__n) * (pi / 2) - (pi / 4)
                        xAxis = axes[(x + 3) % 3]
                        yAxis = axes[(x + 4) % 3]
                        zAxis = axes[(x + 5) % 3]
                        v = (xAxis * (-cos(a) * sin(b)) + yAxis *
                             (sin(a) * cos(b)) + zAxis * (cos(a) * cos(b))) * s
                        v.normalize()
                        normal.addData3f(v)
                        vertex.addData3f(v * self.__radius)
                        texcoord.addData2f(i * 1.0, j * 1.0)
                        color.addData4f(self.__ocean_color)
                face = face + 1
        prim = self.__heightmap_primitive()
        geom = Geom(vdata)
        geom.addPrimitive(prim)
        return geom
Пример #6
0
	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
Пример #7
0
def make_geom(vertices, normals, colors, texcoords):
    if panda3d is None: raise ImportError("Cannot locate Panda3D")
    format = "V3"
    if normals is not None:
        assert len(normals) == len(vertices)
        format += "n3"

    if colors is not None:
        assert len(colors) == len(vertices)
        format += "cp"

    if texcoords is not None:
        assert len(texcoords) == len(vertices)
        format += "t2"
    format = getattr(GeomVertexFormat, "get" + format)()
    vdata = GeomVertexData("", format, Geom.UHStatic)

    v_vertex = GeomVertexWriter(vdata, 'vertex')
    if normals is not None: v_normals = GeomVertexWriter(vdata, 'normal')
    if colors is not None: v_colors = GeomVertexWriter(vdata, 'color')
    if texcoords is not None: v_texcoords = GeomVertexWriter(vdata, 'texcoord')

    for n in range(len(vertices)):
        v_vertex.addData3f(*vertices[n])
        if normals is not None: v_normals.addData3f(*normals[n])
        if colors is not None: v_colors.addData4f(*colors[n])
        if texcoords is not None: v_texcoords.addData2f(*texcoords[n])

    return Geom(vdata)
Пример #8
0
    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
Пример #9
0
    def makeSquare(x1, y1, z1, x2, y2, z2):
        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(1.0, 0.0, 0.0, 1.0)
        # color.addData4f(0.0, 1.0, 0.0, 1.0)
        # color.addData4f(0.0, 0.0, 1.0, 1.0)
        # color.addData4f(1.0, 0.0, 1.0, 1.0)

        color.addData4f(1.0, 1.0, 1.0, 1.0)
        color.addData4f(1.0, 1.0, 1.0, 1.0)
        color.addData4f(1.0, 1.0, 1.0, 1.0)
        color.addData4f(1.0, 1.0, 1.0, 1.0)

        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
Пример #10
0
def make_square(x1, y1, z1, x2, y2, z2, tex_coord):
    format = GeomVertexFormat.getV3n3t2()
    vdata = GeomVertexData("square", format, Geom.UHStatic)

    vertex = GeomVertexWriter(vdata, "vertex")
    normal = GeomVertexWriter(vdata, "normal")
    texcoord = GeomVertexWriter(vdata, "texcoord")

    # make sure we draw the sqaure in the right plane
    if x1 != x2:
        vertex.addData3f(x1, y1, z1)
        vertex.addData3f(x2, y1, z1)
        vertex.addData3f(x2, y2, z2)
        vertex.addData3f(x1, y2, z2)

    else:
        vertex.addData3f(x1, y1, z1)
        vertex.addData3f(x2, y2, z1)
        vertex.addData3f(x2, y2, z2)
        vertex.addData3f(x1, y1, z2)

    normal.addData3f(my_normalize(Vec3(2 * x1 - 1, 2 * y1 - 1, 2 * z1 - 1)))
    normal.addData3f(my_normalize(Vec3(2 * x2 - 1, 2 * y2 - 1, 2 * z1 - 1)))
    normal.addData3f(my_normalize(Vec3(2 * x2 - 1, 2 * y2 - 1, 2 * z2 - 1)))
    normal.addData3f(my_normalize(Vec3(2 * x1 - 1, 2 * y1 - 1, 2 * z2 - 1)))

    # adding different colors to the vertex for visibility

    u1, v1, u2, v2 = tex_coord

    texcoord.addData2f(u1, v2)
    texcoord.addData2f(u1, v1)
    texcoord.addData2f(u2, v1)
    texcoord.addData2f(u2, v2)

    # quads arent directly supported by the Geom interface
    # you might be interested in the CardMaker class if you are
    # interested in rectangle though
    tri1 = GeomTriangles(Geom.UHStatic)
    tri2 = GeomTriangles(Geom.UHStatic)

    tri1.addVertex(0)
    tri1.addVertex(1)
    tri1.addVertex(3)

    tri2.addConsecutiveVertices(1, 3)

    tri1.closePrimitive()
    tri2.closePrimitive()

    square = Geom(vdata)
    square.addPrimitive(tri1)
    square.addPrimitive(tri2)

    return square
Пример #11
0
def make_square(x1, y1, z1, x2, y2, z2, tex_coord):
    format = GeomVertexFormat.getV3n3t2()
    vdata = GeomVertexData('square', format, Geom.UHStatic)

    vertex = GeomVertexWriter(vdata, 'vertex')
    normal = GeomVertexWriter(vdata, 'normal')
    texcoord = GeomVertexWriter(vdata, 'texcoord')

    #make sure we draw the sqaure in the right plane
    if x1 != x2:
        vertex.addData3f(x1, y1, z1)
        vertex.addData3f(x2, y1, z1)
        vertex.addData3f(x2, y2, z2)
        vertex.addData3f(x1, y2, z2)

    else:
        vertex.addData3f(x1, y1, z1)
        vertex.addData3f(x2, y2, z1)
        vertex.addData3f(x2, y2, z2)
        vertex.addData3f(x1, y1, z2)

    normal.addData3f(my_normalize(Vec3(2 * x1 - 1, 2 * y1 - 1, 2 * z1 - 1)))
    normal.addData3f(my_normalize(Vec3(2 * x2 - 1, 2 * y2 - 1, 2 * z1 - 1)))
    normal.addData3f(my_normalize(Vec3(2 * x2 - 1, 2 * y2 - 1, 2 * z2 - 1)))
    normal.addData3f(my_normalize(Vec3(2 * x1 - 1, 2 * y1 - 1, 2 * z2 - 1)))

    #adding different colors to the vertex for visibility

    u1, v1, u2, v2 = tex_coord

    texcoord.addData2f(u1, v2)
    texcoord.addData2f(u1, v1)
    texcoord.addData2f(u2, v1)
    texcoord.addData2f(u2, v2)

    #quads arent directly supported by the Geom interface
    #you might be interested in the CardMaker class if you are
    #interested in rectangle though
    tri1 = GeomTriangles(Geom.UHStatic)
    tri2 = GeomTriangles(Geom.UHStatic)

    tri1.addVertex(0)
    tri1.addVertex(1)
    tri1.addVertex(3)

    tri2.addConsecutiveVertices(1, 3)

    tri1.closePrimitive()
    tri2.closePrimitive()

    square = Geom(vdata)
    square.addPrimitive(tri1)
    square.addPrimitive(tri2)

    return square
Пример #12
0
def makeSquare(x1, y1, z1, x2, y2, z2):
    format = GeomVertexFormat.getV3n3cpt2()
    vdata = GeomVertexData('square', format, Geom.UHDynamic)

    #initializing variables
    vertex = GeomVertexWriter(vdata, 'vertex')
    normal = GeomVertexWriter(vdata, 'normal')
    color = GeomVertexWriter(vdata, 'color')
    texcoord = GeomVertexWriter(vdata, 'texcoord')

    #gotta draw the sqaure in the right plane
    #aligning vertexes to the right planes
    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:
        #adding vertexes
        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(1.0, 0.0, 0.0, 1.0)
    color.addData4f(0.0, 1.0, 0.0, 1.0)
    color.addData4f(0.0, 0.0, 1.0, 1.0)
    color.addData4f(1.0, 0.0, 1.0, 1.0)

    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
    tris = GeomTriangles(Geom.UHDynamic)
    tris.addVertices(0, 1, 3)
    tris.addVertices(1, 2, 3)

    #initialize surface
    square = Geom(vdata)
    square.addPrimitive(tris)
    return square
Пример #13
0
def makeSquare(x1, y1, z1, x2, y2, z2):
    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(1.0, 0.0, 0.0, 1.0)
    # color.addData4f(0.0, 1.0, 0.0, 1.0)
    # color.addData4f(0.0, 0.0, 1.0, 1.0)
    # color.addData4f(1.0, 0.0, 1.0, 1.0)

    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
Пример #14
0
    def Square(self):
        format = GeomVertexFormat.getV3n3cpt2()
        vdata = GeomVertexData('cube', format, Geom.UHDynamic)

        vertex = GeomVertexWriter(vdata, 'vertex')
        ################################
        #
        # FACE 1
        #
        ################################
        vert1 = LVector3(self.pos.getX(), self.pos.getY(), self.pos.getZ())
        vert2 = LVector3(vert1.getX() + self.len, vert1.getY(), vert1.getZ())
        vert3 = LVector3(vert2.getX(), vert2.getY() + self.wid, vert2.getZ())
        vert4 = LVector3(vert1.getX(), vert1.getY() + self.wid, vert1.getZ())

        vertex.addData3(vert1)
        vertex.addData3(vert2)
        vertex.addData3(vert3)
        vertex.addData3(vert4)

        normal = GeomVertexWriter(vdata, 'normal')
        norm = (vert4 - vert1).cross(vert2 - vert1)
        norm.normalize()

        normal.addData3(norm)
        normal.addData3(norm)
        normal.addData3(norm)
        normal.addData3(norm)

        color = GeomVertexWriter(vdata, 'color')
        color.addData4f(self.color)
        color.addData4f(self.color)
        color.addData4f(self.color)
        color.addData4f(self.color)

        texcoord = GeomVertexWriter(vdata, 'texcoord')
        texcoord.addData2f(1, 0)
        texcoord.addData2f(1, 1)
        texcoord.addData2f(0, 1)
        texcoord.addData2f(0, 0)

        tris = GeomTriangles(Geom.UHDynamic)

        tris.addVertices(0, 3, 1)
        tris.addVertices(1, 3, 2)

        square = Geom(vdata)
        square.addPrimitive(tris)
        self.prim = square

        self.model = GeomNode(self.name)
        self.model.addGeom(self.prim)
Пример #15
0
def make_square4v(coord1, coord2, coord3, coord4, tex_coord):
    format = GeomVertexFormat.getV3n3t2()
    vdata = GeomVertexData('square', format, Geom.UHStatic)

    vertex = GeomVertexWriter(vdata, 'vertex')
    normal = GeomVertexWriter(vdata, 'normal')
    texcoord = GeomVertexWriter(vdata, 'texcoord')

    #make sure we draw the sqaure in the right plane
    vertex.addData3f(coord1)
    vertex.addData3f(coord2)
    vertex.addData3f(coord3)
    vertex.addData3f(coord4)

    side1 = coord1 - coord2
    side2 = coord1 - coord4
    norm1 = side1.cross(side2)
    side1 = coord2 - coord3
    side2 = coord2 - coord4
    norm2 = side1.cross(side2)

    normal.addData3f(norm1)
    normal.addData3f(norm1)
    normal.addData3f(norm1)
    normal.addData3f(norm2)

    #adding different colors to the vertex for visibility

    u1, v1, u2, v2 = tex_coord

    texcoord.addData2f(u1, v2)
    texcoord.addData2f(u1, v1)
    texcoord.addData2f(u2, v1)
    texcoord.addData2f(u2, v2)

    #quads arent directly supported by the Geom interface
    #you might be interested in the CardMaker class if you are
    #interested in rectangle though

    tri1.addVertex(0)
    tri1.addVertex(1)
    tri1.addVertex(3)

    tri1.addConsecutiveVertices(1, 3)

    tri1.closePrimitive()

    square = Geom(vdata)
    square.addPrimitive(tri1)

    return square
Пример #16
0
def createTexturedUnitQuadGeomNode():
    # Own Geometry

    # format = GeomVertexFormat.getV3c4t2()
    format = GeomVertexFormat.getV3t2()
    vdata = GeomVertexData("textured_quad", format, Geom.UHStatic)
    vdata.setNumRows(4)

    vertexPosWriter = GeomVertexWriter(vdata, "vertex")
    vertexPosWriter.addData3f(0, 0, 0)
    vertexPosWriter.addData3f(1, 0, 0)
    vertexPosWriter.addData3f(1, 0, 1)
    vertexPosWriter.addData3f(0, 0, 1)

    # let's also add color to each vertex
    # colorWriter = GeomVertexWriter(vdata, "color")
    # colorWriter.addData4f(0,0,1,1)
    # colorWriter.addData4f(0,0,1,1)
    # colorWriter.addData4f(0,0,1,1)
    # colorWriter.addData4f(0,0,1,1)

    # let's add texture coordinates (u,v)
    texcoordWriter = GeomVertexWriter(vdata, "texcoord")
    texcoordWriter.addData2f(0, 0)
    texcoordWriter.addData2f(1, 0)
    texcoordWriter.addData2f(1, 1)
    texcoordWriter.addData2f(0, 1)

    # make primitives and assign vertices to them (primitives and primitive
    # groups can be made independently from vdata, and are later assigned
    # to vdata)
    tris = GeomTriangles(Geom.UHStatic)

    # 1st triangle
    tris.addVertices(0, 1, 3)
    tris.closePrimitive()  # the 1st primitive is finished

    # 2nd triangle
    tris.addVertices(1, 2, 3)
    tris.closePrimitive()

    # make a Geom object to hold the primitives
    quadGeom = Geom(vdata)
    quadGeom.addPrimitive(tris)

    # now put quadGeom in a GeomNode. You can now position your geometry
    # in the scene graph.
    quadGeomNode = GeomNode("quad")
    quadGeomNode.addGeom(quadGeom)

    return quadGeomNode
Пример #17
0
def make_square4v(coord1, coord2, coord3, coord4, tex_coord):
    format = GeomVertexFormat.getV3n3t2()
    vdata = GeomVertexData("square", format, Geom.UHStatic)

    vertex = GeomVertexWriter(vdata, "vertex")
    normal = GeomVertexWriter(vdata, "normal")
    texcoord = GeomVertexWriter(vdata, "texcoord")

    # make sure we draw the sqaure in the right plane
    vertex.addData3f(coord1)
    vertex.addData3f(coord2)
    vertex.addData3f(coord3)
    vertex.addData3f(coord4)

    side1 = coord1 - coord2
    side2 = coord1 - coord4
    norm1 = side1.cross(side2)
    side1 = coord2 - coord3
    side2 = coord2 - coord4
    norm2 = side1.cross(side2)

    normal.addData3f(norm1)
    normal.addData3f(norm1)
    normal.addData3f(norm1)
    normal.addData3f(norm2)

    # adding different colors to the vertex for visibility

    u1, v1, u2, v2 = tex_coord

    texcoord.addData2f(u1, v2)
    texcoord.addData2f(u1, v1)
    texcoord.addData2f(u2, v1)
    texcoord.addData2f(u2, v2)

    # quads arent directly supported by the Geom interface
    # you might be interested in the CardMaker class if you are
    # interested in rectangle though

    tri1.addVertex(0)
    tri1.addVertex(1)
    tri1.addVertex(3)

    tri1.addConsecutiveVertices(1, 3)

    tri1.closePrimitive()

    square = Geom(vdata)
    square.addPrimitive(tri1)

    return square
Пример #18
0
def make_square(x1,
                y1,
                z1,
                x2,
                y2,
                z2,
                x3,
                y3,
                z3,
                x4,
                y4,
                z4,
                tex_len=None,
                tex_width=None):
    format = GeomVertexFormat.getV3n3cpt2()
    vdata = GeomVertexData('square', format, Geom.UHDynamic)

    vertex = GeomVertexWriter(vdata, 'vertex')
    normal = GeomVertexWriter(vdata, 'normal')
    texcoord = GeomVertexWriter(vdata, 'texcoord')

    vertex.addData3(x1, y1, z1)
    vertex.addData3(x2, y2, z2)
    vertex.addData3(x3, y3, z3)
    vertex.addData3(x4, y4, z4)

    D = Vec3(x1, y1, z1)
    C = Vec3(x2, y2, z2)
    B = Vec3(x3, y3, z3)
    A = Vec3(x4, y4, z4)
    normal_vec = (C - A).cross(D - B).normalize()

    normal.addData3(normal_vec)
    normal.addData3(normal_vec)
    normal.addData3(normal_vec)
    normal.addData3(normal_vec)

    side_len = math.sqrt((x3 - x1)**2 + (y3 - y1)**2)
    start_width = math.sqrt((x2 - x1)**2 + (y2 - y1)**2)
    end_width = math.sqrt((x4 - x3)**2 + (y4 - y3)**2)

    texcoord.addData2f(0.0, (start_width /
                             tex_width) if tex_width is not None else 1.0)
    texcoord.addData2f(0.0, 0.0)
    texcoord.addData2f((side_len / tex_len) if tex_len is not None else 1.0,
                       0.0)
    texcoord.addData2f(
        (side_len / tex_len) if tex_len is not None else 1.0,
        (end_width / tex_width) if tex_width is not None else 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, 2)
    tris.addVertices(0, 2, 3)

    square = Geom(vdata)
    square.addPrimitive(tris)
    return square
Пример #19
0
def makeCircle(vdata, numVertices=40, offset=Vec3(0, 0, 0), direction=1):
    circleGeom = Geom(vdata)

    vertWriter = GeomVertexWriter(vdata, "vertex")
    normalWriter = GeomVertexWriter(vdata, "normal")
    colorWriter = GeomVertexWriter(vdata, "color")
    uvWriter = GeomVertexWriter(vdata, "texcoord")
    drawWriter = GeomVertexWriter(vdata, "drawFlag")

    #make sure we start at the end of the GeomVertexData so we dont overwrite anything
    #that might be there already
    startRow = vdata.getNumRows()

    vertWriter.setRow(startRow)
    colorWriter.setRow(startRow)
    uvWriter.setRow(startRow)
    normalWriter.setRow(startRow)
    drawWriter.setRow(startRow)

    angle = 2 * math.pi / numVertices
    currAngle = angle

    for i in range(numVertices):
        position = Vec3(
            math.cos(currAngle) + offset.getX(),
            math.sin(currAngle) + offset.getY(), offset.getZ())
        vertWriter.addData3f(position)
        uvWriter.addData2f(position.getX() / 2.0 + 0.5,
                           position.getY() / 2.0 + 0.5)
        colorWriter.addData4f(1.0, 1.0, 1.0, 1.0)
        position.setZ(position.getZ() * direction)
        position.normalize()
        normalWriter.addData3f(position)

        #at default Opengl only draws "front faces" (all shapes whose vertices are arranged CCW). We
        #need direction so we can specify which side we want to be the front face
        currAngle += angle * direction

    circle = GeomTrifans(Geom.UHStatic)
    circle.addConsecutiveVertices(startRow, numVertices)
    circle.closePrimitive()

    circleGeom.addPrimitive(circle)

    return circleGeom
Пример #20
0
class Earth(PandaNode):
    def __init__(self, base_object):
        PandaNode.__init__(self, "Earth")

        self.geom = GeomNode("earth")
        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 = 200
        z = -1000
        dx = 0
        dy = -200

        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(1, 0, 3, 2)

        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_h(90)

        self.texture = base_object.loader.loadTexture(
            base_object.params("earth_texture"))
        self.node.set_texture(self.texture)

        self.node.setLightOff()
        self.node.setColorOff()
        self.node.setTransparency(True)

        # self.node.set_bin('fixed', 3)
        # 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)
Пример #21
0
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)
def makeCircle(vdata, numVertices=40,offset=Vec3(0,0,0), direction=1):
	circleGeom=Geom(vdata)

	vertWriter=GeomVertexWriter(vdata, "vertex")
	normalWriter=GeomVertexWriter(vdata, "normal")
	colorWriter=GeomVertexWriter(vdata, "color")
	uvWriter=GeomVertexWriter(vdata, "texcoord")
	drawWriter=GeomVertexWriter(vdata, "drawFlag")

	#make sure we start at the end of the GeomVertexData so we dont overwrite anything
	#that might be there already
	startRow=vdata.getNumRows()

	vertWriter.setRow(startRow)
	colorWriter.setRow(startRow)
	uvWriter.setRow(startRow)
	normalWriter.setRow(startRow)
	drawWriter.setRow(startRow)

	angle=2*math.pi/numVertices
	currAngle=angle

	for i in range(numVertices):
		position=Vec3(math.cos(currAngle)+offset.getX(), math.sin(currAngle)+offset.getY(),offset.getZ())
		vertWriter.addData3f(position)
		uvWriter.addData2f(position.getX()/2.0+0.5,position.getY()/2.0+0.5)
		colorWriter.addData4f(1.0, 1.0, 1.0, 1.0)
		position.setZ(position.getZ()*direction)
		position.normalize()
		normalWriter.addData3f(position)
		
		#at default Opengl only draws "front faces" (all shapes whose vertices are arranged CCW). We
		#need direction so we can specify which side we want to be the front face
		currAngle+=angle*direction

	circle=GeomTrifans(Geom.UHStatic)
	circle.addConsecutiveVertices(startRow, numVertices)
	circle.closePrimitive()

	circleGeom.addPrimitive(circle)
	
	return circleGeom
Пример #23
0
    def reconstruct(self):
        trianglator = Triangulator()

        #Add vertices to the trianglator
        for vertex in self.vertices:
            trianglator.addPolygonVertex(trianglator.addVertex(vertex))

        trianglator.triangulate()

        #Prepare to create the primative
        self.vdata = GeomVertexData('floor', GeomVertexFormat.getV3n3cpt2(),
                                    Geom.UHStatic)
        vertexW = GeomVertexWriter(self.vdata, 'vertex')
        normalW = GeomVertexWriter(self.vdata, 'normal')
        colorW = GeomVertexWriter(self.vdata, 'color')
        texcoordW = GeomVertexWriter(self.vdata, 'texcoord')

        #Add vertices to the primative
        i = 0
        while i < trianglator.getNumVertices():
            vertex = trianglator.getVertex(i)
            vertexW.addData3f(vertex.x, vertex.y, 0.0)
            normalW.addData3f(0, 0, 1)
            colorW.addData4f(0.1, 0.1, 0.1, 0.5)
            texcoordW.addData2f(0.0, 1.0)
            i += 1

        self.geom = Geom(self.vdata)

        #Add triangles to the primative
        i = 0
        print(trianglator.getNumTriangles())
        while i < trianglator.getNumTriangles():
            tri = GeomTriangles(Geom.UHStatic)
            tri.addVertices(trianglator.getTriangleV0(i),
                            trianglator.getTriangleV1(i),
                            trianglator.getTriangleV2(i))
            tri.closePrimitive()
            self.geom.addPrimitive(tri)
            i += 1

        self.addGeom(self.geom)
Пример #24
0
    def __build_land_mesh(self):
        vdata = GeomVertexData('data', GeomVertexFormat.getV3n3c4t2(),
                               Geom.UHStatic)
        vertex = GeomVertexWriter(vdata, 'vertex')
        normal = GeomVertexWriter(vdata, 'normal')
        texcoord = GeomVertexWriter(vdata, 'texcoord')
        color = GeomVertexWriter(vdata, 'color')

        axes = [Vec3.unitX(), Vec3.unitY(), Vec3.unitZ()]
        face = 0

        for x in range(3):
            for s in [-1, 1]:
                for i in range(self.__n + 1):
                    for j in range(self.__n + 1):
                        a = (i * 1.0 / self.__n) * (pi / 2) - (pi / 4)
                        b = (j * 1.0 / self.__n) * (pi / 2) - (pi / 4)
                        xAxis = axes[(x + 3) % 3]
                        yAxis = axes[(x + 4) % 3]
                        zAxis = axes[(x + 5) % 3]
                        v = (xAxis * (-cos(a) * sin(b)) + yAxis *
                             (sin(a) * cos(b)) + zAxis * (cos(a) * cos(b))) * s
                        v.normalize()
                        normal.addData3f(v)
                        index = self.__height_i(face, i, j)
                        v = v * (
                            1.0 +
                            (self.__height_factor * self.__height_unit *
                             (self.__heightmap[index] - 0.5))) * self.__radius
                        vertex.addData3f(v)
                        texcoord.addData2f(i * 1.0, j * 1.0)
                        c = self.__gradient(self.__color_gradient,
                                            self.__heightmap[index])
                        color.addData4f(c[0] / 255.0, c[1] / 255.0,
                                        c[2] / 255.0, 1.0)
                face = face + 1

        prim = self.__heightmap_primitive()
        geom = Geom(vdata)
        geom.addPrimitive(prim)
        return geom
Пример #25
0
Файл: pd.py Проект: btdevel/bt
def makeSquare(face, rhs=True):
    format=GeomVertexFormat.getV3n3cpt2()
    format=GeomVertexFormat.getV3n3t2()
    vdata=GeomVertexData('square', format, Geom.UHStatic)

    vertex=GeomVertexWriter(vdata, 'vertex')
    normal=GeomVertexWriter(vdata, 'normal')
    #color=GeomVertexWriter(vdata, 'color')
    texcoord=GeomVertexWriter(vdata, 'texcoord')

    if not rhs:
        face = list(reversed(face))

    normalvec = (face[1]-face[0]).cross(face[2]-face[0])
    normalvec.normalize()

    f = 0.9 if rhs else 0.8
    f = 1.0
    for ver in face:
        vertex.addData3f(ver*f)
        normal.addData3f(normalvec)
        #color.addData3f((ver+1.0+2.0)*0.25)
        #color.addData3f(ver*0.0+1.0)

    if not normalvec.z:
        texcoord.addData2f(0.0, 0.0)
        texcoord.addData2f(1.0, 0.0)
        texcoord.addData2f(1.0, 1.0)
        texcoord.addData2f(0.0, 1.0)

    
    tri=GeomTriangles(Geom.UHStatic)
    tri.addVertices(0, 1, 2)
    tri.addVertices(2, 3, 0)
    tri.closePrimitive()

    square=Geom(vdata)
    square.addPrimitive(tri)
    return square
Пример #26
0
	def reconstruct(self):
		trianglator = Triangulator()

		#Add vertices to the trianglator
		for vertex in self.vertices:
			trianglator.addPolygonVertex(trianglator.addVertex(vertex))
		
		trianglator.triangulate()

		#Prepare to create the primative
		self.vdata = GeomVertexData('floor', GeomVertexFormat.getV3n3cpt2(), Geom.UHStatic)
		vertexW = GeomVertexWriter(self.vdata, 'vertex')
		normalW = GeomVertexWriter(self.vdata, 'normal')
		colorW = GeomVertexWriter(self.vdata, 'color')
		texcoordW = GeomVertexWriter(self.vdata, 'texcoord')

		#Add vertices to the primative
		i = 0
		while i < trianglator.getNumVertices():
			vertex = trianglator.getVertex(i)
			vertexW.addData3f(vertex.x,vertex.y,0.0)
			normalW.addData3f(0,0,1)
			colorW.addData4f(0.1,0.1,0.1,0.5)
			texcoordW.addData2f(0.0, 1.0)	
			i+=1

		self.geom = Geom(self.vdata)

		#Add triangles to the primative
		i = 0
		print(trianglator.getNumTriangles())
		while i < trianglator.getNumTriangles():
			tri = GeomTriangles(Geom.UHStatic)
			tri.addVertices(trianglator.getTriangleV0(i),trianglator.getTriangleV1(i),trianglator.getTriangleV2(i))
			tri.closePrimitive()
			self.geom.addPrimitive(tri)
			i+=1

		self.addGeom(self.geom)
def update_nodepath(pandaNode, refinements):
    geom = pandaNode.modifyGeom(0)
    
    vertdata = geom.modifyVertexData()
    prim = geom.modifyPrimitive(0)
    indexdata = prim.modifyVertices()
    
    indexwriter = GeomVertexWriter(indexdata)
    indexwriter.setColumn(0)
    nextTriangleIndex = indexdata.getNumRows()
    
    vertwriter = GeomVertexWriter(vertdata, 'vertex')
    numverts = vertdata.getNumRows()
    vertwriter.setRow(numverts)
    normalwriter = GeomVertexWriter(vertdata, 'normal')
    normalwriter.setRow(numverts)
    uvwriter = GeomVertexWriter(vertdata, 'texcoord')
    uvwriter.setRow(numverts)
    
    for refinement in refinements:
        for op_index in range(len(refinement)):
            vals = refinement[op_index]
            op = vals[0]
            if op == PM_OP.TRIANGLE_ADDITION:
                indexwriter.setRow(nextTriangleIndex)
                nextTriangleIndex += 3
                indexwriter.addData1i(vals[1])
                indexwriter.addData1i(vals[2])
                indexwriter.addData1i(vals[3])
            elif op == PM_OP.INDEX_UPDATE:
                indexwriter.setRow(vals[1])
                indexwriter.setData1i(vals[2])
            elif op == PM_OP.VERTEX_ADDITION:
                numverts += 1
                vertwriter.addData3f(vals[1], vals[2], vals[3])
                normalwriter.addData3f(vals[4], vals[5], vals[6])
                uvwriter.addData2f(vals[7], vals[8])
Пример #28
0
def create_textured_rect(x, z, width, height):
    _format = GeomVertexFormat.getV3t2()
    vdata = GeomVertexData('square', _format, Geom.UHDynamic)

    vertex = GeomVertexWriter(vdata, 'vertex')
    texcoord = GeomVertexWriter(vdata, 'texcoord')

    vertex.addData3(x, 0, z)
    vertex.addData3(x + width, 0, z)
    vertex.addData3(x + width, 0, z + height)
    vertex.addData3(x, 0, z + height)

    texcoord.addData2f(0.0, 0.0)
    texcoord.addData2f(1.0, 0.0)
    texcoord.addData2f(1.0, 1.0)
    texcoord.addData2f(0.0, 1.0)

    tris = GeomTriangles(Geom.UHDynamic)
    tris.addVertices(0, 1, 2)
    tris.addVertices(2, 3, 0)

    square = Geom(vdata)
    square.addPrimitive(tris)
    return square
Пример #29
0
    def make_cube_geom(self,
                       pos=(0, 0, 0),
                       geom_color=(1, 1, 1, 0.5),
                       faces_no_draw=(0, 0, 0, 0, 0, 0)):
        format = GeomVertexFormat.getV3n3cpt2()

        shift_x, shift_y, shift_z = pos

        cube_vertex_list = deepcopy(cube_data["vertexPositions"])
        for vert in cube_vertex_list:
            vert[0] += shift_x
            vert[1] += shift_y
            vert[2] += shift_z

        vdata = GeomVertexData('square', format, Geom.UHDynamic)
        vertex = GeomVertexWriter(vdata, 'vertex')
        normal = GeomVertexWriter(vdata, 'normal')
        color = GeomVertexWriter(vdata, 'color')
        texcoord = GeomVertexWriter(vdata, 'texcoord')

        test_textcoords = []

        # define available vertexes here
        [vertex.addData3(*v) for v in cube_vertex_list]
        [normal.addData3(*n) for n in cube_data["vertexNormals"]]
        [color.addData4f(*geom_color) for _ in cube_vertex_list]
        [texcoord.addData2f(*t) for t in texture_mapping]
        """ CREATE A NEW PRIMITIVE """
        prim = GeomTriangles(Geom.UHStatic)

        # convert from numpy arr mapping to normal faces mapping...
        excluded_normals = [
            normal_face_mapping[self.dict_mapping[i]]
            for i in range(len(faces_no_draw)) if faces_no_draw[i] == 1
        ]

        # only use acceptable indices
        indices = [
            ind for ind in cube_data['indices']
            if cube_data['vertexNormals'][ind] not in excluded_normals
        ]
        [prim.addVertex(v) for v in indices]

        #  N.B: this must correspond to a vertex defined in vdata
        geom = Geom(vdata)  # create a new geometry
        geom.addPrimitive(prim)  # add the primitive to the geometry

        return geom
Пример #30
0
def make_cube_geom(pos=(0, 0, 0), geom_color=(1, 1, 1, 1)):
    format = GeomVertexFormat.getV3n3cpt2()

    shift_x, shift_y, shift_z = pos

    cube_vertex_list = deepcopy(cube_data["vertexPositions"])
    for vert in cube_vertex_list:
        # vert[0] *= scale
        # vert[1] *= scale
        # vert[2] *= scale
        vert[0] += shift_x
        vert[1] += shift_y
        vert[2] += shift_z

    vdata = GeomVertexData('square', format, Geom.UHDynamic)
    vertex = GeomVertexWriter(vdata, 'vertex')
    normal = GeomVertexWriter(vdata, 'normal')
    color = GeomVertexWriter(vdata, 'color')
    texcoord = GeomVertexWriter(vdata, 'texcoord')

    # define available vertexes here

    [normal.addData3(*n) for n in cube_data["vertexNormals"]]
    [vertex.addData3(*v) for v in cube_vertex_list]

    [color.addData4f(*geom_color) for _ in cube_vertex_list]
    [texcoord.addData2f(1, 1) for _ in cube_vertex_list]
    """ CREATE A NEW PRIMITIVE """
    prim = GeomTriangles(Geom.UHStatic)

    # [prim.addVertex(v) for v in vertexes]
    indices = [ind for ind in cube_data['indices']]
    [prim.addVertex(v) for v in indices]

    #  N.B: this must correspond to a vertex defined in vdata
    geom = Geom(vdata)  # create a new geometry
    geom.addPrimitive(prim)  # add the primitive to the geometry

    return geom
Пример #31
0
    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)
Пример #32
0
def getNodeFromController(controller, controlled_prim):
    if type(controlled_prim) is collada.controller.BoundSkinPrimitive:
        ch = Character('simplechar')
        bundle = ch.getBundle(0)
        skeleton = PartGroup(bundle, '<skeleton>')

        character_joints = {}
        for (name, joint_matrix) in controller.joint_matrices.iteritems():
            joint_matrix.shape = (-1)
            character_joints[name] = CharacterJoint(ch, bundle, skeleton, name,
                                                    Mat4(*joint_matrix))

        tbtable = TransformBlendTable()

        for influence in controller.index:
            blend = TransformBlend()
            for (joint_index, weight_index) in influence:
                char_joint = character_joints[controller.getJoint(joint_index)]
                weight = controller.getWeight(weight_index)[0]
                blend.addTransform(JointVertexTransform(char_joint), weight)
            tbtable.addBlend(blend)

        array = GeomVertexArrayFormat()
        array.addColumn(InternalName.make('vertex'), 3, Geom.NTFloat32,
                        Geom.CPoint)
        array.addColumn(InternalName.make('normal'), 3, Geom.NTFloat32,
                        Geom.CPoint)
        array.addColumn(InternalName.make('texcoord'), 2, Geom.NTFloat32,
                        Geom.CTexcoord)
        blendarr = GeomVertexArrayFormat()
        blendarr.addColumn(InternalName.make('transform_blend'), 1,
                           Geom.NTUint16, Geom.CIndex)

        format = GeomVertexFormat()
        format.addArray(array)
        format.addArray(blendarr)
        aspec = GeomVertexAnimationSpec()
        aspec.setPanda()
        format.setAnimation(aspec)
        format = GeomVertexFormat.registerFormat(format)

        dataname = controller.id + '-' + controlled_prim.primitive.material.id
        vdata = GeomVertexData(dataname, format, Geom.UHStatic)
        vertex = GeomVertexWriter(vdata, 'vertex')
        normal = GeomVertexWriter(vdata, 'normal')
        texcoord = GeomVertexWriter(vdata, 'texcoord')
        transform = GeomVertexWriter(vdata, 'transform_blend')

        numtris = 0
        if type(controlled_prim.primitive) is collada.polylist.BoundPolylist:
            for poly in controlled_prim.primitive.polygons():
                for tri in poly.triangles():
                    for tri_pt in range(3):
                        vertex.addData3f(tri.vertices[tri_pt][0],
                                         tri.vertices[tri_pt][1],
                                         tri.vertices[tri_pt][2])
                        normal.addData3f(tri.normals[tri_pt][0],
                                         tri.normals[tri_pt][1],
                                         tri.normals[tri_pt][2])
                        if len(controlled_prim.primitive._texcoordset) > 0:
                            texcoord.addData2f(tri.texcoords[0][tri_pt][0],
                                               tri.texcoords[0][tri_pt][1])
                        transform.addData1i(tri.indices[tri_pt])
                    numtris += 1
        elif type(controlled_prim.primitive
                  ) is collada.triangleset.BoundTriangleSet:
            for tri in controlled_prim.primitive.triangles():
                for tri_pt in range(3):
                    vertex.addData3f(tri.vertices[tri_pt][0],
                                     tri.vertices[tri_pt][1],
                                     tri.vertices[tri_pt][2])
                    normal.addData3f(tri.normals[tri_pt][0],
                                     tri.normals[tri_pt][1],
                                     tri.normals[tri_pt][2])
                    if len(controlled_prim.primitive._texcoordset) > 0:
                        texcoord.addData2f(tri.texcoords[0][tri_pt][0],
                                           tri.texcoords[0][tri_pt][1])
                    transform.addData1i(tri.indices[tri_pt])
                numtris += 1

        tbtable.setRows(SparseArray.lowerOn(vdata.getNumRows()))

        gprim = GeomTriangles(Geom.UHStatic)
        for i in range(numtris):
            gprim.addVertices(i * 3, i * 3 + 1, i * 3 + 2)
            gprim.closePrimitive()

        pgeom = Geom(vdata)
        pgeom.addPrimitive(gprim)

        render_state = getStateFromMaterial(controlled_prim.primitive.material)
        control_node = GeomNode("ctrlnode")
        control_node.addGeom(pgeom, render_state)
        ch.addChild(control_node)

        bundle = AnimBundle('simplechar', 5.0, 2)
        skeleton = AnimGroup(bundle, '<skeleton>')
        root = AnimChannelMatrixXfmTable(skeleton, 'root')

        #hjoint = AnimChannelMatrixXfmTable(root, 'joint1')
        #table = [10, 11, 12, 13, 14, 15, 14, 13, 12, 11]
        #data = PTAFloat.emptyArray(len(table))
        #for i in range(len(table)):
        #    data.setElement(i, table[i])
        #hjoint.setTable(ord('i'), CPTAFloat(data))

        #vjoint = AnimChannelMatrixXfmTable(hjoint, 'joint2')
        #table = [10, 9, 8, 7, 6, 5, 6, 7, 8, 9]
        #data = PTAFloat.emptyArray(len(table))
        #for i in range(len(table)):
        #    data.setElement(i, table[i])
        #vjoint.setTable(ord('j'), CPTAFloat(data))

        wiggle = AnimBundleNode('wiggle', bundle)

        np = NodePath(ch)
        anim = NodePath(wiggle)
        a = Actor(np, {'simplechar': anim})
        a.loop('simplechar')
        return a
        #a.setPos(0, 0, 0)

    else:
        raise Exception("Error: unsupported controller type")
Пример #33
0
def getNodeFromGeom(prim):
        format = GeomVertexFormat.getV3n3t2()
        vdata = GeomVertexData("dataname", format, Geom.UHStatic)
        vertex = GeomVertexWriter(vdata, 'vertex')
        normal = GeomVertexWriter(vdata, 'normal')
        texcoord = GeomVertexWriter(vdata, 'texcoord')
        
        if type(prim) is collada.triangleset.BoundTriangleSet:
            numtris = 0
            for tri in prim.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(prim._texcoordset) > 0:
                        texcoord.addData2f(tri.texcoords[0][tri_pt][0], tri.texcoords[0][tri_pt][1])
                numtris+=1
                
            gprim = GeomTriangles(Geom.UHStatic)
            for i in range(numtris):
                gprim.addVertices(i*3, i*3+1, i*3+2)
                gprim.closePrimitive()
                
        elif type(prim) is collada.polylist.BoundPolygonList:
            numtris = 0
            for poly in prim.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(prim._texcoordset) > 0:
                            texcoord.addData2f(tri.texcoords[0][tri_pt][0], tri.texcoords[0][tri_pt][1])
                    numtris+=1

            gprim = GeomTriangles(Geom.UHStatic)
            for i in range(numtris):
                gprim.addVertices(i*3, i*3+1, i*3+2)
                gprim.closePrimitive()
                
        elif type(prim) is collada.lineset.BoundLineSet:
            numlines = 0
            for line in prim.lines():
                for line_pt in range(2):
                    vertex.addData3f(line.vertices[line_pt][0], line.vertices[line_pt][1], line.vertices[line_pt][2])
                numlines+=1

            gprim = GeomLines(Geom.UHStatic)
            for i in range(numlines):
                gprim.addVertices(i*2, i*2+1)
                gprim.closePrimitive()

        else:
            raise Exception("Error: Unsupported primitive type. Exiting.")
            
        pgeom = Geom(vdata)
        pgeom.addPrimitive(gprim)
        
        render_state = getStateFromMaterial(prim.material)
        node = GeomNode("primitive")
        node.addGeom(pgeom, render_state)
        
        return node
Пример #34
0
class MapPointMngr:
    def __init__(self):
        # self.point_cloud: List[Tuple[Tuple[float, float, float], int]] = []
        self.v_data = None
        self.vert_writer = None
        self.color_writer = None
        self.uv_writer = None
        self.normal_writer = None
        self.draw_writer = None
        self.map_dim = (0, 0)
        self.crit_points_per_hex: List[List[Tuple[Tuple[float, float, float], int]]] = []

    def set_v_data(self, v_data):
        self.v_data = v_data
        self.vert_writer = GeomVertexWriter(self.v_data, "vertex")
        self.color_writer = GeomVertexWriter(self.v_data, "color")
        self.uv_writer = GeomVertexWriter(self.v_data, "texcoord")
        self.normal_writer = GeomVertexWriter(self.v_data, "normal")
        self.draw_writer = GeomVertexWriter(self.v_data, "drawFlag")

    def set_map_dim(self, map_dim: Tuple[int, int]):
        self.map_dim = map_dim

    def add_non_critical_point(self, p: Tuple[float, float, float], hex_x_grid: int, hex_y_grid: int,
                               uv_map: Vec2, n=Vec3(.0, .0, 1.0)) -> int:
        if not self.v_data:
            return -1
        lin_idx = self.linearize(hex_x_grid, hex_y_grid)
        if len(self.crit_points_per_hex) <= lin_idx:
            print("ERROR - can add non critical points only to a existing hexagon ..")
            return -1
        points_hex = self.crit_points_per_hex[lin_idx]
        idx = self.__add_point_to_vdata(p, n, uv_map)
        points_hex.append((p, idx))
        return idx

    def add_critical_point(self, p: Tuple[float, float, float], hex_x_grid: int, hex_y_grid: int,
                           uv_map: Vec2, n=Vec3(.0, .0, 1.0)) -> int:
        if not self.v_data:
            return -1

        lin_idx = self.linearize(hex_x_grid, hex_y_grid)
        if len(self.crit_points_per_hex) == lin_idx:
            # print(f"add center point: {p}")
            # new hexagon and point is a center-point (cannot exist already)
            self.crit_points_per_hex.append([])
            idx = self.__add_point_to_vdata(p, n, uv_map)
            self.crit_points_per_hex[lin_idx].append((p, idx))
            return idx
        else:
            # print(f"add non-center point {p}")
            # existing hexagon - 3 neighbouring hexagons possible
            # if hex_x_grid > 0:
            #     points_west = self.crit_points_per_hex[self.linearize(hex_x_grid-1, hex_y_grid)]
            #     for nei, idx in points_west:
            #         if self.close_enough(p, nei):
            #             return idx
            # if hex_y_grid > 0:
            #     points_south_west = self.crit_points_per_hex[self.linearize(hex_x_grid, hex_y_grid - 1)]
            #     for nei, idx in points_south_west:
            #         if self.close_enough(p, nei):
            #             return idx
            #     points_south_east = self.crit_points_per_hex[self.linearize(hex_x_grid+1, hex_y_grid - 1)]
            #     for nei, idx in points_south_east:
            #         if self.close_enough(p, nei):
            #             return idx
            idx = self.__add_point_to_vdata(p, n, uv_map)
            self.crit_points_per_hex[lin_idx].append((p, idx))
            return idx

        # for vec, idx in self.point_cloud:
        #     if abs(vec[0] - p[0]) < TOL and abs(vec[1] - p[1]) < TOL and abs(vec[2] - p[2]) < TOL:
        #         # print(f"point reused at {vec} -> ({p})")
        #         return idx

        # print(f"new point at {p}")

    def __add_point_to_vdata(self, p, n, uv_map) -> int:
        new_idx = self.v_data.getNumRows()
        self.vert_writer.setRow(new_idx)
        self.color_writer.setRow(new_idx)
        self.uv_writer.setRow(new_idx)
        self.draw_writer.setRow(new_idx)
        self.normal_writer.setRow(new_idx)
        position = Vec3(p[0], p[1], p[2])
        self.vert_writer.addData3f(position)
        self.color_writer.addData4f(.3, .3, .3, 1.0)
        self.normal_writer.addData3f(n)
        self.uv_writer.addData2f(uv_map[0], uv_map[1])  # not sure here
        return new_idx

    def linearize(self, x, y):
        return y * self.map_dim[0] + x

    def close_enough(self, p, other):
        return abs(other[0] - p[0]) < TOL and abs(other[1] - p[1]) < TOL and abs(other[2] - p[2]) < TOL
Пример #35
0
class MeshGenerator():
   
    def __init__(self, name = 'Mesh'):
       
        self.name = name
        self.finished = False
 
        self.format = GeomVertexFormat.getV3c4t2()
        #print self.format
        self.vertexData = GeomVertexData(name, self.format, Geom.UHStatic)
        self.vertexData.setNumRows(26136)
       
        self.mesh = Geom(self.vertexData)
        self.triangles = GeomTriangles(Geom.UHStatic)
        self.triangleData = self.triangles.modifyVertices()
        self.triangleData.setNumRows(26136)
       
        self.vertex = GeomVertexWriter(self.vertexData, 'vertex')
        self.normal = GeomVertexWriter(self.vertexData, 'normal')
        self.color = GeomVertexWriter(self.vertexData, 'color')
        self.texcoord = GeomVertexWriter(self.vertexData, 'texcoord')
       
        self.faceCount = 0
   
    def makeFace(self, x1, y1, z1, x2, y2, z2, id, color):
       
        if x1 != x2:
       
            self.vertex.addData3f(x1, y1, z1)
            self.vertex.addData3f(x2, y1, z1)
            self.vertex.addData3f(x2, y2, z2)
            self.vertex.addData3f(x1, y2, z2)
           
        else:
       
            self.vertex.addData3f(x1, y1, z1)
            self.vertex.addData3f(x2, y2, z1)
            self.vertex.addData3f(x2, y2, z2)
            self.vertex.addData3f(x1, y1, z2)
 
 
        self.color.addData4f(color, color, color, 1.0)
        self.color.addData4f(color, color, color, 1.0)
        self.color.addData4f(color, color, color, 1.0)
        self.color.addData4f(color, color, color, 1.0)
       
        if id == 1:
            self.texcoord.addData2f(0.0, 0.5)
            self.texcoord.addData2f(0.0, 0.0)
            self.texcoord.addData2f(0.25, 0.0)
            self.texcoord.addData2f(0.25, 0.5)
        elif id == 2:
            self.texcoord.addData2f(0.25, 0.5)
            self.texcoord.addData2f(0.25, 0.0)
            self.texcoord.addData2f(0.5, 0.0)
            self.texcoord.addData2f(0.5, 0.5)
        elif id == 3:
            self.texcoord.addData2f(0.5, 0.5)
            self.texcoord.addData2f(0.5, 0.0)
            self.texcoord.addData2f(0.75, 0.0)
            self.texcoord.addData2f(0.75, 0.5)
        elif id == 4:
            self.texcoord.addData2f(0.75, 0.5)
            self.texcoord.addData2f(0.75, 0.0)
            self.texcoord.addData2f(1.0, 0.0)
            self.texcoord.addData2f(1.0, 0.5)
        elif id == 5:
            self.texcoord.addData2f(0.0, 1.0)
            self.texcoord.addData2f(0.0, 0.5)
            self.texcoord.addData2f(0.25, 0.5)
            self.texcoord.addData2f(0.25, 1.0)
        elif id == 6:
            self.texcoord.addData2f(0.25, 1.0)
            self.texcoord.addData2f(0.25, 0.5)
            self.texcoord.addData2f(0.5, 0.5)
            self.texcoord.addData2f(0.5, 1.0)
       
        vertexId = self.faceCount * 4
       
        self.triangles.addVertices(vertexId, vertexId + 1, vertexId + 3)
        self.triangles.addVertices(vertexId + 1, vertexId + 2, vertexId + 3)
       
        self.faceCount += 1
   
    def makeFrontFace(self, x, y, z, id):
        self.makeFace(x + 1, y + 1, z - 1, x, y + 1, z, id, 0.6)
   
    def makeBackFace(self, x, y, z, id):
        self.makeFace(x, y, z - 1, x + 1, y, z, id, 0.85)
   
    def makeRightFace(self, x, y, z, id):
        self.makeFace(x + 1, y, z - 1, x + 1, y + 1, z, id, 1.0)
   
    def makeLeftFace(self, x, y, z, id):
        self.makeFace(x, y + 1, z - 1, x, y, z, id, 0.9)
   
    def makeTopFace(self, x, y, z, id):
        self.makeFace(x + 1, y + 1, z, x, y, z, id, 1.0)
   
    def makeBottomFace(self, x, y, z, id):
        self.makeFace(x, y + 1, z - 1, x + 1, y, z - 1, id, 0.70)
   
    def getMesh(self):
        return self.mesh
   
    def getGeomNode(self):
        if self.finished == False:
            self.triangles.closePrimitive()
            self.mesh.addPrimitive(self.triangles)
            self.finished = True
        geomNode = GeomNode(self.name)
        geomNode.addGeom(self.mesh)
        return geomNode
Пример #36
0
    def Ramp(self):
        format = GeomVertexFormat.getV3n3cpt2()
        vdata = GeomVertexData('square', format, Geom.UHDynamic)

        vertex = GeomVertexWriter(vdata, 'vertex')

        #The corner at Quadrant 2 on face 1 is the starting point of our rectangle

        ################################
        #
        # FACE 1
        #
        ################################
        vert1 = LVector3(self.pos.getX(), self.pos.getY(), self.pos.getZ())
        vert2 = LVector3(vert1.getX() + self.len, vert1.getY(), vert1.getZ())
        vert3 = LVector3(vert2.getX(), vert2.getY() + self.wid, vert2.getZ())
        vert4 = LVector3(vert1.getX(), vert1.getY() + self.wid, vert1.getZ())

        vertex.addData3(vert1)
        vertex.addData3(vert2)
        vertex.addData3(vert3)
        vertex.addData3(vert4)

        normal = GeomVertexWriter(vdata, 'normal')
        norm = (vert4 - vert1).cross(vert2 - vert1)
        norm.normalize()

        normal.addData3(norm)
        normal.addData3(norm)
        normal.addData3(norm)
        normal.addData3(norm)

        color = GeomVertexWriter(vdata, 'color')
        color.addData4f(self.color)
        color.addData4f(self.color)
        color.addData4f(self.color)
        color.addData4f(self.color)

        texcoord = GeomVertexWriter(vdata, 'texcoord')
        texcoord.addData2f(1, 0)
        texcoord.addData2f(1, 1)
        texcoord.addData2f(0, 1)
        texcoord.addData2f(0, 0)

        tris = GeomTriangles(Geom.UHDynamic)

        tris.addVertices(0, 3, 1)
        tris.addVertices(1, 3, 2)

        #####################################
        #
        #   FACE 2
        #
        #####################################

        vert5 = vert1
        vert6 = vert2
        vert7 = LVector3(vert3.getX(), vert3.getY(), vert3.getZ() + self.dep)
        vert8 = LVector3(vert4.getX(), vert4.getY(), vert4.getZ() + self.dep)

        vertex.addData3(vert5)
        vertex.addData3(vert6)
        vertex.addData3(vert7)
        vertex.addData3(vert8)

        norm = (vert8 - vert5).cross(vert6 - vert5)
        norm.normalize()

        normal.addData3(norm)
        normal.addData3(norm)
        normal.addData3(norm)
        normal.addData3(norm)

        color.addData4f(self.color)
        color.addData4f(self.color)
        color.addData4f(self.color)
        color.addData4f(self.color)

        texcoord.addData2f(1, 0)
        texcoord.addData2f(1, 1)
        texcoord.addData2f(0, 1)
        texcoord.addData2f(0, 0)

        tris.addVertices(4, 7, 5)
        tris.addVertices(5, 7, 6)

        ########################################
        #
        #   FACE 3
        #
        ########################################

        vert9 = vert1
        vert10 = vert2
        vert11 = vert6
        vert12 = vert5

        vertex.addData3(vert9)
        vertex.addData3(vert10)
        vertex.addData3(vert11)
        vertex.addData3(vert12)

        norm = (vert12 - vert9).cross(vert10 - vert9)
        norm.normalize()
        normal.addData3(norm)
        normal.addData3(norm)
        normal.addData3(norm)
        normal.addData3(norm)

        color.addData4f(self.color)
        color.addData4f(self.color)
        color.addData4f(self.color)
        color.addData4f(self.color)

        texcoord.addData2f(1, 0)
        texcoord.addData2f(1, 1)
        texcoord.addData2f(0, 1)
        texcoord.addData2f(0, 0)

        tris.addVertices(8, 11, 9)
        tris.addVertices(9, 11, 10)

        ###############################################
        #
        #   FACE 4
        #
        ###############################################

        vert13 = vert1
        vert14 = vert4
        vert15 = vert8
        vert16 = vert5

        vertex.addData3(vert13)
        vertex.addData3(vert14)
        vertex.addData3(vert15)
        vertex.addData3(vert16)

        norm = (vert16 - vert13).cross(vert14 - vert13)
        norm.normalize()
        normal.addData3(norm)
        normal.addData3(norm)
        normal.addData3(norm)
        normal.addData3(norm)

        color.addData4f(self.color)
        color.addData4f(self.color)
        color.addData4f(self.color)
        color.addData4f(self.color)

        texcoord.addData2f(1, 0)
        texcoord.addData2f(1, 1)
        texcoord.addData2f(0, 1)
        texcoord.addData2f(0, 0)

        tris.addVertices(12, 15, 13)
        tris.addVertices(13, 15, 14)

        ############################################
        #
        #   FACE 5
        #
        ############################################

        vert17 = vert2
        vert18 = vert3
        vert19 = vert7
        vert20 = vert6

        vertex.addData3(vert17)
        vertex.addData3(vert18)
        vertex.addData3(vert19)
        vertex.addData3(vert20)

        norm = (vert20 - vert17).cross(vert18 - vert17)
        normal.addData3(norm)
        normal.addData3(norm)
        normal.addData3(norm)
        normal.addData3(norm)

        color.addData4f(self.color)
        color.addData4f(self.color)
        color.addData4f(self.color)
        color.addData4f(self.color)

        texcoord.addData2f(1, 0)
        texcoord.addData2f(1, 1)
        texcoord.addData2f(0, 1)
        texcoord.addData2f(0, 0)

        tris.addVertices(16, 19, 17)
        tris.addVertices(17, 19, 18)

        ramp = Geom(vdata)
        ramp.addPrimitive(tris)
        self.prim = ramp

        self.model = GeomNode(self.name)
        self.model.addGeom(self.prim)
Пример #37
0
    def Prism(self):
        format = GeomVertexFormat.getV3n3cpt2()
        vdata = GeomVertexData('cube', format, Geom.UHDynamic)

        vertex = GeomVertexWriter(vdata, 'vertex')
        ####################################
        #First, we need to create the first face, and then base
        #the other faces on it.
        ####################################
        #
        #   DIAGRAM OF A RECTANGULAR PRISM
        #            |--------|
        #            | Face 6 |<-Depth
        #   |--------|--------|--------|--------|
        #   | Face 4 | Face 2 | Face 3 | Face 1 |  <-Width
        #   |        |        |        |        |
        #   |--------|--------|--------|--------|
        #            | Face 5 |          ^Length
        #            |--------|
        ####################################

        #The corner at Quadrant 2 on face 1 is the starting point of our rectangle

        ################################
        #
        # FACE 1
        #
        ################################
        vert1 = LVector3(self.pos.getX(), self.pos.getY(), self.pos.getZ())
        vert2 = LVector3(vert1.getX() + self.len, vert1.getY(), vert1.getZ())
        vert3 = LVector3(vert2.getX(), vert2.getY() + self.wid, vert2.getZ())
        vert4 = LVector3(vert1.getX(), vert1.getY() + self.wid, vert1.getZ())

        vertex.addData3(vert1)
        vertex.addData3(vert2)
        vertex.addData3(vert3)
        vertex.addData3(vert4)

        normal = GeomVertexWriter(vdata, 'normal')
        norm = (vert4 - vert1).cross(vert2 - vert1)
        norm.normalize()

        normal.addData3(norm)
        normal.addData3(norm)
        normal.addData3(norm)
        normal.addData3(norm)

        color = GeomVertexWriter(vdata, 'color')
        color.addData4f(self.color)
        color.addData4f(self.color)
        color.addData4f(self.color)
        color.addData4f(self.color)

        texcoord = GeomVertexWriter(vdata, 'texcoord')
        texcoord.addData2f(1, 0)
        texcoord.addData2f(1, 1)
        texcoord.addData2f(0, 1)
        texcoord.addData2f(0, 0)

        tris = GeomTriangles(Geom.UHDynamic)

        tris.addVertices(0, 3, 1)
        tris.addVertices(1, 3, 2)

        #####################################
        #
        #   FACE 2
        #
        #####################################

        vert5 = LVector3(vert1.getX(), vert1.getY(), vert1.getZ() - self.dep)
        vert6 = LVector3(vert5.getX() + self.len, vert5.getY(), vert5.getZ())
        vert7 = LVector3(vert6.getX(), vert6.getY() + self.wid, vert6.getZ())
        vert8 = LVector3(vert5.getX(), vert5.getY() + self.wid, vert5.getZ())

        vertex.addData3(vert5)
        vertex.addData3(vert6)
        vertex.addData3(vert7)
        vertex.addData3(vert8)

        norm = (vert8 - vert5).cross(vert6 - vert5)
        norm.normalize()

        normal.addData3(norm)
        normal.addData3(norm)
        normal.addData3(norm)
        normal.addData3(norm)

        color.addData4f(self.color)
        color.addData4f(self.color)
        color.addData4f(self.color)
        color.addData4f(self.color)

        texcoord.addData2f(1, 0)
        texcoord.addData2f(1, 1)
        texcoord.addData2f(0, 1)
        texcoord.addData2f(0, 0)

        tris.addVertices(4, 7, 5)
        tris.addVertices(5, 7, 6)

        ########################################
        #
        #   FACE 3
        #
        ########################################

        vert9 = vert1
        vert10 = vert2
        vert11 = vert6
        vert12 = vert5

        vertex.addData3(vert9)
        vertex.addData3(vert10)
        vertex.addData3(vert11)
        vertex.addData3(vert12)

        norm = (vert12 - vert9).cross(vert10 - vert9)
        norm.normalize()

        normal.addData3(norm)
        normal.addData3(norm)
        normal.addData3(norm)
        normal.addData3(norm)

        color.addData4f(self.color)
        color.addData4f(self.color)
        color.addData4f(self.color)
        color.addData4f(self.color)

        texcoord.addData2f(1, 0)
        texcoord.addData2f(1, 1)
        texcoord.addData2f(0, 1)
        texcoord.addData2f(0, 0)

        tris.addVertices(8, 11, 9)
        tris.addVertices(9, 11, 10)

        ##########################################
        #
        #   FACE 4
        #
        ###########################################

        vert13 = vert4
        vert14 = vert3
        vert15 = vert7
        vert16 = vert8

        vertex.addData3(vert13)
        vertex.addData3(vert14)
        vertex.addData3(vert15)
        vertex.addData3(vert16)

        norm = (vert16 - vert13).cross(vert14 - vert13)
        norm.normalize()

        normal.addData3(norm)
        normal.addData3(norm)
        normal.addData3(norm)
        normal.addData3(norm)

        color.addData4f(self.color)
        color.addData4f(self.color)
        color.addData4f(self.color)
        color.addData4f(self.color)

        texcoord.addData2f(1, 0)
        texcoord.addData2f(1, 1)
        texcoord.addData2f(0, 1)
        texcoord.addData2f(0, 0)

        tris.addVertices(12, 15, 13)
        tris.addVertices(13, 15, 14)

        square = Geom(vdata)
        square.addPrimitive(tris)

        ###############################################
        #
        #   FACE 5
        #
        ###############################################

        vert17 = vert1
        vert18 = vert4
        vert19 = vert8
        vert20 = vert5

        vertex.addData3(vert17)
        vertex.addData3(vert18)
        vertex.addData3(vert19)
        vertex.addData3(vert20)

        norm = (vert20 - vert17).cross(vert18 - vert17)
        norm.normalize()

        normal.addData3(norm)
        normal.addData3(norm)
        normal.addData3(norm)
        normal.addData3(norm)

        color.addData4f(self.color)
        color.addData4f(self.color)
        color.addData4f(self.color)
        color.addData4f(self.color)

        texcoord.addData2f(1, 0)
        texcoord.addData2f(1, 1)
        texcoord.addData2f(0, 1)
        texcoord.addData2f(0, 0)

        tris.addVertices(16, 19, 17)
        tris.addVertices(17, 19, 18)

        ############################################
        #
        #   FACE 6
        #
        ############################################

        vert21 = vert2
        vert22 = vert3
        vert23 = vert7
        vert24 = vert6

        vertex.addData3(vert21)
        vertex.addData3(vert22)
        vertex.addData3(vert23)
        vertex.addData3(vert24)

        norm = (vert21 - vert24).cross(vert21 - vert22)
        norm.normalize()

        normal.addData3(norm)
        normal.addData3(norm)
        normal.addData3(norm)
        normal.addData3(norm)

        color.addData4f(self.color)
        color.addData4f(self.color)
        color.addData4f(self.color)
        color.addData4f(self.color)

        texcoord.addData2f(1, 0)
        texcoord.addData2f(1, 1)
        texcoord.addData2f(0, 1)
        texcoord.addData2f(0, 0)

        tris.addVertices(20, 23, 21)
        tris.addVertices(21, 23, 22)

        square = Geom(vdata)
        square.addPrimitive(tris)
        self.prim = square

        self.model = GeomNode(self.name)
        self.model.addGeom(self.prim)
Пример #38
0
    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}
            )
        ''')
Пример #39
0
    def movePmTo(self, dest_index):
        geom = self.geomPath.node().modifyGeom(0)
        vertdata = geom.modifyVertexData()
        prim = geom.modifyPrimitive(0)
        indexdata = prim.modifyVertices()
        
        indexrewriter = GeomVertexRewriter(indexdata)
        indexrewriter.setColumn(0)
        nextTriangleIndex = indexdata.getNumRows()
        
        vertwriter = GeomVertexWriter(vertdata, 'vertex')
        numverts = vertdata.getNumRows()
        vertwriter.setRow(numverts)
        normalwriter = GeomVertexWriter(vertdata, 'normal')
        normalwriter.setRow(numverts)
        uvwriter = GeomVertexWriter(vertdata, 'texcoord')
        uvwriter.setRow(numverts)
        
        while self.pm_index < dest_index:
            for op_index in range(len(self.pm_refinements[self.pm_index])):
                vals = self.pm_refinements[self.pm_index][op_index]
                op = vals[0]
                if op == PM_OP.TRIANGLE_ADDITION:
                    indexrewriter.setRow(nextTriangleIndex)
                    nextTriangleIndex += 3
                    indexrewriter.addData1i(vals[1])
                    indexrewriter.addData1i(vals[2])
                    indexrewriter.addData1i(vals[3])
                elif op == PM_OP.INDEX_UPDATE:
                    #TODO: ugly workaround for p3d 1.7 bug, change to below for 1.8
                    indexreader = GeomVertexReader(indexdata)
                    indexreader.setColumn(0)
                    indexreader.setRow(vals[1])
                    oldval = indexreader.getData1i()
                    del indexreader
                    
                    #indexrewriter.setRow(vals[1])
                    #oldval = indexrewriter.getData1i()
                    
                    indexrewriter.setRow(vals[1])
                    indexrewriter.setData1i(vals[2])
                    self.pm_refinements[self.pm_index][op_index] = (op, vals[1], oldval)
                elif op == PM_OP.VERTEX_ADDITION:
                    numverts += 1
                    vertwriter.addData3f(vals[1], vals[2], vals[3])
                    normalwriter.addData3f(vals[4], vals[5], vals[6])
                    uvwriter.addData2f(vals[7], vals[8])
                
            self.pm_index += 1

        while self.pm_index > dest_index:
            self.pm_index -= 1
            for op_index in range(len(self.pm_refinements[self.pm_index])):
                vals = self.pm_refinements[self.pm_index][op_index]
                op = vals[0]
                if op == PM_OP.TRIANGLE_ADDITION:
                    nextTriangleIndex -= 3
                elif op == PM_OP.INDEX_UPDATE:
                    #TODO: ugly workaround for p3d 1.7 bug, change to below for 1.8
                    indexreader = GeomVertexReader(indexdata)
                    indexreader.setColumn(0)
                    indexreader.setRow(vals[1])
                    oldval = indexreader.getData1i()
                    del indexreader
                    
                    #indexrewriter.setRow(vals[1])
                    #oldval = indexrewriter.getData1i()
                    
                    indexrewriter.setRow(vals[1])
                    indexrewriter.setData1i(vals[2])
                    self.pm_refinements[self.pm_index][op_index] = (op, vals[1], oldval)
                elif op == PM_OP.VERTEX_ADDITION:
                    numverts -= 1

        if nextTriangleIndex < indexdata.getNumRows():
            indexdata.setNumRows(nextTriangleIndex)
        if numverts < vertdata.getNumRows():
            vertdata.setNumRows(numverts)
Пример #40
0
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'
Пример #41
0
def getNodeFromController(controller, controlled_prim):
    if type(controlled_prim) is collada.controller.BoundSkinPrimitive:
        ch = Character('simplechar')
        bundle = ch.getBundle(0)
        skeleton = PartGroup(bundle, '<skeleton>')

        character_joints = {}
        for (name, joint_matrix) in controller.joint_matrices.iteritems():
            joint_matrix.shape = (-1)
            character_joints[name] = CharacterJoint(ch, bundle, skeleton, name, Mat4(*joint_matrix)) 
        
        tbtable = TransformBlendTable()
        
        for influence in controller.index:
            blend = TransformBlend()
            for (joint_index, weight_index) in influence:
                char_joint = character_joints[controller.getJoint(joint_index)]
                weight = controller.getWeight(weight_index)[0]
                blend.addTransform(JointVertexTransform(char_joint), weight)
            tbtable.addBlend(blend)
            
        array = GeomVertexArrayFormat()
        array.addColumn(InternalName.make('vertex'), 3, Geom.NTFloat32, Geom.CPoint)
        array.addColumn(InternalName.make('normal'), 3, Geom.NTFloat32, Geom.CPoint)
        array.addColumn(InternalName.make('texcoord'), 2, Geom.NTFloat32, Geom.CTexcoord)
        blendarr = GeomVertexArrayFormat()
        blendarr.addColumn(InternalName.make('transform_blend'), 1, Geom.NTUint16, Geom.CIndex)
        
        format = GeomVertexFormat()
        format.addArray(array)
        format.addArray(blendarr)
        aspec = GeomVertexAnimationSpec()
        aspec.setPanda()
        format.setAnimation(aspec)
        format = GeomVertexFormat.registerFormat(format)
        
        dataname = controller.id + '-' + controlled_prim.primitive.material.id
        vdata = GeomVertexData(dataname, format, Geom.UHStatic)
        vertex = GeomVertexWriter(vdata, 'vertex')
        normal = GeomVertexWriter(vdata, 'normal')
        texcoord = GeomVertexWriter(vdata, 'texcoord')
        transform = GeomVertexWriter(vdata, 'transform_blend') 
        
        numtris = 0
        if type(controlled_prim.primitive) is collada.polylist.BoundPolylist:
            for poly in controlled_prim.primitive.polygons():
                for tri in poly.triangles():
                    for tri_pt in range(3):
                        vertex.addData3f(tri.vertices[tri_pt][0], tri.vertices[tri_pt][1], tri.vertices[tri_pt][2])
                        normal.addData3f(tri.normals[tri_pt][0], tri.normals[tri_pt][1], tri.normals[tri_pt][2])
                        if len(controlled_prim.primitive._texcoordset) > 0:
                            texcoord.addData2f(tri.texcoords[0][tri_pt][0], tri.texcoords[0][tri_pt][1])
                        transform.addData1i(tri.indices[tri_pt])
                    numtris+=1
        elif type(controlled_prim.primitive) is collada.triangleset.BoundTriangleSet:
            for tri in controlled_prim.primitive.triangles():
                for tri_pt in range(3):
                    vertex.addData3f(tri.vertices[tri_pt][0], tri.vertices[tri_pt][1], tri.vertices[tri_pt][2])
                    normal.addData3f(tri.normals[tri_pt][0], tri.normals[tri_pt][1], tri.normals[tri_pt][2])
                    if len(controlled_prim.primitive._texcoordset) > 0:
                        texcoord.addData2f(tri.texcoords[0][tri_pt][0], tri.texcoords[0][tri_pt][1])
                    transform.addData1i(tri.indices[tri_pt])
                numtris+=1
                    
        tbtable.setRows(SparseArray.lowerOn(vdata.getNumRows())) 
        
        gprim = GeomTriangles(Geom.UHStatic)
        for i in range(numtris):
            gprim.addVertices(i*3, i*3+1, i*3+2)
            gprim.closePrimitive()
            
        pgeom = Geom(vdata)
        pgeom.addPrimitive(gprim)
        
        render_state = getStateFromMaterial(controlled_prim.primitive.material)
        control_node = GeomNode("ctrlnode")
        control_node.addGeom(pgeom, render_state)
        ch.addChild(control_node)
    
        bundle = AnimBundle('simplechar', 5.0, 2)
        skeleton = AnimGroup(bundle, '<skeleton>')
        root = AnimChannelMatrixXfmTable(skeleton, 'root')
        
        #hjoint = AnimChannelMatrixXfmTable(root, 'joint1') 
        #table = [10, 11, 12, 13, 14, 15, 14, 13, 12, 11] 
        #data = PTAFloat.emptyArray(len(table)) 
        #for i in range(len(table)): 
        #    data.setElement(i, table[i]) 
        #hjoint.setTable(ord('i'), CPTAFloat(data)) 
        
        #vjoint = AnimChannelMatrixXfmTable(hjoint, 'joint2') 
        #table = [10, 9, 8, 7, 6, 5, 6, 7, 8, 9] 
        #data = PTAFloat.emptyArray(len(table)) 
        #for i in range(len(table)): 
        #    data.setElement(i, table[i]) 
        #vjoint.setTable(ord('j'), CPTAFloat(data)) 

        wiggle = AnimBundleNode('wiggle', bundle)

        np = NodePath(ch) 
        anim = NodePath(wiggle) 
        a = Actor(np, {'simplechar' : anim})
        a.loop('simplechar') 
        return a
        #a.setPos(0, 0, 0)
    
    else:
        raise Exception("Error: unsupported controller type")
Пример #42
0
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)
Пример #43
0
 def __init__(self):
 
     self.textures={}
     for k in texMap:
         v=texMap[k]
         tex=loader.loadTexture("gfx/%s"%v)
         tex.setWrapU(Texture.WM_clamp)
         tex.setWrapV(Texture.WM_clamp)
         self.textures[k]=tex
     
     self.viewPoint=(0,0,0)
     self.cubeVtxSrc=[
         # 14 vertices per cube mapped
         # so that UV coords utilize
         # the typical cube unwrap:
         #
         #   ####  <-- square texture
         #   ##U#
         #   BLFR
         #   ##D#    #=unused
         #
         # This form uses 14 vertices per cube since
         # the extra (worldspace overlapped) vertices
         # map different U,V coordinates at the same
         # worldspace coordinates, depending on face
         #   
         # x    y    z    u    v
         (1.00,1.00,1.00,0.00,0.50), # A
         (1.00,1.00,0.00,0.00,0.25), # B
         (0.00,1.00,1.00,0.25,0.50), # C
         (0.00,1.00,0.00,0.25,0.25), # D
         (0.00,0.00,1.00,0.50,0.50), # E
         (0.00,0.00,0.00,0.50,0.25), # F
         (1.00,0.00,1.00,0.75,0.50), # G
         (1.00,0.00,0.00,0.75,0.25), # H
         (1.00,1.00,1.00,1.00,0.50), # I
         (1.00,1.00,0.00,1.00,0.25), # J
         (0.00,1.00,1.00,0.50,0.75), # K
         (1.00,1.00,1.00,0.75,0.75), # L
         (0.00,1.00,0.00,0.50,0.00), # M
         (1.00,1.00,0.00,0.75,0.00)  # N
         ]
     self.triSrc=[
         #
         #  Faces (QUAD/TRIPAIR)
         #  using RHR vertex ordering for
         #  correct face surface normals
         #
         #    front: EFHG/EFH+HGE
         #     rear: CABD/CAB+BDC
         #     left: CDFE/CDF+FEC
         #    right: GHJI/GHJ+JIG
         #    upper: KEGL/KEG+GLK
         #    lower: FMNH/FMN+NHF
         #
         "EFH","HGE",
         "CAB","BDC",
         "CDF","FEC",
         "GHJ","JIG",
         "KEG","GLK",
         "FMN","NHF"
         ]
     #
     # setup cube
     #
     # one cube node will be generated per non-air block
     # since different block id's potentially refer to
     # different textures and thus must be separate nodes
     # of the scene graph.
     #
     #   1. vertices
     self.cubeVtx=GeomVertexData('blockCube',GeomVertexFormat.getV3t2(),Geom.UHStatic)
     self.cubeVtx.setNumRows(len(self.cubeVtxSrc))
     vtxW=GeomVertexWriter(self.cubeVtx,'vertex')
     txcW=GeomVertexWriter(self.cubeVtx,'texcoord')
     for vertex in self.cubeVtxSrc:
         vtxW.addData3f(*vertex[0:3])
         txcW.addData2f(*vertex[3:5])
     #   2. mesh
     self.cubeMesh=GeomTriangles(Geom.UHStatic)
     for tri in self.triSrc:
         for triV in tri:
             triVtxId=ord(triV)-65 # changea 'A'-'N' to 0-13
             self.cubeMesh.addVertex(triVtxId)
         self.cubeMesh.close_primitive()
     #   3. geometry (primitive+vertex pair)
     self.cubeGeom=Geom(self.cubeVtx)
     self.cubeGeom.addPrimitive(self.cubeMesh)
Пример #44
0
    def generate(
            self
    ):  # call this after setting some of the variables to update it
        if not self.vertices:
            return

        if hasattr(self, 'geomNode'):
            self.geomNode.removeAllGeoms()

        static_mode = Geom.UHStatic if self.static else Geom.UHDynamic

        formats = {
            (0, 0, 0): GeomVertexFormat.getV3(),
            (1, 0, 0): GeomVertexFormat.getV3c4(),
            (0, 1, 0): GeomVertexFormat.getV3t2(),
            (0, 0, 1): GeomVertexFormat.getV3n3(),
            (1, 0, 1): GeomVertexFormat.getV3n3c4(),
            (1, 1, 0): GeomVertexFormat.getV3c4t2(),
            (0, 1, 1): GeomVertexFormat.getV3n3t2(),
            (1, 1, 1): GeomVertexFormat.getV3n3c4t2(),
        }

        vertex_format = formats[(bool(self.colors), bool(self.uvs),
                                 bool(self.normals))]
        vdata = GeomVertexData('name', vertex_format, static_mode)
        vdata.setNumRows(len(self.vertices))  # for speed

        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]))

        modes = {
            'triangle': GeomTriangles(static_mode),
            'tristrip': GeomTristrips(static_mode),
            'ngon': GeomTrifans(static_mode),
            'line': GeomLines(static_mode),
            'lines': GeomLinestrips(static_mode),
            'point': GeomPoints(static_mode),
        }
        if self.mode == 'line' and len(self.vertices) % 2 > 0:
            if len(self.vertices) == 1:
                self.mode = point
            print(
                'warning: number of vertices must be even for line mode, ignoring last vert'
            )
            self.vertices = self.vertices[:len(self.vertices) - 1]

        prim = modes[self.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 = GeomNode('mesh')
        self.geomNode.addGeom(geom)
        self.attachNewNode(self.geomNode)
        # print('finished')

        self.recipe = f'''Mesh(
Пример #45
0
def make_square(sq_color):
    # sq_color is a list of tuples, describing each vertex:
    # (r, g, b, a) for [bl, br, tr, tl]
    x1 = -1
    y1 = -1
    z1 = -1
    x2 = 1
    y2 = -1
    z2 = 1
    v_format = GeomVertexFormat.getV3n3cpt2()
    v_data = GeomVertexData('square', v_format, Geom.UHDynamic)

    vertex = GeomVertexWriter(v_data, 'vertex')
    normal = GeomVertexWriter(v_data, 'normal')
    color = GeomVertexWriter(v_data, 'color')
    tex_coord = GeomVertexWriter(v_data, '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(1.0, 0.0, 0.0, 1.0)
    # color.addData4f(0.0, 1.0, 0.0, 1.0)
    # color.addData4f(0.0, 0.0, 1.0, 1.0)
    # color.addData4f(1.0, 0.0, 1.0, 1.0)
    color.addData4f(sq_color[0])  # (0, 0) bottom left
    color.addData4f(sq_color[1])  # (0.5, 0) bottom right
    color.addData4f(sq_color[2])  # (0.5, 0.5) top right
    color.addData4f(sq_color[3])  # (0, 0.5) top left

    tex_coord.addData2f(0.0, 1.0)
    tex_coord.addData2f(0.0, 0.0)
    tex_coord.addData2f(1.0, 0.0)
    tex_coord.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(v_data)
    square.addPrimitive(tris)
    return square
	def makeMountains():

		format=GeomVertexFormat.getV3t2()
		vdata=GeomVertexData('mountains', format, Geom.UHStatic)
		vertex=GeomVertexWriter(vdata, 'vertex')
		texcoord=GeomVertexWriter(vdata, 'texcoord')

		format2=GeomVertexFormat.getV3c4()
		vdata2=GeomVertexData('sky', format2, Geom.UHStatic)
		vertex2=GeomVertexWriter(vdata2, 'vertex')
		color2=GeomVertexWriter(vdata2, 'color')

		numQuads=32

		angle=0
		textureX=0
		angleAdd=math.pi*2/numQuads
		textureXAdd=1.0/numQuads
		currentQuad=0
		numVertices=0

		while currentQuad<numQuads:
			if currentQuad==0:

				vertexX=math.sin(angle)*3000
				vertexY=math.cos(angle)*3000
				vertex.addData3f(vertexX,vertexY,0.0)
				vertex.addData3f(vertexX,vertexY,360.0)

				texcoord.addData2f(1.0, 0.0)
				texcoord.addData2f(1.0, 1.0)

				numVertices=numVertices+2

			vertexX=math.sin(angle)*3000
			vertexY=math.cos(angle)*3000
		
			vertex.addData3f(vertexX,vertexY,0.0)
			vertex.addData3f(vertexX,vertexY,360.0)

			vertex2.addData3f(vertexX,vertexY,360.0)
			color2.addData4f(45.0/255.0,112.0/255.0,255.0/255.0,1.0)
			#color2.addData4f(1.0,1.0,1.0,1.0)

			#print('created vertex at '+str(vertexX)+','+str(vertexY)+',2')
			#print('created vertex at '+str(vertexX)+','+str(vertexY)+',0')

			texcoord.addData2f(textureX, 0.0)
			texcoord.addData2f(textureX, 1.0)
			#print('texturex is '+str(textureX))

			#print('creating vertices v'+str(numVertices)+' and v'+str(numVertices+1))

			numVertices=numVertices+2
			currentQuad=currentQuad+1
			textureX=textureX+textureXAdd
			angle=angle+angleAdd

		vertex2.addData3f(0.0,0.0,360.0)
		#color2.addData4f(1.0,1.0,1.0,1.0)
		color2.addData4f(45.0/255.0,112.0/255.0,255.0/255.0,1.0)

		currentQuad=0
		currentOffset=2
		tris=GeomTriangles(Geom.UHDynamic)

		#print('creating tris - numVertices is '+str(numVertices))

		while currentQuad<numQuads:

			vertexOffsets=[]
			for innerIndex in range(4):
				offset=currentOffset+innerIndex
				#print('comparing '+str(offset)+' with '+str(numVertices-1))
				if offset>numVertices-1:
					offset=offset-numVertices
				vertexOffsets.append(offset)

			#print('adding tri connecting v'+str(vertexOffsets[0])+', v'+str(vertexOffsets[1])+', v'+str(vertexOffsets[3]))
			#print('adding tri connecting v'+str(vertexOffsets[1])+', v'+str(vertexOffsets[3])+', v'+str(vertexOffsets[2]))

			tris.addVertex(vertexOffsets[0])
			tris.addVertex(vertexOffsets[2])
			tris.addVertex(vertexOffsets[1])
			tris.closePrimitive()

			tris.addVertex(vertexOffsets[1])
			tris.addVertex(vertexOffsets[2])
			tris.addVertex(vertexOffsets[3])
			tris.closePrimitive()

			currentOffset=currentOffset+2
			currentQuad=currentQuad+1

		tris2=GeomTriangles(Geom.UHDynamic)
		currentOffset=1

		numTris=numQuads
		currentTri=0
		while currentTri<numTris:

			tris2.addVertex(numTris)
			tris2.addVertex(currentTri)
			if currentTri==numTris-1:
				tris2.addVertex(0)
			else:
				tris2.addVertex(currentTri+1)
			tris2.closePrimitive()

			currentTri=currentTri+1

		mountains=Geom(vdata)
		mountains.addPrimitive(tris)

		sky=Geom(vdata2)
		sky.addPrimitive(tris2)

		snode=GeomNode('mountains')
		snode.addGeom(mountains)

		snode2=GeomNode('sky')
		snode2.addGeom(sky)

		returnValues={"mountains":snode,"sky":snode2}
		return returnValues
Пример #47
0
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'
Пример #48
0
    def createBox(self):
        """
        Create the skybox GeomNode
        :return:
        """

        obj = ''
        obj += "# Skybox\n"
        obj += 'mtllib skybox.mtl\n'


        mtl = '# material for skybox\n'

        fmt = GeomVertexFormat.getV3n3t2()
        vdata = GeomVertexData('skybox', fmt, Geom.UHStatic)
        vdata.setNumRows(24)

        vertex = GeomVertexWriter(vdata, 'vertex')
        normals = GeomVertexWriter(vdata, 'normal')
        texcoord = GeomVertexWriter(vdata, 'texcoord')

        node = GeomNode('skybox')

        for normal in self.normals:
            geom = Geom(vdata)
            prim = GeomTriangles(Geom.UHStatic)

            idx = vertex.getWriteRow()

            verts = self.vertMappings[normal]
            tcs = self.getFaceMapping(normal)

            for v, t in zip(verts, tcs):
                vertex.addData3f(v[0]*2, v[1]*2, v[2]*2)
                normals.addData3f(normal)
                texcoord.addData2f(t)

                obj += 'v {0} {1} {2}\n'.format(v[0]*2, v[1]*2, v[2]*2)
                obj += 'vn {0} {1} {2}\n'.format(*normal)
                obj += 'vt {0} {1}\n'.format(*t)


            tex = self.getFaceTexture(normal)

            prim.addVertices(idx, idx + 1, idx + 3)
            prim.closePrimitive()

            obj += "usemtl {0}\n".format(tex.getName())
            obj += 'f {0}/{0} {1}/{1} {2}/{2}\n'.format(1+idx, 1+idx+1, 1+idx+3)

            prim.addVertices(idx + 1, idx + 2, idx + 3)
            prim.closePrimitive()

            obj += "usemtl {0}\n".format(tex.getName())
            obj += 'f {0}/{0} {1}/{1} {2}/{2}\n'.format(1+idx+1, 1+idx+2, 1+idx+3)

            geom.addPrimitive(prim)

            tex.setWrapU(Texture.WMMirror)
            tex.setWrapV(Texture.WMMirror)

            node.addGeom(geom, RenderState.make(TextureAttrib.make(tex)))


            mtl += "newmtl {0}\n".format(tex.getName())
            mtl += "Ka 1 1 1\n"
            mtl += "Kd 1 1 1\n"
            mtl += "map_Kd {0}\n".format(tex.getFilename().toOsSpecific())

        return node
Пример #49
0
    def pandaRender(self):
        frameList = []
        for node in self.compositeFrames.getiterator('composite-frame'):
            if node.tag == "composite-frame" and node.attrib.get("id") == str(self.internalFrameIndex):
                for frameCallNode in node:
                    for frameNode in self.frames.getiterator('frame'):
                        if frameNode.tag == "frame" and frameNode.attrib.get("id") == frameCallNode.attrib.get("id"):
                            offsetX = 0 if frameCallNode.attrib.get("offset-x") == None else float(frameCallNode.attrib.get("offset-x"))
                            offsetY = 0 if frameCallNode.attrib.get("offset-y") == None else float(frameCallNode.attrib.get("offset-y"))
                            tweenId = frameCallNode.attrib.get("tween")
                            frameInTween = 0 if frameCallNode.attrib.get("frame-in-tween") == None else int(frameCallNode.attrib.get("frame-in-tween"))
                            addWidth = 0 if frameNode.attrib.get("w") == None else float(frameNode.attrib.get("w"))
                            addHeight = 0 if frameNode.attrib.get("h") == None else float(frameNode.attrib.get("h"))
                            sInPixels = 0 if frameNode.attrib.get("s") == None else float(frameNode.attrib.get("s"))
                            tInPixels = 0 if frameNode.attrib.get("t") == None else float(frameNode.attrib.get("t"))
                            swInPixels = sInPixels + addWidth
                            thInPixels = tInPixels + addHeight
                            s = (sInPixels / self.baseWidth)
                            t = 1 - (tInPixels / self.baseHeight) # Complemented to deal with loading image upside down.
                            S = (swInPixels / self.baseWidth)
                            T = 1 - (thInPixels / self.baseHeight) # Complemented to deal with loading image upside down.
                            blend = "overwrite" if frameCallNode.attrib.get("blend") == None else frameCallNode.attrib.get("blend")
                            scaleX = 1 if frameCallNode.attrib.get("scale-x") == None else float(frameCallNode.attrib.get("scale-x"))
                            scaleY = 1 if frameCallNode.attrib.get("scale-y") == None else float(frameCallNode.attrib.get("scale-y"))
                            color = Color(1,1,1,1)
                            tweenHasColor = False
                            frameCallHasColor = False
                            frameCallColorName = frameCallNode.attrib.get("color-name")
                            if frameCallColorName != None:
                                # Get color at frame call as first resort.
                                frameCallHasColor = True
                                for colorNode in self.colors.getiterator('color'):
                                    if colorNode.tag == 'color' and colorNode.attrib.get("name") == frameCallColorName:
                                        R = 1 if colorNode.attrib.get("r") == None else float(colorNode.attrib.get("r"))
                                        G = 1 if colorNode.attrib.get("g") == None else float(colorNode.attrib.get("g"))
                                        B = 1 if colorNode.attrib.get("b") == None else float(colorNode.attrib.get("b"))
                                        A = 1 if colorNode.attrib.get("a") == None else float(colorNode.attrib.get("a"))
                                        color = Color(R, G, B, A)
                                        break # leave for loop when we find the correct color
                                pass

                            if tweenId != None and tweenId != "0":
                                # Get color at tween frame as second resort.
                                thisTween = None
                                frameLength = 1
                                advancementFunction = "linear"
                                foundTween = False
                                pointList = []
                                colorList = []
                                for tweenNode in self.tweens.getiterator('motion-tween'):
                                    if tweenNode.tag == "motion-tween" and tweenNode.attrib.get("id") == tweenId:
                                        foundTween = True
                                        frameLength = 1 if tweenNode.attrib.get("length-in-frames") == None else tweenNode.attrib.get("length-in-frames")
                                        advancementFunction = "linear" if tweenNode.attrib.get("advancement-function") == None else tweenNode.attrib.get("advancement-function")
                                        for pointOrColorNode in tweenNode.getiterator():
                                            if pointOrColorNode.tag == "point":
                                                pX = 0 if pointOrColorNode.attrib.get("x") == None else float(pointOrColorNode.attrib.get("x"))
                                                pY = 0 if pointOrColorNode.attrib.get("y") == None else float(pointOrColorNode.attrib.get("y"))
                                                pointList.append(Point(pX, pY, 0))
                                            elif pointOrColorNode.tag == "color-state":
                                                colorName = "white" if pointOrColorNode.attrib.get("name") == None else pointOrColorNode.attrib.get("name")
                                                for colorNode in self.colors.getiterator('color'):
                                                    if colorNode.tag == 'color' and colorNode.attrib.get("name") == colorName:
                                                        R = 1 if colorNode.attrib.get("r") == None else float(colorNode.attrib.get("r"))
                                                        G = 1 if colorNode.attrib.get("g") == None else float(colorNode.attrib.get("g"))
                                                        B = 1 if colorNode.attrib.get("b") == None else float(colorNode.attrib.get("b"))
                                                        A = 1 if colorNode.attrib.get("a") == None else float(colorNode.attrib.get("a"))
                                                        colorList.append(Color(R, G, B, A))
                                                        break # leave for loop when we find the correct color reference
                                            pass # Run through all child nodes of selected tween
                                        break # Exit after finding correct tween
                                pass
                                if foundTween:
                                    thisTween = Tween(frameLength, advancementFunction, pointList, colorList)
                                    offset = thisTween.XYFromFrame(frameInTween);
                                    offsetFromTweenX = int(offset.X);
                                    offsetFromTweenY = int(offset.Y);
                                    offsetX += int(offset.X);
                                    offsetY += int(offset.Y);
                                    if thisTween.hasColorComponent():
                                        tweenHasColor = True;
                                        if frameCallHasColor == False:
                                            color = thisTween.colorFromFrame(frameInTween);
                                    pass
                            if frameNode.attrib.get("color-name") != None and frameCallHasColor == False and tweenHasColor == False:
                                # Get color at frame definition as last resort.
                                for colorNode in colors.getiterator('color'):
                                    if colorNode.tag == 'color' and colorNode.attrib.get("name") == frameNode.attrib.get("color-name"):
                                        R = 1 if colorNode.attrib.get("r") == None else float(colorNode.attrib.get("r"))
                                        G = 1 if colorNode.attrib.get("g") == None else float(colorNode.attrib.get("g"))
                                        B = 1 if colorNode.attrib.get("b") == None else float(colorNode.attrib.get("b"))
                                        A = 1 if colorNode.attrib.get("a") == None else float(colorNode.attrib.get("a"))
                                        color = Color(R, G, B, A)
                                        break # leave for loop when we find the correct color
                                pass
                            rotationZ = 0 if frameCallNode.attrib.get("rotation-z") == None else float(frameCallNode.attrib.get("rotation-z"))
                            frameList.append(Frame(Bound(offsetX, offsetY, addWidth, addHeight), s, t, S, T, blend, scaleX, scaleY, color, rotationZ))
                    pass 
                break # Leave once we've found the appropriate frame

        # Prepare tracking list of consumed nodes.
        self.clearNodesForDrawing()
        # Make an identifier to tack onto primitive names in Panda3d's scene graph.
        frameIndexForName = 1
                
        # Loop through loaded frames that make up composite frame.
        for loadedFrame in frameList:              
            # For debugging purposes, print the object.
            if False:
                loadedFrame.printAsString()
            
            # Set up place to store primitive 3d object; note: requires vertex data made by GeomVertexData
            squareMadeByTriangleStrips = GeomTristrips(Geom.UHDynamic)
              
            # Set up place to hold 3d data and for the following coordinates:
            #   square's points (V3: x, y, z), 
            #   the colors at each point of the square (c4: r, g, b, a), and
            #   for the UV texture coordinates at each point of the square     (t2: S, T).
            vertexData = GeomVertexData('square-'+str(frameIndexForName), GeomVertexFormat.getV3c4t2(), Geom.UHDynamic)
            vertex = GeomVertexWriter(vertexData, 'vertex')
            color = GeomVertexWriter(vertexData, 'color')
            texcoord = GeomVertexWriter(vertexData, 'texcoord') 
              
            # Add the square's data
            # Upper-Left corner of square
            vertex.addData3f(-loadedFrame.bound.Width / 2.0, 0, -loadedFrame.bound.Height / 2.0)
            color.addData4f(loadedFrame.color.R,loadedFrame.color.G,loadedFrame.color.B,loadedFrame.color.A)
            texcoord.addData2f(loadedFrame.s, loadedFrame.T)

            # Upper-Right corner of square
            vertex.addData3f(loadedFrame.bound.Width / 2.0, 0, -loadedFrame.bound.Height / 2.0)
            color.addData4f(loadedFrame.color.R,loadedFrame.color.G,loadedFrame.color.B,loadedFrame.color.A)
            texcoord.addData2f(loadedFrame.S, loadedFrame.T)
            
            # Lower-Left corner of square
            vertex.addData3f(-loadedFrame.bound.Width / 2.0, 0, loadedFrame.bound.Height / 2.0)
            color.addData4f(loadedFrame.color.R,loadedFrame.color.G,loadedFrame.color.B,loadedFrame.color.A)
            texcoord.addData2f(loadedFrame.s, loadedFrame.t)
            
            # Lower-Right corner of square
            vertex.addData3f(loadedFrame.bound.Width / 2.0, 0, loadedFrame.bound.Height / 2.0)
            color.addData4f(loadedFrame.color.R,loadedFrame.color.G,loadedFrame.color.B,loadedFrame.color.A)
            texcoord.addData2f(loadedFrame.S, loadedFrame.t)

            # Pass data to primitive
            squareMadeByTriangleStrips.addNextVertices(4)
            squareMadeByTriangleStrips.closePrimitive()
            square = Geom(vertexData)
            square.addPrimitive(squareMadeByTriangleStrips)
            # Pass primtive to drawing node
            drawPrimitiveNode=GeomNode('square-'+str(frameIndexForName))    
            drawPrimitiveNode.addGeom(square)
            # Pass node to scene (effect camera)
            nodePath = self.effectCameraNodePath.attachNewNode(drawPrimitiveNode)
            # Linear dodge:
            if loadedFrame.blendMode == "darken":
                nodePath.setAttrib(ColorBlendAttrib.make(ColorBlendAttrib.MAdd, ColorBlendAttrib.OOneMinusFbufferColor, ColorBlendAttrib.OOneMinusIncomingColor))
                pass
            elif loadedFrame.blendMode == "multiply":
                nodePath.setAttrib(ColorBlendAttrib.make(ColorBlendAttrib.MAdd, ColorBlendAttrib.OFbufferColor, ColorBlendAttrib.OZero))
                pass
            elif loadedFrame.blendMode == "color-burn":
                nodePath.setAttrib(ColorBlendAttrib.make(ColorBlendAttrib.MAdd, ColorBlendAttrib.OZero, ColorBlendAttrib.OOneMinusIncomingColor))
                pass
            elif loadedFrame.blendMode == "linear-burn":
                nodePath.setAttrib(ColorBlendAttrib.make(ColorBlendAttrib.MAdd, ColorBlendAttrib.OZero, ColorBlendAttrib.OIncomingColor))
                pass
            elif loadedFrame.blendMode == "lighten":
                nodePath.setAttrib(ColorBlendAttrib.make(ColorBlendAttrib.MMax, ColorBlendAttrib.OIncomingColor, ColorBlendAttrib.OFbufferColor))
                pass
            elif loadedFrame.blendMode == "color-dodge":
                nodePath.setAttrib(ColorBlendAttrib.make(ColorBlendAttrib.MAdd, ColorBlendAttrib.OOne, ColorBlendAttrib.OOne))
                pass
            elif loadedFrame.blendMode == "linear-dodge":
                nodePath.setAttrib(ColorBlendAttrib.make(ColorBlendAttrib.MAdd, ColorBlendAttrib.OOne, ColorBlendAttrib.OOneMinusIncomingColor))
                pass
            else: # Overwrite:
                nodePath.setAttrib(ColorBlendAttrib.make(ColorBlendAttrib.MAdd, ColorBlendAttrib.OIncomingAlpha, ColorBlendAttrib.OOneMinusIncomingAlpha))
                pass
            nodePath.setDepthTest(False)
            # Apply texture
            nodePath.setTexture(self.tex)
            # Apply translation, then rotation, then scaling to node.
            nodePath.setPos((loadedFrame.bound.X + loadedFrame.bound.Width / 2.0, 1, -loadedFrame.bound.Y - loadedFrame.bound.Height / 2.0))
            nodePath.setR(loadedFrame.rotationZ)
            nodePath.setScale(loadedFrame.scaleX, 1, loadedFrame.scaleY)
            nodePath.setTwoSided(True)
            self.consumedNodesList.append(nodePath)
            frameIndexForName = frameIndexForName + 1
        # Loop continues on through each frame called in the composite frame.
        pass
Пример #50
0
def makeSquare(x1, y1, z1, x2, y2, z2, color):       # This is straight copied off the Panda3d 'procedural cube' example https://github.com/panda3d/panda3d/blob/master/samples/procedural-cube/main.py#L11
    
    format = GeomVertexFormat.getV3n3cpt2()
    vdata = GeomVertexData('square', format, Geom.UHDynamic)

    vertex = GeomVertexWriter(vdata, 'vertex')
    normal = GeomVertexWriter(vdata, 'normal')
    color_setter = 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
    if np.sum(color) > 0:
        a = 1  # Alpha transparency
    else: a = 0

    # Handling channel size 1 or 3
    if np.size(color) == 1:     
        for i in range(4):      # Have to run this 4 times cuz each vertex on the square has a color setting
            color_setter.addData2f(color,a)
    elif np.size(color) == 3:
        r, g, b = color[0], color[1], color[2]
        for i in range(4): 
            color_setter.addData4f(r,g,b,a)


    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 makeTrack(segments):

	format=GeomVertexFormat.getV3t2()

	vdata=GeomVertexData('track', format, Geom.UHStatic)
	vertex=GeomVertexWriter(vdata, 'vertex')
	texcoord=GeomVertexWriter(vdata, 'texcoord')

	vdata2=GeomVertexData('startline', format, Geom.UHStatic)
	vertex2=GeomVertexWriter(vdata2, 'vertex')
	texcoord2=GeomVertexWriter(vdata2, 'texcoord')

	numVertices=0
	twat=0
	for segmentIndex in range(len(segments)):
		currentSegment=segments[segmentIndex]

		if segmentIndex==0:
			nextSegment=segments[segmentIndex+1]
			currentStartLineLeftPoint=Geometry.Point.CreateByInterpolation(currentSegment.getMidPoint(),currentSegment.getLeftPoint(),100,77.5);
			currentStartLineRightPoint=Geometry.Point.CreateByInterpolation(currentSegment.getMidPoint(),currentSegment.getRightPoint(),100,77.5);
			nextStartLineLeftPoint=Geometry.Point.CreateByInterpolation(nextSegment.getMidPoint(),nextSegment.getLeftPoint(),100,77.5);
			nextStartLineRightPoint=Geometry.Point.CreateByInterpolation(nextSegment.getMidPoint(),nextSegment.getRightPoint(),100,77.5);

			vertex2.addData3f(nextStartLineLeftPoint.getX(),nextStartLineLeftPoint.getY(),0)
			vertex2.addData3f(nextStartLineRightPoint.getX(),nextStartLineRightPoint.getY(),0)
			vertex2.addData3f(currentStartLineLeftPoint.getX(),currentStartLineLeftPoint.getY(),0)
			vertex2.addData3f(currentStartLineRightPoint.getX(),currentStartLineRightPoint.getY(),0)
			texcoord2.addData2f(0.0, 0.0)
			texcoord2.addData2f(12.0, 0.0)
			texcoord2.addData2f(0.0, 2.0)
			texcoord2.addData2f(12.0, 2.0)

		vertex.addData3f(currentSegment.leftPoint.getX(),currentSegment.leftPoint.getY(),0)
		vertex.addData3f(currentSegment.rightPoint.getX(),currentSegment.rightPoint.getY(),0)
		texcoord.addData2f(0.0, 1.0/8*float(twat))
		texcoord.addData2f(1.0, 1.0/8*float(twat))
		#print('vertex at '+str(segmentIndex)+' with v='+str(1.0/8*float(twat)))
		numVertices+=2

		twat=twat+1
		if twat==9:		
			#print('surplus at '+str(segmentIndex)+' with v=0.0')
			vertex.addData3f(currentSegment.leftPoint.getX(),currentSegment.leftPoint.getY(),0)
			vertex.addData3f(currentSegment.rightPoint.getX(),currentSegment.rightPoint.getY(),0)
			texcoord.addData2f(0.0, 0.0)
			texcoord.addData2f(1.0, 0.0)
			numVertices+=2
			twat=1

	#print('vertices created: '+str(numVertices))

	tris=GeomTriangles(Geom.UHDynamic)

	bob=0
	vertexOffset=0
	for index in range(len(segments)):

		vertexOffsets=[]
		for innerIndex in range(4):
			offset=vertexOffset+innerIndex
			if offset>numVertices-1:
				offset=offset-numVertices
			vertexOffsets.append(offset)

		tris.addVertex(vertexOffsets[0])
		tris.addVertex(vertexOffsets[1])
		tris.addVertex(vertexOffsets[3])
		tris.closePrimitive()

		tris.addVertex(vertexOffsets[0])
		tris.addVertex(vertexOffsets[3])
		tris.addVertex(vertexOffsets[2])
		tris.closePrimitive()

		vertexOffset+=2

		bob+=1
		if bob==8:
			vertexOffset+=2
			bob=0

	tris2=GeomTriangles(Geom.UHDynamic)
	tris2.addVertex(0)
	tris2.addVertex(3)
	tris2.addVertex(1)
	tris2.closePrimitive()

	tris2.addVertex(0)
	tris2.addVertex(2)
	tris2.addVertex(3)
	tris2.closePrimitive()

	track=Geom(vdata)
	track.addPrimitive(tris)

	startLine=Geom(vdata2)
	startLine.addPrimitive(tris2)

	snode=GeomNode('tarmac')
	snode.addGeom(track)

	snode2=GeomNode('startline')
	snode2.addGeom(startLine)

	returnValues={"tarmac":snode,"startline":snode2}
	return returnValues

	return snode
    def createNewSphere(self, radius, height, width, vertexcolour = None, transparency = 1):
        ''' 
        Note that the first and the last node of the Thetha_Range should be 0 and 180 Degrees 
        because this will be just one time added to verticies
        '''
        #Format
        format = GeomVertexFormat.getV3n3cpt2()
        #VertexData
        vdata = GeomVertexData('name', format, Geom.UHStatic)


        ##VertexWriter
        vertex      = GeomVertexWriter(vdata, 'vertex')
        normal      = GeomVertexWriter(vdata, 'normal')
        color       = GeomVertexWriter(vdata, 'color')
        texcoord    = GeomVertexWriter(vdata, 'texcoord')
        
        if (vertexcolour == None):
            vertexcolour = [0.5, 0.5, 0.5]
        
        counter = 0
        ### Create the Skeleton of the Sphere
        for j in range(width):
            for i in range(height):
                if (i == 0):
                    vect = self.sphereToKartesian(radius, 0, 0)
                    vertex.addData3f(vect[0],vect[1],vect[2])
                    normal.addData3f(vect[0],vect[1],vect[2])
                    color.addData4f(vertexcolour[0],vertexcolour[1],vertexcolour[2],transparency)
                    texcoord.addData2f(1-(float(j)/(width)), (float(i)/(height)))                   
                elif (i == height-1):
                    vect = self.sphereToKartesian(radius, 0, 180)
                    vertex.addData3f(vect[0],vect[1],vect[2])
                    normal.addData3f(vect[0],vect[1],vect[2])
                    color.addData4f(vertexcolour[0],vertexcolour[1],vertexcolour[2],transparency)
                    texcoord.addData2f(1-(float(j)/(width)), (float(i)/(height)))
                else:
                    vect = self.sphereToKartesian(radius, (float(j)/(width-2)) * 360, (float(i)/(height)) * 180)
                    vertex.addData3f(vect[0],vect[1],vect[2])
                    normal.addData3f(vect[0],vect[1],vect[2])
                    texcoord.addData2f(1-(float(j)/(width-2)), (float(i)/(height)))
                    color.addData4f(vertexcolour[0],vertexcolour[1],vertexcolour[2],transparency)
                    counter += 1

        ### Create Geom
        geom = Geom(vdata)
        
        
        ### Create Top Trifans
        prim = self.createTrifans(0,range(1,width+1))
       #geom.addPrimitive(prim)
        
        ### Create Belttristrips
        
        for i in range(0,height-2):
            prim = self.createTristrips(width, width*i)

            geom.addPrimitive(prim)
        

        ### Create Bottom Trifans
        lastpoint = width*height-1
        a = [i-1 for i in range(lastpoint,lastpoint-width,-1)]
        prim = self.createTrifans(lastpoint,a)
        #geom.addPrimitive(prim)
 
        geomnode = GeomNode('gnode')
        geomnode.addGeom(geom)
        
        return geomnode
    def create_node(self):
        # Set up the vertex arrays
        vformat = GeomVertexFormat.get_v3n3c4t2()
        vdata = GeomVertexData("Data", vformat, Geom.UHDynamic)
        vertex = GeomVertexWriter(vdata, 'vertex')
        normal = GeomVertexWriter(vdata, 'normal')
        color = GeomVertexWriter(vdata, 'color')
        texcoord = GeomVertexWriter(vdata, 'texcoord')
        geom = Geom(vdata)

        # Write vertex data
        for v in range(0, self.res[1] + 1):
            for u in range(0, self.res[0] + 1):
                # vertex_number = u * (self.res[0] + 1) + v
                t_u, t_v = float(u)/float(self.res[0]), float(v)/float(self.res[1])
                # Vertex positions and normals will be overwritten before the first displaying anyways.
                vertex.addData3f(0, 0, 0)
                normal.addData3f(0, 0, 0)
                # Color is actually not an issue and should probably be kicked out of here.
                color.addData4f(1, 1, 1, 1)
                # Texcoords are constant, so this should be moved into its own array.
                texcoord.addData2f(t_u, t_v)

        # Add triangles
        for u in range(0, self.res[0]):
            for v in range(0, self.res[1]):
                # The vertex arrangement (y up, x right)
                # 2 3
                # 0 1
                u_verts = self.res[0] + 1
                v_0 = u       + v       * u_verts
                v_1 = (u + 1) + v       * u_verts
                v_2 = u       + (v + 1) * u_verts
                v_3 = (u + 1) + (v + 1) * u_verts
                tris = GeomTriangles(Geom.UHDynamic)
                tris.addVertices(v_2, v_0, v_1)
                tris.closePrimitive()
                geom.addPrimitive(tris)
                tris = GeomTriangles(Geom.UHDynamic)
                tris.addVertices(v_1, v_3, v_2)
                tris.closePrimitive()
                geom.addPrimitive(tris)

        # Create the actual node
        sphere = GeomNode('geom_node')
        sphere.addGeom(geom)
        sphere_np = NodePath(sphere)
        tex = base.loader.loadTexture("assets/geosphere/geosphere_day.jpg")
        sphere_np.setTexture(tex)
        self.sphere_np = sphere_np
        self.sphere_vdata = vdata

        # -----
        vformat = GeomVertexFormat.get_v3n3c4()
        vdata = GeomVertexData("Data", vformat, Geom.UHDynamic)
        vertex = GeomVertexWriter(vdata, 'vertex')
        color = GeomVertexWriter(vdata, 'color')
        geom = Geom(vdata)
        
        vertex.addData3f(-1, -1, 0)
        color.addData4f(1, 1, 1, 1)

        vertex.addData3f(1, -1, 0)
        color.addData4f(1, 1, 1, 1)

        tris = GeomLines(Geom.UHDynamic)
        tris.addVertices(0, 1)
        tris.closePrimitive()
        geom.addPrimitive(tris)

        connections = GeomNode('geom_node')
        connections.addGeom(geom)
        connections_np = NodePath(connections)
        connections_np.setRenderModeThickness(3)
        self.connections_np = connections_np
        self.connections_vdata = vdata
        self.connections_geom = geom
        
        self.connections_np.reparent_to(sphere_np)

        return sphere_np