Example #1
0
def generic_vtk_read(reader, fname, split=True, **kwds):

    r = reader
    r.initialize(fname)
    mesh = r.outputs[0]

    points = mesh.points.to_array()
    polys = mesh.polys
    faces = polys.to_array()

    faces = faces.reshape((polys.number_of_cells, polys.max_cell_size + 1))
    indexList = faces[:, 1:]

    pts = points.tolist()

    scene = sg.Scene()

    scalars = mesh.point_data.scalars
    if scalars and split:
        scalars = scalars.to_array()
        dim = 1 if len(scalars.shape) == 1 else scalars.shape[-1]
        set_scalars = []
        if dim == 1:
            set_scalars = np.unique(scalars)
        elif dim in (3, 4):
            set_scalars = set(tuple(x) for x in scalars.tolist())

        leaf_index = 100
        for s in set_scalars:
            idx = None
            if dim == 1:
                idx = (scalars[indexList] == s).any(axis=1).nonzero()[0]
            elif dim in (3, 4):
                vertex_has_color = (scalars == s).all(axis=1)
                idx = vertex_has_color[indexList].any(axis=1).nonzero()[0]

            if len(idx) == 0:  #or s <= 99:
                continue
            my_faces = indexList[idx].tolist()
            tset = sg.FaceSet(pointList=pts, indexList=my_faces)
            color = np.random.randint(0, 255, 3).tolist() if dim == 1 else s
            shape = sg.Shape(tset, sg.Material(color))
            if dim == 1:
                shape.id = int(s)
            else:
                if s == (153, 102, 51):
                    shape.id = 1
                elif s == (0, 255, 255):
                    shape.id = 2
                else:
                    shape.id = leaf_index
                    leaf_index += 1
                if dim == 3 and s == (150, 150, 150):
                    continue
            scene.add(shape)
    else:
        tset = sg.FaceSet(pointList=pts, indexList=indexList.tolist())
        scene += tset

    return scene
Example #2
0
    def read(self,fname):
        """ read an ascii point file """
        
        import warnings
        import struct

        stream = file(fname,"r")
        header = stream.readline()
        assert header.strip() == 'ply'
        def nextline():
            line = stream.readline()
            while line.startswith('comment'):
                line = stream.readline()
            return line.strip()

        format = nextline()
        fkeyword, fcoding, fversion = format.split()
        fversion = float(fversion)
        assert fcoding in ['binary_little_endian','binary_big_endian','ascii']
        if fcoding != 'ascii':
            reversebytes = (fcoding.split('_')[1] != sys.byteorder)


        nline = nextline()
        spec = []
        asciitypes = { 'float' : float ,'int' : int , 'uchar' :int, 'char' : int, 'short' : int, 'ushort' : int, 'double' : float }
        unpacktypes = { 'float' : 'f' ,'int' : 'i', 'uchar' : 'B', 'char' : 'b', 'short' : 'h', 'ushort' : 'H', 'double' : 'd' }
        while nline != 'end_header':
            if nline.startswith('element'):
                elementkwd, elementname, elementnb = nline.split()
                spec.append((elementname, int(elementnb), []))
            elif nline.startswith('property'):
                propval = nline.split()
                if len(propval) == 3:
                    propkwd, proptype, propname = propval
                    spec[-1][2].append((propname,proptype))
                    assert proptype in unpacktypes
                elif len(propval) == 5:
                    propkwd, proplist, propsizetype, proptype, propname = propval
                    spec[-1][2].append((propname,(propsizetype,proptype)))
            nline = nextline()
        colorprops = []
        knowncolortypes = ['red','green','blue','diffuse_red','diffuse_green','diffuse_blue','alpha']
        if spec[0][0] == 'vertex':
            for propname, proptype in spec[0][2]:
                if propname in knowncolortypes:
                    colorprops .append(propname)
        if len(colorprops) == 0 : colorprops = None
        else : 
            colorprops.sort(cmp=lambda c1,c2:cmp(knowncolortypes.index(c1),knowncolortypes.index(c2)))
            assert len(colorprops) in [3,4]

        points = []
        colors = []
        faces = []
        for element in spec:
            elemname, elementnb, elemspec = element
            for ielem in range(elementnb):
                ielement = {}
                if fcoding == 'ascii':
                    linevalues = nextline().split()
                    itv = 0
                    for elemprop in elemspec:
                        propname,proptype = elemprop
                        if type(proptype) == tuple:
                            propsizetype, proptype = proptype
                            tr = asciitypes[propsizetype]
                            nbpropv = tr(linevalues[itv]) ; itv += 1
                            value = []
                            tr = asciitypes[proptype]
                            for ival in range(nbpropv):
                                value.append(tr(linevalues[itv])); itv += 1
                        else:
                            tr = asciitypes[proptype]
                            value = tr(linevalues[itv]); itv += 1
                        ielement[propname] = value
                else:
                    def readnextval(stream, ptype):
                        flag = unpacktypes[ptype]
                        psize = struct.calcsize(flag)
                        val = stream.read(psize)
                        if reversebytes:
                            val = ''.join(list(reversed(val)))
                        return struct.unpack(flag, val)[0]

                    for elemprop in elemspec:
                        propname,proptype = elemprop
                        if type(proptype) == tuple:
                            propsizetype, proptype = proptype
                            nbpropv = readnextval(stream, propsizetype)
                            value = []
                            for ival in range(nbpropv):
                                value.append(readnextval(stream, proptype))
                        else:
                            value = readnextval(stream, proptype)
                        ielement[propname] = value
                if elemname == 'vertex':
                    points.append((ielement['x'],ielement['y'],ielement['z']))
                    if colorprops:
                        val = [ielement[cni] for cni in colorprops]
                        if colorprops[3] == 'alpha':
                            val[3] = 255 - val[3]
                        else:
                            val.append(0)
                        colors.append(tuple(val))
                elif elemname == 'face':
                    faces.append(ielement['vertex_indices'])
        if colors == []: colors = None
        if len(faces) == 0:
            return sg.Scene([sg.Shape(sg.PointSet(points, colors))])
        else:
            return sg.Scene([sg.Shape(sg.FaceSet(points, faces, colorList=colors))])

#codec = PlyCodec()
#sg.SceneFactory.get().registerCodec(codec)
Example #3
0
 def read(self, fname):
     t = gtsread(fname)
     return sg.Scene([sg.Shape(t)])
Example #4
0
def extract_mtg_visu(g, mtg_name, dict_results, directory, sim_id=0):

    #mtg_file = directory + '\\architectures\\' + mtg_name
    g = update_mtg(g, mtg_name, dict_results, directory, sim_id)
    scn = create_scene(g)
    matM = pglsc.Material((0, 255, 0))
    matF = pglsc.Material((213, 231, 81))
    matm = pglsc.Material((0, 0, 255))
    mcm = cm.get_cmap('jet')
    cmap = LinearSegmentedColormap.from_list('name', ['red', 'blue'])

    acc = 0
    for vid in g.vertices(scale=3):
        acc += 1
        n = g.node(vid)
        if n.label.startswith("M"):
            pos = (n.XX, n.YY, n.ZZ)
            if n.leaf_area != 0:
                sca = np.sqrt(n.leaf_area / 0.00353284)
                ll = 0.11
                lw = 0.027
                points = [(0, -lw, 0.03), (ll, -lw, 0.03), (ll, 0, 0),
                          (ll, lw, 0.03), (0, lw, 0.03), (0, 0, 0)]
                # list of indices
                indices = [(0, 1, 2, 5), (2, 3, 4, 5)]
                # creating the geometry
                leaf = QuadSet(points, indices)
                # creating a texture from a file
                tex = ImageTexture("./apple-leaf.png")
                # the coordinates of the texture that we may use
                texCoord = [(0, 0), (1, 0), (1, 0.5), (1, 1), (0, 1), (0, 0.5)]
                # how we associate the coordinates of the texture to
                # the vertices of the quad
                texCoordIndices = [(0, 1, 2, 5), (2, 3, 4, 5)]
                # adding those informations to the geometry
                leaf.texCoordList = texCoord
                leaf.texCoordIndexList = texCoordIndices
                from math import pi
                leaf = pglsc.Scaled(sca, sca, sca, leaf)
                angle = random.randrange(0, 70, 15)
                leaf = pglsc.AxisRotated((0, 1, 0), radians(angle), leaf)
                leaf = pglsc.AxisRotated((0, 0, 1), radians(acc * 140), leaf)
                import openalea.plantgl.all as pgl
                geom = pglsc.Translated(pos,
                                        leaf)  # unit conversion for plantgl
                scn.add(pglsc.Shape(geom, tex))
        elif n.label.startswith("F"):
            pos = (n.XX, n.YY, n.ZZ)
            geom = pglsc.Translated(
                pos, pglsc.Sphere(0.03))  # unit conversion for plantgl
            scn.add(pglsc.Shape(geom, matF))
        elif n.label.startswith("m"):
            pos = (n.XX, n.YY, n.ZZ)
            geom = pglsc.Translated(
                pos, pglsc.Sphere(0.010))  # unit conversion for plantgl
            #mat = pglsc.Material([int(v * 255) for v in mcm(int(n.inhibiting * 255))[:3]])
            mat = pglsc.Material(
                [int(v * 255) for v in cmap(int(n.final_proba * 255))[:3]])
            scn.add(pglsc.Shape(geom, mat))
    #return(scene)
    pglgui.Viewer.display(scn)