Ejemplo n.º 1
0
    def __build_Star_Sphere(self, bg_stars):
        from panda3d.core import GeomVertexWriter, GeomVertexFormat, GeomVertexData
        from panda3d.core import Geom, GeomNode, GeomPoints, AmbientLight
        self.star_sphere_np.removeNode()
        
        # Fill GeomVertexData.
        vformat = GeomVertexFormat.getV3c4()
        vdata = GeomVertexData("Data", vformat, Geom.UHStatic) 
        vertices = GeomVertexWriter(vdata, "vertex")
        colours = GeomVertexWriter(vdata, "color")
        for coords in bg_stars:
            x, y, z = coords
            vertices.addData3f(x, y, z)
            colours.addData4f(1, 1, 1, 1)
            
        # Render bg stars.
        bg_stars = GeomPoints(Geom.UHStatic)
        bg_stars.addNextVertices(_env.STAR_COUNT)
        bg_stars_geom = Geom(vdata)
        bg_stars_geom.addPrimitive(bg_stars)
        star_sphere = GeomNode("star_sphere")
        star_sphere.addGeom(bg_stars_geom)
        star_sphere_np = NodePath(star_sphere)

        star_sphere_np.reparentTo(self.NP)
        return star_sphere_np
Ejemplo n.º 2
0
class PointMaker():
    def __init__(self, name):
        self.name = name
        self.new()

    def new(self):
        self.point = 0
        self.vdata = GeomVertexData(
        self.name, GeomVertexFormat.get_v3c4(), Geom.UHStatic)
        self.vdata.set_num_rows(2)
        self.vertex = GeomVertexWriter(self.vdata, 'vertex')
        self.color = GeomVertexWriter(self.vdata, 'color')
        self.prim = GeomPoints(Geom.UHStatic)

    def add(self, pos=(0,0,0), color=(1,1,1,1)):
        self.vertex.add_data3(pos[0],pos[1],pos[2]+0.02)
        self.color.add_data4(color)
        self.prim.add_vertex(self.point)
        self.point += 1

    def wrap_up(self):
        self.prim.close_primitive()
        geom = Geom(self.vdata)
        geom.add_primitive(self.prim)
        node = GeomNode('point')
        node.add_geom(geom)
        return NodePath(node)
Ejemplo n.º 3
0
    def __build_Star_Sphere(self, bg_stars):
        from panda3d.core import GeomVertexWriter, GeomVertexFormat, GeomVertexData
        from panda3d.core import Geom, GeomNode, GeomPoints, AmbientLight
        self.star_sphere_np.removeNode()

        # Fill GeomVertexData.
        vformat = GeomVertexFormat.getV3c4()
        vdata = GeomVertexData("Data", vformat, Geom.UHStatic)
        vertices = GeomVertexWriter(vdata, "vertex")
        colours = GeomVertexWriter(vdata, "color")
        for coords in bg_stars:
            x, y, z = coords
            vertices.addData3f(x, y, z)
            colours.addData4f(1, 1, 1, 1)

        # Render bg stars.
        bg_stars = GeomPoints(Geom.UHStatic)
        bg_stars.addNextVertices(_env.STAR_COUNT)
        bg_stars_geom = Geom(vdata)
        bg_stars_geom.addPrimitive(bg_stars)
        star_sphere = GeomNode("star_sphere")
        star_sphere.addGeom(bg_stars_geom)
        star_sphere_np = NodePath(star_sphere)

        star_sphere_np.reparentTo(self.NP)
        return star_sphere_np
Ejemplo n.º 4
0
def makePoints(n=1000):
    """ make a cloud of points that are a single node VS branching and making subnodes to control display """

    #points = np.random.uniform(-10,10,(n,4))
    #points = np.random.randn(n,3)
    points = np.cumsum(np.random.randint(-1,2,(n,3)), axis=0) #classic random walk
    #colors = np.random.rand(n,4)
    clr4 = np.random.rand(1,4)

    #points = [(0,0,0)]

    fmt = GeomVertexFormat.getV3c4() #3 component vertex, w/ 4 comp color
    vertexData = GeomVertexData('points', fmt, Geom.UHStatic)

    verts = GeomVertexWriter(vertexData, 'vertex')
    color = GeomVertexWriter(vertexData, 'color')

    #for point,clr4 in zip(points,colors):
    for point in points:
        verts.addData3f(*point)
        #color.addData4f(*point)
        color.addData4f(*clr4[0])
        #color.addData4f(.1,.1,.1,1)

    #pointCloud = GeomLinestrips(Geom.UHStatic) #this is f*****g cool!
    #pointCloud = GeomTristrips(Geom.UHStatic) #this is f*****g cool!
    pointCloud = GeomPoints(Geom.UHStatic)
    pointCloud.addConsecutiveVertices(0,n) #warning may error since n-1?
    pointCloud.closePrimitive()

    cloud = Geom(vertexData)
    cloud.addPrimitive(pointCloud)
    return cloud
Ejemplo n.º 5
0
 def new(self):
     self.point = 0
     self.vdata = GeomVertexData(
     self.name, GeomVertexFormat.get_v3c4(), Geom.UHStatic)
     self.vdata.set_num_rows(2)
     self.vertex = GeomVertexWriter(self.vdata, 'vertex')
     self.color = GeomVertexWriter(self.vdata, 'color')
     self.prim = GeomPoints(Geom.UHStatic)
Ejemplo n.º 6
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)
Ejemplo n.º 7
0
    def __init__(self):
        ShowBase.__init__(self)

        PanditorDisableMouseFunc()
        camera.setPos(0.0, 0.0, 50.0)
        camera.lookAt(0.0)
        PanditorEnableMouseFunc()

        # 1) create GeomVertexData
        frmt = GeomVertexFormat.getV3n3cp()
        vdata = GeomVertexData('triangle', frmt, Geom.UHDynamic)

        # 2) create Writers/Rewriters (must all be created before any readers and readers are one-pass-temporary)
        vertex = GeomVertexRewriter(vdata, 'vertex')
        normal = GeomVertexRewriter(vdata, 'normal')
        color = GeomVertexRewriter(vdata, 'color')

        zUp = Vec3(0, 0, 1)
        wt = Vec4(1.0, 1.0, 1.0, 1.0)
        gr = Vec4(0.5, 0.5, 0.5, 1.0)

        # 3) write each column on the vertex data object (for speed, have a different writer for each column)
        def addPoint(x, y, z):
            vertex.addData3f(x, y, z)
            normal.addData3f(zUp)
            color.addData4f(wt)

        addPoint(0.0, 0.0, 0.0)
        addPoint(5.0, 0.0, 0.0)
        addPoint(0.0, 5.0, 0.0)
        addPoint(5.0, 5.0, 0.0)

        # 4) create a primitive and add the vertices via index (not truely associated with the actual vertex table, yet)
        tris = GeomTriangles(Geom.UHDynamic)
        tris.addVertices(0, 1, 2)
        tris.closePrimitive()  # exception thrown if verts added != 3, other types inform Panda how many verts/primitive
        tris.addVertices(2, 1, 3)
        print "vdataPoints", vdata.getArrays()[0]
        # 5.1) (adding to scene) create a Geom and add primitives of like base-type i.e. triangles and triangle strips
        geom = Geom(vdata)
        geom.addPrimitive(tris)
        # 5.2) create a GeomNode to hold the Geom(s) and add the Geom(s)
        gn = GeomNode('gnode')
        gn.addGeom(geom)
        # 5.3) attache the node to the scene
        gnNodePath = render.attachNewNode(gn)

        geomPts = Geom(vdata)
        pts = GeomPoints(Geom.UHStatic)
        pts.addVertices(0, 1, 2)
        pts.closePrimitive()
        geomPts.addPrimitive(pts)
        pointsNode = GeomNode('points_node')
        pointsNode.addGeom(geomPts)
        pointsNP = render.attachNewNode(pointsNode)
        pointsNP.setZ(0.5)

        render.ls()
Ejemplo n.º 8
0
 def __node(self):
     # this function creates and returns particles' GeomNode
     points = GeomPoints(GeomEnums.UH_static)
     points.addNextVertices(self.__numPart)
     format_ = GeomVertexFormat.getEmpty()
     geom = Geom(GeomVertexData("abc", format_, GeomEnums.UH_static))
     geom.addPrimitive(points)
     geom.setBounds(OmniBoundingVolume())  # always render it
     node = GeomNode("node")
     node.addGeom(geom)
     return node
Ejemplo n.º 9
0
 def makeGeom(self, points, colors, sizes):
     #format = GeomVertexFormat.getV3c4()
     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)
     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, 'vertex')
     self.colorwriter = GeomVertexWriter(vdata, 'color')
     self.sizewriter = GeomVertexWriter(vdata, '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
Ejemplo n.º 10
0
 def __init__(self):
     ShowBase.__init__(self)
     vertexFormat = GeomVertexFormat.getV3c4()
     self.vertexData = GeomVertexData("data", vertexFormat, Geom.UHDynamic)
     geometry = Geom(self.vertexData)
     self.primitive = GeomPoints(Geom.UHDynamic)
     geometry.addPrimitive(self.primitive)
     node = GeomNode("node")
     node.addGeom(geometry)
     self.nodePath = NodePath(node)
     self.nodePath.setPos(0, 0, 0)
     self.nodePath.setRenderModeThickness(10.0)
     self.camera.setPos(0.0, -10.0, 0.0)
     self.disableMouse()
     self.nodePath.reparentTo(self.render)
Ejemplo n.º 11
0
def makePoint(point=(0,0,0)):
    clr4 = [1,1,1,1]
    fmt = GeomVertexFormat.getV3c4() #3 component vertex, w/ 4 comp color
    vertexData = GeomVertexData('points', fmt, Geom.UHStatic)
    verts = GeomVertexWriter(vertexData, 'vertex')
    verts.addData3f(*point)
    color = GeomVertexWriter(vertexData, 'color')
    color.addData4f(*clr4)
    pointCloud = GeomPoints(Geom.UHStatic)
    pointCloud.addVertex(0)
    pointCloud.closePrimitive()
    cloud = Geom(vertexData)
    cloud.addPrimitive(pointCloud)
    cloudNode = GeomNode('point')
    cloudNode.addGeom(cloud)
    return cloudNode
Ejemplo n.º 12
0
	def draw_vert(self,v, v_color):
		format = GeomVertexFormat.getV3cp()
		vdata=GeomVertexData('vert', format, Geom.UHDynamic)
		vertex=GeomVertexWriter(vdata, 'vertex')
		color=GeomVertexWriter(vdata, 'color')
		vertex.addData3f(0.0,0.0,0.0)
		color.addData4f(v_color)		
		mesh = Geom(vdata)
		point = GeomPoints(Geom.UHDynamic)
		point.addVertex(0)
		point.closePrimitive()
		mesh.addPrimitive(point)
		vert_node = GeomNode(self.mesh.name+'_vert_'+str(v.ID))
		vert_node.addGeom(mesh)
		vert_node.setTag('ID',str(v.ID))
		rendered_vert = self.render_root.attachNewNode(vert_node)
		rendered_vert.setPos(v.pos.x,v.pos.y,v.pos.z)
		rendered_vert.setRenderModeThickness(5.0)
		self.render_nodes['vert_'+str(v.ID)] = rendered_vert
Ejemplo n.º 13
0
 def draw_rain_mesh(self):
     _format = GeomVertexFormat.get_v3cp()
     self.rain_vdata = GeomVertexData('rain', _format, Geom.UHDynamic)
     self.rain_vdata.setNumRows(self.n_points**2)
     vertex = GeomVertexWriter(self.rain_vdata, 'vertex')
     color = GeomVertexWriter(self.rain_vdata, 'color')
     for j in range(self.n_points):
         for i in range(self.n_points):
             # Rain Vertices
             vertex.addData3f(self.x[j][i], self.y[j][i], self.n_points)
             # Rain Colors
             color.addData4f(0.3, 0.3, 1, 0)
     # Rain Primitive
     prim = GeomPoints(Geom.UHDynamic)
     for j in range(self.n_points):
         for i in range(self.n_points):
             prim.add_vertices(j * (self.n_points) + i,
                               j * (self.n_points) + i,
                               j * (self.n_points) + i)
     geom = Geom(self.rain_vdata)
     prim.closePrimitive()
     geom.addPrimitive(prim)
     node = GeomNode('gnode')
     node.addGeom(geom)
     rain_nodePath = render.attachNewNode(node)
     rain_nodePath.setTransparency(TransparencyAttrib.MAlpha)
     rain_nodePath.setAntialias(AntialiasAttrib.MAuto)
     rain_nodePath.setRenderModeThickness(2)
     rain_nodePath.setPos(-50, -50, 0)
Ejemplo n.º 14
0
def makeSprite(name, texture, scale, add = False):
    from panda3d.core import (GeomVertexFormat, GeomVertexData, GeomEnums,
                              InternalName, GeomVertexWriter, GeomPoints,
                              Geom, GeomNode, NodePath, TextureStage,
                              TexGenAttrib, BoundingSphere)
    format = GeomVertexFormat.getV3()
    data = GeomVertexData(name + "_data", format, GeomEnums.UHStatic)
    writer = GeomVertexWriter(data, InternalName.getVertex())
    writer.addData3f((0, 0, 0))
    primitive = GeomPoints(GeomEnums.UHStatic)
    primitive.addVertex(0)
    primitive.closePrimitive()
    geom = Geom(data)
    geom.addPrimitive(primitive)
    geomNode = GeomNode(name)
    geomNode.addGeom(geom)
    np = NodePath(geomNode)
    np.setLightOff(1)
    np.setMaterialOff(1)
    np.setRenderModePerspective(True)
    ts = TextureStage('sprite')
    if add:
        ts.setMode(TextureStage.MAdd)
    np.setTexture(ts, texture)
    np.setTexGen(ts, TexGenAttrib.MPointSprite)

    np.setDepthWrite(False)
    np.setDepthOffset(1)
    np.setTransparency(True)
    np.node().setBounds(BoundingSphere((0, 0, 0), 1))
    np.node().setFinal(True)
    np.flattenStrong()
    np.setScale(scale)

    return np
Ejemplo n.º 15
0
def create_GeomNode_Single_Point(color_vec4=Vec4(1., 1., 1., 1.)):
    # ---- step 1: create point at (0,0,0) and close the primitive

    format = GeomVertexFormat.getV3c4()
    vdata = GeomVertexData("colored_point", format, Geom.UHStatic)
    vdata.setNumRows(4)

    # add color to each vertex
    colorWriter = GeomVertexWriter(vdata, "color")

    # add a vertex position to each vertex
    vertexPosWriter = GeomVertexWriter(vdata, "vertex")

    # just one origin point vertex, it gets transformed later
    # to it's intended position
    vertexPosWriter.addData3f(0., 0., 0.)
    colorWriter.addData4f(color_vec4)

    # build the primitive
    pointsprimitive = GeomPoints(Geom.UHStatic)
    pointsprimitive.addVertex(0)
    pointsprimitive.closePrimitive()  # this resets all the data contained in the vertexPosWriter and colorWriter

    # ----- step 3: make a GeomNode out of the Geom (to which the Primitives have been added)

    # make a Geom object to hold the primitives
    geom = Geom(vdata)
    geom.addPrimitive(pointsprimitive)

    geom_node = GeomNode("colored_point_node")
    geom_node.addGeom(geom)

    return geom_node
Ejemplo n.º 16
0
def makePoints(n=1000):
    """ make a cloud of points that are a single node VS branching and making subnodes to control display """

    #points = np.random.uniform(-10,10,(n,4))
    #points = np.random.randn(n,3)
    points = np.cumsum(np.random.randint(-1, 2, (n, 3)),
                       axis=0)  #classic random walk
    #colors = np.random.rand(n,4)
    clr4 = np.random.rand(1, 4)

    #points = [(0,0,0)]

    fmt = GeomVertexFormat.getV3c4()  #3 component vertex, w/ 4 comp color
    vertexData = GeomVertexData('points', fmt, Geom.UHStatic)

    verts = GeomVertexWriter(vertexData, 'vertex')
    color = GeomVertexWriter(vertexData, 'color')

    #for point,clr4 in zip(points,colors):
    for point in points:
        verts.addData3f(*point)
        #color.addData4f(*point)
        color.addData4f(*clr4[0])
        #color.addData4f(.1,.1,.1,1)

    #pointCloud = GeomLinestrips(Geom.UHStatic) #this is f*****g cool!
    #pointCloud = GeomTristrips(Geom.UHStatic) #this is f*****g cool!
    pointCloud = GeomPoints(Geom.UHStatic)
    pointCloud.addConsecutiveVertices(0, n)  #warning may error since n-1?
    pointCloud.closePrimitive()

    cloud = Geom(vertexData)
    cloud.addPrimitive(pointCloud)
    return cloud
Ejemplo n.º 17
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()
        """
Ejemplo n.º 18
0
    def __init__(self):
        ShowBase.__init__(self)

        PanditorDisableMouseFunc()
        camera.setPos(0.0, 0.0, 50.0)
        camera.lookAt(0.0)
        PanditorEnableMouseFunc()

        # 1) create GeomVertexData
        frmt = GeomVertexFormat.getV3n3cp()
        vdata = GeomVertexData('triangle', frmt, Geom.UHDynamic)

        # 2) create Writers/Rewriters (must all be created before any readers and readers are one-pass-temporary)
        vertex = GeomVertexRewriter(vdata, 'vertex')
        normal = GeomVertexRewriter(vdata, 'normal')
        color = GeomVertexRewriter(vdata, 'color')

        zUp = Vec3(0, 0, 1)
        wt = Vec4(1.0, 1.0, 1.0, 1.0)
        gr = Vec4(0.5, 0.5, 0.5, 1.0)

        # 3) write each column on the vertex data object (for speed, have a different writer for each column)
        def addPoint(x, y, z):
            vertex.addData3f(x, y, z)
            normal.addData3f(zUp)
            color.addData4f(wt)

        addPoint(0.0, 0.0, 0.0)
        addPoint(5.0, 0.0, 0.0)
        addPoint(0.0, 5.0, 0.0)
        addPoint(5.0, 5.0, 0.0)

        # 4) create a primitive and add the vertices via index (not truely associated with the actual vertex table, yet)
        tris = GeomTriangles(Geom.UHDynamic)
        tris.addVertices(0, 1, 2)
        tris.closePrimitive(
        )  # exception thrown if verts added != 3, other types inform Panda how many verts/primitive
        tris.addVertices(2, 1, 3)
        print "vdataPoints", vdata.getArrays()[0]
        # 5.1) (adding to scene) create a Geom and add primitives of like base-type i.e. triangles and triangle strips
        geom = Geom(vdata)
        geom.addPrimitive(tris)
        # 5.2) create a GeomNode to hold the Geom(s) and add the Geom(s)
        gn = GeomNode('gnode')
        gn.addGeom(geom)
        # 5.3) attache the node to the scene
        gnNodePath = render.attachNewNode(gn)

        geomPts = Geom(vdata)
        pts = GeomPoints(Geom.UHStatic)
        pts.addVertices(0, 1, 2)
        pts.closePrimitive()
        geomPts.addPrimitive(pts)
        pointsNode = GeomNode('points_node')
        pointsNode.addGeom(geomPts)
        pointsNP = render.attachNewNode(pointsNode)
        pointsNP.setZ(0.5)

        render.ls()
Ejemplo n.º 19
0
    def __init__(self, data, timescale, scale, record, dark_matter,
                 no_ordinary_matter):
        self.data = data
        self.scale = scale
        self.timescale = timescale
        self.dark_matter = dark_matter
        self.no_ordinary_matter = no_ordinary_matter

        self.n_particles = self.data.shape[1]
        ShowBase.__init__(self)
        vdata = GeomVertexData('galaxies', GeomVertexFormat.get_v3c4(),
                               Geom.UHStatic)
        vdata.setNumRows(self.n_particles)
        self.vertex = GeomVertexWriter(vdata, 'vertex')
        color = GeomVertexWriter(vdata, 'color')
        for i in range(self.n_particles):
            if (self.data[0][i].dark_matter and
                    not self.dark_matter) or (not self.data[0][i].dark_matter
                                              and self.no_ordinary_matter):
                continue
            pos = self.data[0][i].pos / self.scale
            self.vertex.addData3(*pos)
            color.addData4(1, 1, 1, 1)
        prim = GeomPoints(Geom.UHStatic)
        prim.add_consecutive_vertices(0, self.n_particles - 1)
        geom = Geom(vdata)
        geom.addPrimitive(prim)
        node = GeomNode('gnode')
        node.addGeom(geom)
        nodePath = self.render.attach_new_node(node)
        nodePath.setRenderModeThickness(2)
        self.disableMouse()
        self.useTrackball()
        self.trackball.node().set_pos(0, 100, 0)
        self.trackball.node().set_hpr(90, 0, 90)
        self.setBackgroundColor(0, 0, 0)
        self.taskMgr.add(self.update_task, "VertexUpdateTask")
        self.record(record)
Ejemplo n.º 20
0
def makePoint(point=(0, 0, 0)):
    clr4 = [1, 1, 1, 1]
    fmt = GeomVertexFormat.getV3c4()  #3 component vertex, w/ 4 comp color
    vertexData = GeomVertexData('points', fmt, Geom.UHStatic)
    verts = GeomVertexWriter(vertexData, 'vertex')
    verts.addData3f(*point)
    color = GeomVertexWriter(vertexData, 'color')
    color.addData4f(*clr4)
    pointCloud = GeomPoints(Geom.UHStatic)
    pointCloud.addVertex(0)
    pointCloud.closePrimitive()
    cloud = Geom(vertexData)
    cloud.addPrimitive(pointCloud)
    cloudNode = GeomNode('point')
    cloudNode.addGeom(cloud)
    return cloudNode
Ejemplo n.º 21
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
Ejemplo n.º 22
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
Ejemplo n.º 23
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
Ejemplo n.º 24
0
 def draw_vert(self, v, v_color):
     format = GeomVertexFormat.getV3cp()
     vdata = GeomVertexData('vert', format, Geom.UHDynamic)
     vertex = GeomVertexWriter(vdata, 'vertex')
     color = GeomVertexWriter(vdata, 'color')
     vertex.addData3f(0.0, 0.0, 0.0)
     color.addData4f(v_color)
     mesh = Geom(vdata)
     point = GeomPoints(Geom.UHDynamic)
     point.addVertex(0)
     point.closePrimitive()
     mesh.addPrimitive(point)
     vert_node = GeomNode(self.mesh.name + '_vert_' + str(v.ID))
     vert_node.addGeom(mesh)
     vert_node.setTag('ID', str(v.ID))
     rendered_vert = self.render_root.attachNewNode(vert_node)
     rendered_vert.setPos(v.pos.x, v.pos.y, v.pos.z)
     rendered_vert.setRenderModeThickness(5.0)
     self.render_nodes['vert_' + str(v.ID)] = rendered_vert
Ejemplo n.º 25
0
def make_cloud_node(pts, col=LColorf(1.0, 0.0, 0.0, 1.0)):
    ptCloudData = GeomVertexData("PointCloudData", GeomVertexFormat.getV3c4(),
                                 GeomEnums.UH_static)
    vertexWriter = GeomVertexWriter(ptCloudData, Thread.getCurrentThread())
    vertexWriter.setColumn("vertex")
    colorWriter = GeomVertexWriter(ptCloudData, Thread.getCurrentThread())
    colorWriter.setColumn("color")

    for (x, y, z) in pts:
        vertexWriter.addData3(x, y, z)
        colorWriter.addData4(col)

    geomPts = GeomPoints(GeomEnums.UH_static)
    geomPts.addConsecutiveVertices(0, len(pts))
    geomPts.closePrimitive()

    geom = Geom(ptCloudData)
    geom.addPrimitive(geomPts)

    node = GeomNode("PointCloudNode")
    node.addGeom(geom, RenderState.makeEmpty())
    return node
Ejemplo n.º 26
0
class UI(ShowBase):

    def __init__(self):
        ShowBase.__init__(self)
        vertexFormat = GeomVertexFormat.getV3c4()
        self.vertexData = GeomVertexData("data", vertexFormat, Geom.UHDynamic)
        geometry = Geom(self.vertexData)
        self.primitive = GeomPoints(Geom.UHDynamic)
        geometry.addPrimitive(self.primitive)
        node = GeomNode("node")
        node.addGeom(geometry)
        self.nodePath = NodePath(node)
        self.nodePath.setPos(0, 0, 0)
        self.nodePath.setRenderModeThickness(10.0)
        self.camera.setPos(0.0, -10.0, 0.0)
        self.disableMouse()
        self.nodePath.reparentTo(self.render)

    def add_task(self, task):
        def task_wrapper(taskObject):
            task()
            return Task.cont
        self.taskMgr.add(task_wrapper)

    def set_points(self, position, color):
        assert len(position) == len(color)
        self.vertexData.setNumRows(len(position))
        self.primitive.clearVertices()
        for i in range(len(position)):
            self.primitive.addVertex(i)
        self.primitive.closePrimitive()
        positionWriter = GeomVertexWriter(self.vertexData, "vertex")
        colorWriter = GeomVertexWriter(self.vertexData, "color")
        for p, c in zip(position, color):
            positionWriter.addData3f(p[0], p[1], p[2])
            colorWriter.addData4f(c[0], c[1], c[2], c[3])
Ejemplo n.º 27
0
    def __make_points(vertices, colours=None, geom: Geom = None) -> Geom:
        """
        This function is largely inspired by panda3d_viewer's implementation.

        Copyright (c) 2020, Igor Kalevatykh

        Permission is hereby granted, free of charge, to any person obtaining a copy
        of this software and associated documentation files (the "Software"), to deal
        in the Software without restriction, including without limitation the rights
        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        copies of the Software, and to permit persons to whom the Software is
        furnished to do so, subject to the following conditions:

        The above copyright notice and this permission notice shall be included in all
        copies or substantial portions of the Software.

        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
        EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
        MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
        IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
        DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
        OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
        OR OTHER DEALINGS IN THE SOFTWARE.
        """

        if not isinstance(vertices, np.ndarray):
            vertices = np.asarray(vertices, dtype=np.float32)

        if colours is not None:
            if not isinstance(colours, np.ndarray):
                colours = np.asarray(colours)
            if colours.dtype != np.uint8:
                colours = np.uint8(colours * 255)
            vertices = np.column_stack((vertices.view(dtype=np.uint32).reshape(-1, 3),
                                        colours.view(dtype=np.uint32)))

        data = vertices.tostring()

        if geom is None:
            if vertices.strides[0] == 12:
                vformat = GeomVertexFormat.get_v3()
            elif vertices.strides[0] == 16:
                vformat = GeomVertexFormat.get_v3c4()
            else:
                raise ValueError('Incompatible point clout format: {},{}'.format(vertices.dtype, vertices.shape))

            vdata = GeomVertexData('vdata', vformat, Geom.UHDynamic)
            vdata.unclean_set_num_rows(len(vertices))
            vdata.modify_array_handle(0).set_subdata(0, len(data), data)

            prim = GeomPoints(Geom.UHDynamic)
            prim.clear_vertices()
            prim.add_consecutive_vertices(0, len(vertices))
            prim.close_primitive()

            geom = Geom(vdata)
            geom.add_primitive(prim)
        else:
            vdata = geom.modify_vertex_data()
            vdata.unclean_set_num_rows(len(vertices))
            vdata.modify_array_handle(0).set_subdata(0, len(data), data)

            prim = geom.modify_primitive(0)
            prim.clear_vertices()
            prim.add_consecutive_vertices(0, len(vertices))
            prim.close_primitive()

        return geom
Ejemplo n.º 28
0
def draw_shape(angles, width, radius):
    res = 10
    if radius == 0:
        point = GeomNode('gnode')
        vdata = GeomVertexData('occ', GeomVertexFormat.getV3(), Geom.UHStatic)
        vdata.setNumRows(1)
        vertex = GeomVertexWriter(vdata, 'vertex')
        vertex.addData3f(0, 0, 0)

        geom = Geom(vdata)
        g = GeomPoints(Geom.UHStatic)
        g.addVertex(0)
        geom.addPrimitive(g)
        point.addGeom(geom)
        return point, point
    #first, sort angles in ascending order
    #if negative is given, translate to range of 2pi
    for i in range(len(angles)):
        if angles[i] < 0: angles[i] = 360 + angles[i]
    angles.sort()
    angles = [math.radians(a) for a in angles]
    angles.append(angles[0])  #read first angle to account for wrapping around

    #function = 'w/sin(theta)'

    vdata = GeomVertexData('occ', GeomVertexFormat.getV3(), Geom.UHStatic)
    vdata.setNumRows(1)
    vertex = GeomVertexWriter(vdata, 'vertex')

    numverts = [3] * (len(angles) - 1
                      )  #center, and two points on function lines

    for i in range(len(angles) - 1):
        #find center point
        #L = [None,None]
        #sign = [-1,1]
        #for p in range(2):
        #    theta1 = angles[i+p] - sign[p]*math.pi/2
        #    theta2 = angles[i+p] + sign[p]*math.pi/4
        #    x1 = width*math.cos(theta1)
        #    y1 = width*math.sin(theta1)
        #    r = math.sqrt(2*width**2)
        #    x2 = r*math.cos(theta2)
        #    y2 = r*math.sin(theta2)
        #    L[p] = line([x1,y1], [x2,y2])
        #R = intersection(L[0],L[1])

        #if R is False:
        #    R = [x1,y1] #if parallel, shift both lines down by y_width
        #vertex.addData3f(R[0],R[1],1)
        difang = (angles[i + 1] - angles[i]) / 2
        l = width / math.sin(difang)
        avgang = (angles[i] + angles[i + 1]) / 2
        x0 = l * math.cos(avgang)
        y0 = l * math.sin(avgang)
        vertex.addData3f(x0, y0, 1)

        newang1 = angles[i] + (math.pi / 2 - math.acos(width / radius))
        x = radius * math.cos(newang1)
        y = radius * math.sin(newang1)
        vertex.addData3f(x, y, 1)
        newang2 = angles[i + 1] - (math.pi / 2 - math.acos(width / radius))
        for angle in arc(newang1, newang2, res):
            vertex.addData3f(radius * math.cos(math.radians(angle)),
                             radius * math.sin(math.radians(angle)), 1)
            numverts[i] = numverts[i] + 1
        x = radius * math.cos(newang2)
        y = radius * math.sin(newang2)
        vertex.addData3f(x, y, 1)

    #copy all data to the bottom, moving it down to z = -1
    vertread = GeomVertexReader(vdata, 'vertex')
    while not vertread.isAtEnd():
        v = vertread.getData3f()
        vertex.addData3f(v[0], v[1], -1)

    #draw
    geom = Geom(vdata)
    #draw top
    for i in range(len(angles) - 1):
        for j in range(numverts[i] - 2):
            ind = sum(numverts[0:i]) + j
            g = GeomTriangles(Geom.UHStatic)
            g.add_vertices(ind - j, ind + 1, ind + 2)
            geom.addPrimitive(g)

    #draw bottom
    for i in range(len(angles) - 1):
        for j in range(numverts[i] - 2):
            ind = sum(numverts) + sum(numverts[0:i]) + j
            g = GeomTriangles(Geom.UHStatic)
            g.add_vertices(ind - j, ind + 2, ind + 1)
            geom.addPrimitive(g)

    #draw edges
    for i in range(len(angles) - 1):
        for j in range(numverts[i] - 1):
            ind = sum(numverts[0:i]) + j
            g = GeomTriangles(Geom.UHStatic)
            g.add_vertices(ind, ind + sum(numverts), ind + 1)
            g.add_vertices(ind + sum(numverts), ind + 1 + sum(numverts),
                           ind + 1)
            geom.addPrimitive(g)
        g = GeomTriangles(Geom.UHStatic)
        ind = sum(numverts[0:i])
        indx = sum(numverts[0:i + 1])
        g.add_vertices(indx - 1, indx + sum(numverts) - 1, ind)
        g.add_vertices(indx + sum(numverts) - 1, sum(numverts) + ind, ind)
        geom.addPrimitive(g)

    #outline object
    lines = Geom(vdata)
    l = GeomLines(Geom.UHStatic)
    for i in range(len(angles) - 1):
        for j in range(numverts[i] - 1):
            ind = sum(numverts[0:i]) + j
            l.add_vertices(ind, ind + 1)
            l.add_vertices(sum(numverts) + ind, sum(numverts) + ind + 1)
        ind = sum(numverts[0:i])
        indx = sum(numverts[0:i + 1])
        l.add_vertices(ind, indx - 1)
        l.add_vertices(sum(numverts) + ind, sum(numverts) + indx - 1)
        l.add_vertices(ind + 1, sum(numverts) + ind + 1)
        l.add_vertices(indx - 1, sum(numverts) + indx - 1)
        lines.addPrimitive(l)

    node = GeomNode('gnode')
    node.addGeom(geom)
    nodeL = GeomNode('gnode')
    nodeL.addGeom(lines)
    return node, nodeL
Ejemplo n.º 29
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(
Ejemplo n.º 30
0
alight.setColor(Vec4(0.2, 0.2, 0.2, 1))
dlnp.setHpr(0, -60, 0)
#altRender.setLight(dlnp)
#altRender.setLight(alnp)

# vertex writer
vdata = GeomVertexData('points', GeomVertexFormat.getV3(), Geom.UHDynamic)
vwriter = GeomVertexWriter(vdata, 'vertex')

# 100 randomly generated vertex coordinates
for i in range(100):
    vwriter.addData3f(uniform(-100, 100), uniform(-100, 100),
                      uniform(-100, 100))

# create geom
points = GeomPoints(Geom.UHDynamic)
points.addNextVertices(100)
points.closePrimitive()
geo = Geom(vdata)
geo.addPrimitive(points)
gnode = GeomNode('points')
gnode.addGeom(geo)
np = render.attachNewNode(gnode)

# point sprite effect
np.setTransparency(TransparencyAttrib.MDual)
np.setTexGen(TextureStage.getDefault(), TexGenAttrib.MPointSprite)
np.setTexture(altBuffer.getTexture())
np.setRenderModePerspective(True)
np.setRenderModeThickness(8)
Ejemplo n.º 31
0
    def generate(
            self
    ):  # call this after setting some of the variables to update it
        if hasattr(self, 'geomNode'):
            self.geomNode.removeAllGeoms()

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

        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}
            )
        ''')
Ejemplo n.º 32
0
def make_points(vertices, colors=None, texture_coords=None, geom=None):
    """Make or update existing points set geometry.

    Arguments:
        root_path {str} -- path to the group's root node
        name {str} -- node name within a group
        vertices {list} -- point coordinates (and other data in a point cloud format)

    Keyword Arguments:
        colors {list} -- colors (default: {None})
        texture_coords {list} -- texture coordinates (default: {None})
        geom {Geom} -- geometry to update (default: {None})

    Returns:
        Geom -- p3d geometry
    """
    if not isinstance(vertices, np.ndarray):
        vertices = np.asarray(vertices, dtype=np.float32)

    if colors is not None:
        if not isinstance(colors, np.ndarray):
            colors = np.asarray(colors)
        if colors.dtype != np.uint8:
            colors = np.uint8(colors * 255)
        vertices = np.column_stack((
            vertices.view(dtype=np.uint32).reshape(-1, 3),
            colors.view(dtype=np.uint32)))

    if texture_coords is not None:
        if not isinstance(texture_coords, np.ndarray):
            texture_coords = np.asarray(texture_coords)
        vertices = np.column_stack((
            vertices.view(dtype=np.uint32).reshape(-1, 3),
            texture_coords.view(dtype=np.uint32).reshape(-1, 2)))

    data = vertices.tostring()

    if geom is None:
        if vertices.strides[0] == 12:
            vformat = GeomVertexFormat.get_v3()
        elif vertices.strides[0] == 16:
            vformat = GeomVertexFormat.get_v3c4()
        elif vertices.strides[0] == 20:
            vformat = GeomVertexFormat.get_v3t2()
        else:
            raise ViewerError('Incompatible point clout format: {},{}'.format(
                vertices.dtype, vertices.shape))

        vdata = GeomVertexData('vdata', vformat, Geom.UHDynamic)
        vdata.unclean_set_num_rows(len(vertices))
        vdata.modify_array_handle(0).set_subdata(0, len(data), data)

        prim = GeomPoints(Geom.UHDynamic)
        prim.clear_vertices()
        prim.add_consecutive_vertices(0, len(vertices))
        prim.close_primitive()

        geom = Geom(vdata)
        geom.add_primitive(prim)
    else:
        vdata = geom.modify_vertex_data()
        vdata.unclean_set_num_rows(len(vertices))
        vdata.modify_array_handle(0).set_subdata(0, len(data), data)

        prim = geom.modify_primitive(0)
        prim.clear_vertices()
        prim.add_consecutive_vertices(0, len(vertices))
        prim.close_primitive()

    return geom