Пример #1
0
    def _pipeline_default(self):
        grid = self.vtk_grid
        grid.set_execute_method(self.create_grid)
        grid.modified()

        trans = tvtk.Transform()
        trans.rotate_x(90.)
        cyl = self.vtk_cylinder
        cyl.transform = trans

        clip1 = tvtk.ClipVolume(input=grid.structured_points_output,
                                clip_function=self.vtk_cylinder,
                                inside_out=1)

        clip2 = tvtk.ClipDataSet(input=clip1.output,
                                 clip_function=self.vtk_quadric,
                                 inside_out=1)

        topoly = tvtk.GeometryFilter(input=clip2.output)
        norms = tvtk.PolyDataNormals(input=topoly.output)

        transF = tvtk.TransformFilter(input=norms.output,
                                      transform=self.transform)
        self.config_pipeline()
        #clip1.update()
        grid.modified()
        return transF
Пример #2
0
def main(hdf5_animation_file):
    weights = None
    with h5py.File(hdf5_animation_file, 'r') as f:
        verts = f['verts'].value
        tris = f['tris'].value
        if 'weights' in f:
            weights = f['weights'].value

    pd = tvtk.PolyData(points=verts[0], polys=tris)
    normals = tvtk.PolyDataNormals(input=pd, splitting=False)
    actor = tvtk.Actor(mapper=tvtk.PolyDataMapper(input=normals.output))
    actor.property.set(edge_color=(0.5, 0.5, 0.5), ambient=0.0,
                       specular=0.15, specular_power=128., shading=True, diffuse=0.8)

    fig = mlab.figure(bgcolor=(1,1,1))
    fig.scene.add_actor(actor)

    @mlab.animate(delay=40, ui=False)
    def animation():
        for i in count():
            if weights is not None:
                w_str = ",".join(["%0.2f"] * weights.shape[1])
                print ("Frame %d Weights = " + w_str) % tuple([i] + weights[i].tolist())
            frame = i % len(verts)
            pd.points = verts[frame]
            fig.scene.render()
            yield

    a = animation()
    fig.scene.z_minus_view()
    mlab.show()
Пример #3
0
    def _pipeline_default(self):
        grid = self.vtk_grid
        #grid.set_execute_method(self.create_grid)
        grid.modified()

        trans = tvtk.Transform()
        trans.rotate_x(90.)
        cyl = self.vtk_cylinder
        cyl.transform = trans

        clip1 = tvtk.ClipVolume(input_connection=grid.output_port,
                                clip_function=self.vtk_cylinder,
                                inside_out=1)

        self.clip2.set(input_connection=clip1.output_port,
                       clip_function=self.vtk_sphere,
                       inside_out=1)

        topoly = tvtk.GeometryFilter(input_connection=self.clip2.output_port)
        norms = tvtk.PolyDataNormals(input_connection=topoly.output_port)

        transF = tvtk.TransformFilter(input_connection=norms.output_port,
                                      transform=self.transform)
        self.config_pipeline()
        grid.modified()
        return transF
Пример #4
0
def cal_mesh_normals_api(verts,tris):
    pd = tvtk.PolyData(points=verts, polys=tris)
    n = tvtk.PolyDataNormals(input=pd,splitting=False)
    n.update()
    norms = n.output.point_data.normals
    #already normalized
    return norms
Пример #5
0
def main(hdf5_animation_file, sid='50004', pid='jiggle_on_toes'):
    with h5py.File(hdf5_animation_file, 'r') as f:
        verts = f[sid + '_' + pid].value.transpose([2, 0, 1])
        tris = f['faces'].value

    pd = tvtk.PolyData(points=verts[0], polys=tris)
    normals = tvtk.PolyDataNormals(input=pd, splitting=False)
    actor = tvtk.Actor(mapper=tvtk.PolyDataMapper(input=normals.output))
    actor.property.set(edge_color=(0.5, 0.5, 0.5),
                       ambient=0.0,
                       specular=0.15,
                       specular_power=128.,
                       shading=True,
                       diffuse=0.8)

    fig = mlab.figure(bgcolor=(1, 1, 1))
    fig.scene.add_actor(actor)

    @mlab.animate(delay=40, ui=False)
    def animation():
        for i in count():
            frame = i % len(verts)
            pd.points = verts[frame]
            fig.scene.render()
            yield

    a = animation()
    fig.scene.z_minus_view()
    mlab.show()
Пример #6
0
def meshBody(fileName, scale=(1., 1., 1.)):
  """
  Return a mesh actor and the appropriate static transform.
  """
  reader = FILE_READER[splitext(fileName)[1]](file_name=fileName)
  output = reader.output

  # if a scale is set we have to apply it
  if map(float, scale) != [1., 1., 1.]:
    tpdf_transform = tvtk.Transform()
    tpdf_transform.identity()
    tpdf_transform.scale(scale)
    tpdf = tvtk.TransformPolyDataFilter(input=reader.output, transform=tpdf_transform)
    tpdf.update()
    output = tpdf.output

  # compute mesh normal to have a better render and reverse mesh normal
  # if the scale flip them
  pdn = tvtk.PolyDataNormals(input=output)
  pdn.update()
  output = pdn.output

  pdm = tvtk.PolyDataMapper(input=output)
  actor = tvtk.Actor(mapper=pdm)
  actor.user_transform = tvtk.Transform()

  return actor, sva.PTransformd.Identity()
Пример #7
0
 def _pipeline_default(self):
     cyl = self.vtk_cylinder
     norms = tvtk.PolyDataNormals(input_connection=cyl.output_port)
     transF1 = tvtk.TransformFilter(input_connection=norms.output_port,
                                    transform=self.cyl_trans)
     transF2 = tvtk.TransformFilter(input_connection=transF1.output_port,
                                    transform=self.transform)
     self.config_pipeline()
     return transF2
Пример #8
0
def polydata_actor(polydata, compute_normals=True):
    """ create a vtk actor with given polydata as input """
    if compute_normals:
        normals = tvtk.PolyDataNormals(splitting=False)
        configure_input_data(normals, polydata)
        polydata = normals
    actor = tvtk.Actor(mapper=tvtk.PolyDataMapper())
    configure_input(actor.mapper, polydata)
    actor.mapper.lookup_table.hue_range = (0.33, 0.)
    return actor
Пример #9
0
    def __init__(self, verts1, verts2, tris=None, lines=None, as_points=False, 
                 scalars=None, scalars2=None, vmin=None, vmax=None,
                 actor_property=dict(specular=0.1, specular_power=128., diffuse=0.5),
                 ):
        if tris is None:
            if lines is None:
                rep = 'points'
            else:
                rep = 'wireframe'
        else:
            rep = 'surface'
        super(Morpher, self).__init__()
        self._verts1, self._verts2 = verts1, verts2
        self._polydata = tvtk.PolyData(points=verts1)
        if rep == 'points':
            self._polydata.verts = np.r_[:len(verts1)].reshape(-1,1)
        if tris is not None:
            self._polydata.polys = tris
        if lines is not None:
            self._polydata.lines = lines
        n = tvtk.PolyDataNormals(splitting=False)
        configure_input_data(n, self._polydata)
        self._actor = tvtk.Actor(mapper=tvtk.PolyDataMapper())
        configure_input(self._actor.mapper, n)
        self._actor.property.representation = rep
        if rep == 'points':
            self._actor.property.point_size = 5
        if as_points and scalars is None:
            self._polydata.point_data.scalars = \
                    np.random.uniform(0, 255, (len(verts1), 3)).astype(np.uint8)

        self._scalars12 = None
        if scalars is not None:
            self._polydata.point_data.scalars = scalars
            # automatically determine minimum/maximum from scalars if not given by user
            if vmin is None:
                vmin = scalars.min()
                if scalars2 is not None:
                    vmin = min(vmin, scalars2.min())
            if vmax is None:
                vmax = scalars.max()
                if scalars2 is not None:
                    vmax = max(vmax, scalars2.max())
            if scalars.ndim == 1:
                self._actor.mapper.use_lookup_table_scalar_range = False
                self._actor.mapper.scalar_range = (vmin, vmax)
                self._actor.mapper.lookup_table.hue_range = (0.33, 0)
            # when scalars of second mesh given we need to store both scalars in order
            # to interpolate between them during rendering
            if scalars2 is not None:
                self._scalars12 = (scalars, scalars2)
        else:
            self._actor.property.set(**actor_property)
        mlab.gcf().scene.add_actor(self._actor)
Пример #10
0
def compute_polydata_normals(polydata):
    pdnormals = tvtk.PolyDataNormals(compute_cell_normals=True,
                                     compute_point_normals=True,
                                     splitting=False,
                                     consistency=False,
                                     auto_orient_normals=False)
    pdnormals.set_input_data(polydata)
    pdnormals.update()
    pd_with_normals = pdnormals.output
    normals = pd_with_normals.cell_data.normals

    return normals.to_array()
Пример #11
0
def vismesh(pts,
            tris,
            color=None,
            edge_visibility=False,
            shader=None,
            triangle_scalars=None,
            colors=None,
            nan_color=None,
            **kwargs):
    if 'scalars' in kwargs and np.asarray(kwargs['scalars']).ndim == 2:
        colors = kwargs['scalars']
        del kwargs['scalars']
    # VTK does not allow bool arrays as scalars normally, so convert to float
    if 'scalars' in kwargs and np.asarray(kwargs['scalars']).dtype == np.bool:
        kwargs['scalars'] = kwargs['scalars'].astype(np.float)

    tm = mlab.triangular_mesh(pts[:, 0],
                              pts[:, 1],
                              pts[:, 2],
                              tris,
                              color=color,
                              **kwargs)
    if shader is not None:
        tm.actor.property.load_material(shader)
        tm.actor.actor.property.shading = True
    diffuse = 1.0 if colors is not None else 0.8
    tm.actor.actor.property.set(edge_visibility=edge_visibility,
                                line_width=1,
                                specular=0.0,
                                specular_power=128.,
                                diffuse=diffuse)
    if triangle_scalars is not None:
        tm.actor.mapper.input.cell_data.scalars = triangle_scalars
        tm.actor.mapper.set(scalar_mode='use_cell_data',
                            use_lookup_table_scalar_range=False,
                            scalar_visibility=True)
        if "vmin" in kwargs and "vmax" in kwargs:
            tm.actor.mapper.scalar_range = kwargs["vmin"], kwargs["vmax"]
    if colors is not None:
        # this basically is a hack which doesn't quite work,
        # we have to completely replace the polydata behind the hands of mayavi
        tm.mlab_source.dataset.point_data.scalars = colors.astype(np.uint8)
        normals = tvtk.PolyDataNormals(splitting=False)
        configure_input_data(normals, tm.mlab_source.dataset)
        configure_input(tm.actor.mapper, normals)
    if nan_color is not None:
        if len(nan_color) == 3:
            nan_color = list(nan_color) + [1]
        tm.module_manager.scalar_lut_manager.lut.nan_color = nan_color
        tm.update_pipeline()
    return tm
Пример #12
0
def mesh_as_vtk_actor(verts,
                      tris,
                      compute_normals=True,
                      return_polydata=True,
                      scalars=None):
    pd = tvtk.PolyData(points=verts, polys=tris)
    if scalars is not None:
        pd.point_data.scalars = scalars
    if compute_normals:
        normals = tvtk.PolyDataNormals(input=pd, splitting=False).output
    else:
        normals = pd
    actor = tvtk.Actor(mapper=tvtk.PolyDataMapper(input=normals))
    if return_polydata:
        return actor, pd
    else:
        return actor
Пример #13
0
    def _pipeline_default(self):
        grid = self.vtk_grid
        #grid.set_execute_method(self.create_grid)
        grid.modified()

        trans = tvtk.Transform()
        trans.rotate_x(90.)
        cyl = self.vtk_cylinder
        cyl.transform = trans

        clip1 = tvtk.ClipVolume(input_connection=grid.output_port,
                                clip_function=self.vtk_cylinder,
                                inside_out=1)

        self.clip2.set(input_connection=clip1.output_port,
                       clip_function=self.vtk_sphere1,
                       inside_out=1)

        self.clip3.set(input_connection=self.clip2.output_port,
                       clip_function=self.vtk_sphere3,
                       inside_out=1)

        clip4 = tvtk.ClipDataSet(input_connection=self.clip3.output_port,
                                 clip_function=self.vtk_sphere2,
                                 inside_out=1)

        clip5 = tvtk.ClipDataSet(input_connection=self.clip3.output_port,
                                 clip_function=self.vtk_sphere2,
                                 inside_out=0)

        topoly = tvtk.GeometryFilter(input_connection=clip4.output_port)
        topoly2 = tvtk.GeometryFilter(input_connection=clip5.output_port)

        append = tvtk.AppendPolyData()
        append.add_input_connection(topoly.output_port)
        append.add_input_connection(topoly2.output_port)

        norms = tvtk.PolyDataNormals(input_connection=append.output_port)

        transF = tvtk.TransformFilter(input_connection=norms.output_port,
                                      transform=self.transform)

        self.on_geometry_changed()
        self.config_pipeline()
        grid.modified()
        return transF
Пример #14
0
 def _pipeline_default(self):
     cyl = self.vtk_disk
     norms = tvtk.PolyDataNormals(input_connection=cyl.output_port)
     
     tube = tvtk.TubeFilter(input_connection=self.line.output_port)
     
     append = tvtk.AppendPolyData()
     append.add_input_connection(norms.output_port)
     append.add_input_connection(tube.output_port)
     
     transF1 = tvtk.TransformFilter(input_connection=append.output_port, 
                                    transform=self.cyl_trans)
     
     transF2 = tvtk.TransformFilter(input_connection=transF1.output_port, 
                                    transform=self.transform)
     self.config_pipeline()
     return transF2
Пример #15
0
 def __init__(self, Xmean, tris, components):
     HasTraits.__init__(self)
     self._components = components
     self._max_component_index = len(components)
     self._Xmean = Xmean
     self.pd = tvtk.PolyData(points=Xmean, polys=tris)
     self.normals = tvtk.PolyDataNormals(splitting=False)
     configure_input_data(self.normals, self.pd)
     mapper = tvtk.PolyDataMapper(immediate_mode_rendering=True)
     self.actor = tvtk.Actor(mapper=mapper)
     configure_input(self.actor.mapper, self.normals)
     self.actor.mapper.lookup_table = tvtk.LookupTable(
         hue_range=(0.45, 0.6),
         saturation_range=(0., 0.8),
         value_range=(.6, 1.),
     )
     self.scene.add_actor(self.actor)
     self.timer = Timer(40, self.animate().next)
Пример #16
0
    def _pipeline_default(self):
        grid = self.vtk_grid
        #grid.set_execute_method(self.create_grid)
        grid.modified()

        quad = self.vtk_quadric
        quad.transform = self.ellipse_trans

        clip = tvtk.ClipVolume(input_connection=grid.output_port,
                               clip_function=quad,
                               inside_out=0)

        topoly = tvtk.GeometryFilter(input_connection=clip.output_port)
        norm = tvtk.PolyDataNormals(input_connection=topoly.output_port)
        transF = tvtk.TransformFilter(input_connection=norm.output_port,
                                      transform=self.transform)
        self.config_pipeline()
        grid.modified()
        return transF
Пример #17
0
    def _pipeline_default(self):
        cyl = self.cyl
        cyl.resolution = 63  #use a prime no to avoid vertex degeneracy
        # Important to ensure the cylinder end doesn't coincide with the corner of the cube
        cyl.height = self.thickness - 1
        cyl.radius = self.diameter / 2.0
        cyl.center = (0, (self.thickness / 2) - 1, 0)
        print("thickness", self.thickness)
        print("diameter", self.diameter)
        size = max(self.thickness, self.diameter) * 2
        cube = self.cube
        cube.set_bounds(0, size, 0, size, 0, size)

        tf = tvtk.Transform()
        tf.post_multiply()
        tf.rotate_x(-45.0)
        tf.rotate_wxyz(35.26438968275, 0, 0, 1)

        tfilt = tvtk.TransformFilter(input_connection=cube.output_port)
        tfilt.transform = tf

        tri1 = tvtk.TriangleFilter(input_connection=cyl.output_port)
        tri2 = tvtk.TriangleFilter(input_connection=tfilt.output_port)
        tri1.update()
        tri2.update()

        intersect = tvtk.BooleanOperationPolyDataFilter()
        intersect.operation = "intersection"
        intersect.add_input_connection(0, tri1.output_port)
        intersect.add_input_connection(1, tri2.output_port)
        intersect.tolerance = 1e-8

        tf2 = tvtk.Transform()
        tf2.rotate_x(90.0)
        tf2.rotate_y(60.0)
        orient = tvtk.TransformFilter(input_connection=intersect.output_port,
                                      transform=tf2)

        norm = tvtk.PolyDataNormals(input_connection=orient.output_port)
        transF = tvtk.TransformFilter(input_connection=norm.output_port,
                                      transform=self.transform)
        self.config_pipeline()
        return transF
Пример #18
0
def vismesh(pts,
            tris,
            color=None,
            edge_visibility=False,
            shader=None,
            triangle_scalars=None,
            colors=None,
            **kwargs):
    if 'scalars' in kwargs and np.asarray(kwargs['scalars']).ndim == 2:
        colors = kwargs['scalars']
        del kwargs['scalars']
    tm = mlab.triangular_mesh(pts[:, 0],
                              pts[:, 1],
                              pts[:, 2],
                              tris,
                              color=color,
                              **kwargs)
    if shader is not None:
        tm.actor.property.load_material(shader)
        tm.actor.actor.property.shading = True
    diffuse = 1.0 if colors is not None else 0.8
    tm.actor.actor.property.set(edge_visibility=edge_visibility,
                                line_width=1,
                                specular=0.0,
                                specular_power=128.,
                                diffuse=diffuse)
    if triangle_scalars is not None:
        tm.mlab_source.dataset.cell_data.scalars = triangle_scalars
        tm.actor.mapper.set(scalar_mode='use_cell_data',
                            use_lookup_table_scalar_range=False,
                            scalar_visibility=True)
        if "vmin" in kwargs and "vmax" in kwargs:
            tm.actor.mapper.scalar_range = kwargs["vmin"], kwargs["vmax"]
    if colors is not None:
        # this basically is a hack which doesn't quite work,
        # we have to completely replace the polydata behind the hands of mayavi
        tm.mlab_source.dataset.point_data.scalars = colors.astype(np.uint8)
        tm.actor.mapper.input = tvtk.PolyDataNormals(
            input=tm.mlab_source.dataset, splitting=False).output
    return tm
Пример #19
0
    def add_static_background(self, data2D):

        self.sp2 = copy.copy(self.sp)
        self.z2 = np.reshape(np.transpose(data2D), (-1, ))

        self.sp2.point_data.scalars = self.z2
        self.geom_filter2 = tvtk.ImageDataGeometryFilter(input=self.sp2)
        self.warp2 = tvtk.WarpScalar(input=self.geom_filter2.output)
        self.normals2 = tvtk.PolyDataNormals(input=self.warp2.output)

        # The rest of the VTK pipeline.
        self.m2 = tvtk.PolyDataMapper(
            input=self.normals2.output)  #,scalar_range=(self.vmin, self.vmax))
        self.p = tvtk.Property(opacity=1.0,
                               color=(0.5, 0.5, 0.5),
                               representation="w")
        self.a2 = tvtk.Actor(mapper=self.m2, property=self.p)

        self.ren.add_actor(self.a2)

        self.rwi.initialize()
        self.ren.reset_camera()
Пример #20
0
def compute_normals(pts, faces):
    pd = tvtk.PolyData(points=pts, polys=faces)
    n = tvtk.PolyDataNormals(splitting=False)
    configure_input_data(n, pd)
    n.update()
    return n.output.point_data.normals.to_array()
Пример #21
0
    z = numpy.reshape(numpy.transpose(5.0*numpy.sin(r)/r), (-1,) )

# Now set the scalar data for the StructuredPoints object.  The
# scalars of the structured points object will be a view into our
# Numeric array.  Thus, if we change `z` in-place, the changes will
# automatically affect the VTK arrays.
sp.point_data.scalars = z

# Convert this to a PolyData object.
geom_filter = tvtk.ImageDataGeometryFilter(input=sp)

# Now warp this using the scalar value to generate a carpet plot.
warp = tvtk.WarpScalar(input=geom_filter.output)

# Smooth the resulting data so it looks good.
normals = tvtk.PolyDataNormals(input=warp.output)

# The rest of the VTK pipeline.
m = tvtk.PolyDataMapper(input=normals.output,
                        scalar_range=(min(z), max(z)))
a = tvtk.Actor(mapper=m)

ren = tvtk.Renderer(background=(0.5, 0.5, 0.5))
ren.add_actor(a)

# Get a nice view.
cam = ren.active_camera
cam.azimuth(-60)
cam.roll(90)

# Create a RenderWindow, add the renderer and set its size.
Пример #22
0
def flip_normals(stl_fname):
    # reading the stl file and getting the triangle data
    reader = tvtk.STLReader()
    reader.file_name = stl_fname
    reader.update()

    ordering = []
    polydata = reader.output
    points = polydata.points.to_array()
    x, y, z = points.T

    data = polydata.polys.to_array()
    data.shape = data.size // 4, 4
    ordering = np.delete(data, 0, 1)

    # getting normal data of the stl file
    normals = tvtk.PolyDataNormals()
    configure_input(normals, polydata)
    normals.compute_point_normals = 0
    normals.compute_cell_normals = 1
    normals.update()
    polydata_normals = normals.output

    u, v, w = polydata_normals.cell_data.normals.to_array().T
    fig = mlab.figure(bgcolor=(0, 0, 0))

    # renders the given stl file
    triangles = mlab.triangular_mesh(x,
                                     y,
                                     z,
                                     ordering,
                                     figure=fig,
                                     opacity=0.6)

    # coordinates of centroids of the trianlges
    centroids = np.sum(points[ordering], axis=1) / 3
    centroids_x, centroids_y, centroids_z = centroids.T

    # renders normals at centroids
    normals = mlab.quiver3d(centroids_x,
                            centroids_y,
                            centroids_z,
                            u,
                            v,
                            w,
                            figure=fig)
    centroids = mlab.points3d(centroids_x,
                              centroids_y,
                              centroids_z,
                              color=(0.2, 0.6, 0.1),
                              resolution=15)

    outline = mlab.outline(line_width=3)
    outline.outline_mode = "cornered"
    outline_size = centroids.glyph.glyph_source.glyph_source.radius * 0.3
    outline.bounds = (centroids_x[0] - outline_size, centroids_x[0] +
                      outline_size, centroids_y[0] - outline_size,
                      centroids_y[0] + outline_size, centroids_z[0] -
                      outline_size, centroids_z[0] + outline_size)

    ###########################################################################

    # refer to examples/mayavi/data_interaction/select_red_balls.py for
    # detailed information on using the callback
    glyph_normals = centroids.glyph.glyph_source.glyph_source.output.points.\
        to_array()

    def picker_callback(picker):
        if picker.actor in centroids.actor.actors:
            centroid_id = picker.point_id // glyph_normals.shape[0]
            if centroid_id != -1:
                x, y, z = centroids_x[centroid_id], centroids_y[centroid_id], \
                    centroids_z[centroid_id]
                u[centroid_id], v[centroid_id], w[centroid_id] = \
                    -1*u[centroid_id], -1*v[centroid_id], -1*w[centroid_id]
                normals.mlab_source.set(u=u, v=v, w=w)
                outline.bounds = (x - outline_size, x + outline_size,
                                  y - outline_size, y + outline_size,
                                  z - outline_size, z + outline_size)

    picker = fig.on_mouse_pick(picker_callback)
    picker.tolerance = 0.01
    mlab.title("Click on centroid to invert normal",
               color=(1, 1, 1),
               figure=fig)
Пример #23
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()
Пример #24
0
# Now set the scalar data for the StructuredPoints object.  The
# scalars of the structured points object will be a view into our
# Numeric array.  Thus, if we change `z` in-place, the changes will
# automatically affect the VTK arrays.
sp.point_data.scalars = z

# Convert this to a PolyData object.
geom_filter = tvtk.ImageDataGeometryFilter()
configure_input(geom_filter, sp)

# Now warp this using the scalar value to generate a carpet plot.
warp = tvtk.WarpScalar()
configure_input(warp, geom_filter)

# Smooth the resulting data so it looks good.
normals = tvtk.PolyDataNormals()
configure_input(normals, warp)

# The rest of the VTK pipeline.
m = tvtk.PolyDataMapper(scalar_range=(min(z), max(z)))
configure_input(m, normals)

a = tvtk.Actor(mapper=m)

ren = tvtk.Renderer(background=(0.5, 0.5, 0.5))
ren.add_actor(a)

# Get a nice view.
cam = ren.active_camera
cam.azimuth(-60)
cam.roll(90)
Пример #25
0
    def initialize(self, X, Y, initial_data=None, vmin=None, vmax=None):
        """
		Create objects to plot on
		"""
        if initial_data == None:
            initial_data = zeros(shape(X))
            if vmin == None:
                self.vmin = -1.0
            if vmax == None:
                self.vmax = 1.0
        else:
            if vmin == None:
                self.vmin = np.min(np.min(initial_data))
            if vmax == None:
                self.vmax = np.max(np.max(initial_data))
        x_min = np.min(np.min(X))
        y_min = np.min(np.min(Y))
        x_max = np.max(np.max(X))
        y_max = np.max(np.max(Y))
        x_middle = (x_min + x_max) / 2
        y_middle = (y_min + y_max) / 2
        z_middle = np.mean(np.mean(initial_data))
        L = x_max - x_min
        diffs = np.shape(X)
        x_diff = diffs[0]
        y_diff = diffs[1]
        z_diff = 1.0  #self.vmax-self.vmin

        self.tvtk = tvtk
        self.sp = tvtk.StructuredPoints(origin=(x_middle, y_middle, z_middle),
                                        dimensions=(x_diff, y_diff, 1),
                                        spacing=(2 * L / (x_diff - 1),
                                                 2 * L / (y_diff - 1), 100.0))

        self.z = np.transpose(initial_data).flatten()

        self.sp.point_data.scalars = self.z
        self.geom_filter = tvtk.ImageDataGeometryFilter(input=self.sp)
        self.warp = tvtk.WarpScalar(input=self.geom_filter.output)
        self.normals = tvtk.PolyDataNormals(input=self.warp.output)

        # The rest of the VTK pipeline.
        self.m = tvtk.PolyDataMapper(input=self.normals.output,
                                     scalar_range=(self.vmin, self.vmax))
        p = tvtk.Property(opacity=0.5, color=(1, 1, 1), representation="s")
        self.a = tvtk.Actor(mapper=self.m, property=p)

        self.ren = tvtk.Renderer(background=(0.0, 0.0, 0.0))

        self.ren.add_actor(self.a)

        # Get a nice view.
        self.cam = self.ren.active_camera
        self.cam.azimuth(-50)
        self.cam.roll(90)

        # Create a RenderWindow, add the renderer and set its size.
        self.rw = tvtk.RenderWindow(size=(800, 800))
        self.rw.add_renderer(self.ren)

        # Create the RenderWindowInteractor
        self.rwi = tvtk.RenderWindowInteractor(render_window=self.rw)

        self.rwi.initialize()
        self.ren.reset_camera()
        self.rwi.render()
Пример #26
0
 def test_help_trait(self):
     """Test if the help attribute is correct."""
     n = tvtk.PolyDataNormals()
     t = n.traits()
     test = t['splitting'].help != t['non_manifold_traversal'].help
     self.assertEqual(test, True)
Пример #27
0
def make_surf_actor(x,
                    y,
                    z,
                    warp=1,
                    scale=[1.0, 1.0, 1.0],
                    make_actor=True,
                    *args,
                    **kwargs):
    """Creates a surface given regularly spaced values of x, y and the
    corresponding z as arrays.  Also works if z is a function.
    Currently works only for regular data - can be enhanced later.

    Parameters
    ----------

        x -- Array of x points (regularly spaced)

        y -- Array if y points (regularly spaced)

        z -- A 2D array for the x and y points with x varying fastest
        and y next.  Also will work if z is a callable which supports
        x and y arrays as the arguments.

        warp -- If true, warp the data to show a 3D surface
        (default = 1).

        scale -- Scale the x, y and z axis as per passed values.
        Defaults to [1.0, 1.0, 1.0].

        make_actor -- also create actors suitably (default True)

        args -- additional positional arguments for func()
        (default is empty)

        kwargs -- a dict of additional keyword arguments for func()
        (default is empty)
    """

    if callable(z):
        zval = numpy.ravel(sampler(x, y, z, *args, **kwargs))
        x, y = squeeze(x), squeeze(y)
    else:
        x, y = squeeze(x), squeeze(y)
        _check_sanity(x, y, z)
        zval = numpy.ravel(z)
        assert len(zval) > 0, "z is empty - nothing to plot!"

    xs = x * scale[0]
    ys = y * scale[1]
    data = _create_structured_points_direct(xs, ys, zval)
    if not make_actor:
        return data
    if warp:
        geom_f = tvtk.ImageDataGeometryFilter()
        configure_input_data(geom_f, data)

        warper = tvtk.WarpScalar(scale_factor=scale[2])
        configure_input_data(warper, geom_f.output)
        normals = tvtk.PolyDataNormals(feature_angle=45)
        configure_input_data(normals, warper.output)

        mapper = tvtk.PolyDataMapper(scalar_range=(min(zval), max(zval)))
        configure_input_data(mapper, normals.output)
    else:
        mapper = tvtk.PolyDataMapper(scalar_range=(min(zval), max(zval)))
        configure_input_data(mapper, data)
    actor = _make_actor(mapper=mapper)
    return data, actor
Пример #28
0
def compute_normals(pd):
    n = tvtk.PolyDataNormals(input=pd, splitting=False)
    n.update()
    return n.output.point_data.normals