Esempio n. 1
0
    def create_model(self):
        # Set up the vertex arrays
        vformatArray = GeomVertexArrayFormat()
        # Panda3D implicitly generates a bounding volume from a
        # column named "vertex", so you either
        # * have a column of that name, or
        # * add a bounding volume yourself.
        vformatArray.addColumn(InternalName.make("vertex"), 3, Geom.NTFloat32,
                               Geom.CPoint)
        vformatArray.addColumn(InternalName.make("color"), 4, Geom.NTFloat32,
                               Geom.CColor)

        vformat = GeomVertexFormat()
        vformat.addArray(vformatArray)
        vformat = GeomVertexFormat.registerFormat(vformat)

        vdata = GeomVertexData("Data", vformat, Geom.UHStatic)
        vertex = GeomVertexWriter(vdata, 'vertex')
        color = GeomVertexWriter(vdata, 'color')

        geom = Geom(vdata)

        # Vertex data
        vertex.addData3f(1.5, 0, -1)
        color.addData4f(1, 0, 0, 1)
        vertex.addData3f(-1.5, 0, -1)
        color.addData4f(0, 1, 0, 1)
        vertex.addData3f(0, 0, 1)
        color.addData4f(0, 0, 1, 1)

        # Primitive
        tri = GeomPatches(3, Geom.UHStatic)
        tri.add_vertex(2)
        tri.add_vertex(1)
        tri.add_vertex(0)
        tri.close_primitive()
        geom.addPrimitive(tri)

        # Create the actual node
        node = GeomNode('geom_node')
        node.addGeom(geom)
        np = NodePath(node)

        # Shader, initial shader vars, number of instances
        np.set_shader(
            Shader.load(Shader.SL_GLSL,
                        vertex="shader.vert",
                        tess_control="shader.tesc",
                        tess_evaluation="shader.tese",
                        geometry="shader.geom",
                        fragment="shader.frag"))
        np.set_shader_input("time", 0.0)
        np.set_shader_input("tess_level", 32.0)
        np.set_instance_count(num_instances)
        np.set_shader_input("numInstances", num_instances)
        return np
Esempio n. 2
0
def getFaceFormat():
    global FaceFormat
    if not FaceFormat:
        arr = GeomVertexArrayFormat()
        arr.addColumn(InternalName.getVertex(), 3, GeomEnums.NTStdfloat, GeomEnums.CPoint)
        arr.addColumn(InternalName.getNormal(), 3, GeomEnums.NTStdfloat, GeomEnums.CNormal)
        arr.addColumn(InternalName.getTangent(), 3, GeomEnums.NTStdfloat, GeomEnums.CVector)
        arr.addColumn(InternalName.getBinormal(), 3, GeomEnums.NTStdfloat, GeomEnums.CVector)
        arr.addColumn(InternalName.getTexcoord(), 2, GeomEnums.NTStdfloat, GeomEnums.CTexcoord)
        FaceFormat = GeomVertexFormat.registerFormat(arr)
    return FaceFormat
Esempio n. 3
0
    def __init__(self, __occupying_unit = None, __occupiable = True, 
	x = 0, z = 0, r = 5, tag = 0):
        self.__occupying_unit = __occupying_unit
        self.__occupiable = __occupiable
	self.__r = r
	self.__x = x
	self.__z = z
	self.__tag = tag
	
	#Procedurally creating a hex!
	geometry_array = GeomVertexArrayFormat()
	geometry_array.addColumn(InternalName.make('vertex'), 3, Geom.NTFloat32, Geom.CPoint)
	geometry_array.addColumn(InternalName.make('normal'), 3, Geom.NTFloat32, Geom.CPoint)
	format = GeomVertexFormat()
	format.addArray(geometry_array)
	format = GeomVertexFormat.registerFormat(format)
	self.__vdata = GeomVertexData('Hex', format, Geom.UHStatic)
	self.__vertex = GeomVertexWriter(self.__vdata, 'vertex')
	self.__normal = GeomVertexWriter(self.__vdata, 'normal')

	#Vertex 1
	self.__vertex.addData3f(self.__x, self.__z+self.__r, 0)
	self.__normal.addData3f(1, 0, 0)
	#Vertex 2
	self.__vertex.addData3f(self.__x+self.__r*sin(pi/3), self.__z+self.__r*cos(pi/3), 0)
	self.__normal.addData3f(1, 0, 0)
	#Vertex 3
	self.__vertex.addData3f(self.__x+self.__r*sin(pi/3), self.__z-self.__r*cos(pi/3), 0)
	self.__normal.addData3f(1, 0, 0)
	#Vertex 4
	self.__vertex.addData3f(self.__x, self.__z-self.__r, 0)
	self.__normal.addData3f(1, 0, 0)
	#Vertex 5
	self.__vertex.addData3f(self.__x-self.__r*sin(pi/3), self.__z-self.__r*cos(pi/3), 0)
	self.__normal.addData3f(1, 0, 0)
	#Vertex 6
	self.__vertex.addData3f(self.__x-self.__r*sin(pi/3), self.__z+self.__r*cos(pi/3), 0)
	self.__normal.addData3f(1, 0, 0)

	self.__hex_primitive = GeomTrifans(Geom.UHStatic)
	self.__hex_primitive.addVertices(5, 4)
	self.__hex_primitive.addVertices(3, 2)
	self.__hex_primitive.addVertices(1, 0)

	self.__hex_primitive.closePrimitive()
	self.__hex_geometry = Geom(self.__vdata)
	self.__hex_geometry.addPrimitive(self.__hex_primitive)
	self.__hex_node = GeomNode('HexNode')
	self.__hex_node.addGeom(self.__hex_geometry)

	nodePath = render.attachNewNode(self.__hex_node)
	nodePath.setTag( "hex", str(tag) )
	nodePath.node().setIntoCollideMask(BitMask32.bit(1))
	nodePath.hide()
Esempio n. 4
0
    def create_model(self):
        # Set up the vertex arrays
        vformatArray = GeomVertexArrayFormat()
        # Panda3D implicitly generates a bounding volume from a
        # column named "vertex", so you either
        # * have a column of that name, or
        # * add a bounding volume yourself.
        vformatArray.addColumn(InternalName.make("vertex"), 3, Geom.NTFloat32, Geom.CPoint)
        vformatArray.addColumn(InternalName.make("color"), 4, Geom.NTFloat32, Geom.CColor)

        vformat = GeomVertexFormat()
        vformat.addArray(vformatArray)
        vformat = GeomVertexFormat.registerFormat(vformat)

        vdata = GeomVertexData("Data", vformat, Geom.UHStatic)
        vertex = GeomVertexWriter(vdata, 'vertex')
        color = GeomVertexWriter(vdata, 'color')

        geom = Geom(vdata)

        # Vertex data
        vertex.addData3f(1.5, 0, -1)
        color.addData4f(1, 0, 0, 1)
        vertex.addData3f(-1.5, 0, -1)
        color.addData4f(0, 1, 0, 1)
        vertex.addData3f(0, 0, 1)
        color.addData4f(0, 0, 1, 1)

        # Primitive
        tri = GeomPatches(3, Geom.UHStatic)
        tri.add_vertex(2)
        tri.add_vertex(1)
        tri.add_vertex(0)
        tri.close_primitive()
        geom.addPrimitive(tri)

        # Create the actual node
        node = GeomNode('geom_node')
        node.addGeom(geom)
        np = NodePath(node)

        # Shader, initial shader vars, number of instances
        np.set_shader(Shader.load(Shader.SL_GLSL,
                                  vertex = "shader.vert",
                                  tess_control = "shader.tesc",
                                  tess_evaluation = "shader.tese",
                                  geometry = "shader.geom",
                                  fragment = "shader.frag"))
        np.set_shader_input("time", 0.0)
        np.set_shader_input("tess_level", 32.0)
        np.set_instance_count(num_instances)
        np.set_shader_input("numInstances", num_instances)
        return np
Esempio n. 5
0
    def __init__(self):
        formatArray = GeomVertexArrayFormat()
        formatArray.addColumn(
            InternalName.make("drawFlag"), 1, Geom.NTUint8, Geom.COther)

        format = GeomVertexFormat(GeomVertexFormat.getV3n3cpt2())
        format.addArray(formatArray)
        self.format = GeomVertexFormat.registerFormat(format)

        # bodydata = GeomVertexData("body vertices", format, Geom.UHStatic)

        self.barkTexture = loader.loadTexture("../asset/TreeGenerator/barkTexture.jpg")
Esempio n. 6
0
    def __init__(self):
        formatArray = GeomVertexArrayFormat()
        formatArray.addColumn(InternalName.make("drawFlag"), 1, Geom.NTUint8,
                              Geom.COther)

        format = GeomVertexFormat(GeomVertexFormat.getV3n3cpt2())
        format.addArray(formatArray)
        self.format = GeomVertexFormat.registerFormat(format)

        bodydata = GeomVertexData("body vertices", format, Geom.UHStatic)

        self.barkTexture = loader.loadTexture("barkTexture.jpg")
        treeNodePath = NodePath("Tree Holder")
        makeFractalTree(bodydata, treeNodePath, LVector3(4, 4, 7))

        treeNodePath.setTexture(self.barkTexture, 1)
        treeNodePath.reparentTo(render)

        self.accept("q", self.regenTree)
        self.accept("w", self.addTree)
        self.accept("arrow_up", self.upIterations)
        self.accept("arrow_down", self.downIterations)
        self.accept("arrow_right", self.upCopies)
        self.accept("arrow_left", self.downCopies)

        self.numIterations = 11
        self.numCopies = 4

        self.upDownEvent = OnscreenText(
            text="Up/Down: Increase/Decrease the number of iterations (" +
            str(self.numIterations) + ")",
            parent=base.a2dTopLeft,
            align=TextNode.ALeft,
            style=1,
            fg=(1, 1, 1, 1),
            pos=(0.06, -0.22),
            scale=.05,
            mayChange=True)

        self.leftRightEvent = OnscreenText(
            text="Left/Right: Increase/Decrease branching (" +
            str(self.numCopies) + ")",
            parent=base.a2dTopLeft,
            align=TextNode.ALeft,
            style=1,
            fg=(1, 1, 1, 1),
            pos=(0.06, -0.28),
            scale=.05,
            mayChange=True)
Esempio n. 7
0
File: util.py Progetto: svfgit/solex
 def __build_Writers(self):
     # Build Vdata.
     array = GeomVertexArrayFormat()
     for field_name, field_spec_name in list(self.field_types.items()):
         field_specs = self._data_types[field_spec_name][:-1]
         array.addColumn(InternalName.make(field_name), *field_specs)
     vformat = GeomVertexFormat()
     vformat.addArray(array)
     vformat = GeomVertexFormat.registerFormat(vformat)
     vdata = GeomVertexData("data", vformat, Geom.UHStatic)
     
     # Build GeomVertexWriters.
     writers = {}
     for field_name in list(self.field_types.keys()):
         writers[field_name] = GeomVertexWriter(vdata, field_name)
     return vdata, writers
Esempio n. 8
0
    def registerObject(self, obj):
        """ Registers a new dynamic object, this will store an index for every
        vertex, which can be used to read and store last position data in order
        to compute the velocity. This method also assigns the standard animated
        shader to the node """

        self.debug("Registering dynamic object")

        # Find all GeomNodes
        for node in obj.findAllMatches("**/+GeomNode"):
            geomNode = node.node()
            geomCount = geomNode.getNumGeoms()

            # Find all Geoms
            for i in xrange(geomCount):

                # Modify vertex data
                geom = geomNode.modifyGeom(i)
                geomVertexData = geom.modifyVertexData()

                # Add a new column named "dovindex" to the vertex data
                formatArray = GeomVertexArrayFormat()
                formatArray.addColumn(InternalName.make("dovindex"), 1,
                                      GeomEnums.NTUint32, GeomEnums.CIndex)
                newArrayFormat = GeomVertexFormat(geomVertexData.getFormat())
                newArrayFormat.addArray(formatArray)
                newArrayFormat = GeomVertexFormat.registerFormat(
                    newArrayFormat)

                # Convert the old vertex data and assign the new vertex data
                convertedVertexData = geomVertexData.convertTo(newArrayFormat)
                geom.setVertexData(convertedVertexData)

                # Write the per-vertex indices the dovindex column
                newVertexData = geom.modifyVertexData()
                vtxReader = GeomVertexReader(newVertexData, "vertex")
                indexWriter = GeomVertexWriter(newVertexData, "dovindex")

                while not vtxReader.isAtEnd():
                    data = vtxReader.getData3f()
                    indexWriter.setData1i(self.currentIndex)
                    self.currentIndex += 1

                if self.currentIndex > self.maxVertexCount:
                    self.error("Max dynamic vertex count of",
                               self.maxVertexCount, "reached!")
Esempio n. 9
0
def pandageom_from_points(vertices, rgba=None, name=''):
    """
    pack the vertices into a panda3d point cloud geom
    :param vertices:
    :param rgba: rgba color for each vertex, can be list or nparray (rgb is also acceptable)
    :param name:
    :return:
    author: weiwei
    date: 20170328, 20210116, 20220721
    """
    if rgba is None:
        # default
        vertex_rgbas = np.asarray([[0, 0, 0, 255]] * len(vertices),
                                  dtype=np.uint8)
    if isinstance(rgba, list):
        rgba = np.array(rgba)
    if not isinstance(rgba, np.array):
        raise ValueError('rgba must be a list or an nparray!')
    if len(rgba) == 1:
        vertex_rgbas = np.tile((rgba * 255).astype(np.uint8),
                               (len(vertices), 1))
    elif len(rgba) == len(vertices):
        vertex_rgbas = (rgba * 255).astype(np.uint8)
    n_color_bit = rgba.shape[1]
    vertformat = GeomVertexFormat()
    arrayformat = GeomVertexArrayFormat()
    arrayformat.addColumn(InternalName.getVertex(), 3, GeomEnums.NTFloat32,
                          GeomEnums.CPoint)
    vertformat.addArray(arrayformat)
    arrayformat = GeomVertexArrayFormat()
    arrayformat.addColumn(InternalName.getColor(), n_color_bit,
                          GeomEnums.NTUint8, GeomEnums.CColor)
    vertformat.addArray(arrayformat)
    vertformat = GeomVertexFormat.registerFormat(vertformat)
    vertexdata = GeomVertexData(name, vertformat, Geom.UHStatic)
    vertexdata.modifyArrayHandle(0).copyDataFrom(
        np.ascontiguousarray(vertices, dtype=np.float32))
    vertexdata.modifyArrayHandle(1).copyDataFrom(vertex_rgbas)
    primitive = GeomPoints(Geom.UHStatic)
    primitive.setIndexType(GeomEnums.NTUint32)
    primitive.modifyVertices(-1).modifyHandle().copyDataFrom(
        np.arange(len(vertices), dtype=np.uint32))
    geom = Geom(vertexdata)
    geom.addPrimitive(primitive)
    return geom
Esempio n. 10
0
def pandageom_from_points(vertices, rgba_list=None, name=''):
    """
    pack the vertices into a panda3d point cloud geom
    :param vertices:
    :param rgba_list: a list with a single 1x4 nparray or with len(vertices) 1x4 nparray
    :param name:
    :return:
    author: weiwei
    date: 20170328, 20210116
    """
    if rgba_list is None:
        # default
        vertex_rgbas = np.array([[0, 0, 0, 255]] * len(vertices),
                                dtype=np.uint8)
    elif type(rgba_list) is not list:
        raise Exception('rgba\_list must be a list!')
    elif len(rgba_list) == 1:
        vertex_rgbas = np.tile((np.array(rgba_list[0]) * 255).astype(np.uint8),
                               (len(vertices), 1))
    elif len(rgba_list) == len(vertices):
        vertex_rgbas = (np.array(rgba_list) * 255).astype(np.uint8)
    else:
        raise ValueError(
            'rgba_list must be a list of one or len(vertices) 1x4 nparray!')
    vertformat = GeomVertexFormat()
    arrayformat = GeomVertexArrayFormat()
    arrayformat.addColumn(InternalName.getVertex(), 3, GeomEnums.NTFloat32,
                          GeomEnums.CPoint)
    vertformat.addArray(arrayformat)
    arrayformat = GeomVertexArrayFormat()
    arrayformat.addColumn(InternalName.getColor(), 4, GeomEnums.NTUint8,
                          GeomEnums.CColor)
    vertformat.addArray(arrayformat)
    vertformat = GeomVertexFormat.registerFormat(vertformat)
    vertexdata = GeomVertexData(name, vertformat, Geom.UHStatic)
    vertexdata.modifyArrayHandle(0).copyDataFrom(
        np.ascontiguousarray(vertices, dtype=np.float32))
    vertexdata.modifyArrayHandle(1).copyDataFrom(vertex_rgbas)
    primitive = GeomPoints(Geom.UHStatic)
    primitive.setIndexType(GeomEnums.NTUint32)
    primitive.modifyVertices(-1).modifyHandle().copyDataFrom(
        np.arange(len(vertices), dtype=np.uint32))
    geom = Geom(vertexdata)
    geom.addPrimitive(primitive)
    return geom
    def registerObject(self, obj):
        """ Registers a new dynamic object, this will store an index for every
        vertex, which can be used to read and store last position data in order
        to compute the velocity. This method also assigns the standard animated
        shader to the node """

        self.debug("Registering dynamic object")

        # Find all GeomNodes
        for node in obj.findAllMatches("**/+GeomNode"):
            geomNode = node.node()
            geomCount = geomNode.getNumGeoms()

            # Find all Geoms
            for i in xrange(geomCount):

                # Modify vertex data
                geom = geomNode.modifyGeom(i)
                geomVertexData = geom.modifyVertexData()

                # Add a new column named "dovindex" to the vertex data
                formatArray = GeomVertexArrayFormat() 
                formatArray.addColumn(InternalName.make("dovindex"), 1, GeomEnums.NTUint32, GeomEnums.CIndex) 
                newArrayFormat = GeomVertexFormat(geomVertexData.getFormat())
                newArrayFormat.addArray(formatArray)
                newArrayFormat = GeomVertexFormat.registerFormat(newArrayFormat)

                # Convert the old vertex data and assign the new vertex data
                convertedVertexData = geomVertexData.convertTo(newArrayFormat)
                geom.setVertexData(convertedVertexData)

                # Write the per-vertex indices the dovindex column 
                newVertexData = geom.modifyVertexData()
                vtxReader = GeomVertexReader(newVertexData, "vertex")
                indexWriter = GeomVertexWriter(newVertexData, "dovindex")

                while not vtxReader.isAtEnd():
                    data = vtxReader.getData3f()
                    indexWriter.setData1i(self.currentIndex)
                    self.currentIndex += 1

                if self.currentIndex > self.maxVertexCount:
                    self.error("Max dynamic vertex count of", self.maxVertexCount, "reached!")
Esempio n. 12
0
def load_pcd_content(content,
                     w=2,
                     color_mode="intensity",
                     intensity_filter=50):
    pc = pypcd.PointCloud.from_buffer(content)
    fmt = GeomVertexFormat()  #3 component vertex, w/ 4 comp color
    fmt_arr = GeomVertexArrayFormat()
    fmt_arr.addColumn(InternalName.make('vertex'), 3, Geom.NTFloat32,
                      Geom.CPoint)
    fmt_color_arr = GeomVertexArrayFormat()
    fmt_color_arr.addColumn(InternalName.make('color'), 4, Geom.NTUint8,
                            Geom.CColor)
    fmt.addArray(fmt_arr)
    fmt.addArray(fmt_color_arr)
    fmt = GeomVertexFormat.registerFormat(fmt)

    vertexData = GeomVertexData('points', fmt, Geom.UHStatic)
    pointCloud = GeomPoints(Geom.UHStatic)

    pc.pc_data.dtype = numpy.dtype("<f4")
    v, c = arrayfilter.vertices_filter(pc.pc_data.reshape((pc.points, 4)))
    for i in xrange(len(v)):
        pointCloud.addVertex(i)
        pointCloud.closePrimitive()

    arr = GeomVertexArrayData(fmt.getArray(0), GeomEnums.UHStream)
    datahandle = arr.modifyHandle()
    datahandle.copyDataFrom(v)
    vertexData.setArray(0, arr)

    arr = GeomVertexArrayData(fmt.getArray(1), GeomEnums.UHStream)
    datahandle = arr.modifyHandle()
    datahandle.copyDataFrom(c)
    vertexData.setArray(1, arr)

    cloud = Geom(vertexData)
    cloud.addPrimitive(pointCloud)
    cloudNode = GeomNode('points')
    cloudNode.addGeom(cloud)
    cloudNodePath = NodePath(cloudNode)
    cloudNodePath.setRenderModeThickness(w)
    cloudNodePath.setRenderModePerspective(True)
    return cloudNode
Esempio n. 13
0
    def __init__(self):
        formatArray = GeomVertexArrayFormat()
        formatArray.addColumn(
            InternalName.make("drawFlag"), 1, Geom.NTUint8, Geom.COther)

        format = GeomVertexFormat(GeomVertexFormat.getV3n3cpt2())
        format.addArray(formatArray)
        self.format = GeomVertexFormat.registerFormat(format)

        bodydata = GeomVertexData("body vertices", format, Geom.UHStatic)

        self.barkTexture = loader.loadTexture("barkTexture.jpg")
        treeNodePath = NodePath("Tree Holder")
        makeFractalTree(bodydata, treeNodePath, LVector3(4, 4, 7))

        treeNodePath.setTexture(self.barkTexture, 1)
        treeNodePath.reparentTo(render)

        self.accept("q", self.regenTree)
        self.accept("w", self.addTree)
        self.accept("arrow_up", self.upIterations)
        self.accept("arrow_down", self.downIterations)
        self.accept("arrow_right", self.upCopies)
        self.accept("arrow_left", self.downCopies)

        self.numIterations = 11
        self.numCopies = 4

        self.upDownEvent = OnscreenText(
            text="Up/Down: Increase/Decrease the number of iterations (" + str(
                self.numIterations) + ")",
            parent=base.a2dTopLeft, align=TextNode.ALeft,
            style=1, fg=(1, 1, 1, 1), pos=(0.06, -0.22),
            scale=.05, mayChange=True)

        self.leftRightEvent = OnscreenText(
            text="Left/Right: Increase/Decrease branching (" + str(
                self.numCopies) + ")",
            parent=base.a2dTopLeft, align=TextNode.ALeft,
            style=1, fg=(1, 1, 1, 1), pos=(0.06, -0.28),
            scale=.05, mayChange=True)
Esempio n. 14
0
 def makeGeom(self, points, colors, sizes):
     #format = GeomVertexFormat.getV3c4()
     array = GeomVertexArrayFormat()
     array.addColumn(InternalName.get_vertex(), 3, Geom.NTFloat32, Geom.CPoint)
     array.addColumn(InternalName.get_color(), 4, Geom.NTFloat32, Geom.CColor)
     array.addColumn(InternalName.get_size(), 1, Geom.NTFloat32, Geom.COther)
     format = GeomVertexFormat()
     format.addArray(array)
     format = GeomVertexFormat.registerFormat(format)
     vdata = GeomVertexData('vdata', format, Geom.UH_static)
     vdata.unclean_set_num_rows(len(points))
     self.vwriter = GeomVertexWriter(vdata, InternalName.get_vertex())
     self.colorwriter = GeomVertexWriter(vdata, InternalName.get_color())
     self.sizewriter = GeomVertexWriter(vdata, InternalName.get_size())
     geompoints = GeomPoints(Geom.UH_static)
     geompoints.reserve_num_vertices(len(points))
     index = 0
     for (point, color, size) in zip(points, colors, sizes):
         self.vwriter.addData3f(*point)
         self.colorwriter.addData4f(*color)
         self.sizewriter.addData1f(size)
         geompoints.addVertex(index)
         #geompoints.closePrimitive()
         index += 1
     geom = Geom(vdata)
     geom.addPrimitive(geompoints)
     return geom
Esempio n. 15
0
    def __init__(self, base, obj, **kwargs):
        super(GalaxyView, self).__init__(base, obj, **kwargs)

        array = GeomVertexArrayFormat()
        array.addColumn(InternalName.make('vertex'), 3, Geom.NTFloat32,
                        Geom.CPoint)
        array.addColumn(InternalName.make('color'), 4, Geom.NTFloat32,
                        Geom.CColor)
        array.addColumn(InternalName.make('size'), 1, Geom.NTFloat32,
                        Geom.COther)
        gmformat = GeomVertexFormat()
        gmformat.addArray(array)
        gmformat = GeomVertexFormat.registerFormat(gmformat)

        vdata = GeomVertexData('points', gmformat, Geom.UHDynamic)

        vertex = GeomVertexWriter(vdata, 'vertex')
        color = GeomVertexWriter(vdata, 'color')
        size = GeomVertexWriter(vdata, 'size')

        self.node = NodePath('galaxy')
        self.node.reparentTo(self.base.render)
        self.node.setTransparency(TransparencyAttrib.MAlpha)

        lumsort = sorted([star.luminosity for star in self.obj.stars])
        #highest_luminosity = lumsort[-1]
        median_luminosity = lumsort[len(lumsort) / 2]
        for star in self.obj.stars:
            vertex.addData3f(star.galpos.x, star.galpos.y, star.galpos.z)
            color.addData4f(star.red, star.green, star.blue, 1.0)
            #size.addData1f(min(100, max(5, 10-star.magnitude/2)))
            sizeval = 10 + log(star.luminosity)
            size.addData1f(min(30, max(10, sizeval)))

        prim = GeomPoints(Geom.UHStatic)
        prim.addConsecutiveVertices(0, len(self.obj.stars))
        prim.closePrimitive()

        geom = Geom(vdata)
        geom.addPrimitive(prim)

        node = GeomNode('gnode')
        node.addGeom(geom)

        galaxy_node = self.node.attachNewNode(node)
        galaxy_node.setRenderModeThickness(1)
        ts = TextureStage.getDefault()  #TextureStage('ts')
        #ts.setMode(TextureStage.MGlow)
        galaxy_node.setTexGen(ts, TexGenAttrib.MPointSprite)
        galaxy_node.setTexture(
            ts, self.base.loader.loadTexture('texture/flare.png'))
        #galaxy_node.setRenderModePerspective(True)

        galaxy_node.setBin("unsorted", 1)
        galaxy_node.setDepthWrite(0)
        galaxy_node.setTransparency(1)

        self.setup_glow_shader()
        """
Esempio n. 16
0
    def get_render_mesh(self):
        array = GeomVertexArrayFormat()
        array.addColumn("vertex", 3, Geom.NTFloat32, Geom.CPoint)
        array.addColumn("barycenter", 3, Geom.NTFloat32, Geom.CPoint)
        vertex_format = GeomVertexFormat()
        vertex_format.addArray(array)
        vertex_format = GeomVertexFormat.registerFormat(vertex_format)

        v_data = GeomVertexData('mesh', vertex_format, Geom.UHStatic)
        v_data.setNumRows(len(self.nodes))
        vertex = GeomVertexWriter(v_data, 'vertex')
        barycenter = GeomVertexWriter(v_data, 'barycenter')

        prim = GeomTriangles(Geom.UHStatic)
        vertex_id = 0
        for elem in self.elements:
            def node_coords(e, i): return self.nodes[e.nodes[i]].coordinate

            vertex.addData3(node_coords(elem, 0).x, node_coords(elem, 0).y, 0)
            vertex.addData3(node_coords(elem, 1).x, node_coords(elem, 1).y, 0)
            vertex.addData3(node_coords(elem, 2).x, node_coords(elem, 2).y, 0)
            barycenter.addData3(1, 0, 0)
            barycenter.addData3(0, 1, 0)
            barycenter.addData3(0, 0, 1)
            prim.addVertices(vertex_id, vertex_id + 1, vertex_id + 2)
            vertex_id += 3

            vertex.addData3(node_coords(elem, 2).x, node_coords(elem, 2).y, 0)
            vertex.addData3(node_coords(elem, 3).x, node_coords(elem, 3).y, 0)
            vertex.addData3(node_coords(elem, 0).x, node_coords(elem, 0).y, 0)
            barycenter.addData3(1, 0, 0)
            barycenter.addData3(0, 1, 0)
            barycenter.addData3(0, 0, 1)
            prim.addVertices(vertex_id, vertex_id + 1, vertex_id + 2)
            vertex_id += 3

        geom = Geom(v_data)
        geom.addPrimitive(prim)
        return geom
Esempio n. 17
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")
Esempio n. 18
0
def getVertexData(vertex,
                  vertex_index,
                  normal=None,
                  normal_index=None,
                  texcoordset=(),
                  texcoord_indexset=(),
                  textangentset=(),
                  textangent_indexset=(),
                  texbinormalset=(),
                  texbinormal_indexset=()):

    format = GeomVertexFormat()
    formatArray = GeomVertexArrayFormat()

    indices2stack = [vertex_index.reshape(-1, 1)]
    alldata = [vertex]
    formatArray.addColumn(InternalName.make("vertex"), 3, Geom.NTFloat32,
                          Geom.CPoint)
    if normal is not None:
        indices2stack.append(normal_index.reshape(-1, 1))
        alldata.append(collada.util.normalize_v3(numpy.copy(normal)))
        formatArray.addColumn(InternalName.make("normal"), 3, Geom.NTFloat32,
                              Geom.CVector)
    if len(texcoordset) > 0:
        indices2stack.append(texcoord_indexset[0].reshape(-1, 1))
        alldata.append(texcoordset[0])
        formatArray.addColumn(InternalName.make("texcoord"), 2, Geom.NTFloat32,
                              Geom.CTexcoord)
    if len(textangentset) > 0:
        indices2stack.append(textangent_indexset[0].reshape(-1, 1))
        alldata.append(textangentset[0])
        formatArray.addColumn(InternalName.make("tangent"), 3, Geom.NTFloat32,
                              Geom.CVector)
    if len(texbinormalset) > 0:
        indices2stack.append(texbinormal_indexset[0].reshape(-1, 1))
        alldata.append(texbinormalset[0])
        formatArray.addColumn(InternalName.make("binormal"), 3, Geom.NTFloat32,
                              Geom.CVector)

    #have to flatten and reshape like this so that it's contiguous
    stacked_indices = numpy.hstack(indices2stack).flatten().reshape(
        (-1, len(indices2stack)))

    #index_map - maps each unique value back to a location in the original array it came from
    #   eg. stacked_indices[index_map] == unique_stacked_indices
    #inverse_map - maps original array locations to their location in the unique array
    #   e.g. unique_stacked_indices[inverse_map] == stacked_indices
    unique_stacked_indices, index_map, inverse_map = numpy.unique(
        stacked_indices.view([('', stacked_indices.dtype)] *
                             stacked_indices.shape[1]),
        return_index=True,
        return_inverse=True)
    unique_stacked_indices = unique_stacked_indices.view(
        stacked_indices.dtype).reshape(-1, stacked_indices.shape[1])

    #unique returns as int64, so cast back
    index_map = numpy.cast['uint32'](index_map)
    inverse_map = numpy.cast['uint32'](inverse_map)

    #sort the index map to get a list of the index of the first time each value was encountered
    sorted_map = numpy.cast['uint32'](numpy.argsort(index_map))

    #since we're sorting the unique values, we have to map the inverse_map to the new index locations
    backwards_map = numpy.zeros_like(sorted_map)
    backwards_map[sorted_map] = numpy.arange(len(sorted_map),
                                             dtype=numpy.uint32)

    #now this is the new unique values and their indices
    unique_stacked_indices = unique_stacked_indices[sorted_map]
    inverse_map = backwards_map[inverse_map]

    #combine the unique stacked indices into unique stacked data
    data2stack = []
    for idx, data in enumerate(alldata):
        data2stack.append(data[unique_stacked_indices[:, idx]])
    unique_stacked_data = numpy.hstack(data2stack).flatten()
    unique_stacked_data.shape = (-1)
    all_data = unique_stacked_data.tostring()

    format.addArray(formatArray)
    format = GeomVertexFormat.registerFormat(format)

    vdata = GeomVertexData("dataname", format, Geom.UHStatic)
    arr = GeomVertexArrayData(format.getArray(0), GeomEnums.UHStream)
    datahandle = arr.modifyHandle()
    datahandle.setData(all_data)
    all_data = None
    vdata.setArray(0, arr)
    datahandle = None
    arr = None

    indexFormat = GeomVertexArrayFormat()
    indexFormat.addColumn(InternalName.make("index"), 1, Geom.NTUint32,
                          Geom.CIndex)
    indexFormat = GeomVertexArrayFormat.registerFormat(indexFormat)
    indexArray = GeomVertexArrayData(indexFormat, GeomEnums.UHStream)
    indexHandle = indexArray.modifyHandle()
    indexData = inverse_map.tostring()
    indexHandle.setData(indexData)
    return vdata, indexArray
Esempio n. 19
0
 def __generate_Vformats(self):
     vformat_dict = {}
     # Simple.
     array = GeomVertexArrayFormat()
     array.addColumn(InternalName.make("vertex"), 3, Geom.NTFloat32,
                     Geom.CPoint)
     vformat = GeomVertexFormat()
     vformat.addArray(array)
     vformat_dict['simp'] = GeomVertexFormat.registerFormat(vformat)
     # Low.
     array = GeomVertexArrayFormat()
     array.addColumn(InternalName.make("vertex"), 3, Geom.NTFloat32,
                     Geom.CPoint)
     array.addColumn(InternalName.make("color"), 4, Geom.NTFloat32,
                     Geom.CColor)
     vformat = GeomVertexFormat()
     vformat.addArray(array)
     vformat_dict['low'] = GeomVertexFormat.registerFormat(vformat)
     # Mid.
     array = GeomVertexArrayFormat()
     array.addColumn(InternalName.make("vertex"), 3, Geom.NTFloat32,
                     Geom.CPoint)
     array.addColumn(InternalName.make("mapcoord"), 2, Geom.NTFloat32,
                     Geom.CTexcoord)
     vformat = GeomVertexFormat()
     vformat.addArray(array)
     vformat_dict['mid'] = GeomVertexFormat.registerFormat(vformat)
     # High (patches).
     array = GeomVertexArrayFormat()
     array.addColumn(InternalName.make("vertex"), 3, Geom.NTFloat32,
                     Geom.CPoint)
     array.addColumn(InternalName.make("mapcoord"), 2, Geom.NTFloat32,
                     Geom.CTexcoord)
     array.addColumn(InternalName.make("texcoord"), 2, Geom.NTFloat32,
                     Geom.CTexcoord)
     vformat = GeomVertexFormat()
     vformat.addArray(array)
     vformat_dict['high'] = GeomVertexFormat.registerFormat(vformat)
     return vformat_dict
def add_button(self, text, label_id, pos_x, pos_y, width=0.0, hight=0.1):
    if width == 0.0:
        for c in range(len(text)/2):
            width += 0.08
    ls = LineSegs("lines")
    ls.setColor(0,1,0,1)
    ls.drawTo(-width/2, 0, hight/2)
    ls.drawTo(width/2, 0, hight/2)
    ls.drawTo(width/2, 0,-hight/2)
    ls.drawTo(-width/2, 0,-hight/2)
    ls.drawTo(-width/2, 0, hight/2)
    border = ls.create(False)
    border.setTag('back_ground', '1')
    
    array = GeomVertexArrayFormat()
    array.addColumn("vertex", 4, Geom.NTFloat32, Geom.CPoint)
    arr_format = GeomVertexFormat()
    arr_format.addArray(array)
    arr_format = GeomVertexFormat.registerFormat(arr_format)

    vdata = GeomVertexData('fill', arr_format, Geom.UHStatic)
    vdata.setNumRows(4)
    vertex = GeomVertexWriter(vdata, 'vertex')

    vertex.addData3f(-width/2, 0, hight/2)
    vertex.addData3f(width/2, 0, hight/2)
    vertex.addData3f(-width/2, 0,-hight/2)
    vertex.addData3f(width/2, 0,-hight/2)

    prim = GeomTristrips(Geom.UHStatic)
    prim.addVertex(0)
    prim.addVertex(1)
    prim.addVertex(2)
    prim.addVertex(3)

    geom = Geom(vdata)
    geom.addPrimitive(prim)
    node = GeomNode('gnode')
    node.addGeom(geom)
    nodePath = NodePath("button")
    nodePath.attachNewNode(node)
    nodePath.setPos(0,0,0)
    nodePath.setTag('button', '1')
    nodePath.setBin("unsorted", 0)
    nodePath.setDepthTest(False)
    nodePath.setColor(0,0,0,1)
    nodePath.attachNewNode(border)

    nodePath1 = NodePath("button")
    nodePath1.attachNewNode(node)
    nodePath1.setPos(0,0,0)
    nodePath1.setTag('button1', '1')
    nodePath1.setBin("unsorted", 0)
    nodePath1.setDepthTest(False)
    nodePath1.setColor(0,1,0,1)
    nodePath1.attachNewNode(border)


    button=DirectFrame( 
                        enableEdit=1,                      
                        text=text,
                        geom=nodePath,
                        text_scale=0.05,
                        text_fg=(0,1,0,1),
                        borderWidth=(1,1), 
                        relief = None,
                        text_pos=(0,-0.01,0),
                        textMayChange=1,
                        state=DGG.NORMAL,
                        parent=aspect2d
                        )
    button.setPos(pos_x,0,pos_y)
    button.bind(DGG.B1PRESS, button_click, [button])
    button.bind(DGG.WITHIN, button_hover, [button])
    button.bind(DGG.WITHOUT, button_no_hover, [button])
    # button.resetFrameSize()
    # self.button.bind(DGG.WITHIN, self.onMouseHoverInFunction, [button, some_value1])

    defines.ENTITIES[defines.ENTITY_ID] = {'CATEGORY':'button', 'BUTTON':button, 'NODE':nodePath, 'LABEL':label_id,'STATUS': 0}
    defines.ENTITY_ID += 1
Esempio n. 21
0
 def __generate_Vformats(self):
     vformat_dict = {}
     # Simple.
     array = GeomVertexArrayFormat()
     array.addColumn(InternalName.make("vertex"), 3, Geom.NTFloat32, Geom.CPoint)
     vformat = GeomVertexFormat()
     vformat.addArray(array)
     vformat_dict['simp'] = GeomVertexFormat.registerFormat(vformat)
     # Low.
     array = GeomVertexArrayFormat()
     array.addColumn(InternalName.make("vertex"), 3, Geom.NTFloat32, Geom.CPoint)
     array.addColumn(InternalName.make("color"), 4, Geom.NTFloat32, Geom.CColor)
     vformat = GeomVertexFormat()
     vformat.addArray(array)
     vformat_dict['low'] = GeomVertexFormat.registerFormat(vformat)
     # Mid.
     array = GeomVertexArrayFormat()
     array.addColumn(InternalName.make("vertex"), 3, Geom.NTFloat32, Geom.CPoint)
     array.addColumn(InternalName.make("mapcoord"), 2, Geom.NTFloat32, Geom.CTexcoord)
     vformat = GeomVertexFormat()
     vformat.addArray(array)
     vformat_dict['mid'] = GeomVertexFormat.registerFormat(vformat)
     # High (patches).
     array = GeomVertexArrayFormat()
     array.addColumn(InternalName.make("vertex"), 3, Geom.NTFloat32, Geom.CPoint)
     array.addColumn(InternalName.make("mapcoord"), 2, Geom.NTFloat32, Geom.CTexcoord)
     array.addColumn(InternalName.make("texcoord"), 2, Geom.NTFloat32, Geom.CTexcoord)
     vformat = GeomVertexFormat()
     vformat.addArray(array)
     vformat_dict['high'] = GeomVertexFormat.registerFormat(vformat)
     return vformat_dict
Esempio n. 22
0
    def __init__(self, size, pos, depth, mask, spec = WaterSpec()):
        NodePath.__init__(self, 'waterNode')
        self.setPos(pos)

        self.spec = spec
        self.pos = pos
        self.depth = depth
        self.size = size
        self.mask = mask
        self.height = pos[2]
        
        normal = (0, 0, 1)
        tangent = (normal[0], normal[2], -normal[1])
        binormal = (normal[2], normal[1], -normal[0])
        
        # Build array for new format.
        array = GeomVertexArrayFormat()
        array.addColumn(InternalName.make('vertex'), 3, Geom.NTFloat32, Geom.CPoint)
        array.addColumn(InternalName.make('texcoord'), 2, Geom.NTFloat32, Geom.CTexcoord)
        array.addColumn(InternalName.make('normal'), 3, Geom.NTFloat32, Geom.CVector)
        array.addColumn(InternalName.make('binormal'), 3, Geom.NTFloat32, Geom.CVector)
        array.addColumn(InternalName.make('tangent'), 3, Geom.NTFloat32, Geom.CVector)

        # Create and register format.
        format = GeomVertexFormat()
        format.addArray(array)
        format = GeomVertexFormat.registerFormat(format)

        vdata = GeomVertexData('waterPlanes', format, Geom.UHStatic)
        vdata.setNumRows(4)
        vtxWriter = GeomVertexWriter(vdata, 'vertex')
        tcWriter = GeomVertexWriter(vdata, 'texcoord')
        tnWriter = GeomVertexWriter(vdata, 'tangent')
        bnWriter = GeomVertexWriter(vdata, 'binormal')
        normWriter = GeomVertexWriter(vdata, 'normal')
        # top left corner
        vtxWriter.addData3f(size[0], size[3], 0)
        tcWriter.addData2f(0, 1)
        normWriter.addData3f(*normal)
        tnWriter.addData3f(*tangent)
        bnWriter.addData3f(*binormal)
        # bottom left corner
        vtxWriter.addData3f(size[0], size[2], 0)
        tcWriter.addData2f(0, 0)
        normWriter.addData3f(*normal)
        tnWriter.addData3f(*tangent)
        bnWriter.addData3f(*binormal)
        # top right corner
        vtxWriter.addData3f(size[1], size[3], 0)
        tcWriter.addData2f(1, 1)
        normWriter.addData3f(*normal)
        tnWriter.addData3f(*tangent)
        bnWriter.addData3f(*binormal)
        # bottom right corner
        vtxWriter.addData3f(size[1], size[2], 0)
        tcWriter.addData2f(1, 0)
        normWriter.addData3f(*normal)
        tnWriter.addData3f(*tangent)
        bnWriter.addData3f(*binormal)
        
        topTris = GeomTriangles(Geom.UHStatic)
        topTris.addVertices(0, 1, 2)
        topTris.addVertices(3, 2, 1)
        topGeom = Geom(vdata)
        topGeom.addPrimitive(topTris)
        self.topNP = self.attachNewNode(GeomNode('waterTop'))
        self.topNP.node().addGeom(topGeom)
        
        # Reverse the winding for the bottom water plane
        botTris = GeomTriangles(Geom.UHStatic)
        botTris.addVertices(2, 1, 0)
        botTris.addVertices(1, 2, 3)        
        botGeom = Geom(vdata)
        botGeom.addPrimitive(botTris)
        self.botNP = self.attachNewNode(GeomNode('waterBot'))
        self.botNP.node().addGeom(botGeom)

        # Create an AABB which defines the volume of this water.
        self.aabb = BoundingBox(Point3(size[0], size[2], -depth), Point3(size[1], size[3], 0))
        self.aabb.xform(self.getMat(render))
        
        self.cubemap = base.bspLoader.getClosestCubemapTexture(self.getPos(render))

        self.dudvFrame = 0
Esempio n. 23
0
def makeVertexFormat(color = True, normal = False, texcoord = False, tan_binorm = False):
	myArray = GeomVertexArrayFormat()
	myArray.addColumn(InternalName.make('vertex'), 3, Geom.NTFloat32, Geom.CPoint)
	if color:
		myArray.addColumn(InternalName.make('color'), 4, Geom.NTFloat32, Geom.CColor)
	if normal:
		myArray.addColumn(InternalName.make('normal'), 3, Geom.NTFloat32, Geom.CVector)
	if texcoord:
		myArray.addColumn(InternalName.make('texcoord'), 2, Geom.NTFloat32, Geom.CTexcoord)
	if tan_binorm:
		myArray.addColumn(InternalName.make('tangent'), 3, Geom.NTFloat32, Geom.CVector)
		myArray.addColumn(InternalName.make('binormal'), 3, Geom.NTFloat32, Geom.CVector)
	myFormat = GeomVertexFormat()
	myFormat.addArray(myArray)
	myFormat = GeomVertexFormat.registerFormat(myFormat)
	
	return myFormat
Esempio n. 24
0
def empty_geom(prefix,
               nb_data,
               nb_vertices,
               points=False,
               normal=True,
               texture=True,
               color=False,
               tanbin=False):
    array = GeomVertexArrayFormat()
    array.addColumn(InternalName.make('vertex'), 3, Geom.NTFloat32,
                    Geom.CPoint)
    if color:
        array.addColumn(InternalName.make('color'), 4, Geom.NTFloat32,
                        Geom.CColor)
    if texture:
        array.addColumn(InternalName.make('texcoord'), 2, Geom.NTFloat32,
                        Geom.CTexcoord)
    if normal:
        array.addColumn(InternalName.make('normal'), 3, Geom.NTFloat32,
                        Geom.CVector)
    if tanbin:
        array.addColumn(InternalName.make('binormal'), 3, Geom.NTFloat32,
                        Geom.CVector)
        array.addColumn(InternalName.make('tangent'), 3, Geom.NTFloat32,
                        Geom.CVector)
    format = GeomVertexFormat()
    format.addArray(array)
    format = GeomVertexFormat.registerFormat(format)
    gvd = GeomVertexData('gvd', format, Geom.UHStatic)
    if nb_data != 0:
        gvd.unclean_set_num_rows(nb_data)
    geom = Geom(gvd)
    gvw = GeomVertexWriter(gvd, 'vertex')
    if color:
        gcw = GeomVertexWriter(gvd, 'color')
    else:
        gcw = None
    if texture:
        gtw = GeomVertexWriter(gvd, 'texcoord')
    else:
        gtw = None
    if normal:
        gnw = GeomVertexWriter(gvd, 'normal')
    else:
        gnw = None
    if tanbin:
        gtanw = GeomVertexWriter(gvd, 'tangent')
        gbiw = GeomVertexWriter(gvd, 'binormal')
    else:
        gtanw = None
        gbiw = None
    if points:
        prim = GeomPoints(Geom.UHStatic)
    else:
        prim = GeomTriangles(Geom.UHStatic)
    if nb_vertices != 0:
        prim.reserve_num_vertices(nb_vertices)
    return (gvw, gcw, gtw, gnw, gtanw, gbiw, prim, geom)
Esempio n. 25
0
from panda3d.core import Material, NodePath, PerlinNoise3, PNMImage, Point3
from panda3d.core import Shader, Texture, TextureStage
from panda3d.core import VBase4, Vec3

from utils import convertToPatches, shape_generator_advanced


#you cant normalize in-place so this is a helper function
def normalize(vec):
    vec.normalize()
    return vec


# Build array for new format.
array = GeomVertexArrayFormat()
array.addColumn(InternalName.make(b'vertex'), 3, Geom.NTFloat32, Geom.CPoint)
array.addColumn(InternalName.make(b'texcoord'), 2, Geom.NTFloat32, Geom.CTexcoord)
array.addColumn(InternalName.make(b'normal'), 3, Geom.NTFloat32, Geom.CVector)
array.addColumn(InternalName.make(b'binormal'), 3, Geom.NTFloat32, Geom.CVector)
array.addColumn(InternalName.make(b'tangent'), 3, Geom.NTFloat32, Geom.CVector)

# Create and register format.
format = GeomVertexFormat()
format.addArray(array)
format = GeomVertexFormat.registerFormat(format)


def frange(start, stop, step):
    r = start
    while r < stop:
        yield r
Esempio n. 26
0
    def sample(self, segs, wrap_x=False, wrap_y=False, two_sided=False):
        self.comp_env.reset()

        x_segs, y_segs = segs
        array = GeomVertexArrayFormat()

        for column_name, column_func in self.comp_env.funcs.items():
            dtype = column_func.dtype_out
            if issubclass(dtype, Vec2):
                col_type = 2
            elif issubclass(dtype, Vec3):
                col_type = 3
            elif issubclass(dtype, Vec4):
                col_type = 4
            array.addColumn(
                column_name,
                col_type,
                Geom.NTFloat32,
                Geom.CPoint,
            )

        vformat = GeomVertexFormat()
        vformat.addArray(array)
        vformat = GeomVertexFormat.registerFormat(vformat)
        vdata = GeomVertexData("Data", vformat, Geom.UHDynamic)

        columns = {}
        for column_name in self.comp_env.outputs:
            columns[column_name] = GeomVertexWriter(vdata, column_name)

        geom = Geom(vdata)

        # Vertices
        x_vertices = x_segs + 1
        y_vertices = y_segs + 1
        if wrap_x:
            x_vertices -= 1
        if wrap_y:
            y_vertices -= 1

        for x in range(x_vertices):
            for y in range(y_vertices):
                x_norm = float(x) / float(x_segs)
                y_norm = float(y) / float(y_segs)

                self.comp_env.set_value('xy', Vec2(x_norm, y_norm))
                self.comp_env.compute()

                for column_name in self.comp_env.outputs:
                    writer = columns[column_name]
                    dtype = self.comp_env.funcs[column_name].dtype_out
                    data = self.comp_env.values[column_name]

                    if issubclass(dtype, Vec2):
                        writer.addData2f(data)
                    elif issubclass(dtype, Vec3):
                        writer.addData3f(data)
                    elif issubclass(dtype, Vec4):
                        writer.addData4f(data)

        # Triangles
        tris = GeomTriangles(Geom.UHStatic)
        for x in range(x_segs):
            for y in range(y_segs):
                # v1   v3
                #
                # v0   v2
                v_0 = x * y_vertices + y
                v_1 = x * y_vertices + y + 1
                v_2 = (x + 1) * y_vertices + y
                v_3 = (x + 1) * y_vertices + y + 1

                if wrap_x and x == x_segs - 1:
                    v_2 = y
                    v_3 = y + 1
                if wrap_y and y == y_segs - 1:
                    v_1 = x * y_vertices
                    v_3 = (x + 1) * y_vertices
                if wrap_x and x == x_segs - 1 and wrap_y and y == y_segs - 1:
                    v_3 = 0

                tris.addVertices(v_0, v_2, v_3)
                tris.addVertices(v_0, v_3, v_1)
                if two_sided:
                    tris.addVertices(v_0, v_3, v_2)
                    tris.addVertices(v_0, v_1, v_3)
        tris.closePrimitive()
        geom.addPrimitive(tris)

        node = GeomNode('geom_node')
        node.addGeom(geom)
        return node
Esempio n. 27
0
def getVertexData(vertex, vertex_index, normal=None, normal_index=None,
                  texcoordset=(), texcoord_indexset=(),
                  textangentset=(), textangent_indexset=(),
                  texbinormalset=(), texbinormal_indexset=()):
    
    format = GeomVertexFormat()
    formatArray = GeomVertexArrayFormat()
    
    indices2stack = [vertex_index.reshape(-1, 1)]
    alldata = [vertex]
    formatArray.addColumn(InternalName.make("vertex"), 3, Geom.NTFloat32, Geom.CPoint)
    if normal is not None:
        indices2stack.append(normal_index.reshape(-1, 1))
        alldata.append(collada.util.normalize_v3(numpy.copy(normal)))
        formatArray.addColumn(InternalName.make("normal"), 3, Geom.NTFloat32, Geom.CVector)
    if len(texcoordset) > 0:
        indices2stack.append(texcoord_indexset[0].reshape(-1, 1))
        alldata.append(texcoordset[0])
        formatArray.addColumn(InternalName.make("texcoord"), 2, Geom.NTFloat32, Geom.CTexcoord)
    if len(textangentset) > 0:
        indices2stack.append(textangent_indexset[0].reshape(-1, 1))
        alldata.append(textangentset[0])
        formatArray.addColumn(InternalName.make("tangent"), 3, Geom.NTFloat32, Geom.CVector)
    if len(texbinormalset) > 0:
        indices2stack.append(texbinormal_indexset[0].reshape(-1, 1))
        alldata.append(texbinormalset[0])
        formatArray.addColumn(InternalName.make("binormal"), 3, Geom.NTFloat32, Geom.CVector)
        
    #have to flatten and reshape like this so that it's contiguous
    stacked_indices = numpy.hstack(indices2stack).flatten().reshape((-1, len(indices2stack)))

    #index_map - maps each unique value back to a location in the original array it came from
    #   eg. stacked_indices[index_map] == unique_stacked_indices
    #inverse_map - maps original array locations to their location in the unique array
    #   e.g. unique_stacked_indices[inverse_map] == stacked_indices
    unique_stacked_indices, index_map, inverse_map = numpy.unique(stacked_indices.view([('',stacked_indices.dtype)]*stacked_indices.shape[1]), return_index=True, return_inverse=True)
    unique_stacked_indices = unique_stacked_indices.view(stacked_indices.dtype).reshape(-1,stacked_indices.shape[1])
    
    #unique returns as int64, so cast back
    index_map = numpy.cast['uint32'](index_map)
    inverse_map = numpy.cast['uint32'](inverse_map)
    
    #sort the index map to get a list of the index of the first time each value was encountered
    sorted_map = numpy.cast['uint32'](numpy.argsort(index_map))
    
    #since we're sorting the unique values, we have to map the inverse_map to the new index locations
    backwards_map = numpy.zeros_like(sorted_map)
    backwards_map[sorted_map] = numpy.arange(len(sorted_map), dtype=numpy.uint32)
    
    #now this is the new unique values and their indices
    unique_stacked_indices = unique_stacked_indices[sorted_map]
    inverse_map = backwards_map[inverse_map]
    
    #combine the unique stacked indices into unique stacked data
    data2stack = []
    for idx, data in enumerate(alldata):
        data2stack.append(data[unique_stacked_indices[:,idx]])
    unique_stacked_data = numpy.hstack(data2stack).flatten()
    unique_stacked_data.shape = (-1)
    all_data = unique_stacked_data.tostring()

    format.addArray(formatArray)
    format = GeomVertexFormat.registerFormat(format)
    
    vdata = GeomVertexData("dataname", format, Geom.UHStatic)
    arr = GeomVertexArrayData(format.getArray(0), GeomEnums.UHStream)
    datahandle = arr.modifyHandle()
    datahandle.setData(all_data)
    all_data = None
    vdata.setArray(0, arr)
    datahandle = None
    arr = None

    indexFormat = GeomVertexArrayFormat()
    indexFormat.addColumn(InternalName.make("index"), 1, Geom.NTUint32, Geom.CIndex)
    indexFormat = GeomVertexArrayFormat.registerFormat(indexFormat)
    indexArray = GeomVertexArrayData(indexFormat, GeomEnums.UHStream)
    indexHandle = indexArray.modifyHandle()
    indexData = inverse_map.tostring()
    indexHandle.setData(indexData)
    return vdata, indexArray
Esempio n. 28
0
    def build(self):
        # http://www.panda3d.org/forums/viewtopic.php?t=11528
        """Create the geometry from the submitted arrays"""
        verts = self.verts
        polys = self.polys
        self.geomnode = GeomNode('geometry')
        self.color_lookup = []
        if not self.vnorms:
            self.getNormals()
        if not self.uvs:
            self.getUVMapping()
        if self.use_tangents:
            self.getTangents()

        # Build array for new format.
        array = GeomVertexArrayFormat()
        array.addColumn(InternalName.make(b'vertex'), 3, Geom.NTFloat32, Geom.CPoint)
        array.addColumn(InternalName.make(b'texcoord'), 2, Geom.NTFloat32, Geom.CTexcoord)
        array.addColumn(InternalName.make(b'normal'), 3, Geom.NTFloat32, Geom.CVector)
        if self.use_tangents:
            array.addColumn(InternalName.make(b'binormal'), 3, Geom.NTFloat32, Geom.CVector)
            array.addColumn(InternalName.make(b'tangent'), 3, Geom.NTFloat32, Geom.CVector)

        # Create and register format.
        format = GeomVertexFormat()
        format.addArray(array)
        format = GeomVertexFormat.registerFormat(format)

        geoms = []
        for i in range(len(self.colors)):
            vdata = GeomVertexData('ngon', format, Geom.UHStatic)
            geom = Geom(vdata)
            tri = GeomTriangles(Geom.UHStatic)
            vertex = GeomVertexWriter(vdata, b'vertex')
            normal = GeomVertexWriter(vdata, b'normal')
            texcoord = GeomVertexWriter(vdata, b'texcoord')
            geoms.append({'geom':geom,
                          'tri':tri,
                          'vertex':vertex,
                          'texcoord':texcoord,
                          'normal':normal,
                          'index':0,
                          'vdata':vdata,
                          'color':i})
            if self.use_tangents:
                tangent = GeomVertexWriter(vdata, b'tangent')
                binormal = GeomVertexWriter(vdata, b'binormal')
                geoms[i]['tangent'] = tangent
                geoms[i]['binormal'] = binormal

        for poly_index in range(len(polys)):
            color_index = self.colors.index(self.mats[poly_index])
            vertcount = geoms[color_index]['index']

            p = polys[poly_index]
            poly = [verts[i] for i in p]
            uvs = self.uvs[poly_index]
            norm = [self.vnorms[i] for i in p]
            if self.use_tangents:
                binorm = [self.binorms[i] for i in p]
                tan = [self.tans[i] for i in p]
            reindexed = [] # New vertex indices per-poly

            for v in poly:
                geoms[color_index]['vertex'].addData3f(v[0], v[1], v[2])
                reindexed.append(vertcount)
                vertcount += 1
            geoms[color_index]['index'] = vertcount
            for i in range(len(poly)):
                geoms[color_index]['normal'].addData3f(Vec3(norm[i][0], norm[i][1], norm[i][2]))
                if self.use_tangents:
                    geoms[color_index]['binormal'].addData3f(Vec3(binorm[i][0], binorm[i][1], binorm[i][2]))
                    geoms[color_index]['tangent'].addData3f(Vec3(tan[i][0], tan[i][1], tan[i][2]))
            for tvert in uvs:
                geoms[color_index]['texcoord'].addData2f(tvert[0], tvert[1])

            triangulated = self.getFanning(reindexed) # Use new vertex indices
            for tri_index in range(len(triangulated)):
                t = triangulated[tri_index]
                tri = geoms[color_index]['tri']
                tri.addVertices(t[0], t[1], t[2])

        for color_index in range(len(self.colors)):
            geom = geoms[color_index]['geom']
            tri = geoms[color_index]['tri']
            tri.closePrimitive()
            geom.addPrimitive(tri)
            self.geomnode.addGeom(geom)
            self.color_lookup.append(color_index)
Esempio n. 29
0
def makeVertexFormat(color=True,
                     normal=False,
                     texcoord=False,
                     tan_binorm=False):
    myArray = GeomVertexArrayFormat()
    myArray.addColumn(InternalName.make('vertex'), 3, Geom.NTFloat32,
                      Geom.CPoint)
    if color:
        myArray.addColumn(InternalName.make('color'), 4, Geom.NTFloat32,
                          Geom.CColor)
    if normal:
        myArray.addColumn(InternalName.make('normal'), 3, Geom.NTFloat32,
                          Geom.CVector)
    if texcoord:
        myArray.addColumn(InternalName.make('texcoord'), 2, Geom.NTFloat32,
                          Geom.CTexcoord)
    if tan_binorm:
        myArray.addColumn(InternalName.make('tangent'), 3, Geom.NTFloat32,
                          Geom.CVector)
        myArray.addColumn(InternalName.make('binormal'), 3, Geom.NTFloat32,
                          Geom.CVector)
    myFormat = GeomVertexFormat()
    myFormat.addArray(myArray)
    myFormat = GeomVertexFormat.registerFormat(myFormat)

    return myFormat
Esempio n. 30
0
            if not res.has_key(tree):
                res[tree] = []
            x = random.randint(sx, ex)
            y = random.randint(sy, ey)
            z = self.world.map3d[x, y]
            if 0 < z < self.config.low_mount_level[1]:
                res[tree].append((x, y, z))

        self[item] = res
        return res


# Shit for f*****g trees

formatArray = GeomVertexArrayFormat()
formatArray.addColumn(InternalName.make("drawFlag"), 1, Geom.NTUint8,
                      Geom.COther)

treeform = GeomVertexFormat(GeomVertexFormat.getV3n3cpt2())
treeform.addArray(formatArray)
treeform = GeomVertexFormat.registerFormat(treeform)


#this draws the body of the tree. This draws a ring of vertices and connects the rings with
#triangles to form the body.
#this keepDrawing paramter tells the function wheter or not we're at an end
#if the vertices before you were an end, dont draw branches to it
def draw_body(nodePath,
              vdata,
              pos,
              vecList,
              radius=1,
Esempio n. 31
0
def add_button(self, text, label_id, pos_x, pos_y, width=0.0, hight=0.1):
    if width == 0.0:
        for c in range(len(text) / 2):
            width += 0.08
    ls = LineSegs("lines")
    ls.setColor(0, 1, 0, 1)
    ls.drawTo(-width / 2, 0, hight / 2)
    ls.drawTo(width / 2, 0, hight / 2)
    ls.drawTo(width / 2, 0, -hight / 2)
    ls.drawTo(-width / 2, 0, -hight / 2)
    ls.drawTo(-width / 2, 0, hight / 2)
    border = ls.create(False)
    border.setTag('back_ground', '1')

    array = GeomVertexArrayFormat()
    array.addColumn("vertex", 4, Geom.NTFloat32, Geom.CPoint)
    arr_format = GeomVertexFormat()
    arr_format.addArray(array)
    arr_format = GeomVertexFormat.registerFormat(arr_format)

    vdata = GeomVertexData('fill', arr_format, Geom.UHStatic)
    vdata.setNumRows(4)
    vertex = GeomVertexWriter(vdata, 'vertex')

    vertex.addData3f(-width / 2, 0, hight / 2)
    vertex.addData3f(width / 2, 0, hight / 2)
    vertex.addData3f(-width / 2, 0, -hight / 2)
    vertex.addData3f(width / 2, 0, -hight / 2)

    prim = GeomTristrips(Geom.UHStatic)
    prim.addVertex(0)
    prim.addVertex(1)
    prim.addVertex(2)
    prim.addVertex(3)

    geom = Geom(vdata)
    geom.addPrimitive(prim)
    node = GeomNode('gnode')
    node.addGeom(geom)
    nodePath = NodePath("button")
    nodePath.attachNewNode(node)
    nodePath.setPos(0, 0, 0)
    nodePath.setTag('button', '1')
    nodePath.setBin("unsorted", 0)
    nodePath.setDepthTest(False)
    nodePath.setColor(0, 0, 0, 1)
    nodePath.attachNewNode(border)

    nodePath1 = NodePath("button")
    nodePath1.attachNewNode(node)
    nodePath1.setPos(0, 0, 0)
    nodePath1.setTag('button1', '1')
    nodePath1.setBin("unsorted", 0)
    nodePath1.setDepthTest(False)
    nodePath1.setColor(0, 1, 0, 1)
    nodePath1.attachNewNode(border)

    button = DirectFrame(enableEdit=1,
                         text=text,
                         geom=nodePath,
                         text_scale=0.05,
                         text_fg=(0, 1, 0, 1),
                         borderWidth=(1, 1),
                         relief=None,
                         text_pos=(0, -0.01, 0),
                         textMayChange=1,
                         state=DGG.NORMAL,
                         parent=aspect2d)
    button.setPos(pos_x, 0, pos_y)
    button.bind(DGG.B1PRESS, button_click, [button])
    button.bind(DGG.WITHIN, button_hover, [button])
    button.bind(DGG.WITHOUT, button_no_hover, [button])
    # button.resetFrameSize()
    # self.button.bind(DGG.WITHIN, self.onMouseHoverInFunction, [button, some_value1])

    defines.ENTITIES[defines.ENTITY_ID] = {
        'CATEGORY': 'button',
        'BUTTON': button,
        'NODE': nodePath,
        'LABEL': label_id,
        'STATUS': 0
    }
    defines.ENTITY_ID += 1
Esempio n. 32
0
            if not res.has_key(tree):
                res[tree] = []
            x = random.randint(sx, ex)
            y = random.randint(sy, ey)
            z = self.world.map3d[x, y]
            if 0 < z < self.config.low_mount_level[1]:
                res[tree].append((x, y, z))

        self[item] = res
        return res


# Shit for f*****g trees

formatArray = GeomVertexArrayFormat()
formatArray.addColumn(InternalName.make("drawFlag"), 1, Geom.NTUint8, Geom.COther)

treeform = GeomVertexFormat(GeomVertexFormat.getV3n3cpt2())
treeform.addArray(formatArray)
treeform = GeomVertexFormat.registerFormat(treeform)


# this draws the body of the tree. This draws a ring of vertices and connects the rings with
# triangles to form the body.
# this keepDrawing paramter tells the function wheter or not we're at an end
# if the vertices before you were an end, dont draw branches to it
def draw_body(nodePath, vdata, pos, vecList, radius=1, keepDrawing=True, numVertices=3):

    circleGeom = Geom(vdata)

    vertWriter = GeomVertexWriter(vdata, "vertex")
Esempio n. 33
0
    def __init__(self,
                 __occupying_unit=None,
                 __occupiable=True,
                 x=0,
                 z=0,
                 r=5,
                 tag=0):
        self.__occupying_unit = __occupying_unit
        self.__occupiable = __occupiable
        self.__r = r
        self.__x = x
        self.__z = z
        self.__tag = tag

        #Procedurally creating a hex!
        geometry_array = GeomVertexArrayFormat()
        geometry_array.addColumn(InternalName.make('vertex'), 3,
                                 Geom.NTFloat32, Geom.CPoint)
        geometry_array.addColumn(InternalName.make('normal'), 3,
                                 Geom.NTFloat32, Geom.CPoint)
        format = GeomVertexFormat()
        format.addArray(geometry_array)
        format = GeomVertexFormat.registerFormat(format)
        self.__vdata = GeomVertexData('Hex', format, Geom.UHStatic)
        self.__vertex = GeomVertexWriter(self.__vdata, 'vertex')
        self.__normal = GeomVertexWriter(self.__vdata, 'normal')

        #Vertex 1
        self.__vertex.addData3f(self.__x, self.__z + self.__r, 0)
        self.__normal.addData3f(1, 0, 0)
        #Vertex 2
        self.__vertex.addData3f(self.__x + self.__r * sin(pi / 3),
                                self.__z + self.__r * cos(pi / 3), 0)
        self.__normal.addData3f(1, 0, 0)
        #Vertex 3
        self.__vertex.addData3f(self.__x + self.__r * sin(pi / 3),
                                self.__z - self.__r * cos(pi / 3), 0)
        self.__normal.addData3f(1, 0, 0)
        #Vertex 4
        self.__vertex.addData3f(self.__x, self.__z - self.__r, 0)
        self.__normal.addData3f(1, 0, 0)
        #Vertex 5
        self.__vertex.addData3f(self.__x - self.__r * sin(pi / 3),
                                self.__z - self.__r * cos(pi / 3), 0)
        self.__normal.addData3f(1, 0, 0)
        #Vertex 6
        self.__vertex.addData3f(self.__x - self.__r * sin(pi / 3),
                                self.__z + self.__r * cos(pi / 3), 0)
        self.__normal.addData3f(1, 0, 0)

        self.__hex_primitive = GeomTrifans(Geom.UHStatic)
        self.__hex_primitive.addVertices(5, 4)
        self.__hex_primitive.addVertices(3, 2)
        self.__hex_primitive.addVertices(1, 0)

        self.__hex_primitive.closePrimitive()
        self.__hex_geometry = Geom(self.__vdata)
        self.__hex_geometry.addPrimitive(self.__hex_primitive)
        self.__hex_node = GeomNode('HexNode')
        self.__hex_node.addGeom(self.__hex_geometry)

        nodePath = render.attachNewNode(self.__hex_node)
        nodePath.setTag("hex", str(tag))
        nodePath.node().setIntoCollideMask(BitMask32.bit(1))
        nodePath.hide()
Esempio n. 34
0
    def __init__(self):
        array_format = GeomVertexArrayFormat()
        array_format.addColumn(
            InternalName.make(ArrayFormatColunm.Vertex.value), 3,
            Geom.NT_float32, Geom.C_point)
        array_format.addColumn(
            InternalName.make(ArrayFormatColunm.Color.value), 4, Geom.NT_uint8,
            Geom.C_color)
        array_format.addColumn(
            InternalName.make(ArrayFormatColunm.Normal.value), 3,
            Geom.NT_float32, Geom.C_normal)
        array_format.addColumn(
            InternalName.make(ArrayFormatColunm.Tangent.value), 3,
            Geom.NT_float32, Geom.C_vector)
        array_format.addColumn(
            InternalName.make(ArrayFormatColunm.Binormal.value), 3,
            Geom.NT_float32, Geom.C_vector)
        array_format.addColumn(
            InternalName.make(ArrayFormatColunm.UVMap.value), 2,
            Geom.NT_float32, Geom.C_texcoord)

        self.vertex_format = GeomVertexFormat()
        self.vertex_format.addArray(array_format)
        self.vertex_format = GeomVertexFormat.registerFormat(
            self.vertex_format)
Esempio n. 35
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")
Esempio n. 36
0
from opensimplex import OpenSimplex
from panda3d.core import (
    Geom,
    GeomLinesAdjacency,
    GeomNode,
    GeomVertexArrayFormat,
    GeomVertexFormat,
    GeomVertexData,
    GeomVertexWriter,
)

from utils.colour import WHITE
from utils.math import *

array4 = GeomVertexArrayFormat()
array4.addColumn("vertex", 4, Geom.NTFloat32, Geom.COther)
array4.addColumn("normal", 4, Geom.NTFloat32, Geom.COther)
array4.addColumn("colour", 4, Geom.NTFloat32, Geom.CColor)

format4 = GeomVertexFormat()
format4.addArray(array4)
format4 = GeomVertexFormat.registerFormat(format4)


class Mesh4:
    """
    Base class for meshes in R4.

    Args:
        vertices :: array_like (N,4)
            A list of vertex positions in the mesh.