예제 #1
0
    def __init__(self, name = 'Mesh'):
       
        self.name = name
        self.finished = False
 
        self.format = GeomVertexFormat.getV3c4t2()
        #print self.format
        self.vertexData = GeomVertexData(name, self.format, Geom.UHStatic)
        self.vertexData.setNumRows(26136)
       
        self.mesh = Geom(self.vertexData)
        self.triangles = GeomTriangles(Geom.UHStatic)
        self.triangleData = self.triangles.modifyVertices()
        self.triangleData.setNumRows(26136)
       
        self.vertex = GeomVertexWriter(self.vertexData, 'vertex')
        self.normal = GeomVertexWriter(self.vertexData, 'normal')
        self.color = GeomVertexWriter(self.vertexData, 'color')
        self.texcoord = GeomVertexWriter(self.vertexData, 'texcoord')
       
        self.faceCount = 0
예제 #2
0
    def __init__(self, point_cloud_size):
        format = GeomVertexFormat.getV3c4t2()
        vdata = GeomVertexData('point', format, Geom.UHDynamic)
        self._pos_writer = GeomVertexWriter(vdata, 'vertex')
        self._color_writer = GeomVertexWriter(vdata, 'color')
        self._tex_writer = GeomVertexWriter(vdata, 'texcoord')
        self._point_cloud_size = point_cloud_size
        self._prev_point_cloud_size = 0

        assert point_cloud_size > 0
        vdata.setNumRows(point_cloud_size * 6)
        self._tex_writer.set_row(0)
        set_texture(self._tex_writer, point_cloud_size)
        pnts = GeomTriangles(Geom.UHStatic)
        pnts.addConsecutiveVertices(0, 3 * 2 * point_cloud_size)
        pnts.closePrimitive()
        points_geom = Geom(vdata)
        points_geom.addPrimitive(pnts)
        snode = GeomNode('points')
        snode.addGeom(points_geom)
        dir_name = osp.dirname(__file__)
        # print(osp.join(dir_name, 'pnts_vs.glsl'))
        vs_shader = osp.join(dir_name, 'pnts_vs.glsl')
        fs_shader = osp.join(dir_name, 'pnts_fs.glsl')
        myShader = Shader.load(
            Shader.SL_GLSL,
            vertex=Filename.fromOsSpecific(vs_shader).getFullpath(),
            fragment=Filename.fromOsSpecific(fs_shader).getFullpath())

        assert myShader is not None
        self.points_node = base.render.attachNewNode(snode)
        self.points_node.setPos(0., 0., 0.)
        self.points_node.set_shader(myShader)
        self.points_node.set_shader_input(
            "view_size", (base.win.getXSize(), base.win.getYSize()))
        self.points_node.node().setBounds(
            BoundingBox((-1000., -1000., -1000.), (1000., 1000., 1000.)))
        self.points_node.setTransparency(TransparencyAttrib.MAlpha)
예제 #3
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(
예제 #4
0
class Mesh(NodePath):

    _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(),
    }

    _modes = {
        'triangle': GeomTriangles,
        'tristrip': GeomTristrips,
        'ngon': GeomTrifans,
        'line': GeomLinestrips,
        'point': GeomPoints,
    }

    def __init__(self,
                 vertices=None,
                 triangles=None,
                 colors=None,
                 uvs=None,
                 normals=None,
                 static=True,
                 mode='triangle',
                 thickness=1):
        super().__init__('mesh')

        self.vertices = vertices
        self.triangles = triangles
        self.colors = colors
        self.uvs = uvs
        self.normals = normals
        self.static = static
        self.mode = mode
        self.thickness = thickness

        for var in (('vertices', vertices), ('triangles', triangles),
                    ('colors', colors), ('uvs', uvs), ('normals', normals)):
            name, value = var
            if value is None:
                setattr(self, name, list())

        if self.vertices:
            self.generate()

    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)
            # self.set_render_mode_perspective(True)

        # print('finished')

    @property
    def recipe(self):
        if hasattr(self, '_recipe'):
            return self._recipe

        return 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}
            )
        ''')

    @recipe.setter
    def recipe(self, value):
        self._recipe = value

    def __add__(self, other):
        self.vertices += other.vertices
        self.triangles += other.triangles
        if other.colors:
            self.colors += other.colors
        else:
            self.colors += (color.white, ) * len(other.vertices)

        self.normals += other.normals
        self.uvs += other.uvs

    def __deepcopy__(self, memo):
        m = Mesh(self.vertices, self.triangles, self.colors, self.uvs,
                 self.normals, self.static, self.mode, self.thickness)
        m.name = self.name
        return m

    @property
    def thickness(self):
        return self.getRenderModeThickness()

    @thickness.setter
    def thickness(self, value):
        self.setRenderModeThickness(value)

    @property
    def triangles(self):
        if self._triangles == None:
            self._triangles = [(i, i + 1, i + 2)
                               for i in range(0, len(self.vertices), 3)]

        return self._triangles

    @triangles.setter
    def triangles(self, value):
        self._triangles = value

    def generate_normals(self, smooth=True):
        self.normals = list(
            generate_normals(self.vertices, self.triangles, smooth))
        self.generate()
        return self.normals

    def colorize(self,
                 left=color.white,
                 right=color.blue,
                 down=color.red,
                 up=color.green,
                 back=color.white,
                 forward=color.white,
                 smooth=True,
                 world_space=True):
        colorize(self, left, right, down, up, back, forward, smooth,
                 world_space)

    def project_uvs(self, aspect_ratio=1, direction='forward'):
        project_uvs(self, aspect_ratio)

    def clear(self, regenerate=True):
        self.vertices, self.triangles, self.colors, self.uvs, self.normals = list(
        ), list(), list(), list(), list()
        if regenerate:
            self.generate()

    def save(self, name='', path=application.compressed_models_folder):
        if not application.compressed_models_folder.exists():
            application.compressed_models_folder.mkdir()

        if not name and hasattr(self, 'path'):
            name = self.path.stem
            if not '.' in name:
                name += '.ursinamesh'

        if name.endswith('ursinamesh'):
            with open(path / name, 'w') as f:
                # recipe = self.recipe.replace('LVector3f', '')
                f.write(self.recipe)
            print('saved .ursinamesh to:', path / name)

        elif name.endswith('.obj'):
            from ursina.mesh_importer import ursina_mesh_to_obj
            ursina_mesh_to_obj(self, name, path)

        elif name.endswith('.bam'):
            success = self.writeBamFile(path / name)
            print('saved .bam to:', path / name)
예제 #5
0
class Mesh(NodePath):

    _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(),
    }

    _modes = {
        'triangle': GeomTriangles,
        'tristrip': GeomTristrips,
        'ngon': GeomTrifans,
        'line': GeomLinestrips,
        'point': GeomPoints,
    }

    def __init__(self,
                 vertices=None,
                 triangles=None,
                 colors=None,
                 uvs=None,
                 normals=None,
                 static=True,
                 mode='triangle',
                 thickness=1):
        super().__init__('mesh')

        self.vertices = vertices
        self.triangles = triangles
        self.colors = colors
        self.uvs = uvs
        self.normals = normals
        self.static = static
        self.mode = mode
        self.thickness = thickness

        for var in (('vertices', vertices), ('triangles', triangles),
                    ('colors', colors), ('uvs', uvs), ('normals', normals)):
            name, value = var
            if value is None:
                setattr(self, name, list())

        if self.vertices:
            self.vertices = [tuple(v) for v in self.vertices]
            self.generate()

    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

        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)

        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 = GeomNode('mesh')
        self.geomNode.addGeom(geom)
        self.attachNewNode(self.geomNode)

        # if self.normals:
        #     self.normals = [tuple(e) for e in self.normals]
        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}
            )
        ''')
        # print('finished')

    def __add__(self, other):
        self.vertices += other.vertices
        self.triangles += other.triangles
        if other.colors:
            self.colors += other.colors
        else:
            self.colors += (color.white, ) * len(other.vertices)

        self.normals += other.normals
        self.uvs += other.uvs

    @property
    def thickness(self):
        return self.getRenderModeThickness()

    @thickness.setter
    def thickness(self, value):
        self.setRenderModeThickness(value)

    @property
    def triangles(self):
        if self._triangles == None:
            self._triangles = [(i, i + 1, i + 2)
                               for i in range(0, len(self.vertices), 3)]

        return self._triangles

    @triangles.setter
    def triangles(self, value):
        self._triangles = value

    def generate_normals(self, smooth=True):
        self.normals = list(
            generate_normals(self.vertices, self.triangles, smooth))
        self.generate()
        return self.normals

    def colorize(self,
                 left=color.white,
                 right=color.blue,
                 down=color.red,
                 up=color.green,
                 back=color.white,
                 forward=color.white,
                 smooth=True,
                 world_space=True):
        colorize(self, left, right, down, up, back, forward, smooth,
                 world_space)

    def project_uvs(self, aspect_ratio=1, direction='forward'):
        project_uvs(self, aspect_ratio)

    def clear(self, regenerate=True):
        self.vertices, self.triangles, self.colors, self.uvs, self.normals = list(
        ), list(), list(), list(), list()
        if regenerate:
            self.generate()

    def save(self, name, path=application.asset_folder, filetype='ursinamesh'):
        if filetype == 'ursinamesh':
            if not '.' in name:
                name += '.ursinamesh'

            with open(path / name, 'w') as f:
                recipe = self.recipe.replace('LVector3f', '')
                f.write(recipe)

        elif filetype == 'obj':
            from ursina.mesh_importer import ursina_mesh_to_obj
            ursina_mesh_to_obj(self, name, path)
예제 #6
0
파일: Effect.py 프로젝트: gaconkzk/tethical
    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
예제 #7
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

        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': GeomLinestrips(static_mode),
            'point': GeomPoints(static_mode),
        }

        if self.mode != 'line' or not self._triangles:
            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)

        else:  # line with segments defnined in triangles
            for line in self._triangles:
                prim = modes[self.mode]
                for e in line:
                    prim.addVertex(e)
                prim.close_primitive()
                geom = Geom(vdata)
                geom.addPrimitive(prim)

        self.geomNode = GeomNode('mesh')
        self.geomNode.addGeom(geom)
        self.attachNewNode(self.geomNode)

        # if self.normals:
        #     self.normals = [tuple(e) for e in self.normals]
        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}
            )
        ''')