Exemplo n.º 1
0
def arrow_actor(color=colors.peacock, opacity=1.0, resolution=24):
    """ Creates a 3D Arrow and returns an actor. """
    source = tvtk.ArrowSource(tip_resolution=resolution,
                              shaft_resolution=resolution)
    mapper = tvtk.PolyDataMapper(input=source.output)
    prop = tvtk.Property(opacity=opacity, color=color)
    actor = tvtk.Actor(mapper=mapper, property=prop)
    return actor
Exemplo n.º 2
0
 def _glyph_dict_default(self):
     g = {'glyph_source2d': tvtk.GlyphSource2D(glyph_type='arrow', filled=False),
          'arrow_source': tvtk.ArrowSource(),
          'cone_source': tvtk.ConeSource(height=1.0, radius=0.2, resolution=15),
          'cylinder_source': tvtk.CylinderSource(height=1.0, radius=0.15,
                                                 resolution=10),
          'sphere_source': tvtk.SphereSource(),
          'cube_source': tvtk.CubeSource(),
          'axes': tvtk.Axes(symmetric=1)}
     return g
Exemplo n.º 3
0
 def _createVector(self, vector, frame, color):
   source = tvtk.ArrowSource()
   pdm = tvtk.PolyDataMapper(input=source.output)
   actor = tvtk.Actor(mapper=pdm)
   actor.user_transform = tvtk.Transform()
   actor.property.color = color
   norm = vector.norm()
   actor.scale = (norm,)*3
   quat = e.Quaterniond()
   # arrow are define on X axis
   quat.setFromTwoVectors(vector, e.Vector3d.UnitX())
   X = sva.PTransformd(quat)*frame
   setActorTransform(actor, X)
   return actor, X
Exemplo n.º 4
0
 def __source_dict_default(self):
     """Default value for source dict."""
     sd = {
         'arrow': tvtk.ArrowSource(),
         'cone': tvtk.ConeSource(),
         'cube': tvtk.CubeSource(),
         'cylinder': tvtk.CylinderSource(),
         'disk': tvtk.DiskSource(),
         'earth': tvtk.EarthSource(),
         'line': tvtk.LineSource(),
         'outline': tvtk.OutlineSource(),
         'plane': tvtk.PlaneSource(),
         'point': tvtk.PointSource(),
         'polygon': tvtk.RegularPolygonSource(),
         'sphere': tvtk.SphereSource(),
         'superquadric': tvtk.SuperquadricSource(),
         'textured sphere': tvtk.TexturedSphereSource(),
         'glyph2d': tvtk.GlyphSource2D()
     }
     return sd
Exemplo n.º 5
0
 def _createVector(self, vector, frame, color):
     source = tvtk.ArrowSource()
     # pdm = tvtk.PolyDataMapper(input=source.output)
     pdm = tvtk.PolyDataMapper()
     # https://github.com/enthought/mayavi/issues/521
     pdm.input_connection = source.output_port
     # configure_input_data(pdm, source)
     prop = tvtk.Property(color=color)
     actor = tvtk.Actor(mapper=pdm, property=prop)
     actor.user_transform = tvtk.Transform()
     # commented due to api change, new lines are above Actor creation
     # actor.property.color = color
     norm = vector.norm()
     actor.scale = (norm, ) * 3
     quat = e.Quaterniond()
     # arrow are define on X axis
     quat.setFromTwoVectors(vector, e.Vector3d.UnitX())
     X = sva.PTransformd(quat) * frame
     transform.setActorTransform(actor, X)
     return actor, X
Exemplo n.º 6
0
    def __init__(self):
        self.el = 0.0
        self.az = 0.0

        # Create an arrow.
        arrow = tvtk.ArrowSource()

        # Transform it suitably so it is oriented correctly.
        t = tvtk.Transform()
        tf = tvtk.TransformFilter()
        tf.transform = t
        t.rotate_y(90.0)
        t.translate((-2, 0, 0))
        configure_input_data(tf, arrow.output)

        mapper = tvtk.PolyDataMapper()
        configure_input(mapper, tf)

        self.actor = actor = tvtk.Follower()
        actor.mapper = mapper
        prop = actor.property
        prop.color = 0, 1, 1
        prop.ambient = 0.5
        prop.diffuse = 0.5
Exemplo n.º 7
0
# -*- coding: utf-8 -*-
from .example_cut_plane import read_data
import numpy as np
from tvtk.api import tvtk
from scpy2.tvtk.tvtkhelp import ivtk_scene, event_loop, make_outline

plot3d = read_data()
grid = plot3d.output.get_block(0)

mask = tvtk.MaskPoints(random_mode=True, on_ratio=50)
mask.set_input_data(grid)

arrow_source = tvtk.ArrowSource()
arrows = tvtk.Glyph3D(input_connection=mask.output_port,
                      scale_factor=2 /
                      np.max(grid.point_data.scalars.to_array()))
arrows.set_source_connection(arrow_source.output_port)

arrows_mapper = tvtk.PolyDataMapper(scalar_range=grid.point_data.scalars.range,
                                    input_connection=arrows.output_port)
arrows_actor = tvtk.Actor(mapper=arrows_mapper)

center = grid.center
sphere = tvtk.SphereSource(center=(2, center[1], center[2]),
                           radius=2,
                           phi_resolution=6,
                           theta_resolution=6)
sphere_mapper = tvtk.PolyDataMapper(input_connection=sphere.output_port)

sphere_actor = tvtk.Actor(mapper=sphere_mapper)
sphere_actor.property.set(representation="wireframe", color=(0, 0, 0))
Exemplo n.º 8
0
__author__ = "ddw20191222"

from tvtk.api import tvtk
from chapter2_2 import ivtk_scene, event_loop

plot3d = tvtk.MultiBlockPLOT3DReader(xyz_file_name="combxyz.bin",
                                     q_file_name="combq.bin",
                                     scalar_function_number=100,
                                     vector_function_number=200)
plot3d.update()  # 让plot3d 计算并且读取数据

grid = plot3d.output.get_block(0)  #获取读入的数据集对象

# 对数据进行随机选择,每50个点选择一个点
mask = tvtk.MaskPoints(random_mode=True, on_ratio=50)
mask.set_input_data(grid)

glyph_source = tvtk.ArrowSource()

# 绘制箭头
glyph = tvtk.Glyph3D(input_connection=mask.output_port, scale_factor=4)
glyph.set_source_connection(glyph_source.output_port)

m = tvtk.PolyDataMapper(scalar_range=grid.point_data.scalars.range,
                        input_connection=glyph.output_port)
a = tvtk.Actor(mapper=m)

win = ivtk_scene(a)
win.scene.isometric_view()
event_loop()
Exemplo n.º 9
0
    def vtk_actors(self):
        if (self.actors is None):
            self.actors = []
            points = _getfem_to_tvtk_points(self.sl.pts())
            (triangles, cv2tr) = self.sl.splxs(2)
            triangles = numpy.array(triangles.transpose(), 'I')
            data = tvtk.PolyData(points=points, polys=triangles)
            if self.scalar_data is not None:
                data.point_data.scalars = numpy.array(self.scalar_data)
            if self.vector_data is not None:
                data.point_data.vectors = numpy.array(self.vector_data)
            if self.glyph_name is not None:
                mask = tvtk.MaskPoints()
                mask.maximum_number_of_points = self.glyph_nb_pts
                mask.random_mode = True
                mask.input = data

                if self.glyph_name == 'default':
                    if self.vector_data is not None:
                        self.glyph_name = 'arrow'
                    else:
                        self.glyph_name = 'ball'

                glyph = tvtk.Glyph3D()
                glyph.scale_mode = 'scale_by_vector'
                glyph.color_mode = 'color_by_scalar'
                #glyph.scale_mode = 'data_scaling_off'
                glyph.vector_mode = 'use_vector'  # or 'use_normal'
                glyph.input = mask.output
                if self.glyph_name == 'arrow':
                    glyph.source = tvtk.ArrowSource().output
                elif self.glyph_name == 'ball':
                    glyph.source = tvtk.SphereSource().output
                elif self.glyph_name == 'cone':
                    glyph.source = tvtk.ConeSource().output
                elif self.glyph_name == 'cylinder':
                    glyph.source = tvtk.CylinderSource().output
                elif self.glyph_name == 'cube':
                    glyph.source = tvtk.CubeSource().output
                else:
                    raise Exception("Unknown glyph name..")
                #glyph.scaling = 1
                #glyph.scale_factor = self.glyph_scale_factor
                data = glyph.output

            if self.show_faces:
                ##                if self.deform is not None:
                ##                    data.point_data.vectors = array(numarray.transpose(self.deform))
                ##                    warper = tvtk.WarpVector(input=data)
                ##                    data = warper.output
                ##                lut = tvtk.LookupTable()
                ##                lut.hue_range = 0.667,0
                ##                c=gf_colormap('tripod')
                ##                lut.number_of_table_values=c.shape[0]
                ##                for i in range(0,c.shape[0]):
                ##                    lut.set_table_value(i,c[i,0],c[i,1],c[i,2],1)

                self.mapper = tvtk.PolyDataMapper(input=data)
                self.mapper.scalar_range = self.scalar_data_range
                self.mapper.scalar_visibility = True
                # Create mesh actor for display
                self.actors += [tvtk.Actor(mapper=self.mapper)]
            if self.show_edges:
                (Pe, E1, E2) = self.sl.edges()
                if Pe.size:
                    E = numpy.array(
                        numpy.concatenate((E1.transpose(), E2.transpose()),
                                          axis=0), 'I')
                    edges = tvtk.PolyData(points=_getfem_to_tvtk_points(Pe),
                                          polys=E)
                    mapper_edges = tvtk.PolyDataMapper(input=edges)
                    actor_edges = tvtk.Actor(mapper=mapper_edges)
                    actor_edges.property.representation = 'wireframe'
                    #actor_edges.property.configure_traits()
                    actor_edges.property.color = self.edges_color
                    actor_edges.property.line_width = self.edges_width
                    actor_edges.property.ambient = 0.5
                    self.actors += [actor_edges]
            if self.sl.nbsplxs(1):
                # plot tubes
                (seg, cv2seg) = self.sl.splxs(1)
                seg = numpy.array(seg.transpose(), 'I')
                data = tvtk.Axes(origin=(0, 0, 0),
                                 scale_factor=0.5,
                                 symmetric=1)
                data = tvtk.PolyData(points=points, lines=seg)
                tube = tvtk.TubeFilter(radius=0.4,
                                       number_of_sides=10,
                                       vary_radius='vary_radius_off',
                                       input=data)
                mapper = tvtk.PolyDataMapper(input=tube.output)
                actor_tubes = tvtk.Actor(mapper=mapper)
                #actor_tubes.property.representation = 'wireframe'
                actor_tubes.property.color = self.tube_color
                #actor_tubes.property.line_width = 8
                #actor_tubes.property.ambient = 0.5

                self.actors += [actor_tubes]

            if self.use_scalar_bar:
                self.scalar_bar = tvtk.ScalarBarActor(
                    title=self.scalar_data_name,
                    orientation='horizontal',
                    width=0.8,
                    height=0.07)
                self.scalar_bar.position_coordinate.coordinate_system = 'normalized_viewport'
                self.scalar_bar.position_coordinate.value = 0.1, 0.01, 0.0
                self.actors += [self.scalar_bar]

            if (self.lookup_table is not None):
                self.set_colormap(self.lookup_table)

        return self.actors
Exemplo n.º 10
0
def main(*anim_files):
    fig = mlab.figure(bgcolor=(1, 1, 1))
    all_verts = []
    pds = []
    actors = []
    datasets = []
    glyph_pds = []
    glyph_actors = []

    colors = cycle([(1, 1, 1), (1, 0, 0), (0, 1, 0), (0, 0, 1)])

    for i, (f, color) in enumerate(zip(anim_files, colors)):
        data = h5py.File(f, 'r')
        verts = data['verts'].value
        tris = data['tris'].value
        print f
        print "  Vertices: ", verts.shape
        print "  Triangles: ", tris.shape
        datasets.append(data)

        # setup mesh
        pd = tvtk.PolyData(points=verts[0], polys=tris)
        normals = tvtk.PolyDataNormals(compute_point_normals=True,
                                       splitting=False)
        configure_input_data(normals, pd)
        actor = tvtk.Actor(mapper=tvtk.PolyDataMapper())
        configure_input(actor.mapper, normals)
        actor.mapper.immediate_mode_rendering = True
        actor.visibility = False
        fig.scene.add_actor(actor)

        actors.append(actor)
        all_verts.append(verts)
        pds.append(normals)

        # setup arrows
        arrow = tvtk.ArrowSource(tip_length=0.25,
                                 shaft_radius=0.03,
                                 shaft_resolution=32,
                                 tip_resolution=4)
        glyph_pd = tvtk.PolyData()
        glyph = tvtk.Glyph3D()
        scale_factor = verts.reshape(-1, 3).ptp(0).max() * 0.1
        glyph.set(scale_factor=scale_factor,
                  scale_mode='scale_by_vector',
                  color_mode='color_by_scalar')
        configure_input_data(glyph, glyph_pd)
        configure_source_data(glyph, arrow)
        glyph_actor = tvtk.Actor(mapper=tvtk.PolyDataMapper(),
                                 visibility=False)
        configure_input(glyph_actor.mapper, glyph)
        fig.scene.add_actor(glyph_actor)

        glyph_actors.append(glyph_actor)
        glyph_pds.append(glyph_pd)

    actors[0].visibility = True
    glyph_actors[0].visibility = True

    class Viewer(HasTraits):
        animator = Instance(Animator)
        visible = Enum(*range(len(pds)))
        normals = Bool(True)
        export_off = Button
        restpose = Bool(True)
        show_scalars = Bool(True)
        show_bones = Bool(True)
        show_actual_bone_centers = Bool(False)

        def _export_off_changed(self):
            fd = FileDialog(title='Export OFF',
                            action='save as',
                            wildcard='OFF Meshes|*.off')
            if fd.open() == OK:
                v = all_verts[self.visible][self.animator.current_frame]
                save_off(fd.path, v, tris)

        @on_trait_change('visible, normals, restpose, show_scalars, show_bones'
                         )
        def _changed(self):
            for a in actors + glyph_actors:
                a.visibility = False
            for d in pds:
                d.compute_point_normals = self.normals
            actors[self.visible].visibility = True
            actors[self.visible].mapper.scalar_visibility = self.show_scalars
            glyph_actors[self.visible].visibility = self.show_bones
            #for i, visible in enumerate(self.visibilities):
            #    actors[i].visibility = visible
            self.animator.render = True

        def show_frame(self, frame):
            v = all_verts[self.visible][frame]
            dataset = datasets[self.visible]
            if not self.restpose:
                rbms_frame = dataset['rbms'][frame]
                v = v * dataset.attrs['scale'] + dataset.attrs['verts_mean']
                v = blend_skinning(v,
                                   dataset['segments'].value,
                                   rbms_frame,
                                   method=dataset.attrs['skinning_method'])
            pds[self.visible].input.points = v
            if 'scalar' in dataset and self.show_scalars:
                if dataset['scalar'].shape[0] == all_verts[
                        self.visible].shape[0]:
                    scalar = dataset['scalar'][frame]
                else:
                    scalar = dataset['scalar'].value
                pds[self.visible].input.point_data.scalars = scalar
            else:
                pds[self.visible].input.point_data.scalars = None
            if 'bone_transformations' in dataset and self.show_bones:
                W = dataset['bone_blendweights'].value
                T = dataset['bone_transformations'].value
                gpd = glyph_pds[self.visible]
                if self.show_actual_bone_centers:
                    verts0 = dataset['verts_restpose'].value
                    mean_bonepoint = verts0[W.argmax(axis=1)]  # - T[0,:,:,3]
                    #mean_bonepoint = np.array([
                    #    np.average(verts0, weights=w, axis=0) for w in W])
                    #gpd.points = np.repeat(mean_bonepoint + T[frame,:,:,3], 3, 0)
                    #print np.tile(mean_bonepoint + T[frame,:,:,3], 3).reshape((-1, 3))
                    #gpd.points = np.tile(mean_bonepoint + T[frame,:,:,3], 3).reshape((-1, 3))
                    pts = []
                    for i in xrange(T.shape[1]):
                        #offset = V.transform(V.hom4(mean_bonepoint[i]), T[frame,i,:,:])
                        offset = np.dot(T[frame, i], V.hom4(mean_bonepoint[i]))
                        pts += [offset] * 3
                    gpd.points = np.array(pts)

                else:
                    bonepoint = np.array(
                        [np.average(v, weights=w, axis=0) for w in W])
                    gpd.points = np.repeat(bonepoint, 3, 0)
                gpd.point_data.vectors = \
                        np.array(map(np.linalg.inv, T[frame,:,:,:3])).reshape(-1, 3)
                # color vertices
                vert_colors = vertex_weights_to_colors(W)
                pds[self.visible].input.point_data.scalars = vert_colors
                bone_colors = hue_linspace_colors(W.shape[0],
                                                  sat=0.8,
                                                  light=0.7)
                gpd.point_data.scalars = np.repeat(bone_colors, 3, 0)

        view = View(
            Group(
                Group(Item('visible'),
                      Item('export_off'),
                      Item('normals'),
                      Item('restpose'),
                      Item('show_scalars'),
                      Item('show_bones'),
                      Item('show_actual_bone_centers'),
                      label="Viewer"),
                Item('animator', style='custom', show_label=False),
            ))

    app = Viewer()
    animator = Animator(verts.shape[0], app.show_frame)
    app.animator = animator
    app.edit_traits()
    mlab.show()