Exemplo n.º 1
0
def mesh_display(points,
                 triangles,
                 color=[190, 205, 205],
                 transparency=0,
                 add=False):
    import openalea.plantgl.all as pgl
    if color is None:
        color = [np.random.randint(0, 255) for i in xrange(3)]
    mat = pgl.Material(tuple(color), diffuse=0.25, transparency=transparency)
    s = pgl.Scene()
    s += pgl.Shape(pgl.FaceSet(points, triangles), mat)
    if add:
        pgl.Viewer.add(s)
    else:
        pgl.Viewer.display(s)
Exemplo n.º 2
0
def show_sources(sun, north=0, scene=None, distance=5, radius=0.1):
    sc = pgl.Scene()
    if scene is not None:
        sc.add(scene)
    elevation, azimuth, luminance = [numpy.array(x) for x in sun]
    az = -(azimuth + north)
    colors = jet_colors(luminance)
    pgl_colors = [pgl.Material(pgl.Color3(r, g, b)) for r, g, b in colors]
    sph = pgl.Sphere(radius)
    pos = cartesian(elevation, az, distance)
    pgl_pos = [pgl.Vector3(*p) for p in pos]
    for i, vect in enumerate(pgl_pos):
        shape = pgl.Translated(vect, sph)
        sc.add(pgl.Shape(shape, pgl_colors[i]))
    pgl.Viewer.display(sc)
    return sc
Exemplo n.º 3
0
            def fn_add(self):

                index = max(self.__lp.get_colors().keys()) + 1 if len(
                    self.__lp.get_colors().keys()) else 0

                self.__lp.set_color(
                    index, pgl.Material(ambient=(80, 80, 80), diffuse=1))
                editor = make_color_editor(self.__lp.get_color(index),
                                           index,
                                           no_name=True)
                editor.observe(
                    self.__on_editor_changed(self.__lp.get_color(index)))
                box.children = (*box.children, editor)

                if self.__auto_save:
                    self.__save()
                if self.__auto_apply:
                    self.on_lpy_context_change(self.__lp.dumps())
Exemplo n.º 4
0
    def _local2global(self, vid, matrix, color):
        g = self._graph
        geometry = g.vertex_property("geometry")
        colors = g.vertex_property("color")
        final_geometry = g.vertex_property("final_geometry")
        shape = geometry.get(vid)
        edge_type = g.edge_property("edge_type")

        if shape:
            if color:
                shape = pgl.Shape(transform4(matrix, shape), pgl.Material(color))
            else:
                shape = pgl.Shape(transform4(matrix, shape))
            shape.id = vid
            final_geometry[vid] = shape

        if color:
            colors[vid] = color
Exemplo n.º 5
0
def add_sky(scene, sky, distance=4, radius=0.05):
    sph = pgl.Sphere(radius)
    #blue = pgl.Material(pgl.Color3(0, 0, 150))
    elevation, azimuth, luminance = sky
    colors = jet_colors(luminance)
    pgl_colors = [pgl.Material(pgl.Color3(r, g, b)) for r, g, b in colors]
    # elevations46 = [9.23] * 10 + [10.81] * 5 + [26.57] * 5 + [31.08] * 10 + [
    #                 47.41] * 5 + [52.62] * 5 + [69.16] * 5 + [90]
    # azimuths46 = [12.23, 59.77, 84.23, 131.77, 156.23, 203.77, 228.23, 275.77,
    #               300.23, 347.77, 36, 108, 180, 252, 324, 0, 72, 144, 216, 288,
    #               23.27, 48.73, 95.27, 120.73, 167.27, 192.73, 239.27, 264.73,
    #               311.27, 336.73, 0, 72, 144, 216, 288, 36, 108, 180, 252, 324,
    #               0, 72, 144, 216, 288, 180]
    pos = cartesian(numpy.radians(elevation), numpy.radians(azimuth), distance)
    pgl_pos = [pgl.Vector3(*p) for p in pos]
    for i, vect in enumerate(pgl_pos):
        shape = pgl.Translated(vect, sph)
        scene.add(pgl.Shape(shape, pgl_colors[i]))
    return scene
Exemplo n.º 6
0
    def sweep(vid):
        _color = pgl.Material(color(vid))
        if diams and (vid in diams):
            diameters = diams[vid]
            if isinstance(diameters, (list, tuple)):
                _geom = pgl.Extrusion(
                    pgl.Polyline(map(pgl.Vector3, geoms[vid])), section,
                    pgl.Point2Array(zip(diams[vid], diams[vid])))
            else:
                _geom = pgl.Extrusion(
                    pgl.Polyline(map(pgl.Vector3, geoms[vid])), section,
                    pgl.Point2Array([(diameters, diameters)
                                     for i in range(len(geoms))]))

        else:
            _geom = pgl.Extrusion(pgl.Polyline(map(pgl.Vector3, geoms[vid])),
                                  section)

        return pgl.Shape(_geom, _color)
Exemplo n.º 7
0
def plotDirect(latitude,
               longitude,
               jourJul,
               startH,
               stopH,
               step=30,
               decalSun=1,
               decalGMT=0):
    sunPos = getDirectLight(latitude, longitude, jourJul, startH, stopH, step,
                            decalSun, decalGMT)
    sc = pgl.Scene()
    for i in range(len(sunPos)):
        #print sunPos[i][0],sunPos[i][1], sunPos[i][2]
        pos = pgl.Vector3(
            pgl.Vector3.Spherical(30, radians(sunPos[i][0]),
                                  radians(90 - sunPos[i][1])))
        sc += pgl.Shape(pgl.Translated(pos, pgl.Sphere(1)), pgl.Material(),
                        i + 1)
    pgl.Viewer.display(sc)
    return sc
Exemplo n.º 8
0
 def pgl_surface_mesh(self,
                      grid_size=128,
                      grid_resolution=1,
                      potential_value=0.5,
                      color=[190, 205, 205],
                      transparency=0):
     points, triangles = self.surface_mesh(grid_size, grid_resolution,
                                           potential_value)
     import openalea.plantgl.all as pgl
     if color is None:
         color = [np.random.randint(0, 255) for i in xrange(3)]
     mat = pgl.Material(tuple(color),
                        diffuse=0.25,
                        transparency=transparency)
     s = pgl.Scene()
     s += pgl.Shape(
         pgl.FaceSet(
             pgl.Point3Array(points),
             pgl.Index3Array([[int(i) for i in tr] for tr in triangles])),
         mat)
     return s
Exemplo n.º 9
0
def view_kdtree(kdtree, bbox=[[-1., 1.],[-1., 1.],[-1., 1.]], radius=0.05):
    import numpy as np
    import openalea.plantgl.all as pgl

    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)
	if dim == 0:
			scene += pgl.Shape(pgl.Polyline(plane_points+[plane_points[0]],width=2),pgl.Material(ambient=(255,0,0)))
	if dim == 1:
			scene += pgl.Shape(pgl.Polyline(plane_points+[plane_points[0]],width=2),pgl.Material(ambient=(0,255,0)))
	if dim == 2:
			scene += pgl.Shape(pgl.Polyline(plane_points+[plane_points[0]],width=2),pgl.Material(ambient=(0,0,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
Exemplo n.º 10
0
    def dart_display(self, radius=0.1, coef=0.8, add=False):
        import openalea.plantgl.all as pgl

        sphere = pgl.Sphere(radius, slices=16, stacks=16)
        coal = pgl.Material(ambient=(8, 10, 13),
                            diffuse=3.,
                            specular=(89, 89, 89),
                            shininess=0.3)
        purple = pgl.Material(ambient=(72, 28, 72),
                              diffuse=2.,
                              specular=(89, 89, 89),
                              shininess=0.3)
        green = pgl.Material(ambient=(0, 88, 9),
                             diffuse=2.,
                             specular=(89, 89, 89),
                             shininess=0.3)
        blue = pgl.Material(ambient=(9, 0, 88),
                            diffuse=2.,
                            specular=(89, 89, 89),
                            shininess=0.3)

        font = pgl.Font(size=10)

        s = pgl.Scene()

        dart_points = {}

        for dart in self.darts():
            dart_point = self.get_position(dart)
            dart_face_center = self.element_center(dart, 2)
            dart_edge_center = self.element_center(dart, 1)

            dart_face_point = dart_face_center + coef * (dart_point -
                                                         dart_face_center)
            dart_face_edge_center = dart_face_center + coef * (
                dart_edge_center - dart_face_center)

            dart_edge_point = dart_face_edge_center + coef * (
                dart_face_point - dart_face_edge_center)
            dart_middle_edge_point = dart_face_edge_center + 0.33 * (
                dart_edge_point - dart_face_edge_center)

            dart_points[dart] = [dart_edge_point, dart_middle_edge_point]

            s += pgl.Shape(pgl.Translated(dart_points[dart][0], sphere), coal)
            # s += pgl.Shape(pgl.Translated(np.mean(dart_points[dart],axis=0), pgl.Text(str(dart),fontstyle=font)), coal, id=dart)
            s += pgl.Shape(pgl.Polyline(dart_points[dart], width=2), coal)

        for dart in self.darts():
            alpha_0_points = []
            alpha_0_points += [dart_points[dart][1]]
            alpha_0_points += [dart_points[self.alpha(0, dart)][1]]
            s += pgl.Shape(pgl.Polyline(alpha_0_points, width=5), purple)

            alpha_1_points = []
            alpha_1_points += [
                0.66 * dart_points[dart][0] + 0.33 * dart_points[dart][1]
            ]
            alpha_1_points += [
                0.66 * dart_points[self.alpha(1, dart)][0] +
                0.33 * dart_points[self.alpha(1, dart)][1]
            ]
            s += pgl.Shape(pgl.Polyline(alpha_1_points, width=5), green)

            alpha_2_points = []
            alpha_2_points += [
                0.33 * dart_points[dart][0] + 0.66 * dart_points[dart][1]
            ]
            alpha_2_points += [
                0.33 * dart_points[self.alpha(2, dart)][0] +
                0.66 * dart_points[self.alpha(2, dart)][1]
            ]
            s += pgl.Shape(pgl.Polyline(alpha_2_points, width=5), blue)

        if add:
            pgl.Viewer.add(s)
        else:
            pgl.Viewer.display(s)
Exemplo n.º 11
0
#!/usr/bin/env python
"""Contains basic material definitions.

:version: pon mar 19 16:32:21 CET 2007

:author:  szymon stoma
"""
__docformat__ = "restructuredtext en"

import openalea.plantgl.all as pgl

white = pgl.Material(ambient=pgl.Color3(255, 255, 255),
                     name="White",
                     diffuse=1,
                     specular=pgl.Color3(40, 40, 40),
                     emission=pgl.Color3(0, 0, 0),
                     shininess=1,
                     transparency=0)

red = pgl.Material(ambient=pgl.Color3(255, 0, 0),
                   name="Red",
                   diffuse=1,
                   specular=pgl.Color3(40, 40, 40),
                   emission=pgl.Color3(0, 0, 0),
                   shininess=1,
                   transparency=0)
green = pgl.Material(ambient=pgl.Color3(0, 255, 0),
                     name="Green",
                     diffuse=1,
                     specular=pgl.Color3(40, 40, 40),
                     emission=pgl.Color3(0, 0, 0),
Exemplo n.º 12
0
import openalea.plantgl.all as pgl
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from nose import with_setup

import warnings
if not QCoreApplication.instance() is None:
    warnings.warn("A QApplication is already running")
else:
    app = QApplication([])
    pgl.Viewer.start()

red = pgl.Material(ambient=pgl.Color3(60, 10, 30), diffuse=3)
green = pgl.Material(ambient=pgl.Color3(30, 60, 10), diffuse=3)
blue = pgl.Material(ambient=pgl.Color3(10, 30, 60), diffuse=3)


def setup_func():
    sc = pgl.Scene()
    sc += pgl.Shape(pgl.Box(1, 1, 1), red, id=1)
    sc += pgl.Shape(pgl.Translated(4, 4, 6, pgl.Sphere(1)), blue, id=2)
    sc += pgl.Shape(pgl.Translated(2, 3, -3, pgl.Cone(1, 2)), green, id=3)
    sc += pgl.Shape(pgl.Translated(-8, 3, -2, pgl.Box(4, 2, 0.5)), blue, id=4)
    sc += pgl.Shape(pgl.Translated(
        -4, -2, 5, pgl.EulerRotated(3.14, 2.7, 0, pgl.Cone(2, 5))),
                    green,
                    id=5)
    sc += pgl.Shape(pgl.Translated(4, -3, -3, pgl.Sphere(2)), red, id=6)
    return sc

Exemplo n.º 13
0
def stand_material(r=20, g=100, b=60, spec_name="houppier_mat"):
    return stand_mat.setdefault(
        spec_name, pgl.Material(spec_name, pgl.Color3(r, g, b), 0.5))
Exemplo n.º 14
0
  - plantgl
  - random
  - math
  - pgl_utils

Module for generating stands of tree according to mesure.

"""

__docformat__ = "restructuredtext en"

import openalea.plantgl.all as pgl
from openalea.plantgl.ext.pgl_utils import sphere, arrow, color, createSwung
from openalea.core import *

houppier_mat = pgl.Material("houppier_mat", pgl.Color3(20, 100, 60), 0.5)
trunk_mat = pgl.Material("trunk_mat", pgl.Color3(50, 28, 6), 2)

stand_mat = {"houppier_mat": houppier_mat, "trunk_mat": trunk_mat}


def stand_material(r=20, g=100, b=60, spec_name="houppier_mat"):
    return stand_mat.setdefault(
        spec_name, pgl.Material(spec_name, pgl.Color3(r, g, b), 0.5))


from math import pi, cos, sin, radians


def makeScene(trees, midCr=0.5, wood=True, random=False):
    #treeList = treesFromFile(file)
Exemplo n.º 15
0
def visu(g,
         plot_prop=None,
         min_value=None,
         max_value=None,
         tt=1001,
         cmap='jet',
         fmt='%6.0f',
         elmnt_labels=None,
         elmnt_color_dict=None,
         def_elmnt_color_dict=False,
         use_mtg_color=False,
         snap_shot_path=None,
         scene=None,
         view_result=True):
    """
    Displays 3D moke-up using `plantgl` package.

    :Parameters:
    - **g**: an MTG object
    - **plot_prop**: string, an MTG property to plot
    - **min_value**: float, minimum property value for the color scale
    - **max_value**: float, maximum property value for the color scale
    - **cmap**: string, def('jet'), the colormap to use; only active when `plot_prop` is given or `use_mtg_color` is True
    - **fmt**: string, a legal text format, def('%6.0f'), the string format of matplotlib colorbar
    - **elmnt_labels**: a list of strings refering to the desired mtg elemnts to be displayed
    - **elmnt_colors_dict**: a dictionary of RGB color tuples for given mtg labels
    - **def_elmnt_color_dict**: logical, if `True`, uses :func:`default_color_dict()` to set a dictionary of RGB color tuples with `elmnt_labels` as keys
    - **use_mtg_color**: logical, if `True`, . If `False` uses the 'color' property from mtg nodes
    - **snap_shot_path**: string, if given, saves scene snapshot to the defined path and file name
    - **scene**: def None,if given, adds scene shapes to it
    """

    MyScene = pgl.Scene() if scene == None else scene

    if plot_prop is not None:
        prop = [g.node(vid).properties()[plot_prop] for vid in g.property(plot_prop) \
                if not g.node(vid).label.startswith('soil')]
        if min_value is None: min_value = min(prop)
        if max_value is None: max_value = max(prop)

        g, cb = pglcolor.colorbar(g,
                                  property_name=plot_prop,
                                  cmap=cmap,
                                  lognorm=False,
                                  N=6,
                                  fmt=fmt,
                                  min_value=min_value,
                                  max_value=max_value)
        #        cb.patch.set_facecolor((0.2, 0.2, 0.2, 1.0))
        g = pglcolor.colormap(g, property_name=plot_prop, cmap=cmap,\
                                lognorm=False,min_value=min_value,\
                                max_value=max_value)

        for vid in g.property(plot_prop).keys():
            try:
                n = g.node(vid)
                mesh = n.geometry
                Scene_shape = pgl.Shape(mesh,
                                        pgl.Material(pgl.Color3(n.color)))
                MyScene.add(Scene_shape)
            except:
                pass

    else:

        if elmnt_labels is None:
            elmnt_labels = default_element_list()

        if elmnt_color_dict is None:
            if def_elmnt_color_dict:
                def_color_dict = default_color_dict()
                elmnt_color_dict = {
                    key_: def_color_dict[key_]
                    for key_ in elmnt_labels
                }
            elif use_mtg_color == False:
                raise StandardError(
                    "Elements colors are missing. You may set elmnt_color_dict=True to use default colors provied by default_color_dict()."
                )

        for vid in g.property('geometry'):
            n = g.node(vid)
            if n.label.startswith(tuple(elmnt_labels)):
                mesh = n.geometry
                label = n.label
                if use_mtg_color:
                    color = n.color
                else:
                    for i in tuple(elmnt_labels):
                        if i in label: color = elmnt_color_dict[i]


#                color=(50,50,50) if vid != tt else (255,255,0)
                Scene_shape = pgl.Shape(mesh, pgl.Material(pgl.Color3(color)))
                MyScene.add(Scene_shape)

    if view_result:
        pgl.Viewer.display(MyScene)

    if snap_shot_path:
        pgl.Viewer.saveSnapshot(snap_shot_path)

    return MyScene
Exemplo n.º 16
0
def visu(g,
         plot_prop=None,
         min_value=None,
         max_value=None,
         cmap='jet',
         fmt='%6.0f',
         elmnt_labels=None,
         elmnt_color_dict=None,
         def_elmnt_color_dict=False,
         use_mtg_color=False,
         snap_shot_path=None,
         scene=None,
         view_result=True):
    """Displays 3D moke-up using `plantgl` package.

    Args:
        g (openalea.mtg.mtg.MTG): an MTG object
        plot_prop (str): name of an MTG property to plot
        min_value (float): minimum value for the color scale
        max_value (float): maximum value for the color scale
        cmap (str): the colormap to use; only active when `plot_prop` is given or `use_mtg_color` is True (default='jet)
        fmt (str): format of matplotlib colorbar ticklabels (default='%6.0f')
        elmnt_labels (list): the desired MTG elemnts to be displayed
        elmnt_color_dict (dict): RGB color tuples for the given MTG labels
        def_elmnt_color_dict (bool): if True, uses DEFAULT_COLORS` to set a dictionary of RGB color tuples with
            `elmnt_labels` as keys (default=False)
        use_mtg_color (bool): if True, the 'color' property from MTG nodes is used (default=False)
        snap_shot_path (str or None): path to save scene snapshot (default=None)
        scene (Scene): if given, adds scene shapes to it (default=None)
        view_result (bool): if True, the scene is displayed (default=False)

    Returns:
        (Scene)

    """

    my_scene = pgl.Scene() if scene is None else scene

    if plot_prop is not None:
        prop = [
            g.node(vid).properties()[plot_prop]
            for vid in g.property(plot_prop)
            if not g.node(vid).label.startswith('soil')
        ]
        if min_value is None:
            min_value = min(prop)
        if max_value is None:
            max_value = max(prop)

        g, cb = pglcolor.colorbar(g,
                                  property_name=plot_prop,
                                  cmap=cmap,
                                  lognorm=False,
                                  N=6,
                                  fmt=fmt,
                                  min_value=min_value,
                                  max_value=max_value)
        #        cb.patch.set_facecolor((0.2, 0.2, 0.2, 1.0))
        g = pglcolor.colormap(g,
                              property_name=plot_prop,
                              cmap=cmap,
                              lognorm=False,
                              min_value=min_value,
                              max_value=max_value)

        for vid in g.property(plot_prop).keys():
            try:
                n = g.node(vid)
                mesh = n.geometry
                scene_shape = pgl.Shape(mesh,
                                        pgl.Material(pgl.Color3(n.color)))
                my_scene.add(scene_shape)
            except:
                pass

    else:

        if elmnt_labels is None:
            elmnt_labels = DEFAULT_ELEMENTS

        if elmnt_color_dict is None:
            if def_elmnt_color_dict:
                def_color_dict = DEFAULT_COLORS
                elmnt_color_dict = {
                    key_: def_color_dict[key_]
                    for key_ in elmnt_labels
                }
            elif not use_mtg_color:
                raise Exception(
                    "Element colors are missing. You may set elmnt_color_dict=True to use default colors"
                    "provied by DEFAULT_COLORS.")

        for vid in g.property('geometry'):
            n = g.node(vid)
            if n.label.startswith(tuple(elmnt_labels)):
                mesh = n.geometry
                label = n.label
                if use_mtg_color:
                    color = n.color
                else:
                    for i in tuple(elmnt_labels):
                        if i in label: color = elmnt_color_dict[i]
                #                color=(50,50,50) if vid != tt else (255,255,0)
                scene_shape = pgl.Shape(mesh, pgl.Material(pgl.Color3(color)))
                my_scene.add(scene_shape)

    if view_result:
        pgl.Viewer.display(my_scene)

    if snap_shot_path:
        pgl.Viewer.saveSnapshot(snap_shot_path)

    return my_scene