Exemple #1
0
def get_source_leaf_and_max_height(g,
                                   position='center',
                                   relative_height=2. / 3):
    tesselator = pgl.Tesselator()
    bbc = pgl.BBoxComputer(tesselator)
    leaves = get_leaves(g, label='LeafElement')
    centroids = g.property('centroid')
    geometries = g.property('geometry')
    targets = list(leaf for leaf in leaves if leaf in geometries.iterkeys())
    for vid in targets:
        if is_iterable(geometries[vid]):
            bbc.process(pgl.Scene(geometries[vid]))
        else:
            bbc.process(pgl.Scene([pgl.Shape(geometries[vid])]))
        center = bbc.result.getCenter()
        centroids[vid] = center
    zmax = max(centroids.items(), key=lambda x: x[1][2])[1][2]
    distances = {
        vid: pgl.norm(centroids[vid] - (0, 0, relative_height * zmax))
        for vid in centroids
    }
    if position == 'center':
        return min(distances.items(), key=lambda x: x[1])[0], zmax
    elif position == 'border':
        return max(distances.items(), key=lambda x: x[1])[0], zmax
Exemple #2
0
 def centroid(vid):
     if is_iterable(geometries[vid]):
         bbc.process(pgl.Scene(geometries[vid]))
     else:
         bbc.process(pgl.Scene([pgl.Shape(geometries[vid])]))
     center = bbc.result.getCenter()
     centroids[vid] = center
Exemple #3
0
    def bbox_distance(g1, g2):

        bbc.process(pgl.Scene([g1]))
        bbox1 = bbc.result
        bbc.process(pgl.Scene([g2]))
        bbox2 = bbc.result

        return bbox1.distance(bbox2)
Exemple #4
0
    def bbox_distance(g1, g2):

        bbc.process(pgl.Scene([g1]))
        bbox1 = bbc.result
        bbc.process(pgl.Scene([g2]))
        bbox2 = bbc.result

        # TODO bbox.lowerLeftCorner, bbox.upperRightCorner
        return bbox1.distance(bbox2)
Exemple #5
0
 def get_leaf_height(self, leaf_geom):
     from openalea.plantgl import all as pgl
     tesselator = pgl.Tesselator()
     bbc = pgl.BBoxComputer(tesselator)
     if self.is_iterable(leaf_geom):
         bbc.process(pgl.Scene(leaf_geom))
     else:
         bbc.process(pgl.Scene([pgl.Shape(leaf_geom)]))
     return bbc.result.getCenter()[2]
Exemple #6
0
def scenegraph(rootedgraph):
    # traverse the graph
    g = deepcopy(rootedgraph)
    g = getSMScale(g)
    scene = pgl.Scene()

    g.add_vertex_property('final_geometry')
    final_geometry = g.vertex_property("final_geometry")

    traverse2(g.root, g)
    scene.merge(pgl.Scene(final_geometry.values()))
    return scene
Exemple #7
0
def to_scene(obj):
    scene = pgl.Scene()
    if obj is None:
        pass
    elif isinstance(obj, pgl.Scene):
        scene = obj
    else:
        if isinstance(obj, list):
            scene = pgl.Scene(obj)
        else:
            scene = pgl.Scene([obj])
    return scene
Exemple #8
0
 def representation(self):
    mat = pgl.Material('mblue',(0,0,200),transparency=0.8)
    mat2 = pgl.Material('mred',(200,0,0),transparency=0.8)
    if not self.maxvalue: self.maxvalue = max(self.values)
    if self.maxvalue <= 0: return pgl.Scene()
    sc = pgl.Scene()
    for i, v in enumerate(self.values):
        size = v/(2*self.maxvalue)
        if size > 1e-2:
          sc += pgl.Shape(pgl.Translated(self.getVoxelCenterFromId(i),pgl.Box(self.getVoxelSize()*size)),mat,i)
        else:
          sc += pgl.Shape(pgl.Translated(self.getVoxelCenterFromId(i),pgl.Box(self.getVoxelSize()*0.1)),mat2,i)
    return sc
Exemple #9
0
def parse(cmds):
    import openalea.plantgl.all as pgl
 
    objmap = {'Black' : pgl.Color3.BLACK, 'White' : pgl.Color3.WHITE, 'Red' : pgl.Color3.RED, 'Green' : pgl.Color3.GREEN, 'Blue' : pgl.Color3.BLUE, 'Cyan' : pgl.Color3.CYAN, 'Magenta' : pgl.Color3(255,0,255), 'Yellow' : pgl.Color3.YELLOW }
    shapes = []
    
    currentid = 0
    while currentid < len(cmds):
        currentid, obj = parse_object(cmds, currentid, objmap)
        if type(obj) == pgl.Shape:
            shapes.append(obj)

    if len(shapes) > 0 : return pgl.Scene(shapes)
    else : return pgl.Scene([pgl.Shape(obj) for obj in objmap if isinstance(obj, pgl.Geometry)])
Exemple #10
0
    def build_scene_with_colors(self, colors):
        scene = pgl.Scene()
        n = len(colors)
        for i, (label, count) in enumerate(self.indexes):
            pid = plant_id(label)
            plant = self.plants[pid]
            if is_leaf(label):
                lid = leaf_id(label)
                geom = plant["leaves"][lid]
            elif is_stem(label):
                geom = plant["stems"]
            else:
                geom = self.soil["soil"]
            if count == 0:
                geom.colorList = []
                geom.colorPerVertex = False

            assert 3 * len(geom.colorList) == count
            if i >= n or type(colors[i]) == float:
                geom.colorList.append(pgl.Color4(10, 10, 10, 0))
            else:
                r, g, b = colors[i]
                geom.colorList.append(pgl.Color4(r, g, b, 0))

        for plant in list(self.plants.values()):
            leaves = plant["leaves"]
            stems = plant["stems"]
            for leaf in list(leaves.values()):
                scene += leaf
            if len(stems.pointList) > 0:
                scene += stems
        if "soil" in self.soil:
            scene += self.soil["soil"]

        self.scene = scene
Exemple #11
0
    def build_scene(self,
                    leaf_material=None,
                    stem_material=None,
                    soil_material=None):
        if not leaf_material:
            leaf_material = pgl.Material(pgl.Color3(0, 180, 0))

        if not stem_material:
            stem_material = pgl.Material(pgl.Color3(0, 130, 0))
        if not soil_material:
            soil_material = pgl.Material(pgl.Color3(170, 85, 0))

        scene = pgl.Scene()
        for id, plant in self.plants.items():
            leaves = plant["leaves"]
            stems = plant["stems"]
            for lid, leaf in leaves.items():
                shape = pgl.Shape(leaf, leaf_material)
                shape.name = str(lid)
                scene.add(shape)
            if len(stems.pointList) > 0:
                shape = pgl.Shape(stems, stem_material)
                shape.name = str(id)
                scene.add(shape)
        if "soil" in self.soil:
            shape = pgl.Shape(self.soil["soil"], soil_material)
            scene.add(shape)

        self.scene = scene
Exemple #12
0
def plot(g, prop_cmap='radius', cmap='jet', lognorm=False):
    """
    Exemple:

        >>> from openalea.plantgl.all import *
        >>> s = plot()
        >>> shapes = dict( (x.getId(), x.geometry) for x in s)
        >>> Viewer.display(s)
    """
    visitor = get_root_visitor()

    turtle = turt.PglTurtle()
    turtle.down(180)
    scene = turt.TurtleFrame(g, visitor=visitor, turtle=turtle, gc=False)

    # Compute color from radius
    color.colormap(g, prop_cmap, cmap=cmap, lognorm=lognorm)

    shapes = dict((sh.getId(), sh) for sh in scene)

    colors = g.property('color')
    for vid in colors:
        if vid in shapes:
            shapes[vid].appearance = pgl.Material(colors[vid])
    scene = pgl.Scene(shapes.values())
    return scene
Exemple #13
0
def toPglScene(ptList, mass=None, radius=0.5):
    """generate a box-based scene from a point list"""
    scene = pgl.Scene()
    x = y = z = 0
    if (mass == None):
        colors = [gradient(0)] * len(ptList)
    else:
        colors = []
        step = (max(mass) - min(mass)) / 7
        if (step == 0):
            step = 1
        for m in mass:
            colors.append(gradient(int((m - min(mass)) / step)))

    for i in range(len(ptList)):
        pt = ptList[i]
        try:
            x = pt[0] * 2 * radius
        except IndexError:
            x = 00.3
        try:
            y = pt[1] * 2 * radius
        except IndexError:
            y = 0
        try:
            z = pt[2] * 2 * radius
        except IndexError:
            z = 0
        #scene.add( disc( x,y,z ) )
        #scene.add( sphere( x, y, z , color=colors[ i ]) )
        scene.add(box(x, y, z, radius=radius, color=colors[i], id=i + 1))
    return scene
Exemple #14
0
def replicate_scene(scene, domain, replicate=None):
    """ replicate the scene around the domain
    """
    if replicate is None:
        newscene = scene
        newdomain = domain
    else:
        dx = abs(domain[0][0] - domain[1][0])
        dy = abs(domain[0][1] - domain[1][1])

        newscene = pgl.Scene()
        for tx in (-dx, 0, dx):
            for ty in (-dy, 0, dy):
                rep = scene.deepcopy()
                for sh in rep:
                    sh.geometry = pgl.Translated(tx, ty, 0, sh.geometry)
                newscene += rep
        newdomain = ((domain[0][0] - dx, domain[0][1] - dy),
                     (domain[1][0] + dx, domain[1][1] + dy))
        if replicate == 1:
            replicate = None
        else:
            replicate -= 1
        newscene, newdomain = replicate_scene(newscene, newdomain, replicate)
    return newscene, newdomain
Exemple #15
0
def plot(pf, length=1.e-4, has_radius=False, r_base=1., r_tip=0.25, visitor=None, prop_cmap=None):
    """
    Example:

        >>> from openalea.plantgl.all import *
        >>> s = plot()
        >>> shapes = dict( (x.getId(), x.geometry) for x in s)
        >>> Viewer.display(s)
    """
    g = pf.g
    turtle = turt.PglTurtle()
    turtle.down(180)
    scene = turt.TurtleFrame(g, visitor=visitor, turtle=turtle, gc=False)

    # Compute color from radius
    if prop_cmap:
        my_colormap(g,prop_cmap)

    shapes = dict( (sh.getId(),sh) for sh in scene)

    colors = g.property('color')
    for vid in colors:
        shapes[vid].appearance = pgl.Material(colors[vid])
    scene = pgl.Scene(list(shapes.values()))
    return scene
Exemple #16
0
  def toPglScene( self, geometry=None ):
    """
    Generate a PlantGL scene of the MST with the given geometry which size
    must be normalized ( < 1), default is a box
    """
    if self.dim < 4:
      scene = pgl.Scene()
      if geometry == None:
        geometry = pgl.Box(0.4)
      ( ptList, size ) = self.absolutePos()
      #x = y = z = 0
      for pt in ptList :
        try:
          x = pt[ 0 ]
        except IndexError:
          x = 0
        try:
          y = pt[ 1 ]
        except IndexError:
          y = 0
        try:
          z = pt[ 2 ]
        except IndexError:
          z = 0
        scene.add( pgl.Translated( (x, y, z), geometry ))
    else:
      print "Bad dimension"

    return scene
Exemple #17
0
def mesh2shapes(scene):
    """ Convert all the meshes containing colors into independent shapes.

    """
    if isinstance(scene, pgl.Scene):
        scene = scene
    else:
        # Case caribu scene
        scene = scene.scene

    new_scene = pgl.Scene()
    for shape in scene:
        g = shape.geometry
        if isinstance(g, pgl.TriangleSet) and len(g.colorList) > 0:
            # convert the mesh into shapes with different colors
            pts = g.pointList
            indx = g.indexList
            colors = g.colorList
            for i, ind in enumerate(indx):
                new_geom = pgl.TriangleSet([], [])
                new_geom.indexList.append(pgl.Index3(0, 1, 2))
                for k in ind:
                    new_geom.pointList.append(pts[k])
                _shape = pgl.Shape(new_geom,
                                   pgl.Material(pgl.Color3(colors[i])))
                new_scene.add(_shape)
        else:
            new_scene.add(shape)
    return new_scene,
Exemple #18
0
def view_kdtree(kdtree, bbox=[[-1., 1.], [-1., 1.], [-1., 1.]], radius=0.05):
    import numpy as np

    scene = pgl.Scene()

    sphere = pgl.Sphere(radius, slices=16, stacks=16)

    silver = pgl.Material(ambient=(49, 49, 49),
                          diffuse=3.,
                          specular=(129, 129, 129),
                          shininess=0.4)
    gold = pgl.Material(ambient=(63, 50, 18),
                        diffuse=3.,
                        specular=(160, 141, 93),
                        shininess=0.4)

    if isinstance(kdtree, KDNode):
        dim = kdtree.axis
        plane_bbox = [b for i, b in enumerate(bbox) if i != dim]
        plane_points = []
        plane_points += [
            np.insert([plane_bbox[0][0], plane_bbox[1][0]], dim,
                      kdtree.pivot[dim])
        ]
        plane_points += [
            np.insert([plane_bbox[0][0], plane_bbox[1][1]], dim,
                      kdtree.pivot[dim])
        ]
        plane_points += [
            np.insert([plane_bbox[0][1], plane_bbox[1][1]], dim,
                      kdtree.pivot[dim])
        ]
        plane_points += [
            np.insert([plane_bbox[0][1], plane_bbox[1][0]], dim,
                      kdtree.pivot[dim])
        ]

        left_bbox = np.copy(bbox).astype(float)
        right_bbox = np.copy(bbox).astype(float)
        left_bbox[dim, 1] = kdtree.pivot[dim]
        right_bbox[dim, 0] = kdtree.pivot[dim]

        scene += pgl.Shape(pgl.Translated(kdtree.pivot, sphere), gold)
        scene += view_kdtree(kdtree.left_child, bbox=left_bbox, radius=radius)
        scene += view_kdtree(kdtree.right_child,
                             bbox=right_bbox,
                             radius=radius)
        # scene += pgl.Shape(pgl.Polyline(plane_points+[plane_points[0]],width=2),pgl.Material(ambient=(0,0,0)))
        scene += pgl.Shape(
            pgl.Polyline(plane_points + [plane_points[0]], width=2),
            pgl.Material(ambient=tuple(list(np.insert([0, 0], dim, 255)))))
        scene += pgl.Shape(pgl.FaceSet(plane_points, [range(4)]),
                           pgl.Material(ambient=(0, 0, 0), transparency=0.6))

    else:
        assert (type(kdtree) == list) or (isinstance(kdtree, np.ndarray))
        for p in kdtree:
            scene += pgl.Shape(pgl.Translated(p, sphere), silver)

    return scene
Exemple #19
0
    def to_scene(self, conversion=1.0, name=None):
        r"""Create a PlantGL scene from a Ply dictionary.

        Args:
            conversion (float, optional): Conversion factor that should be
                applied to the vertices. Defaults to 1.0.
            name (str, optional): Name that should be given to the created
                PlantGL symbol. Defaults to None and is ignored.

        Returns:
        

        """
        import openalea.plantgl.all as pgl
        smb_class, args, kwargs = self.to_geom_args(conversion=conversion,
                                                    name=name)
        smb = smb_class(*args, **kwargs)
        if name is not None:
            smb.setName(name)
        if self.get('material', None) is not None:
            mat = pgl.Material(self['material'])
            shp = pgl.Shape(smb, mat)
        else:
            shp = pgl.Shape(smb)
        if name is not None:
            shp.setName(name)
        scn = pgl.Scene([shp])
        return scn
Exemple #20
0
    def plot(self, dfvox, dfmap, minval=None, maxval=None):
        output = pandas.merge(dfmap, dfvox)
        output = output.sort_values(
            'primitive_index'
        )  # sort is needed to ensure matching with triangulation indices
        par = output['PAR']
        if minval is None:
            minval = min(par)
        if maxval is None:
            maxval = max(par)
        cmap = ColorMap()

        scene = pgl.Scene()
        discretizer = pgl.Discretizer()

        for sh in self.scene:
            discretizer.process(sh)
            mesh = discretizer.result
            mesh.colorList = []
            mesh.colorPerVertex = False
            colors = map(lambda x: cmap(x, minval, maxval, 250., 20.),
                         par[output['shape_id'] == sh.id])
            for color in colors:
                r, g, b = color
                mesh.colorList.append(pgl.Color4(r, g, b, 0))

            scene.add(mesh)

        pgl.Viewer.display(scene)

        return scene
Exemple #21
0
def visualise_plants(g, vids=[], positions=[]):
    max_scale = g.max_scale()
    t = pgl.PglTurtle()
    if not vids:
        vids = g.component_roots_at_scale(g.root, scale=max_scale)
        x = -9
        y = -12
        dx = 2.
        dy = 4.
        positions = [(x+(count%9)*dx,y+(count/9)*dy,0) for count in range(len(vids))]
    else:
        vids = [cid for vid in vids for cid in g.component_roots_at_scale_iter(vid, scale=max_scale)]

    assert len(vids) == len(positions)
    n= len(vids)

    scenes = pgl.Scene()
    for i, vid in enumerate(vids):
        #position = (x+(count%9)*dx,y+(count/9)*dy,0)
        position = positions[i]
        t = pgl.PglTurtle()
        #t.move(position)
        scene = turtle.traverse_with_turtle(g, vid, visitor=strawberry_visitor, turtle=t, gc=False)

        ds = scene.todict()

        for shid in ds:
            for sh in ds[shid]:
                sh.geometry = pgl.Translated(position, sh.geometry)
                scenes.add(sh)
    return scenes
Exemple #22
0
def test_class_interface():
    scene = pgl.Scene()
    scene.add(pgl.Sphere(radius=0.1))
    pov = PovRay()
    pov.render(scene)
    reader = cv2.imread
    im = pov.get_image(reader)
    return im
Exemple #23
0
def oneScHullScene(scgroup,pointsbyshape):#aka hullscene
  """cree les cvxHull des groupes de scgroup"""
  sc = pgl.Scene()
  m = color(20,150,20, trans=True)
  for ids in scgroup:
    pts = ptUnion(pointsbyshape,ids)
    sc += pgl.Shape(pgl.fit('convexhull',pgl.Polyline(pts)),m)
  return sc
Exemple #24
0
def get_source_leaf(g, position_source=2./3):
    tesselator = pgl.Tesselator()
    bbc = pgl.BBoxComputer(tesselator)
    leaves = get_leaves(g, label='LeafElement')
    centroids = g.property('centroid')
    geometries = g.property('geometry')
    targets = list(leaf for leaf in leaves if leaf in geometries.iterkeys())
    for vid in targets:
        if isinstance(geometries[vid], collections.Iterable):
            bbc.process(pgl.Scene(geometries[vid]))
        else:
            bbc.process(pgl.Scene([pgl.Shape(geometries[vid])]))
        center = bbc.result.getCenter()
        centroids[vid] = center
    zmax = max(centroids.items(), key=lambda x:x[1][2])[1][2]
    distances = {vid:pgl.norm(centroids[vid]-(0,0,position_source*zmax)) for vid in centroids}
    return min(distances.items(), key=lambda x:x[1])[0]
def plotSkyTurtle():
  pgl.Viewer.start()
  sc = pgl.Scene()
  for i in range(len(elevations)):
    pos = pgl.Vector3(pgl.Vector3.Spherical(30,radians(azimuths[i]),radians(90-elevations[i])))
    sc += pgl.Shape(pgl.Translated(pos,pgl.Sphere(0.5)),pgl.Material(),i+1)
  pgl.Viewer.display(sc)
  return sc
Exemple #26
0
def viewMesures(file):
    treeList = treesFromFile(file)
    scene = pgl.Scene()
    for i in range(len(treeList)):
        t = treeList[i]
        mes = t.mesures(i)
        for sh in mes:
            scene.add(sh)
    pgl.Viewer.display(scene)
Exemple #27
0
def test_scene():
    ds = pgl.Sphere()
    t = pgl.Tapered(1., 1., ds)
    t2 = pgl.Translated(0., 0., 1., ds)
    sc = pgl.Scene([
        pgl.Shape(t, pgl.Material((255, 0, 0))),
        pgl.Shape(t2, pgl.Material((0, 255, 0)))
    ])
    jsonconversion(sc)
Exemple #28
0
def display_leaves(g):
    green = pgl.Material(pgl.Color3(0, 150, 0))
    scene = pgl.Scene()
    for vid, geom in g.property('geometry').items():
        sh = pgl.Shape(geom, green)
        sh.id = vid
        scene.add(sh)
    pgl.Viewer.display(scene)
    return scene
Exemple #29
0
    def scenegraph(self):
        # traverse the graph
        g = self._graph
        if self._scene:
            return self._scene
        else:
            self._scene = pgl.Scene()

        self.visited = set()

        self._graph.add_vertex_property('final_geometry')
        final_geometry = g.vertex_property("final_geometry")

        transfos = [pgl.Matrix4()]

        self.traverse2(g.root)
        self._scene.merge(pgl.Scene(final_geometry.values()))
        return self._scene
Exemple #30
0
def stand_box(domain):
    '''
    
    domain: 3D bounding box of the stand
    '''
    # list of points
    z_base = domain[0][2]
    z_top = domain[1][2]
    sides_points = [
        domain[0],  # coordinates of bottom right corner
        (domain[1][0], domain[0][1], z_base),
        (domain[1][0], domain[1][1],
         z_base),  # coordinates of bottom left corner
        (domain[0][0], domain[1][1], z_base),
        (domain[0][0], domain[0][1], z_top),  # coordinates of top right corner
        (domain[1][0], domain[0][1], z_top),
        (domain[1][0], domain[1][1], z_top),  # coordinates of top left corner
        (domain[0][0], domain[1][1], z_top)
    ]

    bottom_points = [
        domain[0],  # coordinates of bottom right corner
        (domain[1][0], domain[0][1], z_base),
        (domain[1][0], domain[1][1],
         z_base),  # coordinates of bottom left corner
        (domain[0][0], domain[1][1], z_base)
    ]

    # list of indices to make the quads of the sides from the points
    side_indices = [
        (0, 1, 5, 4),  #
        (1, 2, 6, 5),  # indices for 
        (2, 3, 7, 6),  # side faces
        (3, 0, 4, 7)
    ]  #

    # list of indices to make the quads of the bottom from the points
    bottom_indices = [(0, 1, 2, 3)]  # indices for bottom face

    # list of colors
    side_color = pgl.Color3(0, 0, 0)
    bottom_color = pgl.Color3(255, 255, 255)

    # construction of the geometry for the sides
    side_box = pgl.QuadSet(sides_points, side_indices)
    # construction of the geometry for the bottom
    bottom_box = pgl.QuadSet(bottom_points, bottom_indices)

    # create 2 shapes: 1 with side_color, 1 with bottom_color
    sides_shape = pgl.Shape(side_box, pgl.Material(side_color))
    bottom_shape = pgl.Shape(bottom_box, pgl.Material(bottom_color))

    scene = pgl.Scene()
    scene.add(sides_shape)
    scene.add(bottom_shape)

    return scene