| 1 |
"""Module dedicated to widgets.""" |
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
|
| 5 |
from itertools import product |
| 6 |
import pathlib |
| 7 |
from typing import TYPE_CHECKING |
| 8 |
|
| 9 |
import numpy as np |
| 10 |
|
| 11 |
import pyvista as pv |
| 12 |
from pyvista import _vtk |
| 13 |
from pyvista._deprecate_positional_args import _deprecate_positional_args |
| 14 |
from pyvista.core._vtk_utilities import vtk_version_info |
| 15 |
from pyvista.core.utilities.arrays import get_array |
| 16 |
from pyvista.core.utilities.arrays import get_array_association |
| 17 |
from pyvista.core.utilities.helpers import _NORMALS |
| 18 |
from pyvista.core.utilities.helpers import generate_plane |
| 19 |
from pyvista.core.utilities.misc import _NoNewAttrMixin |
| 20 |
from pyvista.core.utilities.misc import assert_empty_kwargs |
| 21 |
from pyvista.core.utilities.misc import try_callback |
| 22 |
|
| 23 |
from .affine_widget import AffineWidget3D |
| 24 |
from .colors import Color |
| 25 |
from .opts import PickerType |
| 26 |
from .utilities.algorithms import add_ids_algorithm |
| 27 |
from .utilities.algorithms import algorithm_to_mesh_handler |
| 28 |
from .utilities.algorithms import crinkle_algorithm |
| 29 |
from .utilities.algorithms import outline_algorithm |
| 30 |
from .utilities.algorithms import pointset_to_polydata_algorithm |
| 31 |
from .utilities.algorithms import set_algorithm_input |
| 32 |
|
| 33 |
if TYPE_CHECKING: |
| 34 |
from pyvista import ImageData |
| 35 |
from pyvista.core._typing_core import InteractionEventType |
| 36 |
from pyvista.core._typing_core import VectorLike |
| 37 |
|
| 38 |
|
| 39 |
def _parse_interaction_event(interaction_event: InteractionEventType): |
| 40 |
"""Parse the interaction event. |
| 41 |
|
| 42 |
Parameters |
| 43 |
---------- |
| 44 |
interaction_event : InteractionEventType |
| 45 |
The VTK interaction event to use for triggering the callback. Accepts |
| 46 |
either the strings ``'start'``, ``'end'``, ``'always'`` or a |
| 47 |
:vtk:`vtkCommand.EventIds`. |
| 48 |
|
| 49 |
Returns |
| 50 |
------- |
| 51 |
:vtk:`vtkCommand.EventIds` |
| 52 |
VTK Event type. |
| 53 |
|
| 54 |
""" |
| 55 |
if not isinstance(interaction_event, (_vtk.vtkCommand.EventIds, str)): |
| 56 |
msg = ( # type: ignore[unreachable] |
| 57 |
'Expected type for `interaction_event` is either a str ' |
| 58 |
'or an instance of `vtk.vtkCommand.EventIds`.' |
| 59 |
f' ({type(interaction_event)}) was given.' |
| 60 |
) |
| 61 |
raise TypeError(msg) |
| 62 |
|
| 63 |
if isinstance(interaction_event, _vtk.vtkCommand.EventIds): |
| 64 |
return interaction_event |
| 65 |
|
| 66 |
event_map = { |
| 67 |
'start': _vtk.vtkCommand.StartInteractionEvent, |
| 68 |
'end': _vtk.vtkCommand.EndInteractionEvent, |
| 69 |
'always': _vtk.vtkCommand.InteractionEvent, |
| 70 |
} |
| 71 |
if interaction_event not in event_map: |
| 72 |
expected = ', '.join(f'`{e}`' for e in event_map) |
| 73 |
msg = ( |
| 74 |
f'Expected value for `interaction_event` is {expected}. {interaction_event} was given.' |
| 75 |
) |
| 76 |
raise ValueError(msg) |
| 77 |
|
| 78 |
return event_map[interaction_event] |
| 79 |
|
| 80 |
|
| 81 |
class WidgetComponent(_NoNewAttrMixin): |
| 82 |
"""Plotter widget component. |
| 83 |
|
| 84 |
Owns every interactive widget (box, plane, line, slider, sphere, |
| 85 |
spline, button, radio button, measurement, logo, camera, camera3d) |
| 86 |
that has been attached to the owning plotter, along with the |
| 87 |
derived meshes some widgets generate. Constructed lazily on first |
| 88 |
access of ``plotter.widgets`` and registered for close-time |
| 89 |
teardown via ``__plotter_close__``. |
| 90 |
|
| 91 |
The plotter exposes the public widget surface (``add_*_widget``, |
| 92 |
``clear_*_widgets``, ``add_mesh_clip_box``, etc.) as forwarding |
| 93 |
shims that delegate here. |
| 94 |
|
| 95 |
Parameters |
| 96 |
---------- |
| 97 |
plotter : pyvista.BasePlotter |
| 98 |
Owning plotter. Stored as a strong reference; the component's |
| 99 |
lifetime is bounded by the plotter's lifetime. |
| 100 |
|
| 101 |
Attributes |
| 102 |
---------- |
| 103 |
box_widgets : list |
| 104 |
:vtk:`vtkBoxWidget` instances added via :meth:`add_box_widget`. |
| 105 |
box_clipped_meshes : list |
| 106 |
Meshes produced by box-widget clipping in :meth:`add_mesh_clip_box`. |
| 107 |
plane_widgets : list |
| 108 |
:vtk:`vtkImplicitPlaneWidget` instances added via |
| 109 |
:meth:`add_plane_widget`. |
| 110 |
plane_clipped_meshes : list |
| 111 |
Meshes produced by plane-widget clipping in |
| 112 |
:meth:`add_mesh_clip_plane`. |
| 113 |
plane_sliced_meshes : list |
| 114 |
Meshes produced by plane-widget slicing in :meth:`add_mesh_slice`. |
| 115 |
line_widgets : list |
| 116 |
:vtk:`vtkLineWidget` instances added via :meth:`add_line_widget`. |
| 117 |
slider_widgets : list |
| 118 |
:vtk:`vtkSliderWidget` instances added via |
| 119 |
:meth:`add_slider_widget`. |
| 120 |
threshold_meshes : list |
| 121 |
Meshes produced by threshold sliders in :meth:`add_mesh_threshold`. |
| 122 |
isovalue_meshes : list |
| 123 |
Meshes produced by isovalue sliders in :meth:`add_mesh_isovalue`. |
| 124 |
spline_widgets : list |
| 125 |
:vtk:`vtkSplineWidget` instances added via |
| 126 |
:meth:`add_spline_widget`. |
| 127 |
spline_sliced_meshes : list |
| 128 |
Meshes produced by spline slicing in :meth:`add_mesh_slice_spline`. |
| 129 |
sphere_widgets : list |
| 130 |
:vtk:`vtkSphereWidget` instances added via |
| 131 |
:meth:`add_sphere_widget`. |
| 132 |
button_widgets : list |
| 133 |
Checkbox / radio button widgets. |
| 134 |
radio_button_widget_dict : dict |
| 135 |
Mapping of group name to the radio buttons in that group. |
| 136 |
radio_button_title_dict : dict |
| 137 |
Mapping of group name to title actors for that group. |
| 138 |
distance_widgets : list |
| 139 |
Measurement widgets added via :meth:`add_measurement_widget`. |
| 140 |
logo_widgets : list |
| 141 |
Logo widgets added via :meth:`add_logo_widget`. |
| 142 |
camera_widgets : list |
| 143 |
Camera-orientation widgets added via |
| 144 |
:meth:`add_camera_orientation_widget`. |
| 145 |
camera3d_widgets : list |
| 146 |
3D camera widgets added via :meth:`add_camera3d_widget`. |
| 147 |
|
| 148 |
.. versionadded:: 0.48.0 |
| 149 |
|
| 150 |
""" |
| 151 |
|
| 152 |
def __init__(self, plotter): |
| 153 |
"""Initialize the widget component.""" |
| 154 |
self._plotter = plotter |
| 155 |
self.camera_widgets = [] |
| 156 |
self.box_widgets = [] |
| 157 |
self.box_clipped_meshes = [] |
| 158 |
self.plane_widgets = [] |
| 159 |
self.plane_clipped_meshes = [] |
| 160 |
self.plane_sliced_meshes = [] |
| 161 |
self.line_widgets = [] |
| 162 |
self.slider_widgets = [] |
| 163 |
self.threshold_meshes = [] |
| 164 |
self.isovalue_meshes = [] |
| 165 |
self.spline_widgets = [] |
| 166 |
self.spline_sliced_meshes = [] |
| 167 |
self.sphere_widgets = [] |
| 168 |
self.button_widgets = [] |
| 169 |
self.radio_button_widget_dict = {} |
| 170 |
self.radio_button_title_dict = {} |
| 171 |
self.distance_widgets = [] |
| 172 |
self.logo_widgets = [] |
| 173 |
self.camera3d_widgets = [] |
| 174 |
|
| 175 |
@_deprecate_positional_args(allowed=['callback']) |
| 176 |
def add_box_widget( # noqa: PLR0917 |
| 177 |
self, |
| 178 |
callback, |
| 179 |
bounds=None, |
| 180 |
factor=1.25, |
| 181 |
rotation_enabled: bool = True, # noqa: FBT001, FBT002 |
| 182 |
color=None, |
| 183 |
use_planes: bool = False, # noqa: FBT001, FBT002 |
| 184 |
outline_translation: bool = True, # noqa: FBT001, FBT002 |
| 185 |
pass_widget: bool = False, # noqa: FBT001, FBT002 |
| 186 |
interaction_event: InteractionEventType = 'end', |
| 187 |
): |
| 188 |
"""Add a box widget to the scene. |
| 189 |
|
| 190 |
This is useless without a callback function. You can pass a |
| 191 |
callable function that takes a single argument, the PolyData |
| 192 |
box output from this widget, and performs a task with that |
| 193 |
box. |
| 194 |
|
| 195 |
Parameters |
| 196 |
---------- |
| 197 |
callback : callable |
| 198 |
The method called every time the box is updated. This has |
| 199 |
two options: Take a single argument, the ``PolyData`` box |
| 200 |
(default) or if ``use_planes=True``, then it takes a |
| 201 |
single argument of the plane collection as a :vtk:`vtkPlanes` |
| 202 |
object. |
| 203 |
|
| 204 |
bounds : tuple(float) |
| 205 |
Length 6 tuple of the bounding box where the widget is |
| 206 |
placed. |
| 207 |
|
| 208 |
factor : float, optional |
| 209 |
An inflation factor to expand on the bounds when placing. |
| 210 |
|
| 211 |
rotation_enabled : bool, optional |
| 212 |
If ``False``, the box widget cannot be rotated and is |
| 213 |
strictly orthogonal to the Cartesian axes. |
| 214 |
|
| 215 |
color : ColorLike, optional |
| 216 |
Either a string, rgb sequence, or hex color string. |
| 217 |
Defaults to :attr:`pyvista.global_theme.font.color |
| 218 |
<pyvista.plotting.themes._Font.color>`. |
| 219 |
|
| 220 |
use_planes : bool, optional |
| 221 |
Changes the arguments passed to the callback to the planes |
| 222 |
that make up the box. |
| 223 |
|
| 224 |
outline_translation : bool, optional |
| 225 |
If ``False``, the box widget cannot be translated and is |
| 226 |
strictly placed at the given bounds. |
| 227 |
|
| 228 |
pass_widget : bool, optional |
| 229 |
If ``True``, the widget will be passed as the last |
| 230 |
argument of the callback. |
| 231 |
|
| 232 |
interaction_event : InteractionEventType, optional |
| 233 |
The VTK interaction event to use for triggering the |
| 234 |
callback. Accepts either the strings ``'start'``, ``'end'``, |
| 235 |
``'always'`` or a :vtk:`vtkCommand.EventIds`. |
| 236 |
|
| 237 |
.. versionchanged:: 0.38.0 |
| 238 |
Now accepts either strings or :vtk:`vtkCommand.EventIds`. |
| 239 |
|
| 240 |
Returns |
| 241 |
------- |
| 242 |
:vtk:`vtkBoxWidget` |
| 243 |
Box widget. |
| 244 |
|
| 245 |
Examples |
| 246 |
-------- |
| 247 |
Shows an interactive box that is used to resize and relocate a sphere. |
| 248 |
|
| 249 |
>>> import pyvista as pv |
| 250 |
>>> import numpy as np |
| 251 |
>>> pl = pv.Plotter() |
| 252 |
>>> def simulate(widget): |
| 253 |
... bounds = widget.bounds |
| 254 |
... new_center = np.array( |
| 255 |
... [ |
| 256 |
... (bounds[0] + bounds[1]) / 2, |
| 257 |
... (bounds[2] + bounds[3]) / 2, |
| 258 |
... (bounds[4] + bounds[5]) / 2, |
| 259 |
... ] |
| 260 |
... ) |
| 261 |
... new_radius = ( |
| 262 |
... min( |
| 263 |
... (bounds[1] - bounds[0]) / 2, |
| 264 |
... (bounds[3] - bounds[2]) / 2, |
| 265 |
... (bounds[5] - bounds[4]) / 2, |
| 266 |
... ) |
| 267 |
... - 0.3 |
| 268 |
... ) |
| 269 |
... sphere = pv.Sphere(radius=new_radius, center=new_center) |
| 270 |
... _ = pl.add_mesh(sphere, name='Sphere') |
| 271 |
>>> _ = pl.add_box_widget(callback=simulate) |
| 272 |
>>> pl.show() |
| 273 |
|
| 274 |
""" |
| 275 |
if bounds is None: |
| 276 |
bounds = self._plotter.bounds |
| 277 |
|
| 278 |
def _the_callback(box_widget, _event): |
| 279 |
the_box = pv.PolyData() |
| 280 |
box_widget.GetPolyData(the_box) |
| 281 |
planes = _vtk.vtkPlanes() |
| 282 |
box_widget.GetPlanes(planes) |
| 283 |
if callable(callback): |
| 284 |
args = [planes] if use_planes else [the_box] |
| 285 |
if pass_widget: |
| 286 |
args.append(box_widget) |
| 287 |
try_callback(callback, *args) |
| 288 |
|
| 289 |
box_widget = _vtk.vtkBoxWidget() |
| 290 |
box_widget.GetOutlineProperty().SetColor( |
| 291 |
Color(color, default_color=pv.global_theme.font.color).float_rgb, |
| 292 |
) |
| 293 |
box_widget.SetInteractor(self._plotter.iren.interactor) |
| 294 |
box_widget.SetCurrentRenderer(self._plotter.renderer) |
| 295 |
box_widget.SetPlaceFactor(factor) |
| 296 |
box_widget.SetRotationEnabled(rotation_enabled) |
| 297 |
box_widget.SetTranslationEnabled(outline_translation) |
| 298 |
box_widget.PlaceWidget(bounds) |
| 299 |
box_widget.On() |
| 300 |
box_widget.AddObserver( |
| 301 |
_parse_interaction_event(interaction_event), |
| 302 |
_the_callback, |
| 303 |
) |
| 304 |
_the_callback(box_widget, None) |
| 305 |
|
| 306 |
self.box_widgets.append(box_widget) |
| 307 |
return box_widget |
| 308 |
|
| 309 |
def clear_box_widgets(self): |
| 310 |
"""Remove all of the box widgets.""" |
| 311 |
for box_widget in self.box_widgets: |
| 312 |
box_widget.Off() |
| 313 |
self.box_widgets.clear() |
| 314 |
|
| 315 |
@_deprecate_positional_args(allowed=['mesh']) |
| 316 |
def add_mesh_clip_box( # noqa: PLR0917 |
| 317 |
self, |
| 318 |
mesh, |
| 319 |
invert: bool = False, # noqa: FBT001, FBT002 |
| 320 |
rotation_enabled: bool = True, # noqa: FBT001, FBT002 |
| 321 |
widget_color=None, |
| 322 |
outline_translation: bool = True, # noqa: FBT001, FBT002 |
| 323 |
merge_points: bool = True, # noqa: FBT001, FBT002 |
| 324 |
crinkle: bool = False, # noqa: FBT001, FBT002 |
| 325 |
interaction_event: InteractionEventType = 'end', |
| 326 |
factor=1.25, |
| 327 |
**kwargs, |
| 328 |
): |
| 329 |
"""Clip a mesh using a box widget. |
| 330 |
|
| 331 |
Add a mesh to the scene with a box widget that is used to clip |
| 332 |
the mesh interactively. |
| 333 |
|
| 334 |
The clipped mesh is saved to the ``.box_clipped_meshes`` attribute on |
| 335 |
the plotter. |
| 336 |
|
| 337 |
Parameters |
| 338 |
---------- |
| 339 |
mesh : DataSet | :vtk:`vtkAlgorithm` |
| 340 |
The input dataset to add to the scene and clip or algorithm that |
| 341 |
produces said mesh. |
| 342 |
|
| 343 |
invert : bool, optional |
| 344 |
Flag on whether to flip/invert the clip. |
| 345 |
|
| 346 |
factor : float, optional |
| 347 |
An inflation factor to expand on the bounds when placing. |
| 348 |
|
| 349 |
rotation_enabled : bool, optional |
| 350 |
If ``False``, the box widget cannot be rotated and is strictly |
| 351 |
orthogonal to the cartesian axes. |
| 352 |
|
| 353 |
widget_color : ColorLike, optional |
| 354 |
Color of the widget. Either a string, RGB sequence, or |
| 355 |
hex color string. For example: |
| 356 |
|
| 357 |
* ``color='white'`` |
| 358 |
* ``color='w'`` |
| 359 |
* ``color=[1.0, 1.0, 1.0]`` |
| 360 |
* ``color='#FFFFFF'`` |
| 361 |
|
| 362 |
outline_translation : bool, optional |
| 363 |
If ``False``, the plane widget cannot be translated and is |
| 364 |
strictly placed at the given bounds. |
| 365 |
|
| 366 |
merge_points : bool, optional |
| 367 |
If ``True`` (default), coinciding points of independently |
| 368 |
defined mesh elements will be merged. |
| 369 |
|
| 370 |
crinkle : bool, optional |
| 371 |
Crinkle the clip by extracting the entire cells along the clip. |
| 372 |
|
| 373 |
interaction_event : InteractionEventType, optional |
| 374 |
The VTK interaction event to use for triggering the |
| 375 |
callback. Accepts either the strings ``'start'``, ``'end'``, |
| 376 |
``'always'`` or a :vtk:`vtkCommand.EventIds`. |
| 377 |
|
| 378 |
.. versionchanged:: 0.38.0 |
| 379 |
Changed from ``event_type`` to ``interaction_event`` and now |
| 380 |
accepts either strings and :vtk:`vtkCommand.EventIds`. |
| 381 |
|
| 382 |
**kwargs : dict, optional |
| 383 |
All additional keyword arguments are passed to |
| 384 |
:func:`pyvista.Plotter.add_mesh` to control how the mesh is |
| 385 |
displayed. |
| 386 |
|
| 387 |
Returns |
| 388 |
------- |
| 389 |
:vtk:`vtkActor` |
| 390 |
VTK actor of the mesh. |
| 391 |
|
| 392 |
Examples |
| 393 |
-------- |
| 394 |
Shows an interactive clip box. |
| 395 |
|
| 396 |
>>> import pyvista as pv |
| 397 |
>>> mesh = pv.ParametricConicSpiral() |
| 398 |
>>> pl = pv.Plotter() |
| 399 |
>>> _ = pl.add_mesh_clip_box(mesh, color='white') |
| 400 |
>>> pl.show() |
| 401 |
|
| 402 |
For a full example see :ref:`box_widget_example`. |
| 403 |
|
| 404 |
""" |
| 405 |
from pyvista.core.filters import _get_output # avoids circular import |
| 406 |
|
| 407 |
mesh, algo = algorithm_to_mesh_handler( |
| 408 |
add_ids_algorithm(mesh, point_ids=False, cell_ids=True), |
| 409 |
) |
| 410 |
|
| 411 |
name = kwargs.get('name', mesh.memory_address) |
| 412 |
rng = mesh.get_data_range(kwargs.get('scalars')) |
| 413 |
kwargs.setdefault('clim', kwargs.pop('rng', rng)) |
| 414 |
mesh.set_active_scalars(kwargs.get('scalars', mesh.active_scalars_name)) |
| 415 |
|
| 416 |
self._plotter.add_mesh(outline_algorithm(algo), name=f'{name}-outline', opacity=0.0) |
| 417 |
|
| 418 |
port = 1 if invert else 0 |
| 419 |
|
| 420 |
clipper = _vtk.vtkBoxClipDataSet() |
| 421 |
if not merge_points: |
| 422 |
# vtkBoxClipDataSet uses vtkMergePoints by default |
| 423 |
clipper.SetLocator(_vtk.vtkNonMergingPointLocator()) |
| 424 |
set_algorithm_input(clipper, algo) |
| 425 |
clipper.GenerateClippedOutputOn() |
| 426 |
|
| 427 |
if crinkle: |
| 428 |
crinkler = crinkle_algorithm(clipper.GetOutputPort(port), algo) |
| 429 |
box_clipped_mesh = _get_output(crinkler) |
| 430 |
else: |
| 431 |
box_clipped_mesh = _get_output(clipper, oport=port) |
| 432 |
|
| 433 |
self.box_clipped_meshes.append(box_clipped_mesh) |
| 434 |
|
| 435 |
def callback(planes): |
| 436 |
bounds = [] |
| 437 |
for i in range(planes.GetNumberOfPlanes()): |
| 438 |
plane = planes.GetPlane(i) |
| 439 |
bounds.append(plane.GetNormal()) |
| 440 |
bounds.append(plane.GetOrigin()) |
| 441 |
|
| 442 |
clipper.SetBoxClip(*bounds) |
| 443 |
clipper.Update() |
| 444 |
if crinkle: |
| 445 |
clipped = pv.wrap(crinkler.GetOutputDataObject(0)) |
| 446 |
else: |
| 447 |
clipped = _get_output(clipper, oport=port) |
| 448 |
box_clipped_mesh.shallow_copy(clipped) |
| 449 |
|
| 450 |
self.add_box_widget( |
| 451 |
callback=callback, |
| 452 |
bounds=mesh.bounds, |
| 453 |
factor=factor, |
| 454 |
rotation_enabled=rotation_enabled, |
| 455 |
use_planes=True, |
| 456 |
color=widget_color, |
| 457 |
outline_translation=outline_translation, |
| 458 |
interaction_event=interaction_event, |
| 459 |
) |
| 460 |
|
| 461 |
if crinkle: |
| 462 |
return self._plotter.add_mesh(crinkler, reset_camera=False, **kwargs) |
| 463 |
return self._plotter.add_mesh(clipper.GetOutputPort(port), reset_camera=False, **kwargs) |
| 464 |
|
| 465 |
@_deprecate_positional_args(allowed=['callback']) |
| 466 |
def add_plane_widget( # noqa: PLR0917 |
| 467 |
self, |
| 468 |
callback, |
| 469 |
normal='x', |
| 470 |
origin=None, |
| 471 |
bounds=None, |
| 472 |
factor=1.25, |
| 473 |
color=None, |
| 474 |
assign_to_axis=None, |
| 475 |
tubing: bool = False, # noqa: FBT001, FBT002 |
| 476 |
outline_translation: bool = False, # noqa: FBT001, FBT002 |
| 477 |
origin_translation: bool = True, # noqa: FBT001, FBT002 |
| 478 |
implicit: bool = True, # noqa: FBT001, FBT002 |
| 479 |
pass_widget: bool = False, # noqa: FBT001, FBT002 |
| 480 |
test_callback: bool = True, # noqa: FBT001, FBT002 |
| 481 |
normal_rotation: bool = True, # noqa: FBT001, FBT002 |
| 482 |
interaction_event: InteractionEventType = 'end', |
| 483 |
outline_opacity=None, |
| 484 |
): |
| 485 |
"""Add a plane widget to the scene. |
| 486 |
|
| 487 |
This is useless without a callback function. You can pass a |
| 488 |
callable function that takes two arguments, the normal and |
| 489 |
origin of the plane in that order output from this widget, and |
| 490 |
performs a task with that plane. |
| 491 |
|
| 492 |
Parameters |
| 493 |
---------- |
| 494 |
callback : callable |
| 495 |
The method called every time the plane is updated. Takes |
| 496 |
two arguments, the normal and origin of the plane in that |
| 497 |
order. |
| 498 |
|
| 499 |
normal : str or tuple(float) |
| 500 |
The starting normal vector of the plane. |
| 501 |
|
| 502 |
origin : tuple(float) |
| 503 |
The starting coordinate of the center of the plane. |
| 504 |
|
| 505 |
bounds : tuple(float) |
| 506 |
Length 6 tuple of the bounding box where the widget is placed. |
| 507 |
|
| 508 |
color : ColorLike, optional |
| 509 |
Either a string, rgb list, or hex color string. |
| 510 |
|
| 511 |
factor : float, optional |
| 512 |
An inflation factor to expand on the bounds when placing. |
| 513 |
|
| 514 |
assign_to_axis : str or int, optional |
| 515 |
Assign the normal of the plane to be parallel with a given |
| 516 |
axis: options are ``(0, 'x')``, ``(1, 'y')``, or ``(2, |
| 517 |
'z')``. |
| 518 |
|
| 519 |
tubing : bool, optional |
| 520 |
When using an implicit plane widget, this controls whether |
| 521 |
or not tubing is shown around the plane's boundaries. |
| 522 |
|
| 523 |
outline_translation : bool, optional |
| 524 |
If ``False``, the plane widget cannot be translated and is |
| 525 |
strictly placed at the given bounds. Only valid when using |
| 526 |
an implicit plane. |
| 527 |
|
| 528 |
origin_translation : bool, optional |
| 529 |
If ``False``, the plane widget cannot be translated by its |
| 530 |
origin and is strictly placed at the given origin. Only |
| 531 |
valid when using an implicit plane. |
| 532 |
|
| 533 |
implicit : bool, optional |
| 534 |
When ``True``, a :vtk:`vtkImplicitPlaneWidget` is used and |
| 535 |
when ``False``, a :vtk:`vtkPlaneWidget` is used. |
| 536 |
|
| 537 |
pass_widget : bool, optional |
| 538 |
If ``True``, the widget will be passed as the last |
| 539 |
argument of the callback. |
| 540 |
|
| 541 |
test_callback : bool, optional |
| 542 |
If ``True``, run the callback function after the widget is |
| 543 |
created. |
| 544 |
|
| 545 |
normal_rotation : bool, optional |
| 546 |
Set the opacity of the normal vector arrow to 0 such that |
| 547 |
it is effectively disabled. This prevents the user from |
| 548 |
rotating the normal. This is forced to ``False`` when |
| 549 |
``assign_to_axis`` is set. |
| 550 |
|
| 551 |
interaction_event : InteractionEventType, optional |
| 552 |
The VTK interaction event to use for triggering the |
| 553 |
callback. Accepts either the strings ``'start'``, ``'end'``, |
| 554 |
``'always'`` or a :vtk:`vtkCommand.EventIds`. |
| 555 |
|
| 556 |
.. versionchanged:: 0.38.0 |
| 557 |
Now accepts either strings and :vtk:`vtkCommand.EventIds`. |
| 558 |
|
| 559 |
outline_opacity : bool or float, optional |
| 560 |
Set the visible of outline. Only valid when using |
| 561 |
an implicit plane. Either a bool or float. |
| 562 |
|
| 563 |
.. versionadded:: 0.44.0 |
| 564 |
|
| 565 |
Returns |
| 566 |
------- |
| 567 |
output : :vtk:`vtkImplicitPlaneWidget` | :vtk:`vtkPlaneWidget` |
| 568 |
Plane widget. |
| 569 |
|
| 570 |
Examples |
| 571 |
-------- |
| 572 |
Shows an interactive plane moving along the x-axis in the random-hill example, |
| 573 |
which is used to mark the max altitude at a particular distance x. |
| 574 |
|
| 575 |
>>> import pyvista as pv |
| 576 |
>>> from pyvista import examples |
| 577 |
>>> mesh = examples.load_random_hills() |
| 578 |
>>> pl = pv.Plotter() |
| 579 |
>>> _ = pl.add_mesh(mesh) |
| 580 |
>>> def callback(normal, origin): |
| 581 |
... slc = mesh.slice(normal=normal, origin=origin) |
| 582 |
... origin = list(origin) |
| 583 |
... origin[2] = slc.bounds.z_max |
| 584 |
... peak_plane = pv.Plane( |
| 585 |
... center=origin, |
| 586 |
... direction=[0, 0, 1], |
| 587 |
... i_size=20, |
| 588 |
... j_size=20, |
| 589 |
... ) |
| 590 |
... _ = pl.add_mesh(peak_plane, name='Peak', color='red', opacity=0.4) |
| 591 |
>>> _ = pl.add_plane_widget(callback, normal_rotation=False) |
| 592 |
>>> pl.show() |
| 593 |
|
| 594 |
""" |
| 595 |
if origin is None: |
| 596 |
origin = self._plotter.center |
| 597 |
if bounds is None: |
| 598 |
bounds = self._plotter.bounds |
| 599 |
|
| 600 |
if isinstance(normal, str): |
| 601 |
normal = _NORMALS[normal.lower()] |
| 602 |
|
| 603 |
color = Color(color, default_color=pv.global_theme.font.color) |
| 604 |
|
| 605 |
if assign_to_axis: |
| 606 |
normal_rotation = False |
| 607 |
|
| 608 |
def _the_callback(widget, _event): |
| 609 |
the_plane = _vtk.vtkPlane() |
| 610 |
widget.GetPlane(the_plane) |
| 611 |
normal = the_plane.GetNormal() |
| 612 |
origin = the_plane.GetOrigin() |
| 613 |
if callable(callback): |
| 614 |
if pass_widget: |
| 615 |
try_callback(callback, normal, origin, widget) |
| 616 |
else: |
| 617 |
try_callback(callback, normal, origin) |
| 618 |
|
| 619 |
if implicit: |
| 620 |
plane_widget = _vtk.vtkImplicitPlaneWidget() |
| 621 |
plane_widget.GetNormalProperty().SetColor(color.float_rgb) |
| 622 |
plane_widget.GetOutlineProperty().SetColor(color.float_rgb) |
| 623 |
plane_widget.GetOutlineProperty().SetColor(color.float_rgb) |
| 624 |
plane_widget.GetOutlineProperty().SetOpacity(color.opacity) |
| 625 |
plane_widget.SetTubing(tubing) |
| 626 |
plane_widget.SetOutlineTranslation(outline_translation) |
| 627 |
plane_widget.SetOriginTranslation(origin_translation) |
| 628 |
|
| 629 |
_start_interact = lambda plane_widget, event: plane_widget.SetDrawPlane(True) # noqa: ARG005 |
| 630 |
_stop_interact = lambda plane_widget, event: plane_widget.SetDrawPlane(False) # noqa: ARG005 |
| 631 |
|
| 632 |
plane_widget.SetDrawPlane(False) |
| 633 |
plane_widget.AddObserver(_vtk.vtkCommand.StartInteractionEvent, _start_interact) |
| 634 |
plane_widget.AddObserver(_vtk.vtkCommand.EndInteractionEvent, _stop_interact) |
| 635 |
plane_widget.SetPlaceFactor(factor) |
| 636 |
plane_widget.PlaceWidget(bounds) |
| 637 |
plane_widget.SetOrigin(origin) |
| 638 |
|
| 639 |
if not normal_rotation: |
| 640 |
plane_widget.GetNormalProperty().SetOpacity(0) |
| 641 |
|
| 642 |
if outline_opacity is not None: |
| 643 |
plane_widget.GetOutlineProperty().SetOpacity(float(outline_opacity)) |
| 644 |
|
| 645 |
else: |
| 646 |
# Position of the small plane |
| 647 |
source = _vtk.vtkPlaneSource() |
| 648 |
source.SetNormal(normal) |
| 649 |
source.SetCenter(origin) |
| 650 |
source.SetPoint1( |
| 651 |
origin[0] + (bounds[1] - bounds[0]) * 0.01, |
| 652 |
origin[1] - (bounds[3] - bounds[2]) * 0.01, |
| 653 |
origin[2], |
| 654 |
) |
| 655 |
source.SetPoint2( |
| 656 |
origin[0] - (bounds[1] - bounds[0]) * 0.01, |
| 657 |
origin[1] + (bounds[3] - bounds[2]) * 0.01, |
| 658 |
origin[2], |
| 659 |
) |
| 660 |
source.Update() |
| 661 |
plane_widget = _vtk.vtkPlaneWidget() # type: ignore[assignment] |
| 662 |
plane_widget.SetHandleSize(0.01) |
| 663 |
# Position of the widget |
| 664 |
plane_widget.SetInputData(source.GetOutput()) |
| 665 |
plane_widget.SetRepresentationToOutline() # type: ignore[attr-defined] |
| 666 |
plane_widget.SetPlaceFactor(factor) |
| 667 |
plane_widget.PlaceWidget(bounds) |
| 668 |
plane_widget.SetCenter(origin) # type: ignore[attr-defined] # Necessary |
| 669 |
plane_widget.GetPlaneProperty().SetColor(color.float_rgb) # self.C_LOT[fn]) |
| 670 |
plane_widget.GetHandleProperty().SetColor(color.float_rgb) # type: ignore[attr-defined] |
| 671 |
|
| 672 |
if not normal_rotation: |
| 673 |
plane_widget.GetHandleProperty().SetOpacity(0) # type: ignore[attr-defined] |
| 674 |
|
| 675 |
plane_widget.GetPlaneProperty().SetOpacity(0.5) |
| 676 |
plane_widget.SetInteractor(self._plotter.iren.interactor) |
| 677 |
plane_widget.SetCurrentRenderer(self._plotter.renderer) |
| 678 |
|
| 679 |
if assign_to_axis: |
| 680 |
# Note that normal_rotation was forced to False |
| 681 |
if assign_to_axis in [0, 'x', 'X']: |
| 682 |
plane_widget.NormalToXAxisOn() |
| 683 |
plane_widget.SetNormal(_NORMALS['x']) # type: ignore[arg-type] |
| 684 |
elif assign_to_axis in [1, 'y', 'Y']: |
| 685 |
plane_widget.NormalToYAxisOn() |
| 686 |
plane_widget.SetNormal(_NORMALS['y']) # type: ignore[arg-type] |
| 687 |
elif assign_to_axis in [2, 'z', 'Z']: |
| 688 |
plane_widget.NormalToZAxisOn() |
| 689 |
plane_widget.SetNormal(_NORMALS['z']) # type: ignore[arg-type] |
| 690 |
else: |
| 691 |
msg = 'assign_to_axis not understood' |
| 692 |
raise RuntimeError(msg) |
| 693 |
else: |
| 694 |
plane_widget.SetNormal(normal) |
| 695 |
|
| 696 |
plane_widget.Modified() |
| 697 |
plane_widget.UpdatePlacement() |
| 698 |
plane_widget.On() |
| 699 |
plane_widget.AddObserver( |
| 700 |
_parse_interaction_event(interaction_event), |
| 701 |
_the_callback, |
| 702 |
) |
| 703 |
if test_callback: |
| 704 |
_the_callback(plane_widget, None) # Trigger immediate update |
| 705 |
|
| 706 |
self.plane_widgets.append(plane_widget) |
| 707 |
return plane_widget |
| 708 |
|
| 709 |
def clear_plane_widgets(self): |
| 710 |
"""Remove all of the plane widgets.""" |
| 711 |
for plane_widget in self.plane_widgets: |
| 712 |
plane_widget.Off() |
| 713 |
self.plane_widgets.clear() |
| 714 |
|
| 715 |
@_deprecate_positional_args(allowed=['mesh']) |
| 716 |
def add_mesh_clip_plane( # noqa: PLR0917 |
| 717 |
self, |
| 718 |
mesh, |
| 719 |
normal='x', |
| 720 |
invert: bool = False, # noqa: FBT001, FBT002 |
| 721 |
widget_color=None, |
| 722 |
value=0.0, |
| 723 |
factor=1.25, |
| 724 |
assign_to_axis=None, |
| 725 |
tubing: bool = False, # noqa: FBT001, FBT002 |
| 726 |
origin_translation: bool = True, # noqa: FBT001, FBT002 |
| 727 |
outline_translation: bool = False, # noqa: FBT001, FBT002 |
| 728 |
implicit: bool = True, # noqa: FBT001, FBT002 |
| 729 |
normal_rotation: bool = True, # noqa: FBT001, FBT002 |
| 730 |
crinkle: bool = False, # noqa: FBT001, FBT002 |
| 731 |
interaction_event: InteractionEventType = 'end', |
| 732 |
origin=None, |
| 733 |
outline_opacity=None, |
| 734 |
**kwargs, |
| 735 |
): |
| 736 |
"""Clip a mesh using a plane widget. |
| 737 |
|
| 738 |
Add a mesh to the scene with a plane widget that is used to clip |
| 739 |
the mesh interactively. |
| 740 |
|
| 741 |
The clipped mesh is saved to the ``.plane_clipped_meshes`` |
| 742 |
attribute on the plotter. |
| 743 |
|
| 744 |
Parameters |
| 745 |
---------- |
| 746 |
mesh : DataSet or :vtk:`vtkAlgorithm` |
| 747 |
The input dataset to add to the scene and clip or algorithm that |
| 748 |
produces said mesh. |
| 749 |
|
| 750 |
normal : str or tuple(float), optional |
| 751 |
The starting normal vector of the plane. |
| 752 |
|
| 753 |
invert : bool, optional |
| 754 |
Flag on whether to flip/invert the clip. |
| 755 |
|
| 756 |
widget_color : ColorLike, optional |
| 757 |
Either a string, RGB list, or hex color string. |
| 758 |
|
| 759 |
value : float, optional |
| 760 |
Set the clipping value along the normal direction. |
| 761 |
The default value is 0.0. |
| 762 |
|
| 763 |
factor : float, optional |
| 764 |
An inflation factor to expand on the bounds when placing. |
| 765 |
|
| 766 |
assign_to_axis : str or int, optional |
| 767 |
Assign the normal of the plane to be parallel with a given |
| 768 |
axis. Options are ``(0, 'x')``, ``(1, 'y')``, or ``(2, |
| 769 |
'z')``. |
| 770 |
|
| 771 |
tubing : bool, optional |
| 772 |
When using an implicit plane widget, this controls whether |
| 773 |
or not tubing is shown around the plane's boundaries. |
| 774 |
|
| 775 |
origin_translation : bool, optional |
| 776 |
If ``False``, the plane widget cannot be translated by its |
| 777 |
origin and is strictly placed at the given origin. Only |
| 778 |
valid when using an implicit plane. |
| 779 |
|
| 780 |
outline_translation : bool, optional |
| 781 |
If ``False``, the box widget cannot be translated and is |
| 782 |
strictly placed at the given bounds. |
| 783 |
|
| 784 |
implicit : bool, optional |
| 785 |
When ``True``, a :vtk:`vtkImplicitPlaneWidget` is used and |
| 786 |
when ``False``, a :vtk:`vtkPlaneWidget` is used. |
| 787 |
|
| 788 |
normal_rotation : bool, optional |
| 789 |
Set the opacity of the normal vector arrow to 0 such that |
| 790 |
it is effectively disabled. This prevents the user from |
| 791 |
rotating the normal. This is forced to ``False`` when |
| 792 |
``assign_to_axis`` is set. |
| 793 |
|
| 794 |
crinkle : bool, optional |
| 795 |
Crinkle the clip by extracting the entire cells along the clip. |
| 796 |
|
| 797 |
interaction_event : InteractionEventType, optional |
| 798 |
The VTK interaction event to use for triggering the |
| 799 |
callback. Accepts either the strings ``'start'``, ``'end'``, |
| 800 |
``'always'`` or a :vtk:`vtkCommand.EventIds`. |
| 801 |
|
| 802 |
.. versionchanged:: 0.38.0 |
| 803 |
Now accepts either strings or :vtk:`vtkCommand.EventIds`. |
| 804 |
|
| 805 |
origin : tuple(float), optional |
| 806 |
The starting coordinate of the center of the plane. |
| 807 |
|
| 808 |
outline_opacity : bool or float, optional |
| 809 |
Set the visible of outline. Only valid when using |
| 810 |
an implicit plane. Either a bool or float. |
| 811 |
|
| 812 |
.. versionadded:: 0.44.0 |
| 813 |
|
| 814 |
**kwargs : dict, optional |
| 815 |
All additional keyword arguments are passed to |
| 816 |
:func:`pyvista.Plotter.add_mesh` to control how the mesh is |
| 817 |
displayed. |
| 818 |
|
| 819 |
Returns |
| 820 |
------- |
| 821 |
:vtk:`vtkActor` |
| 822 |
VTK actor of the mesh. |
| 823 |
|
| 824 |
Examples |
| 825 |
-------- |
| 826 |
Shows an interactive plane used to clip the mesh and store it. |
| 827 |
|
| 828 |
>>> import pyvista as pv |
| 829 |
>>> from pyvista import examples |
| 830 |
>>> vol = examples.load_airplane() |
| 831 |
>>> pl = pv.Plotter() |
| 832 |
>>> _ = pl.add_mesh_clip_plane(vol, normal=[0, -1, 0]) |
| 833 |
>>> pl.show(cpos=[-2.1, 0.6, 1.5]) |
| 834 |
>>> pl.widgets.plane_clipped_meshes # doctest:+SKIP |
| 835 |
|
| 836 |
For a full example see :ref:`plane_widget_example`. |
| 837 |
|
| 838 |
""" |
| 839 |
from pyvista.core.filters import _get_output # avoids circular import |
| 840 |
|
| 841 |
mesh, algo = algorithm_to_mesh_handler( |
| 842 |
add_ids_algorithm(mesh, point_ids=False, cell_ids=True), |
| 843 |
) |
| 844 |
|
| 845 |
name = kwargs.get('name', mesh.memory_address) |
| 846 |
rng = mesh.get_data_range(kwargs.get('scalars')) |
| 847 |
kwargs.setdefault('clim', kwargs.pop('rng', rng)) |
| 848 |
mesh.set_active_scalars(kwargs.get('scalars', mesh.active_scalars_name)) |
| 849 |
if origin is None: |
| 850 |
origin = mesh.center |
| 851 |
|
| 852 |
self._plotter.add_mesh(outline_algorithm(algo), name=f'{name}-outline', opacity=0.0) |
| 853 |
|
| 854 |
if isinstance(mesh, _vtk.vtkPolyData): |
| 855 |
clipper = _vtk.vtkClipPolyData() |
| 856 |
# elif isinstance(mesh, vtk.vtkImageData): |
| 857 |
# clipper = vtk.vtkClipVolume() |
| 858 |
# clipper.SetMixed3DCellGeneration(True) |
| 859 |
else: |
| 860 |
clipper = _vtk.vtkTableBasedClipDataSet() # type: ignore[assignment] |
| 861 |
set_algorithm_input(clipper, algo) |
| 862 |
clipper.SetValue(value) |
| 863 |
clipper.SetInsideOut(invert) # invert the clip if needed |
| 864 |
|
| 865 |
if crinkle: |
| 866 |
crinkler = crinkle_algorithm(clipper, algo) |
| 867 |
plane_clipped_mesh = _get_output(crinkler) |
| 868 |
else: |
| 869 |
plane_clipped_mesh = _get_output(clipper) |
| 870 |
self.plane_clipped_meshes.append(plane_clipped_mesh) |
| 871 |
|
| 872 |
def callback(normal, loc): |
| 873 |
function = generate_plane(normal, loc) |
| 874 |
clipper.SetClipFunction(function) # the implicit function |
| 875 |
clipper.Update() # Perform the Cut |
| 876 |
if crinkle: |
| 877 |
clipped = pv.wrap(crinkler.GetOutputDataObject(0)) |
| 878 |
else: |
| 879 |
clipped = pv.wrap(clipper.GetOutput()) |
| 880 |
plane_clipped_mesh.shallow_copy(clipped) |
| 881 |
|
| 882 |
self.add_plane_widget( |
| 883 |
callback=callback, |
| 884 |
bounds=mesh.bounds, |
| 885 |
factor=factor, |
| 886 |
normal=normal, |
| 887 |
color=widget_color, |
| 888 |
tubing=tubing, |
| 889 |
assign_to_axis=assign_to_axis, |
| 890 |
origin_translation=origin_translation, |
| 891 |
outline_translation=outline_translation, |
| 892 |
implicit=implicit, |
| 893 |
origin=origin, |
| 894 |
normal_rotation=normal_rotation, |
| 895 |
interaction_event=interaction_event, |
| 896 |
outline_opacity=outline_opacity, |
| 897 |
) |
| 898 |
|
| 899 |
if crinkle: |
| 900 |
return self._plotter.add_mesh(crinkler, **kwargs) |
| 901 |
return self._plotter.add_mesh(clipper, **kwargs) |
| 902 |
|
| 903 |
@_deprecate_positional_args(allowed=['volume']) |
| 904 |
def add_volume_clip_plane( # noqa: PLR0917 |
| 905 |
self, |
| 906 |
volume, |
| 907 |
normal='x', |
| 908 |
invert: bool = False, # noqa: ARG002, FBT001, FBT002 |
| 909 |
widget_color=None, |
| 910 |
value=0.0, # noqa: ARG002 |
| 911 |
factor=1.25, |
| 912 |
assign_to_axis=None, |
| 913 |
tubing: bool = False, # noqa: FBT001, FBT002 |
| 914 |
origin_translation: bool = True, # noqa: FBT001, FBT002 |
| 915 |
outline_translation: bool = False, # noqa: FBT001, FBT002 |
| 916 |
implicit: bool = True, # noqa: FBT001, FBT002 |
| 917 |
normal_rotation: bool = True, # noqa: FBT001, FBT002 |
| 918 |
interaction_event: InteractionEventType = 'end', |
| 919 |
origin=None, |
| 920 |
outline_opacity=None, |
| 921 |
**kwargs, |
| 922 |
): |
| 923 |
"""Clip a volume using a plane widget. |
| 924 |
|
| 925 |
Parameters |
| 926 |
---------- |
| 927 |
volume : pyvista.plotting.volume.Volume or pyvista.ImageData or pyvista.RectilinearGrid |
| 928 |
New dataset of type :class:`pyvista.ImageData` or |
| 929 |
:class:`pyvista.RectilinearGrid`, or the return value from |
| 930 |
:class:`pyvista.plotting.volume.Volume` from :func:`pyvista.Plotter.add_volume`. |
| 931 |
|
| 932 |
normal : str or tuple(float), optional |
| 933 |
The starting normal vector of the plane. |
| 934 |
|
| 935 |
invert : bool, optional |
| 936 |
Flag on whether to flip/invert the clip. |
| 937 |
|
| 938 |
widget_color : ColorLike, optional |
| 939 |
Either a string, RGB list, or hex color string. |
| 940 |
|
| 941 |
value : float, optional |
| 942 |
Set the clipping value along the normal direction. |
| 943 |
The default value is 0.0. |
| 944 |
|
| 945 |
factor : float, optional |
| 946 |
An inflation factor to expand on the bounds when placing. |
| 947 |
|
| 948 |
assign_to_axis : str or int, optional |
| 949 |
Assign the normal of the plane to be parallel with a given |
| 950 |
axis. Options are ``(0, 'x')``, ``(1, 'y')``, or ``(2, |
| 951 |
'z')``. |
| 952 |
|
| 953 |
tubing : bool, optional |
| 954 |
When using an implicit plane widget, this controls whether |
| 955 |
or not tubing is shown around the plane's boundaries. |
| 956 |
|
| 957 |
origin_translation : bool, optional |
| 958 |
If ``False``, the plane widget cannot be translated by its |
| 959 |
origin and is strictly placed at the given origin. Only |
| 960 |
valid when using an implicit plane. |
| 961 |
|
| 962 |
outline_translation : bool, optional |
| 963 |
If ``False``, the box widget cannot be translated and is |
| 964 |
strictly placed at the given bounds. |
| 965 |
|
| 966 |
implicit : bool, optional |
| 967 |
When ``True``, a :vtk:`vtkImplicitPlaneWidget` is used and |
| 968 |
when ``False``, a :vtk:`vtkPlaneWidget` is used. |
| 969 |
|
| 970 |
normal_rotation : bool, optional |
| 971 |
Set the opacity of the normal vector arrow to 0 such that |
| 972 |
it is effectively disabled. This prevents the user from |
| 973 |
rotating the normal. This is forced to ``False`` when |
| 974 |
``assign_to_axis`` is set. |
| 975 |
|
| 976 |
interaction_event : :vtk:`vtkCommand.EventIds`, optional |
| 977 |
The VTK interaction event to use for triggering the callback. |
| 978 |
|
| 979 |
origin : tuple(float), optional |
| 980 |
The starting coordinate of the center of the plane. |
| 981 |
|
| 982 |
outline_opacity : bool or float, optional |
| 983 |
Set the visible of outline. Only valid when using |
| 984 |
an implicit plane. Either a bool or float. |
| 985 |
|
| 986 |
.. versionadded:: 0.44.0 |
| 987 |
|
| 988 |
**kwargs : dict, optional |
| 989 |
All additional keyword arguments are passed to |
| 990 |
:func:`pyvista.Plotter.add_volume` to control how the volume is |
| 991 |
displayed. Only applicable if ``volume`` is either a |
| 992 |
:class:`pyvista.ImageData` and :class:`pyvista.RectilinearGrid`. |
| 993 |
|
| 994 |
Returns |
| 995 |
------- |
| 996 |
output : :vtk:`vtkPlaneWidget` | :vtk:`vtkImplicitPlaneWidget` |
| 997 |
The VTK plane widget depending on the value of ``implicit``. |
| 998 |
|
| 999 |
See Also |
| 1000 |
-------- |
| 1001 |
:ref:`clip_volume_widget_example` |
| 1002 |
|
| 1003 |
""" |
| 1004 |
if isinstance(volume, (pv.ImageData, pv.RectilinearGrid)): |
| 1005 |
volume = self._plotter.add_volume(volume, **kwargs) |
| 1006 |
elif not isinstance(volume, pv.plotting.volume.Volume): |
| 1007 |
msg = ( |
| 1008 |
'The `volume` parameter type must be either pyvista.ImageData, ' |
| 1009 |
'pyvista.RectilinearGrid, or a pyvista.plotting.volume.Volume ' |
| 1010 |
'from `Plotter.add_volume`.' |
| 1011 |
) |
| 1012 |
raise TypeError(msg) |
| 1013 |
else: |
| 1014 |
assert_empty_kwargs(**kwargs) |
| 1015 |
|
| 1016 |
plane = _vtk.vtkPlane() |
| 1017 |
|
| 1018 |
def callback(normal, origin): # numpydoc ignore=PR01 |
| 1019 |
"""Update the plane used to clip the volume.""" |
| 1020 |
plane.SetNormal(normal) |
| 1021 |
plane.SetOrigin(origin) |
| 1022 |
|
| 1023 |
widget = self.add_plane_widget( |
| 1024 |
callback=callback, |
| 1025 |
bounds=volume.bounds, |
| 1026 |
factor=factor, |
| 1027 |
normal=normal, |
| 1028 |
color=widget_color, |
| 1029 |
tubing=tubing, |
| 1030 |
assign_to_axis=assign_to_axis, |
| 1031 |
origin_translation=origin_translation, |
| 1032 |
outline_translation=outline_translation, |
| 1033 |
implicit=implicit, |
| 1034 |
origin=origin, |
| 1035 |
normal_rotation=normal_rotation, |
| 1036 |
interaction_event=interaction_event, |
| 1037 |
outline_opacity=outline_opacity, |
| 1038 |
) |
| 1039 |
widget.GetPlane(plane) |
| 1040 |
volume.mapper.AddClippingPlane(plane) |
| 1041 |
self.plane_widgets.append(widget) |
| 1042 |
|
| 1043 |
return widget |
| 1044 |
|
| 1045 |
@_deprecate_positional_args(allowed=['mesh']) |
| 1046 |
def add_mesh_slice( # noqa: PLR0917 |
| 1047 |
self, |
| 1048 |
mesh, |
| 1049 |
normal='x', |
| 1050 |
generate_triangles: bool = False, # noqa: FBT001, FBT002 |
| 1051 |
widget_color=None, |
| 1052 |
assign_to_axis=None, |
| 1053 |
tubing: bool = False, # noqa: FBT001, FBT002 |
| 1054 |
factor: float = 1.25, |
| 1055 |
origin_translation: bool = True, # noqa: FBT001, FBT002 |
| 1056 |
outline_translation: bool = False, # noqa: FBT001, FBT002 |
| 1057 |
implicit: bool = True, # noqa: FBT001, FBT002 |
| 1058 |
normal_rotation: bool = True, # noqa: FBT001, FBT002 |
| 1059 |
interaction_event: InteractionEventType = 'end', |
| 1060 |
origin=None, |
| 1061 |
outline_opacity=None, |
| 1062 |
**kwargs, |
| 1063 |
): |
| 1064 |
"""Slice a mesh using a plane widget. |
| 1065 |
|
| 1066 |
Add a mesh to the scene with a plane widget that is used to slice |
| 1067 |
the mesh interactively. |
| 1068 |
|
| 1069 |
The sliced mesh is saved to the ``.plane_sliced_meshes`` attribute on |
| 1070 |
the plotter. |
| 1071 |
|
| 1072 |
Parameters |
| 1073 |
---------- |
| 1074 |
mesh : DataSet | :vtk:`vtkAlgorithm` |
| 1075 |
The input dataset to add to the scene and slice or algorithm that |
| 1076 |
produces said mesh. |
| 1077 |
|
| 1078 |
normal : str or tuple(float), optional |
| 1079 |
The starting normal vector of the plane. |
| 1080 |
|
| 1081 |
generate_triangles : bool, optional |
| 1082 |
If this is enabled (``False`` by default), the output will be |
| 1083 |
triangles otherwise, the output will be the intersection polygons. |
| 1084 |
|
| 1085 |
widget_color : ColorLike, optional |
| 1086 |
Either a string, RGB sequence, or hex color string. Defaults |
| 1087 |
to ``'white'``. |
| 1088 |
|
| 1089 |
assign_to_axis : str or int, optional |
| 1090 |
Assign the normal of the plane to be parallel with a given axis: |
| 1091 |
options are (0, 'x'), (1, 'y'), or (2, 'z'). |
| 1092 |
|
| 1093 |
factor : float, optional |
| 1094 |
Expands the plane bounds. 1.0 means the plane bounds are exactly |
| 1095 |
the bounds of the mesh. |
| 1096 |
|
| 1097 |
tubing : bool, optional |
| 1098 |
When using an implicit plane widget, this controls whether or not |
| 1099 |
tubing is shown around the plane's boundaries. |
| 1100 |
|
| 1101 |
origin_translation : bool, optional |
| 1102 |
If ``False``, the plane widget cannot be translated by its origin |
| 1103 |
and is strictly placed at the given origin. Only valid when using |
| 1104 |
an implicit plane. |
| 1105 |
|
| 1106 |
outline_translation : bool, optional |
| 1107 |
If ``False``, the box widget cannot be translated and is strictly |
| 1108 |
placed at the given bounds. |
| 1109 |
|
| 1110 |
implicit : bool, optional |
| 1111 |
When ``True``, a :vtk:`vtkImplicitPlaneWidget` is used and when |
| 1112 |
``False``, a :vtk:`vtkPlaneWidget` is used. |
| 1113 |
|
| 1114 |
normal_rotation : bool, optional |
| 1115 |
Set the opacity of the normal vector arrow to 0 such that it is |
| 1116 |
effectively disabled. This prevents the user from rotating the |
| 1117 |
normal. This is forced to ``False`` when ``assign_to_axis`` is set. |
| 1118 |
|
| 1119 |
interaction_event : InteractionEventType, optional |
| 1120 |
The VTK interaction event to use for triggering the |
| 1121 |
callback. Accepts either the strings ``'start'``, ``'end'``, |
| 1122 |
``'always'`` or a :vtk:`vtkCommand.EventIds`. |
| 1123 |
|
| 1124 |
origin : tuple(float), optional |
| 1125 |
The starting coordinate of the center of the plane. |
| 1126 |
|
| 1127 |
outline_opacity : bool or float, optional |
| 1128 |
Set the visible of outline. Only valid when using |
| 1129 |
an implicit plane. Either a bool or float. |
| 1130 |
|
| 1131 |
.. versionadded:: 0.44.0 |
| 1132 |
|
| 1133 |
**kwargs : dict, optional |
| 1134 |
All additional keyword arguments are passed to |
| 1135 |
:func:`pyvista.Plotter.add_mesh` to control how the mesh is |
| 1136 |
displayed. |
| 1137 |
|
| 1138 |
Returns |
| 1139 |
------- |
| 1140 |
:vtk:`vtkActor` |
| 1141 |
VTK actor of the mesh. |
| 1142 |
|
| 1143 |
Examples |
| 1144 |
-------- |
| 1145 |
Shows an interactive plane used specifically for slicing. |
| 1146 |
|
| 1147 |
>>> import pyvista as pv |
| 1148 |
>>> from pyvista import examples |
| 1149 |
>>> pl = pv.Plotter() |
| 1150 |
>>> mesh = examples.load_channels() |
| 1151 |
>>> _ = pl.add_mesh(mesh.outline()) |
| 1152 |
>>> _ = pl.add_mesh_slice(mesh, normal=[1, 0, 0.3]) |
| 1153 |
>>> pl.show() |
| 1154 |
|
| 1155 |
For a full example see :ref:`plane_widget_example`. |
| 1156 |
|
| 1157 |
""" |
| 1158 |
mesh, algo = algorithm_to_mesh_handler(mesh) |
| 1159 |
|
| 1160 |
name = kwargs.get('name', mesh.memory_address) |
| 1161 |
rng = mesh.get_data_range(kwargs.get('scalars')) |
| 1162 |
kwargs.setdefault('clim', kwargs.pop('rng', rng)) |
| 1163 |
mesh.set_active_scalars(kwargs.get('scalars', mesh.active_scalars_name)) |
| 1164 |
if origin is None: |
| 1165 |
origin = mesh.center |
| 1166 |
|
| 1167 |
self._plotter.add_mesh( |
| 1168 |
outline_algorithm(algo or mesh), name=f'{name}-outline', opacity=0.0 |
| 1169 |
) |
| 1170 |
|
| 1171 |
alg = _vtk.vtkCutter() # Construct the cutter object |
| 1172 |
set_algorithm_input(alg, algo or mesh) |
| 1173 |
if not generate_triangles: |
| 1174 |
alg.GenerateTrianglesOff() |
| 1175 |
|
| 1176 |
plane_sliced_mesh = pv.wrap(alg.GetOutput()) |
| 1177 |
self.plane_sliced_meshes.append(plane_sliced_mesh) |
| 1178 |
|
| 1179 |
def callback(normal, origin): |
| 1180 |
# create the plane for clipping |
| 1181 |
plane = generate_plane(normal, origin) |
| 1182 |
alg.SetCutFunction(plane) # the cutter to use the plane we made |
| 1183 |
alg.Update() # Perform the Cut |
| 1184 |
plane_sliced_mesh.shallow_copy(alg.GetOutput()) |
| 1185 |
|
| 1186 |
self.add_plane_widget( |
| 1187 |
callback=callback, |
| 1188 |
bounds=mesh.bounds, |
| 1189 |
factor=factor, |
| 1190 |
normal=normal, |
| 1191 |
color=widget_color, |
| 1192 |
tubing=tubing, |
| 1193 |
assign_to_axis=assign_to_axis, |
| 1194 |
origin_translation=origin_translation, |
| 1195 |
outline_translation=outline_translation, |
| 1196 |
implicit=implicit, |
| 1197 |
origin=origin, |
| 1198 |
normal_rotation=normal_rotation, |
| 1199 |
interaction_event=_parse_interaction_event(interaction_event), |
| 1200 |
outline_opacity=outline_opacity, |
| 1201 |
) |
| 1202 |
|
| 1203 |
return self._plotter.add_mesh(alg, **kwargs) |
| 1204 |
|
| 1205 |
@_deprecate_positional_args(allowed=['mesh']) |
| 1206 |
def add_mesh_slice_orthogonal( # noqa: PLR0917 |
| 1207 |
self, |
| 1208 |
mesh, |
| 1209 |
generate_triangles: bool = False, # noqa: FBT001, FBT002 |
| 1210 |
widget_color=None, |
| 1211 |
tubing: bool = False, # noqa: FBT001, FBT002 |
| 1212 |
interaction_event: InteractionEventType = 'end', |
| 1213 |
**kwargs, |
| 1214 |
): |
| 1215 |
"""Slice a mesh with three interactive planes. |
| 1216 |
|
| 1217 |
Adds three interactive plane slicing widgets for orthogonal slicing |
| 1218 |
along each cartesian axis. |
| 1219 |
|
| 1220 |
Parameters |
| 1221 |
---------- |
| 1222 |
mesh : DataSet or :vtk:`vtkAlgorithm` |
| 1223 |
The input dataset to add to the scene and threshold or algorithm |
| 1224 |
that produces said mesh. |
| 1225 |
|
| 1226 |
generate_triangles : bool, optional |
| 1227 |
If this is enabled (``False`` by default), the output will be |
| 1228 |
triangles otherwise, the output will be the intersection polygons. |
| 1229 |
|
| 1230 |
widget_color : ColorLike, optional |
| 1231 |
Color of the widget. Either a string, RGB sequence, or |
| 1232 |
hex color string. For example: |
| 1233 |
|
| 1234 |
* ``color='white'`` |
| 1235 |
* ``color='w'`` |
| 1236 |
* ``color=[1.0, 1.0, 1.0]`` |
| 1237 |
* ``color='#FFFFFF'`` |
| 1238 |
|
| 1239 |
tubing : bool, optional |
| 1240 |
When using an implicit plane widget, this controls whether or not |
| 1241 |
tubing is shown around the plane's boundaries. |
| 1242 |
|
| 1243 |
interaction_event : InteractionEventType, optional |
| 1244 |
The VTK interaction event to use for triggering the |
| 1245 |
callback. Accepts either the strings ``'start'``, ``'end'``, |
| 1246 |
``'always'`` or a :vtk:`vtkCommand.EventIds`. |
| 1247 |
|
| 1248 |
**kwargs : dict, optional |
| 1249 |
All additional keyword arguments are passed to |
| 1250 |
:func:`pyvista.Plotter.add_mesh` to control how the mesh is |
| 1251 |
displayed. |
| 1252 |
|
| 1253 |
Returns |
| 1254 |
------- |
| 1255 |
list |
| 1256 |
List of :vtk:`vtkActor`. |
| 1257 |
|
| 1258 |
Examples |
| 1259 |
-------- |
| 1260 |
Shows an interactive plane sliced along each cartesian axis of the mesh. |
| 1261 |
|
| 1262 |
>>> import pyvista as pv |
| 1263 |
>>> pl = pv.Plotter() |
| 1264 |
>>> mesh = pv.Wavelet() |
| 1265 |
>>> _ = pl.add_mesh(mesh.outline()) |
| 1266 |
>>> _ = pl.add_mesh_slice_orthogonal(mesh) |
| 1267 |
>>> pl.show() |
| 1268 |
|
| 1269 |
""" |
| 1270 |
actors = [] |
| 1271 |
name = kwargs.pop('name', None) |
| 1272 |
for ax in ['x', 'y', 'z']: |
| 1273 |
axkwargs = kwargs.copy() |
| 1274 |
if name: |
| 1275 |
axkwargs['name'] = f'{name}-{ax}' |
| 1276 |
a = self.add_mesh_slice( |
| 1277 |
mesh, |
| 1278 |
assign_to_axis=ax, |
| 1279 |
origin_translation=False, |
| 1280 |
outline_translation=False, |
| 1281 |
generate_triangles=generate_triangles, |
| 1282 |
widget_color=widget_color, |
| 1283 |
tubing=tubing, |
| 1284 |
interaction_event=_parse_interaction_event(interaction_event), |
| 1285 |
**axkwargs, |
| 1286 |
) |
| 1287 |
actors.append(a) |
| 1288 |
|
| 1289 |
return actors |
| 1290 |
|
| 1291 |
@_deprecate_positional_args(allowed=['callback']) |
| 1292 |
def add_line_widget( # noqa: PLR0917 |
| 1293 |
self, |
| 1294 |
callback, |
| 1295 |
bounds=None, |
| 1296 |
factor=1.25, |
| 1297 |
resolution=100, |
| 1298 |
color=None, |
| 1299 |
use_vertices: bool = False, # noqa: FBT001, FBT002 |
| 1300 |
pass_widget: bool = False, # noqa: FBT001, FBT002 |
| 1301 |
interaction_event: InteractionEventType = 'end', |
| 1302 |
): |
| 1303 |
"""Add a line widget to the scene. |
| 1304 |
|
| 1305 |
This is useless without a callback function. You can pass a |
| 1306 |
callable function that takes a single argument, the PolyData |
| 1307 |
line output from this widget, and performs a task with that |
| 1308 |
line. |
| 1309 |
|
| 1310 |
Parameters |
| 1311 |
---------- |
| 1312 |
callback : callable |
| 1313 |
The method called every time the line is updated. This has |
| 1314 |
two options: Take a single argument, the ``PolyData`` line |
| 1315 |
(default) or if ``use_vertices=True``, then it can take |
| 1316 |
two arguments of the coordinates of the line's end points. |
| 1317 |
|
| 1318 |
bounds : tuple(float), optional |
| 1319 |
Length 6 tuple of the bounding box where the widget is |
| 1320 |
placed. |
| 1321 |
|
| 1322 |
factor : float, optional |
| 1323 |
An inflation factor to expand on the bounds when placing. |
| 1324 |
|
| 1325 |
resolution : int, optional |
| 1326 |
The number of points in the line created. |
| 1327 |
|
| 1328 |
color : ColorLike, optional |
| 1329 |
Either a string, rgb sequence, or hex color string. |
| 1330 |
|
| 1331 |
use_vertices : bool, optional |
| 1332 |
Changes the arguments of the callback method to take the end |
| 1333 |
points of the line instead of a PolyData object. |
| 1334 |
|
| 1335 |
pass_widget : bool, default: False |
| 1336 |
If ``True``, the widget will be passed as the last |
| 1337 |
argument of the callback. |
| 1338 |
|
| 1339 |
interaction_event : InteractionEventType, optional |
| 1340 |
The VTK interaction event to use for triggering the |
| 1341 |
callback. Accepts either the strings ``'start'``, ``'end'``, |
| 1342 |
``'always'`` or a :vtk:`vtkCommand.EventIds`. |
| 1343 |
|
| 1344 |
Returns |
| 1345 |
------- |
| 1346 |
:vtk:`vtkLineWidget` |
| 1347 |
Created line widget. |
| 1348 |
|
| 1349 |
Examples |
| 1350 |
-------- |
| 1351 |
Shows an interactive line widget to move the sliced object |
| 1352 |
like in `add_mesh_slice` function. |
| 1353 |
|
| 1354 |
>>> import pyvista as pv |
| 1355 |
>>> from pyvista import examples |
| 1356 |
>>> import numpy as np |
| 1357 |
>>> model = examples.load_channels() |
| 1358 |
>>> pl = pv.Plotter() |
| 1359 |
>>> _ = pl.add_mesh(model, opacity=0.4) |
| 1360 |
>>> def move_center(pointa, pointb): |
| 1361 |
... center = (np.array(pointa) + np.array(pointb)) / 2 |
| 1362 |
... normal = np.array(pointa) - np.array(pointb) |
| 1363 |
... single_slc = model.slice(normal=normal, origin=center) |
| 1364 |
... |
| 1365 |
... _ = pl.add_mesh(single_slc, name='slc') |
| 1366 |
>>> _ = pl.add_line_widget(callback=move_center, use_vertices=True) |
| 1367 |
>>> pl.show() |
| 1368 |
|
| 1369 |
""" |
| 1370 |
if bounds is None: |
| 1371 |
bounds = self._plotter.bounds |
| 1372 |
|
| 1373 |
color = Color(color, default_color=pv.global_theme.font.color) |
| 1374 |
|
| 1375 |
def _the_callback(widget, _event): |
| 1376 |
pointa = widget.GetPoint1() |
| 1377 |
pointb = widget.GetPoint2() |
| 1378 |
if callable(callback): |
| 1379 |
if use_vertices: |
| 1380 |
args = [pointa, pointb] |
| 1381 |
else: |
| 1382 |
the_line = pv.Line(pointa, pointb, resolution=resolution) |
| 1383 |
args = [the_line] |
| 1384 |
if pass_widget: |
| 1385 |
args.append(widget) |
| 1386 |
try_callback(callback, *args) |
| 1387 |
|
| 1388 |
line_widget = _vtk.vtkLineWidget() |
| 1389 |
line_widget.GetLineProperty().SetColor(color.float_rgb) |
| 1390 |
line_widget.SetInteractor(self._plotter.iren.interactor) |
| 1391 |
line_widget.SetCurrentRenderer(self._plotter.renderer) |
| 1392 |
line_widget.SetPlaceFactor(factor) |
| 1393 |
line_widget.PlaceWidget(bounds) |
| 1394 |
line_widget.SetResolution(resolution) |
| 1395 |
line_widget.Modified() |
| 1396 |
line_widget.On() |
| 1397 |
line_widget.AddObserver( |
| 1398 |
_parse_interaction_event(interaction_event), |
| 1399 |
_the_callback, |
| 1400 |
) |
| 1401 |
_the_callback(line_widget, None) |
| 1402 |
|
| 1403 |
self.line_widgets.append(line_widget) |
| 1404 |
return line_widget |
| 1405 |
|
| 1406 |
def clear_line_widgets(self): |
| 1407 |
"""Remove all of the line widgets.""" |
| 1408 |
for line_widget in self.line_widgets: |
| 1409 |
line_widget.Off() |
| 1410 |
self.line_widgets.clear() |
| 1411 |
|
| 1412 |
@_deprecate_positional_args(allowed=['callback', 'data']) |
| 1413 |
def add_text_slider_widget( # noqa: PLR0917 |
| 1414 |
self, |
| 1415 |
callback, |
| 1416 |
data, |
| 1417 |
value=None, |
| 1418 |
pointa=(0.4, 0.9), |
| 1419 |
pointb=(0.9, 0.9), |
| 1420 |
color=None, |
| 1421 |
interaction_event: InteractionEventType = 'end', |
| 1422 |
style=None, |
| 1423 |
): |
| 1424 |
"""Add a text slider bar widget. |
| 1425 |
|
| 1426 |
This is useless without a callback function. You can pass a callable |
| 1427 |
function that takes a single argument, the value of this slider widget, |
| 1428 |
and performs a task with that value. |
| 1429 |
|
| 1430 |
Parameters |
| 1431 |
---------- |
| 1432 |
callback : callable |
| 1433 |
The method called every time the slider is updated. This should take |
| 1434 |
a single parameter: the float value of the slider. |
| 1435 |
|
| 1436 |
data : list |
| 1437 |
The list of possible values displayed on the slider bar. |
| 1438 |
|
| 1439 |
value : float, optional |
| 1440 |
The starting value of the slider. |
| 1441 |
|
| 1442 |
pointa : tuple(float), optional |
| 1443 |
The relative coordinates of the left point of the slider on the |
| 1444 |
display port. |
| 1445 |
|
| 1446 |
pointb : tuple(float), optional |
| 1447 |
The relative coordinates of the right point of the slider on the |
| 1448 |
display port. |
| 1449 |
|
| 1450 |
color : ColorLike, optional |
| 1451 |
Either a string, RGB list, or hex color string. Defaults |
| 1452 |
to :attr:`pyvista.global_theme.font.color |
| 1453 |
<pyvista.plotting.themes._Font.color>`. |
| 1454 |
|
| 1455 |
interaction_event : InteractionEventType, optional |
| 1456 |
The VTK interaction event to use for triggering the |
| 1457 |
callback. Accepts either the strings ``'start'``, ``'end'``, |
| 1458 |
``'always'`` or a :vtk:`vtkCommand.EventIds`. |
| 1459 |
|
| 1460 |
.. versionchanged:: 0.38.0 |
| 1461 |
Changed from ``event_type`` to ``interaction_event`` and now |
| 1462 |
accepts either strings or :vtk:`vtkCommand.EventIds`. |
| 1463 |
|
| 1464 |
style : str, optional |
| 1465 |
The name of the slider style. The list of available styles |
| 1466 |
are in ``pyvista.global_theme.slider_styles``. Defaults to |
| 1467 |
``None``. |
| 1468 |
|
| 1469 |
|
| 1470 |
Returns |
| 1471 |
------- |
| 1472 |
:vtk:`vtkSliderWidget` |
| 1473 |
The VTK slider widget configured to display text. |
| 1474 |
|
| 1475 |
""" |
| 1476 |
if not isinstance(data, list): |
| 1477 |
msg = ( |
| 1478 |
f'The `data` parameter must be a list but {type(data).__name__} was passed instead' |
| 1479 |
) |
| 1480 |
raise TypeError(msg) |
| 1481 |
n_states = len(data) |
| 1482 |
if n_states == 0: |
| 1483 |
msg = 'The input list of values is empty' |
| 1484 |
raise ValueError(msg) |
| 1485 |
delta = (n_states - 1) / float(n_states) |
| 1486 |
# avoid division by zero in case there is only one element |
| 1487 |
delta = 1 if delta == 0 else delta |
| 1488 |
|
| 1489 |
def _the_callback(value): |
| 1490 |
if isinstance(value, float): |
| 1491 |
idx = int(value / delta) |
| 1492 |
# handle limit index |
| 1493 |
if idx == n_states: |
| 1494 |
idx = n_states - 1 |
| 1495 |
if callable(callback): |
| 1496 |
try_callback(callback, data[idx]) |
| 1497 |
|
| 1498 |
slider_widget = self.add_slider_widget( |
| 1499 |
callback=_the_callback, |
| 1500 |
rng=[0, n_states - 1], |
| 1501 |
value=value, |
| 1502 |
pointa=pointa, |
| 1503 |
pointb=pointb, |
| 1504 |
color=color, |
| 1505 |
interaction_event=interaction_event, |
| 1506 |
style=style, |
| 1507 |
) |
| 1508 |
slider_rep = slider_widget.GetRepresentation() |
| 1509 |
slider_rep.ShowSliderLabelOff() |
| 1510 |
|
| 1511 |
def title_callback(widget, _event): |
| 1512 |
value = widget.GetRepresentation().GetValue() |
| 1513 |
idx = int(value / delta) |
| 1514 |
# handle limit index |
| 1515 |
if idx == n_states: |
| 1516 |
idx = n_states - 1 |
| 1517 |
slider_rep.SetTitleText(data[idx]) |
| 1518 |
|
| 1519 |
slider_widget.AddObserver(_parse_interaction_event(interaction_event), title_callback) |
| 1520 |
title_callback(slider_widget, None) |
| 1521 |
return slider_widget |
| 1522 |
|
| 1523 |
@_deprecate_positional_args(allowed=['callback', 'rng']) |
| 1524 |
def add_slider_widget( # noqa: PLR0917 |
| 1525 |
self, |
| 1526 |
callback, |
| 1527 |
rng, |
| 1528 |
value=None, |
| 1529 |
title=None, |
| 1530 |
pointa=(0.4, 0.9), |
| 1531 |
pointb=(0.9, 0.9), |
| 1532 |
color=None, |
| 1533 |
pass_widget: bool = False, # noqa: FBT001, FBT002 |
| 1534 |
interaction_event: InteractionEventType = 'end', |
| 1535 |
style=None, |
| 1536 |
title_height=0.03, |
| 1537 |
title_opacity=1.0, |
| 1538 |
title_color=None, |
| 1539 |
fmt=None, |
| 1540 |
slider_width=None, |
| 1541 |
tube_width=None, |
| 1542 |
): |
| 1543 |
"""Add a slider bar widget. |
| 1544 |
|
| 1545 |
This is useless without a callback function. You can pass a |
| 1546 |
callable function that takes a single argument, the value of |
| 1547 |
this slider widget, and performs a task with that value. |
| 1548 |
|
| 1549 |
Parameters |
| 1550 |
---------- |
| 1551 |
callback : callable |
| 1552 |
Called every time the slider is updated. This should take a single |
| 1553 |
parameter: the float value of the slider. If ``pass_widget=True``, |
| 1554 |
callable should take two parameters: the float value of the slider |
| 1555 |
and the widget itself. |
| 1556 |
|
| 1557 |
rng : tuple(float) |
| 1558 |
Length two tuple of the minimum and maximum ranges of the |
| 1559 |
slider. |
| 1560 |
|
| 1561 |
value : float, optional |
| 1562 |
The starting value of the slider. |
| 1563 |
|
| 1564 |
title : str, optional |
| 1565 |
The string label of the slider widget. |
| 1566 |
|
| 1567 |
pointa : tuple(float), optional |
| 1568 |
The relative coordinates of the left point of the slider |
| 1569 |
on the display port. |
| 1570 |
|
| 1571 |
pointb : tuple(float), optional |
| 1572 |
The relative coordinates of the right point of the slider |
| 1573 |
on the display port. |
| 1574 |
|
| 1575 |
color : ColorLike, optional |
| 1576 |
Either a string, RGB list, or hex color string. Defaults |
| 1577 |
to :attr:`pyvista.global_theme.font.color |
| 1578 |
<pyvista.plotting.themes._Font.color>`. |
| 1579 |
|
| 1580 |
pass_widget : bool, optional |
| 1581 |
If ``True``, the widget will be passed as the last |
| 1582 |
argument of the callback. |
| 1583 |
|
| 1584 |
interaction_event : InteractionEventType, optional |
| 1585 |
The VTK interaction event to use for triggering the |
| 1586 |
callback. Accepts either the strings ``'start'``, ``'end'``, |
| 1587 |
``'always'`` or a :vtk:`vtkCommand.EventIds`. |
| 1588 |
|
| 1589 |
.. versionchanged:: 0.38.0 |
| 1590 |
Changed from ``event_type`` to ``interaction_event`` and now accepts |
| 1591 |
either strings or :vtk:`vtkCommand.EventIds`. |
| 1592 |
|
| 1593 |
style : str, optional |
| 1594 |
The name of the slider style. The list of available styles |
| 1595 |
are in ``pyvista.global_theme.slider_styles``. Defaults to |
| 1596 |
``None``. |
| 1597 |
|
| 1598 |
title_height : float, optional |
| 1599 |
Relative height of the title as compared to the length of |
| 1600 |
the slider. |
| 1601 |
|
| 1602 |
title_opacity : float, optional |
| 1603 |
Opacity of title. Defaults to 1.0. |
| 1604 |
|
| 1605 |
title_color : ColorLike, optional |
| 1606 |
Either a string, RGB sequence, or hex color string. Defaults |
| 1607 |
to the value given in ``color``. |
| 1608 |
|
| 1609 |
fmt : str, optional |
| 1610 |
String formatter used to format numerical data. Defaults |
| 1611 |
to ``None``. |
| 1612 |
|
| 1613 |
slider_width : float, optional |
| 1614 |
Normalized width of the slider. Defaults to the theme's slider width. |
| 1615 |
|
| 1616 |
tube_width : float, optional |
| 1617 |
Normalized width of the tube. Defaults to the theme's tube width. |
| 1618 |
|
| 1619 |
Returns |
| 1620 |
------- |
| 1621 |
:vtk:`vtkSliderWidget` |
| 1622 |
Slider widget. |
| 1623 |
|
| 1624 |
See Also |
| 1625 |
-------- |
| 1626 |
:ref:`multi_slider_widget_example` |
| 1627 |
|
| 1628 |
Examples |
| 1629 |
-------- |
| 1630 |
>>> import pyvista as pv |
| 1631 |
>>> pl = pv.Plotter() |
| 1632 |
>>> def create_mesh(value): |
| 1633 |
... res = int(value) |
| 1634 |
... sphere = pv.Sphere(phi_resolution=res, theta_resolution=res) |
| 1635 |
... pl.add_mesh(sphere, name='sphere', show_edges=True) |
| 1636 |
>>> slider = pl.add_slider_widget( |
| 1637 |
... create_mesh, |
| 1638 |
... [5, 100], |
| 1639 |
... title='Resolution', |
| 1640 |
... title_opacity=0.5, |
| 1641 |
... title_color='red', |
| 1642 |
... fmt='%0.9f', |
| 1643 |
... title_height=0.08, |
| 1644 |
... ) |
| 1645 |
>>> pl.show() |
| 1646 |
|
| 1647 |
""" |
| 1648 |
msg = 'Cannot add a widget to a closed plotter.' |
| 1649 |
iren = self._plotter._get_iren_not_none(msg) |
| 1650 |
|
| 1651 |
if value is None: |
| 1652 |
value = ((rng[1] - rng[0]) / 2) + rng[0] |
| 1653 |
|
| 1654 |
color = Color(color, default_color=pv.global_theme.font.color) |
| 1655 |
title_color = Color(title_color, default_color=color) |
| 1656 |
|
| 1657 |
if fmt is None: |
| 1658 |
fmt = pv.global_theme.font.fmt |
| 1659 |
|
| 1660 |
def normalize(point, viewport): |
| 1661 |
return ( |
| 1662 |
point[0] * (viewport[2] - viewport[0]), |
| 1663 |
point[1] * (viewport[3] - viewport[1]), |
| 1664 |
) |
| 1665 |
|
| 1666 |
pointa = normalize(pointa, self._plotter.renderer.GetViewport()) |
| 1667 |
pointb = normalize(pointb, self._plotter.renderer.GetViewport()) |
| 1668 |
|
| 1669 |
slider_rep = _vtk.vtkSliderRepresentation2D() |
| 1670 |
slider_rep.SetPickable(False) |
| 1671 |
slider_rep.SetMinimumValue(rng[0]) |
| 1672 |
slider_rep.SetMaximumValue(rng[1]) |
| 1673 |
slider_rep.SetValue(value) |
| 1674 |
slider_rep.SetTitleText(title) |
| 1675 |
slider_rep.GetTitleProperty().SetColor(color.float_rgb) |
| 1676 |
slider_rep.GetSliderProperty().SetColor(color.float_rgb) |
| 1677 |
slider_rep.GetCapProperty().SetColor(color.float_rgb) |
| 1678 |
slider_rep.GetLabelProperty().SetColor(color.float_rgb) |
| 1679 |
slider_rep.GetTubeProperty().SetColor(color.float_rgb) |
| 1680 |
slider_rep.GetPoint1Coordinate().SetCoordinateSystemToNormalizedDisplay() |
| 1681 |
slider_rep.GetPoint1Coordinate().SetValue(pointa[0], pointa[1]) |
| 1682 |
slider_rep.GetPoint2Coordinate().SetCoordinateSystemToNormalizedDisplay() |
| 1683 |
slider_rep.GetPoint2Coordinate().SetValue(pointb[0], pointb[1]) |
| 1684 |
slider_rep.SetSliderLength(0.05) |
| 1685 |
slider_rep.SetSliderWidth(0.05) |
| 1686 |
slider_rep.SetEndCapLength(0.01) |
| 1687 |
|
| 1688 |
if style is not None: |
| 1689 |
if not isinstance(style, str): |
| 1690 |
msg = f'Expected type for ``style`` is str but {type(style).__name__} was given.' |
| 1691 |
raise TypeError(msg) |
| 1692 |
slider_style = getattr(pv.global_theme.slider_styles, style) |
| 1693 |
slider_rep.SetSliderLength(slider_style.slider_length) |
| 1694 |
slider_rep.SetSliderWidth(slider_style.slider_width) |
| 1695 |
slider_rep.GetSliderProperty().SetColor(slider_style.slider_color.float_rgb) |
| 1696 |
slider_rep.SetTubeWidth(slider_style.tube_width) |
| 1697 |
slider_rep.GetTubeProperty().SetColor(slider_style.tube_color.float_rgb) |
| 1698 |
slider_rep.GetCapProperty().SetOpacity(slider_style.cap_opacity) |
| 1699 |
slider_rep.SetEndCapLength(slider_style.cap_length) |
| 1700 |
slider_rep.SetEndCapWidth(slider_style.cap_width) |
| 1701 |
|
| 1702 |
if slider_width is not None: |
| 1703 |
slider_rep.SetSliderWidth(slider_width) |
| 1704 |
if tube_width is not None: |
| 1705 |
slider_rep.SetTubeWidth(tube_width) |
| 1706 |
|
| 1707 |
def _the_callback(widget, _event): |
| 1708 |
value = widget.GetRepresentation().GetValue() |
| 1709 |
if callable(callback): |
| 1710 |
if pass_widget: |
| 1711 |
try_callback(callback, value, widget) |
| 1712 |
else: |
| 1713 |
try_callback(callback, value) |
| 1714 |
|
| 1715 |
slider_widget = _vtk.vtkSliderWidget() |
| 1716 |
slider_widget.SetInteractor(iren.interactor) |
| 1717 |
slider_widget.SetCurrentRenderer(self._plotter.renderer) |
| 1718 |
slider_widget.SetRepresentation(slider_rep) |
| 1719 |
slider_widget.GetRepresentation().SetTitleHeight(title_height) # type: ignore[attr-defined] |
| 1720 |
slider_widget.GetRepresentation().GetTitleProperty().SetOpacity(title_opacity) # type: ignore[attr-defined] |
| 1721 |
slider_widget.GetRepresentation().GetTitleProperty().SetColor(title_color.float_rgb) # type: ignore[attr-defined] |
| 1722 |
if fmt is not None: |
| 1723 |
slider_widget.GetRepresentation().SetLabelFormat(fmt) # type: ignore[attr-defined] |
| 1724 |
slider_widget.On() |
| 1725 |
slider_widget.AddObserver(_parse_interaction_event(interaction_event), _the_callback) |
| 1726 |
_the_callback(slider_widget, None) |
| 1727 |
|
| 1728 |
self.slider_widgets.append(slider_widget) |
| 1729 |
return slider_widget |
| 1730 |
|
| 1731 |
def clear_slider_widgets(self): |
| 1732 |
"""Remove all of the slider widgets.""" |
| 1733 |
for slider_widget in self.slider_widgets: |
| 1734 |
slider_widget.Off() |
| 1735 |
self.slider_widgets.clear() |
| 1736 |
|
| 1737 |
@_deprecate_positional_args(allowed=['mesh']) |
| 1738 |
def add_mesh_threshold( # noqa: PLR0917 |
| 1739 |
self, |
| 1740 |
mesh, |
| 1741 |
scalars=None, |
| 1742 |
invert: bool = False, # noqa: FBT001, FBT002 |
| 1743 |
widget_color=None, |
| 1744 |
preference='cell', |
| 1745 |
title=None, |
| 1746 |
pointa=(0.4, 0.9), |
| 1747 |
pointb=(0.9, 0.9), |
| 1748 |
continuous: bool = False, # noqa: FBT001, FBT002 |
| 1749 |
all_scalars: bool = False, # noqa: FBT001, FBT002 |
| 1750 |
method='upper', |
| 1751 |
**kwargs, |
| 1752 |
): |
| 1753 |
"""Apply a threshold on a mesh with a slider. |
| 1754 |
|
| 1755 |
Add a mesh to the scene with a slider widget that is used to |
| 1756 |
threshold the mesh interactively. |
| 1757 |
|
| 1758 |
The threshold mesh is saved to the ``.threshold_meshes`` attribute on |
| 1759 |
the plotter. |
| 1760 |
|
| 1761 |
Parameters |
| 1762 |
---------- |
| 1763 |
mesh : DataSet or :vtk:`vtkAlgorithm` |
| 1764 |
The input dataset to add to the scene and threshold or algorithm |
| 1765 |
that produces said mesh. |
| 1766 |
|
| 1767 |
scalars : str, optional |
| 1768 |
The string name of the scalars on the mesh to threshold and display. |
| 1769 |
|
| 1770 |
invert : bool, default: False |
| 1771 |
Invert the threshold results. That is, cells that would have been |
| 1772 |
in the output with this option off are excluded, while cells that |
| 1773 |
would have been excluded from the output are included. |
| 1774 |
|
| 1775 |
widget_color : ColorLike, optional |
| 1776 |
Color of the widget. Either a string, RGB sequence, or |
| 1777 |
hex color string. For example: |
| 1778 |
|
| 1779 |
* ``color='white'`` |
| 1780 |
* ``color='w'`` |
| 1781 |
* ``color=[1.0, 1.0, 1.0]`` |
| 1782 |
* ``color='#FFFFFF'`` |
| 1783 |
|
| 1784 |
preference : str, default: 'cell' |
| 1785 |
When ``mesh.n_points == mesh.n_cells`` and setting |
| 1786 |
scalars, this parameter sets how the scalars will be |
| 1787 |
mapped to the mesh. Default ``'cell'``, causes the |
| 1788 |
scalars to be associated with the mesh cells. Can be |
| 1789 |
either ``'point'`` or ``'cell'``. |
| 1790 |
|
| 1791 |
title : str, optional |
| 1792 |
The string label of the slider widget. |
| 1793 |
|
| 1794 |
pointa : sequence, default: (0.4, 0.9) |
| 1795 |
The relative coordinates of the left point of the slider |
| 1796 |
on the display port. |
| 1797 |
|
| 1798 |
pointb : sequence, default: (0.9, 0.9) |
| 1799 |
The relative coordinates of the right point of the slider |
| 1800 |
on the display port. |
| 1801 |
|
| 1802 |
continuous : bool, default: False |
| 1803 |
If this is enabled (default is ``False``), use the continuous |
| 1804 |
interval ``[minimum cell scalar, maximum cell scalar]`` |
| 1805 |
to intersect the threshold bound, rather than the set of |
| 1806 |
discrete scalar values from the vertices. |
| 1807 |
|
| 1808 |
all_scalars : bool, default: False |
| 1809 |
If using scalars from point data, all |
| 1810 |
points in a cell must satisfy the threshold when this |
| 1811 |
value is ``True``. When ``False``, any point of the cell |
| 1812 |
with a scalar value satisfying the threshold criterion |
| 1813 |
will extract the cell. Has no effect when using cell data. |
| 1814 |
|
| 1815 |
method : str, default: 'upper' |
| 1816 |
Set the threshold method for single-values, defining which |
| 1817 |
threshold bounds to use. If the ``value`` is a range, this |
| 1818 |
parameter will be ignored, extracting data between the two |
| 1819 |
values. For single values, ``'lower'`` will extract data |
| 1820 |
lower than the ``value``. ``'upper'`` will extract data |
| 1821 |
larger than the ``value``. |
| 1822 |
|
| 1823 |
**kwargs : dict, optional |
| 1824 |
All additional keyword arguments are passed to ``add_mesh`` to |
| 1825 |
control how the mesh is displayed. |
| 1826 |
|
| 1827 |
Returns |
| 1828 |
------- |
| 1829 |
:vtk:`vtkActor` |
| 1830 |
VTK actor of the mesh. |
| 1831 |
|
| 1832 |
""" |
| 1833 |
# avoid circular import |
| 1834 |
from pyvista.core.filters.data_set import _set_threshold_limit |
| 1835 |
|
| 1836 |
mesh, algo = algorithm_to_mesh_handler(mesh) |
| 1837 |
|
| 1838 |
if isinstance(mesh, pv.PointSet): |
| 1839 |
# vtkThreshold is CELL-wise and PointSets have no cells |
| 1840 |
algo = pointset_to_polydata_algorithm(algo or mesh) |
| 1841 |
mesh, algo = algorithm_to_mesh_handler(algo) |
| 1842 |
|
| 1843 |
if isinstance(mesh, pv.MultiBlock): |
| 1844 |
msg = 'MultiBlock datasets are not supported for threshold widget.' |
| 1845 |
raise TypeError(msg) |
| 1846 |
name = kwargs.get('name', mesh.memory_address) |
| 1847 |
if scalars is None: |
| 1848 |
field, scalars = mesh.active_scalars_info |
| 1849 |
arr = get_array(mesh, scalars, preference=preference) |
| 1850 |
if arr is None: |
| 1851 |
msg = 'No arrays present to threshold.' |
| 1852 |
raise ValueError(msg) |
| 1853 |
field = get_array_association(mesh, scalars, preference=preference) |
| 1854 |
|
| 1855 |
rng = mesh.get_data_range(scalars) |
| 1856 |
kwargs.setdefault('clim', kwargs.pop('rng', rng)) |
| 1857 |
if title is None: |
| 1858 |
title = scalars |
| 1859 |
mesh.set_active_scalars(scalars) |
| 1860 |
|
| 1861 |
self._plotter.add_mesh( |
| 1862 |
outline_algorithm(algo or mesh), name=f'{name}-outline', opacity=0.0 |
| 1863 |
) |
| 1864 |
|
| 1865 |
alg = _vtk.vtkThreshold() |
| 1866 |
set_algorithm_input(alg, algo or mesh) |
| 1867 |
alg.SetInputArrayToProcess( |
| 1868 |
0, |
| 1869 |
0, |
| 1870 |
0, |
| 1871 |
field.value, |
| 1872 |
scalars, |
| 1873 |
) # args: (idx, port, connection, field, name) |
| 1874 |
alg.SetUseContinuousCellRange(continuous) |
| 1875 |
alg.SetAllScalars(all_scalars) |
| 1876 |
|
| 1877 |
threshold_mesh = pv.wrap(alg.GetOutput()) |
| 1878 |
self.threshold_meshes.append(threshold_mesh) |
| 1879 |
|
| 1880 |
def callback(value): |
| 1881 |
_set_threshold_limit(alg, value=value, method=method, invert=invert) |
| 1882 |
alg.Update() |
| 1883 |
threshold_mesh.shallow_copy(alg.GetOutput()) |
| 1884 |
|
| 1885 |
self.add_slider_widget( |
| 1886 |
callback=callback, |
| 1887 |
rng=rng, |
| 1888 |
title=title, |
| 1889 |
color=widget_color, |
| 1890 |
pointa=pointa, |
| 1891 |
pointb=pointb, |
| 1892 |
) |
| 1893 |
|
| 1894 |
kwargs.setdefault('reset_camera', False) |
| 1895 |
return self._plotter.add_mesh(alg, scalars=scalars, **kwargs) |
| 1896 |
|
| 1897 |
@_deprecate_positional_args(allowed=['mesh']) |
| 1898 |
def add_mesh_isovalue( # noqa: PLR0917 |
| 1899 |
self, |
| 1900 |
mesh, |
| 1901 |
scalars=None, |
| 1902 |
compute_normals: bool = False, # noqa: FBT001, FBT002 |
| 1903 |
compute_gradients: bool = False, # noqa: FBT001, FBT002 |
| 1904 |
compute_scalars: bool = True, # noqa: FBT001, FBT002 |
| 1905 |
preference='point', |
| 1906 |
title=None, |
| 1907 |
pointa=(0.4, 0.9), |
| 1908 |
pointb=(0.9, 0.9), |
| 1909 |
widget_color=None, |
| 1910 |
**kwargs, |
| 1911 |
): |
| 1912 |
"""Create a contour of a mesh with a slider. |
| 1913 |
|
| 1914 |
Add a mesh to the scene with a slider widget that is used to |
| 1915 |
contour at an isovalue of the *point* data on the mesh |
| 1916 |
interactively. |
| 1917 |
|
| 1918 |
The isovalue mesh is saved to the ``.isovalue_meshes`` |
| 1919 |
attribute on the plotter. |
| 1920 |
|
| 1921 |
.. warning:: |
| 1922 |
This will not work with :class:`pyvista.PointSet` as |
| 1923 |
creating an isovalue is a dimension reducing operation |
| 1924 |
on the geometry and point clouds are zero dimensional. |
| 1925 |
This will similarly fail for point clouds in |
| 1926 |
:class:`pyvista.PolyData`. |
| 1927 |
|
| 1928 |
Parameters |
| 1929 |
---------- |
| 1930 |
mesh : DataSet or :vtk:`vtkAlgorithm` |
| 1931 |
The input dataset to add to the scene and contour or algorithm |
| 1932 |
that produces said mesh. |
| 1933 |
|
| 1934 |
scalars : str, optional |
| 1935 |
The string name of the scalars on the mesh to contour and display. |
| 1936 |
|
| 1937 |
compute_normals : bool, optional |
| 1938 |
Enable or disable the computation of normals. If the |
| 1939 |
output data will be processed by filters that modify |
| 1940 |
topology or geometry, it may be wise to disable computing |
| 1941 |
normals. |
| 1942 |
|
| 1943 |
compute_gradients : bool, optional |
| 1944 |
Enable or disable the computation of gradients. If the |
| 1945 |
output data will be processed by filters that modify |
| 1946 |
topology or geometry, it may be wise to disable computing |
| 1947 |
gradients. |
| 1948 |
|
| 1949 |
compute_scalars : bool, optional |
| 1950 |
Enable or disable the computation of scalars. |
| 1951 |
|
| 1952 |
preference : str, optional |
| 1953 |
When ``mesh.n_points == mesh.n_cells`` and setting |
| 1954 |
scalars, this parameter sets how the scalars will be |
| 1955 |
mapped to the mesh. Default ``'point'``, causes the |
| 1956 |
scalars will be associated with the mesh points. Can be |
| 1957 |
either ``'point'`` or ``'cell'``. |
| 1958 |
|
| 1959 |
title : str, optional |
| 1960 |
The string label of the slider widget. |
| 1961 |
|
| 1962 |
pointa : sequence, optional |
| 1963 |
The relative coordinates of the left point of the slider |
| 1964 |
on the display port. |
| 1965 |
|
| 1966 |
pointb : sequence |
| 1967 |
The relative coordinates of the right point of the slider |
| 1968 |
on the display port. |
| 1969 |
|
| 1970 |
widget_color : ColorLike, optional |
| 1971 |
Color of the widget. Either a string, RGB sequence, or |
| 1972 |
hex color string. For example: |
| 1973 |
|
| 1974 |
* ``color='white'`` |
| 1975 |
* ``color='w'`` |
| 1976 |
* ``color=[1.0, 1.0, 1.0]`` |
| 1977 |
* ``color='#FFFFFF'`` |
| 1978 |
|
| 1979 |
**kwargs : dict, optional |
| 1980 |
All additional keyword arguments are passed to |
| 1981 |
:func:`pyvista.Plotter.add_mesh` to control how the mesh is |
| 1982 |
displayed. |
| 1983 |
|
| 1984 |
Returns |
| 1985 |
------- |
| 1986 |
:vtk:`vtkActor` |
| 1987 |
VTK actor of the mesh. |
| 1988 |
|
| 1989 |
Examples |
| 1990 |
-------- |
| 1991 |
Shows an interactive slider controlling the altitude of the contours. |
| 1992 |
|
| 1993 |
>>> import pyvista as pv |
| 1994 |
>>> from pyvista import examples |
| 1995 |
>>> pl = pv.Plotter() |
| 1996 |
>>> mesh = examples.load_random_hills() |
| 1997 |
>>> _ = pl.add_mesh(mesh, opacity=0.4) |
| 1998 |
>>> _ = pl.add_mesh_isovalue(mesh) |
| 1999 |
>>> pl.show() |
| 2000 |
|
| 2001 |
""" |
| 2002 |
mesh, algo = algorithm_to_mesh_handler(mesh) |
| 2003 |
if isinstance(mesh, pv.PointSet): |
| 2004 |
msg = 'PointSets are 0-dimensional and thus cannot produce contours.' |
| 2005 |
raise TypeError(msg) |
| 2006 |
if isinstance(mesh, pv.MultiBlock): |
| 2007 |
msg = 'MultiBlock datasets are not supported for this widget.' |
| 2008 |
raise TypeError(msg) |
| 2009 |
name = kwargs.get('name', mesh.memory_address) |
| 2010 |
# set the array to contour on |
| 2011 |
if mesh.n_arrays < 1: |
| 2012 |
msg = 'Input dataset for the contour filter must have data arrays.' |
| 2013 |
raise ValueError(msg) |
| 2014 |
if scalars is None: |
| 2015 |
field, scalars = mesh.active_scalars_info |
| 2016 |
else: |
| 2017 |
field = get_array_association(mesh, scalars, preference=preference) |
| 2018 |
# NOTE: only point data is allowed? well cells works but seems buggy? |
| 2019 |
if field != pv.FieldAssociation.POINT: |
| 2020 |
msg = ( |
| 2021 |
f'Contour filter only works on Point data. Array ({scalars}) is in the Cell data.' |
| 2022 |
) |
| 2023 |
raise TypeError(msg) |
| 2024 |
|
| 2025 |
rng = mesh.get_data_range(scalars) |
| 2026 |
kwargs.setdefault('clim', kwargs.pop('rng', rng)) |
| 2027 |
if title is None: |
| 2028 |
title = scalars |
| 2029 |
mesh.set_active_scalars(scalars) |
| 2030 |
|
| 2031 |
alg = _vtk.vtkContourFilter() |
| 2032 |
set_algorithm_input(alg, algo or mesh) |
| 2033 |
alg.SetComputeNormals(compute_normals) |
| 2034 |
alg.SetComputeGradients(compute_gradients) |
| 2035 |
alg.SetComputeScalars(compute_scalars) |
| 2036 |
alg.SetInputArrayToProcess(0, 0, 0, field.value, scalars) |
| 2037 |
alg.SetNumberOfContours(1) # Only one contour level |
| 2038 |
|
| 2039 |
self._plotter.add_mesh( |
| 2040 |
outline_algorithm(algo or mesh), name=f'{name}-outline', opacity=0.0 |
| 2041 |
) |
| 2042 |
|
| 2043 |
isovalue_mesh = pv.wrap(alg.GetOutput()) |
| 2044 |
self.isovalue_meshes.append(isovalue_mesh) |
| 2045 |
|
| 2046 |
def callback(value): |
| 2047 |
alg.SetValue(0, value) |
| 2048 |
alg.Update() |
| 2049 |
isovalue_mesh.shallow_copy(alg.GetOutput()) |
| 2050 |
|
| 2051 |
self.add_slider_widget( |
| 2052 |
callback=callback, |
| 2053 |
rng=rng, |
| 2054 |
title=title, |
| 2055 |
color=widget_color, |
| 2056 |
pointa=pointa, |
| 2057 |
pointb=pointb, |
| 2058 |
) |
| 2059 |
|
| 2060 |
kwargs.setdefault('reset_camera', False) |
| 2061 |
return self._plotter.add_mesh(alg, scalars=scalars, **kwargs) |
| 2062 |
|
| 2063 |
@_deprecate_positional_args(allowed=['callback']) |
| 2064 |
def add_spline_widget( # noqa: PLR0917 |
| 2065 |
self, |
| 2066 |
callback, |
| 2067 |
bounds=None, |
| 2068 |
factor=1.25, |
| 2069 |
n_handles=5, |
| 2070 |
resolution=25, |
| 2071 |
color='yellow', |
| 2072 |
show_ribbon: bool = False, # noqa: FBT001, FBT002 |
| 2073 |
ribbon_color='pink', |
| 2074 |
ribbon_opacity=0.5, |
| 2075 |
pass_widget: bool = False, # noqa: FBT001, FBT002 |
| 2076 |
closed: bool = False, # noqa: FBT001, FBT002 |
| 2077 |
initial_points=None, |
| 2078 |
interaction_event: InteractionEventType = 'end', |
| 2079 |
): |
| 2080 |
"""Create and add a spline widget to the scene. |
| 2081 |
|
| 2082 |
Use the bounds argument to place this widget. Several "handles" are |
| 2083 |
used to control a parametric function for building this spline. Click |
| 2084 |
directly on the line to translate the widget. |
| 2085 |
|
| 2086 |
Parameters |
| 2087 |
---------- |
| 2088 |
callback : callable |
| 2089 |
The method called every time the spline is updated. This passes a |
| 2090 |
:class:`pyvista.PolyData` object to the callback function of the |
| 2091 |
generated spline. |
| 2092 |
|
| 2093 |
bounds : sequence[float], optional |
| 2094 |
Length 6 sequence of the bounding box where the widget is placed. |
| 2095 |
|
| 2096 |
factor : float, optional |
| 2097 |
An inflation factor to expand on the bounds when placing. |
| 2098 |
|
| 2099 |
n_handles : int, optional |
| 2100 |
The number of interactive spheres to control the spline's |
| 2101 |
parametric function. |
| 2102 |
|
| 2103 |
resolution : int, optional |
| 2104 |
The number of points in the spline created between all the handles. |
| 2105 |
|
| 2106 |
color : ColorLike, optional |
| 2107 |
Either a string, RGB sequence, or hex color string. |
| 2108 |
|
| 2109 |
show_ribbon : bool, optional |
| 2110 |
If ``True``, the poly plane used for slicing will also be shown. |
| 2111 |
|
| 2112 |
ribbon_color : ColorLike, optional |
| 2113 |
Color of the ribbon. Either a string, RGB sequence, or |
| 2114 |
hex color string. |
| 2115 |
|
| 2116 |
ribbon_opacity : float, optional |
| 2117 |
Opacity of ribbon. Defaults to 1.0 and must be between |
| 2118 |
``[0, 1]``. |
| 2119 |
|
| 2120 |
pass_widget : bool, optional |
| 2121 |
If ``True``, the widget will be passed as the last argument of the |
| 2122 |
callback. |
| 2123 |
|
| 2124 |
closed : bool, optional |
| 2125 |
Make the spline a closed loop. |
| 2126 |
|
| 2127 |
initial_points : sequence, optional |
| 2128 |
The points to initialize the widget placement. Must have |
| 2129 |
same number of elements as ``n_handles``. If the first and |
| 2130 |
last point are the same, this will be a closed loop |
| 2131 |
spline. |
| 2132 |
|
| 2133 |
interaction_event : InteractionEventType, optional |
| 2134 |
The VTK interaction event to use for triggering the |
| 2135 |
callback. Accepts either the strings ``'start'``, ``'end'``, |
| 2136 |
``'always'`` or a :vtk:`vtkCommand.EventIds`. |
| 2137 |
|
| 2138 |
Returns |
| 2139 |
------- |
| 2140 |
:vtk:`vtkSplineWidget` |
| 2141 |
The newly created spline widget. |
| 2142 |
|
| 2143 |
See Also |
| 2144 |
-------- |
| 2145 |
:ref:`spline_widget_example` |
| 2146 |
|
| 2147 |
Notes |
| 2148 |
----- |
| 2149 |
This widget has trouble displaying certain colors. Use only simple |
| 2150 |
colors (white, black, yellow). |
| 2151 |
|
| 2152 |
""" |
| 2153 |
if initial_points is not None and len(initial_points) != n_handles: |
| 2154 |
msg = '`initial_points` must be length `n_handles`.' |
| 2155 |
raise ValueError(msg) |
| 2156 |
|
| 2157 |
color = Color(color, default_color=pv.global_theme.color) |
| 2158 |
|
| 2159 |
if bounds is None: |
| 2160 |
bounds = self._plotter.bounds |
| 2161 |
|
| 2162 |
ribbon = pv.PolyData() |
| 2163 |
|
| 2164 |
def _the_callback(widget, _event): |
| 2165 |
para_source = _vtk.vtkParametricFunctionSource() |
| 2166 |
para_source.SetParametricFunction(widget.GetParametricSpline()) |
| 2167 |
para_source.Update() |
| 2168 |
polyline = pv.wrap(para_source.GetOutput()) |
| 2169 |
ribbon.shallow_copy(polyline.ribbon(normal=(0, 0, 1), angle=90.0)) |
| 2170 |
if callable(callback): |
| 2171 |
if pass_widget: |
| 2172 |
try_callback(callback, polyline, widget) |
| 2173 |
else: |
| 2174 |
try_callback(callback, polyline) |
| 2175 |
|
| 2176 |
spline_widget = _vtk.vtkSplineWidget() |
| 2177 |
spline_widget.GetLineProperty().SetColor(color.float_rgb) |
| 2178 |
spline_widget.SetNumberOfHandles(n_handles) |
| 2179 |
spline_widget.SetInteractor(self._plotter.iren.interactor) |
| 2180 |
spline_widget.SetCurrentRenderer(self._plotter.renderer) |
| 2181 |
spline_widget.SetPlaceFactor(factor) |
| 2182 |
spline_widget.PlaceWidget(bounds) |
| 2183 |
spline_widget.SetResolution(resolution) |
| 2184 |
if initial_points is not None: |
| 2185 |
spline_widget.InitializeHandles(pv.vtk_points(initial_points)) |
| 2186 |
else: |
| 2187 |
spline_widget.SetClosed(closed) |
| 2188 |
spline_widget.Modified() |
| 2189 |
spline_widget.On() |
| 2190 |
spline_widget.AddObserver( |
| 2191 |
_parse_interaction_event(interaction_event), |
| 2192 |
_the_callback, |
| 2193 |
) |
| 2194 |
_the_callback(spline_widget, None) |
| 2195 |
|
| 2196 |
if show_ribbon: |
| 2197 |
self._plotter.add_mesh(ribbon, color=ribbon_color, opacity=ribbon_opacity) |
| 2198 |
|
| 2199 |
self.spline_widgets.append(spline_widget) |
| 2200 |
return spline_widget |
| 2201 |
|
| 2202 |
def clear_spline_widgets(self): |
| 2203 |
"""Remove all of the spline widgets.""" |
| 2204 |
for spline_widget in self.spline_widgets: |
| 2205 |
spline_widget.Off() |
| 2206 |
self.spline_widgets.clear() |
| 2207 |
|
| 2208 |
@_deprecate_positional_args(allowed=['mesh']) |
| 2209 |
def add_mesh_slice_spline( # noqa: PLR0917 |
| 2210 |
self, |
| 2211 |
mesh, |
| 2212 |
generate_triangles: bool = False, # noqa: FBT001, FBT002 |
| 2213 |
factor=1.25, |
| 2214 |
n_handles=5, |
| 2215 |
resolution=25, |
| 2216 |
widget_color=None, |
| 2217 |
show_ribbon: bool = False, # noqa: FBT001, FBT002 |
| 2218 |
ribbon_color='pink', |
| 2219 |
ribbon_opacity=0.5, |
| 2220 |
initial_points=None, |
| 2221 |
closed: bool = False, # noqa: FBT001, FBT002 |
| 2222 |
interaction_event: InteractionEventType = 'end', |
| 2223 |
**kwargs, |
| 2224 |
): |
| 2225 |
"""Slice a mesh with a spline widget. |
| 2226 |
|
| 2227 |
Add a mesh to the scene with a spline widget that is used to slice |
| 2228 |
the mesh interactively. |
| 2229 |
|
| 2230 |
The sliced mesh is saved to the ``.spline_sliced_meshes`` attribute on |
| 2231 |
the plotter. |
| 2232 |
|
| 2233 |
Parameters |
| 2234 |
---------- |
| 2235 |
mesh : DataSet or :vtk:`vtkAlgorithm` |
| 2236 |
The input dataset to add to the scene and slice along the spline |
| 2237 |
or algorithm that produces said mesh. |
| 2238 |
|
| 2239 |
generate_triangles : bool, optional |
| 2240 |
If this is enabled (``False`` by default), the output will be |
| 2241 |
triangles otherwise, the output will be the intersection polygons. |
| 2242 |
|
| 2243 |
factor : float, optional |
| 2244 |
An inflation factor to expand on the bounds when placing. |
| 2245 |
|
| 2246 |
n_handles : int, optional |
| 2247 |
The number of interactive spheres to control the spline's |
| 2248 |
parametric function. |
| 2249 |
|
| 2250 |
resolution : int, optional |
| 2251 |
The number of points to generate on the spline. |
| 2252 |
|
| 2253 |
widget_color : ColorLike, optional |
| 2254 |
Color of the widget. Either a string, RGB sequence, or |
| 2255 |
hex color string. For example: |
| 2256 |
|
| 2257 |
* ``color='white'`` |
| 2258 |
* ``color='w'`` |
| 2259 |
* ``color=[1.0, 1.0, 1.0]`` |
| 2260 |
* ``color='#FFFFFF'`` |
| 2261 |
|
| 2262 |
show_ribbon : bool, optional |
| 2263 |
If ``True``, the poly plane used for slicing will also be shown. |
| 2264 |
|
| 2265 |
ribbon_color : ColorLike, optional |
| 2266 |
Color of the ribbon. Either a string, RGB sequence, or |
| 2267 |
hex color string. |
| 2268 |
|
| 2269 |
ribbon_opacity : float, optional |
| 2270 |
Opacity of ribbon. Defaults to 1.0 and must be between |
| 2271 |
``[0, 1]``. |
| 2272 |
|
| 2273 |
initial_points : sequence, optional |
| 2274 |
The points to initialize the widget placement. Must have same |
| 2275 |
number of elements as ``n_handles``. If the first and last point |
| 2276 |
are the same, this will be a closed loop spline. |
| 2277 |
|
| 2278 |
closed : bool, optional |
| 2279 |
Make the spline a closed loop. |
| 2280 |
|
| 2281 |
interaction_event : InteractionEventType, optional |
| 2282 |
The VTK interaction event to use for triggering the |
| 2283 |
callback. Accepts either the strings ``'start'``, ``'end'``, |
| 2284 |
``'always'`` or a :vtk:`vtkCommand.EventIds`. |
| 2285 |
|
| 2286 |
**kwargs : dict, optional |
| 2287 |
All additional keyword arguments are passed to |
| 2288 |
:func:`pyvista.Plotter.add_mesh` to control how the mesh is |
| 2289 |
displayed. |
| 2290 |
|
| 2291 |
Returns |
| 2292 |
------- |
| 2293 |
:vtk:`vtkActor` |
| 2294 |
VTK actor of the mesh. |
| 2295 |
|
| 2296 |
""" |
| 2297 |
mesh, algo = algorithm_to_mesh_handler(mesh) |
| 2298 |
name = kwargs.get('name') |
| 2299 |
if name is None: |
| 2300 |
name = mesh.memory_address |
| 2301 |
rng = mesh.get_data_range(kwargs.get('scalars')) |
| 2302 |
kwargs.setdefault('clim', kwargs.pop('rng', rng)) |
| 2303 |
mesh.set_active_scalars(kwargs.get('scalars', mesh.active_scalars_name)) |
| 2304 |
|
| 2305 |
self._plotter.add_mesh( |
| 2306 |
outline_algorithm(algo or mesh), name=f'{name}-outline', opacity=0.0 |
| 2307 |
) |
| 2308 |
|
| 2309 |
alg = _vtk.vtkCutter() # Construct the cutter object |
| 2310 |
# Use the grid as the data we desire to cut |
| 2311 |
set_algorithm_input(alg, algo or mesh) |
| 2312 |
if not generate_triangles: |
| 2313 |
alg.GenerateTrianglesOff() |
| 2314 |
|
| 2315 |
spline_sliced_mesh = pv.wrap(alg.GetOutput()) |
| 2316 |
self.spline_sliced_meshes.append(spline_sliced_mesh) |
| 2317 |
|
| 2318 |
def callback(spline): |
| 2319 |
polyline = spline.GetCell(0) |
| 2320 |
# create the plane for clipping |
| 2321 |
polyplane = _vtk.vtkPolyPlane() |
| 2322 |
polyplane.SetPolyLine(polyline) |
| 2323 |
alg.SetCutFunction(polyplane) # the cutter to use the poly planes |
| 2324 |
alg.Update() # Perform the Cut |
| 2325 |
spline_sliced_mesh.shallow_copy(alg.GetOutput()) |
| 2326 |
|
| 2327 |
self.add_spline_widget( |
| 2328 |
callback=callback, |
| 2329 |
bounds=mesh.bounds, |
| 2330 |
factor=factor, |
| 2331 |
color=widget_color, |
| 2332 |
n_handles=n_handles, |
| 2333 |
resolution=resolution, |
| 2334 |
show_ribbon=show_ribbon, |
| 2335 |
ribbon_color=ribbon_color, |
| 2336 |
ribbon_opacity=ribbon_opacity, |
| 2337 |
initial_points=initial_points, |
| 2338 |
closed=closed, |
| 2339 |
interaction_event=_parse_interaction_event(interaction_event), |
| 2340 |
) |
| 2341 |
|
| 2342 |
return self._plotter.add_mesh(alg, **kwargs) |
| 2343 |
|
| 2344 |
def add_measurement_widget( |
| 2345 |
self, |
| 2346 |
callback=None, |
| 2347 |
color=None, |
| 2348 |
): |
| 2349 |
"""Interactively measure distance with a distance widget. |
| 2350 |
|
| 2351 |
Creates an overlay documenting the selected line and total |
| 2352 |
distance between two mouse left-click interactions. |
| 2353 |
|
| 2354 |
The measurement overlay stays on the rendering until the |
| 2355 |
widget is deleted. Only one measurement can be added by each |
| 2356 |
widget instance. |
| 2357 |
|
| 2358 |
Parameters |
| 2359 |
---------- |
| 2360 |
callback : Callable[[tuple[float, float, float], [tuple[float, float, float], int], float] |
| 2361 |
The method called every time the widget calculates a |
| 2362 |
distance measurement. This callback receives the start |
| 2363 |
point and end point as cartesian coordinate tuples |
| 2364 |
and the calculated distance between the two points. |
| 2365 |
|
| 2366 |
color : ColorLike, optional |
| 2367 |
The color of the measurement widget. |
| 2368 |
|
| 2369 |
Returns |
| 2370 |
------- |
| 2371 |
:vtk:`vtkDistanceWidget` |
| 2372 |
The newly created distance widget. |
| 2373 |
|
| 2374 |
See Also |
| 2375 |
-------- |
| 2376 |
:ref:`distance_measurement_example` |
| 2377 |
|
| 2378 |
""" |
| 2379 |
msg = 'Cannot add a widget to a closed plotter.' |
| 2380 |
iren = self._plotter._get_iren_not_none(msg) |
| 2381 |
|
| 2382 |
if color is None: |
| 2383 |
color = pv.global_theme.font.color.float_rgb |
| 2384 |
color = Color(color) |
| 2385 |
|
| 2386 |
compute = lambda a, b: np.sqrt(np.sum((np.array(b) - np.array(a)) ** 2)) |
| 2387 |
|
| 2388 |
handle = _vtk.vtkPointHandleRepresentation3D() |
| 2389 |
representation = _vtk.vtkDistanceRepresentation3D() |
| 2390 |
representation.SetHandleRepresentation(handle) |
| 2391 |
widget = _vtk.vtkDistanceWidget() |
| 2392 |
widget.SetInteractor(iren.interactor) |
| 2393 |
widget.SetRepresentation(representation) |
| 2394 |
|
| 2395 |
handle.GetProperty().SetColor(*color.float_rgb) |
| 2396 |
representation.GetLabelProperty().SetColor(*color.float_rgb) |
| 2397 |
representation.GetLineProperty().SetColor(*color.float_rgb) |
| 2398 |
|
| 2399 |
iren.picker = PickerType.POINT |
| 2400 |
|
| 2401 |
def place_point(*_): |
| 2402 |
p1 = [0, 0, 0] |
| 2403 |
p2 = [0, 0, 0] |
| 2404 |
representation.GetPoint1DisplayPosition(p1) # type: ignore[arg-type] |
| 2405 |
representation.GetPoint2DisplayPosition(p2) # type: ignore[arg-type] |
| 2406 |
if iren.picker.Pick(p1, self._plotter.renderer): |
| 2407 |
pos1 = iren.picker.GetPickPosition() |
| 2408 |
representation.GetPoint1Representation().SetWorldPosition(pos1) |
| 2409 |
if iren.picker.Pick(p2, self._plotter.renderer): |
| 2410 |
pos2 = iren.picker.GetPickPosition() |
| 2411 |
representation.GetPoint2Representation().SetWorldPosition(pos2) |
| 2412 |
representation.BuildRepresentation() |
| 2413 |
|
| 2414 |
a = representation.GetPoint1Representation().GetWorldPosition() |
| 2415 |
b = representation.GetPoint2Representation().GetWorldPosition() |
| 2416 |
if callable(callback): |
| 2417 |
try_callback(callback, a, b, compute(a, b)) |
| 2418 |
|
| 2419 |
widget.AddObserver(_vtk.vtkCommand.EndInteractionEvent, place_point) |
| 2420 |
|
| 2421 |
widget.On() |
| 2422 |
self.distance_widgets.append(widget) |
| 2423 |
return widget |
| 2424 |
|
| 2425 |
def clear_measure_widgets(self): |
| 2426 |
"""Remove all of the measurement widgets.""" |
| 2427 |
for distance_widget in self.distance_widgets: |
| 2428 |
distance_widget.Off() |
| 2429 |
self.distance_widgets.clear() |
| 2430 |
|
| 2431 |
@_deprecate_positional_args(allowed=['callback']) |
| 2432 |
def add_sphere_widget( # noqa: PLR0917 |
| 2433 |
self, |
| 2434 |
callback, |
| 2435 |
center=(0, 0, 0), |
| 2436 |
radius=0.5, |
| 2437 |
theta_resolution=30, |
| 2438 |
phi_resolution=30, |
| 2439 |
color=None, |
| 2440 |
style='surface', |
| 2441 |
selected_color='pink', |
| 2442 |
indices=None, |
| 2443 |
pass_widget: bool = False, # noqa: FBT001, FBT002 |
| 2444 |
test_callback: bool = True, # noqa: FBT001, FBT002 |
| 2445 |
interaction_event: InteractionEventType = 'end', |
| 2446 |
): |
| 2447 |
"""Add one or many sphere widgets to a scene. |
| 2448 |
|
| 2449 |
Use a sphere widget to control a vertex location. |
| 2450 |
|
| 2451 |
Parameters |
| 2452 |
---------- |
| 2453 |
callback : callable |
| 2454 |
The function to call back when the widget is modified. It takes a |
| 2455 |
single argument: the center of the sphere as an XYZ coordinate (a |
| 2456 |
3-length sequence), unless ``pass_widget=True``, in which case the |
| 2457 |
callback must accept the widget object as the second parameter. If |
| 2458 |
multiple centers are passed in the ``center`` parameter, the |
| 2459 |
callback must also accept an index of that widget. |
| 2460 |
|
| 2461 |
center : sequence[float], optional |
| 2462 |
The cartesian coordinate of the sphere's center when placing it in |
| 2463 |
the scene. If more than one location is passed, then that many |
| 2464 |
widgets will be added and the callback will also be passed the |
| 2465 |
integer index of that widget. |
| 2466 |
|
| 2467 |
radius : float, optional |
| 2468 |
The radius of the sphere. |
| 2469 |
|
| 2470 |
theta_resolution : int, optional |
| 2471 |
Set the number of points in the longitude direction. |
| 2472 |
|
| 2473 |
phi_resolution : int, optional |
| 2474 |
Set the number of points in the latitude direction. |
| 2475 |
|
| 2476 |
color : ColorLike, optional |
| 2477 |
The color of the sphere's surface. If multiple centers |
| 2478 |
are passed, then this must be a list of colors. Each |
| 2479 |
color is either a string, rgb list, or hex color string. |
| 2480 |
For example: |
| 2481 |
|
| 2482 |
* ``color='white'`` |
| 2483 |
* ``color='w'`` |
| 2484 |
* ``color=[1.0, 1.0, 1.0]`` |
| 2485 |
* ``color='#FFFFFF'`` |
| 2486 |
|
| 2487 |
style : str, optional |
| 2488 |
Representation style: ``'surface'`` or ``'wireframe'``. |
| 2489 |
|
| 2490 |
selected_color : ColorLike, optional |
| 2491 |
Color of the widget when selected during interaction. |
| 2492 |
|
| 2493 |
indices : sequence[int], optional |
| 2494 |
Indices to assign the sphere widgets. |
| 2495 |
|
| 2496 |
pass_widget : bool, optional |
| 2497 |
If ``True``, the widget will be passed as the last |
| 2498 |
argument of the callback. |
| 2499 |
|
| 2500 |
test_callback : bool, optional |
| 2501 |
If ``True``, run the callback function after the widget is |
| 2502 |
created. |
| 2503 |
|
| 2504 |
interaction_event : InteractionEventType, optional |
| 2505 |
The VTK interaction event to use for triggering the |
| 2506 |
callback. Accepts either the strings ``'start'``, ``'end'``, |
| 2507 |
``'always'`` or a :vtk:`vtkCommand.EventIds`. |
| 2508 |
|
| 2509 |
Returns |
| 2510 |
------- |
| 2511 |
:vtk:`vtkSphereWidget` |
| 2512 |
The sphere widget. |
| 2513 |
|
| 2514 |
See Also |
| 2515 |
-------- |
| 2516 |
:ref:`sphere_widget_example` |
| 2517 |
|
| 2518 |
""" |
| 2519 |
if color is None: |
| 2520 |
color = pv.global_theme.color.float_rgb |
| 2521 |
selected_color = Color(selected_color) |
| 2522 |
|
| 2523 |
center = np.array(center) |
| 2524 |
num = 1 |
| 2525 |
if center.ndim > 1: |
| 2526 |
num = len(center) |
| 2527 |
|
| 2528 |
if isinstance(color, (list, tuple, np.ndarray)): |
| 2529 |
if len(color) == num and not isinstance(color[0], float): |
| 2530 |
colors = color |
| 2531 |
else: |
| 2532 |
colors = [color] * num |
| 2533 |
else: |
| 2534 |
colors = [color] * num |
| 2535 |
|
| 2536 |
def _the_callback(widget, _event): |
| 2537 |
point = widget.GetCenter() |
| 2538 |
index = widget.WIDGET_INDEX |
| 2539 |
if callable(callback): |
| 2540 |
args = [point, index] if num > 1 else [point] |
| 2541 |
if pass_widget: |
| 2542 |
args.append(widget) |
| 2543 |
try_callback(callback, *args) |
| 2544 |
|
| 2545 |
if indices is None: |
| 2546 |
indices = list(range(num)) |
| 2547 |
|
| 2548 |
for i in range(num): |
| 2549 |
loc = center[i] if center.ndim > 1 else center |
| 2550 |
sphere_widget = _vtk.vtkSphereWidget() |
| 2551 |
sphere_widget.WIDGET_INDEX = indices[i] # type: ignore[attr-defined] # Monkey patch the index |
| 2552 |
if style in 'wireframe': |
| 2553 |
sphere_widget.SetRepresentationToWireframe() |
| 2554 |
else: |
| 2555 |
sphere_widget.SetRepresentationToSurface() |
| 2556 |
sphere_widget.GetSphereProperty().SetColor(Color(colors[i]).float_rgb) |
| 2557 |
sphere_widget.GetSelectedSphereProperty().SetColor(selected_color.float_rgb) |
| 2558 |
sphere_widget.SetInteractor(self._plotter.iren.interactor) |
| 2559 |
sphere_widget.SetCurrentRenderer(self._plotter.renderer) |
| 2560 |
sphere_widget.SetRadius(radius) |
| 2561 |
sphere_widget.SetCenter(loc) |
| 2562 |
sphere_widget.SetThetaResolution(theta_resolution) |
| 2563 |
sphere_widget.SetPhiResolution(phi_resolution) |
| 2564 |
sphere_widget.Modified() |
| 2565 |
sphere_widget.On() |
| 2566 |
sphere_widget.AddObserver( |
| 2567 |
_parse_interaction_event(interaction_event), |
| 2568 |
_the_callback, |
| 2569 |
) |
| 2570 |
self.sphere_widgets.append(sphere_widget) |
| 2571 |
|
| 2572 |
if test_callback is True: |
| 2573 |
# Test call back in the last |
| 2574 |
_the_callback(sphere_widget, None) |
| 2575 |
if num > 1: |
| 2576 |
return self.sphere_widgets |
| 2577 |
|
| 2578 |
return sphere_widget |
| 2579 |
|
| 2580 |
def clear_sphere_widgets(self): |
| 2581 |
"""Remove all of the sphere widgets.""" |
| 2582 |
for sphere_widget in self.sphere_widgets: |
| 2583 |
sphere_widget.Off() |
| 2584 |
self.sphere_widgets.clear() |
| 2585 |
|
| 2586 |
@_deprecate_positional_args(allowed=['actor']) |
| 2587 |
def add_affine_transform_widget( # noqa: PLR0917 |
| 2588 |
self, |
| 2589 |
actor, |
| 2590 |
origin=None, |
| 2591 |
start: bool = True, # noqa: FBT001, FBT002 |
| 2592 |
scale=0.15, |
| 2593 |
line_radius=0.02, |
| 2594 |
always_visible: bool = True, # noqa: FBT001, FBT002 |
| 2595 |
axes_colors=None, |
| 2596 |
axes=None, |
| 2597 |
release_callback=None, |
| 2598 |
interact_callback=None, |
| 2599 |
): |
| 2600 |
"""Add a 3D affine transform widget. |
| 2601 |
|
| 2602 |
This widget allows interactive transformations including translation and |
| 2603 |
rotation using the left mouse button. |
| 2604 |
|
| 2605 |
Parameters |
| 2606 |
---------- |
| 2607 |
actor : pyvista.Actor |
| 2608 |
The actor to which the widget is attached to. |
| 2609 |
origin : sequence[float], optional |
| 2610 |
Origin of the widget. Default is the origin of the main actor. |
| 2611 |
start : bool, default: True |
| 2612 |
If True, start the widget immediately. |
| 2613 |
scale : float, default: 0.15 |
| 2614 |
Scale factor for the widget relative to the length of the actor. |
| 2615 |
line_radius : float, default: 0.02 |
| 2616 |
Relative radius of the lines composing the widget. |
| 2617 |
always_visible : bool, default: True |
| 2618 |
Make the widget always visible. Setting this to ``False`` will cause |
| 2619 |
the widget geometry to be hidden by other actors in the plotter. |
| 2620 |
axes_colors : tuple[ColorLike], optional |
| 2621 |
Uses the theme by default. Configure the individual axis colors by |
| 2622 |
modifying either the theme with ``pyvista.global_theme.axes.x_color = |
| 2623 |
<COLOR>`` or setting this with a ``tuple`` as in ``('r', 'g', 'b')``. |
| 2624 |
axes : numpy.ndarray, optional |
| 2625 |
``(3, 3)`` Numpy array defining the X, Y, and Z axes. By default |
| 2626 |
this matches the default coordinate system. |
| 2627 |
release_callback : callable, optional |
| 2628 |
Call this method when releasing the left mouse button. It is passed |
| 2629 |
the ``user_matrix`` of the actor. |
| 2630 |
interact_callback : callable, optional |
| 2631 |
Call this method when moving the mouse with the left mouse button |
| 2632 |
pressed down and a valid movement actor selected. It is passed the |
| 2633 |
``user_matrix`` of the actor. |
| 2634 |
|
| 2635 |
Returns |
| 2636 |
------- |
| 2637 |
pyvista.plotting.widgets.AffineWidget3D |
| 2638 |
The affine widget. |
| 2639 |
|
| 2640 |
Notes |
| 2641 |
----- |
| 2642 |
After interacting with the actor, the transform will be stored within |
| 2643 |
:attr:`pyvista.Prop3D.user_matrix` but will not be applied to the |
| 2644 |
dataset. Use this matrix in conjunction with |
| 2645 |
:func:`pyvista.DataObjectFilters.transform` to transform the dataset. |
| 2646 |
|
| 2647 |
Examples |
| 2648 |
-------- |
| 2649 |
Add the 3d affine widget. |
| 2650 |
|
| 2651 |
>>> import pyvista as pv |
| 2652 |
>>> pl = pv.Plotter() |
| 2653 |
>>> actor = pl.add_mesh(pv.Sphere()) |
| 2654 |
>>> widget = pl.add_affine_transform_widget(actor) |
| 2655 |
>>> pl.show() |
| 2656 |
|
| 2657 |
Access the transform from the actor. |
| 2658 |
|
| 2659 |
>>> actor.user_matrix |
| 2660 |
array([[1., 0., 0., 0.], |
| 2661 |
[0., 1., 0., 0.], |
| 2662 |
[0., 0., 1., 0.], |
| 2663 |
[0., 0., 0., 1.]]) |
| 2664 |
|
| 2665 |
""" |
| 2666 |
return AffineWidget3D( |
| 2667 |
self._plotter, |
| 2668 |
actor, |
| 2669 |
origin=origin, |
| 2670 |
start=start, |
| 2671 |
scale=scale, |
| 2672 |
line_radius=line_radius, |
| 2673 |
always_visible=always_visible, |
| 2674 |
axes_colors=axes_colors, |
| 2675 |
axes=axes, |
| 2676 |
release_callback=release_callback, |
| 2677 |
interact_callback=interact_callback, |
| 2678 |
) |
| 2679 |
|
| 2680 |
@_deprecate_positional_args(allowed=['callback']) |
| 2681 |
def add_checkbox_button_widget( # noqa: PLR0917 |
| 2682 |
self, |
| 2683 |
callback, |
| 2684 |
value: bool = False, # noqa: FBT001, FBT002 |
| 2685 |
position=(10.0, 10.0), |
| 2686 |
size=50, |
| 2687 |
border_size=5, |
| 2688 |
color_on='blue', |
| 2689 |
color_off='grey', |
| 2690 |
background_color='white', |
| 2691 |
): |
| 2692 |
"""Add a checkbox button widget to the scene. |
| 2693 |
|
| 2694 |
This is useless without a callback function. You can pass a callable |
| 2695 |
function that takes a single argument, the state of this button widget |
| 2696 |
and performs a task with that value. |
| 2697 |
|
| 2698 |
Parameters |
| 2699 |
---------- |
| 2700 |
callback : callable |
| 2701 |
The method called every time the button is clicked. This should take |
| 2702 |
a single parameter: the bool value of the button. |
| 2703 |
|
| 2704 |
value : bool, default: False |
| 2705 |
The default state of the button. |
| 2706 |
|
| 2707 |
position : sequence[float], default: (10.0, 10.0) |
| 2708 |
The absolute coordinates of the bottom left point of the button. |
| 2709 |
|
| 2710 |
size : int, default: 50 |
| 2711 |
The size of the button in number of pixels. |
| 2712 |
|
| 2713 |
border_size : int, default: 5 |
| 2714 |
The size of the borders of the button in pixels. |
| 2715 |
|
| 2716 |
color_on : ColorLike, optional |
| 2717 |
The color used when the button is checked. Default is ``'blue'``. |
| 2718 |
|
| 2719 |
color_off : ColorLike, optional |
| 2720 |
The color used when the button is not checked. Default is ``'grey'``. |
| 2721 |
|
| 2722 |
background_color : ColorLike, optional |
| 2723 |
The background color of the button. Default is ``'white'``. |
| 2724 |
|
| 2725 |
Returns |
| 2726 |
------- |
| 2727 |
:vtk:`vtkButtonWidget` |
| 2728 |
The VTK button widget configured as a checkbox button. |
| 2729 |
|
| 2730 |
Examples |
| 2731 |
-------- |
| 2732 |
The following example generates a static image of the widget. |
| 2733 |
|
| 2734 |
>>> import pyvista as pv |
| 2735 |
>>> mesh = pv.Sphere() |
| 2736 |
>>> pl = pv.Plotter() |
| 2737 |
>>> actor = pl.add_mesh(mesh) |
| 2738 |
>>> def toggle_vis(flag): |
| 2739 |
... actor.SetVisibility(flag) |
| 2740 |
>>> _ = pl.add_checkbox_button_widget(toggle_vis, value=True) |
| 2741 |
>>> pl.show() |
| 2742 |
|
| 2743 |
Download the interactive example at :ref:`checkbox_widget_example`. |
| 2744 |
|
| 2745 |
""" |
| 2746 |
msg = 'Cannot add a widget to a closed plotter.' |
| 2747 |
self._plotter._get_iren_not_none(msg) |
| 2748 |
|
| 2749 |
def create_button(color1, color2, color3, *, dims=(size, size, 1)): |
| 2750 |
color1 = np.array(Color(color1).int_rgb) |
| 2751 |
color2 = np.array(Color(color2).int_rgb) |
| 2752 |
color3 = np.array(Color(color3).int_rgb) |
| 2753 |
|
| 2754 |
n_points = dims[0] * dims[1] |
| 2755 |
button = pv.ImageData(dimensions=dims) |
| 2756 |
arr = np.array([color1] * n_points).reshape(dims[0], dims[1], 3) # fill with color1 |
| 2757 |
arr[1 : dims[0] - 1, 1 : dims[1] - 1] = color2 # apply color2 |
| 2758 |
arr[border_size : dims[0] - border_size, border_size : dims[1] - border_size] = ( |
| 2759 |
color3 # apply color3 |
| 2760 |
) |
| 2761 |
button.point_data['texture'] = arr.reshape(n_points, 3).astype(np.uint8) |
| 2762 |
return button |
| 2763 |
|
| 2764 |
button_on = create_button(color_on, background_color, color_on) |
| 2765 |
button_off = create_button(color_on, background_color, color_off) |
| 2766 |
|
| 2767 |
bounds = [ |
| 2768 |
position[0], |
| 2769 |
position[0] + size, |
| 2770 |
position[1], |
| 2771 |
position[1] + size, |
| 2772 |
0.0, |
| 2773 |
0.0, |
| 2774 |
] |
| 2775 |
|
| 2776 |
button_rep = _vtk.vtkTexturedButtonRepresentation2D() |
| 2777 |
button_rep.SetNumberOfStates(2) |
| 2778 |
button_rep.SetState(value) |
| 2779 |
button_rep.SetButtonTexture(0, button_off) |
| 2780 |
button_rep.SetButtonTexture(1, button_on) |
| 2781 |
button_rep.SetPlaceFactor(1) |
| 2782 |
button_rep.PlaceWidget(bounds) |
| 2783 |
|
| 2784 |
button_widget = _vtk.vtkButtonWidget() |
| 2785 |
button_widget.SetInteractor(self._plotter.iren.interactor) |
| 2786 |
button_widget.SetRepresentation(button_rep) |
| 2787 |
button_widget.SetCurrentRenderer(self._plotter.renderer) |
| 2788 |
button_widget.On() |
| 2789 |
|
| 2790 |
def _the_callback(widget, _event): |
| 2791 |
state = widget.GetRepresentation().GetState() |
| 2792 |
if callable(callback): |
| 2793 |
try_callback(callback, bool(state)) |
| 2794 |
|
| 2795 |
button_widget.AddObserver(_vtk.vtkCommand.StateChangedEvent, _the_callback) |
| 2796 |
self.button_widgets.append(button_widget) |
| 2797 |
return button_widget |
| 2798 |
|
| 2799 |
@_deprecate_positional_args(allowed=['callback', 'radio_button_group']) |
| 2800 |
def add_radio_button_widget( # noqa: PLR0917 |
| 2801 |
self, |
| 2802 |
callback, |
| 2803 |
radio_button_group, |
| 2804 |
value: bool = False, # noqa: FBT001, FBT002 |
| 2805 |
title=None, |
| 2806 |
position=(10.0, 10.0), |
| 2807 |
size=50, |
| 2808 |
border_size=8, |
| 2809 |
color_on='blue', |
| 2810 |
color_off='grey', |
| 2811 |
background_color=None, |
| 2812 |
): |
| 2813 |
"""Add a radio button widget to the scene. |
| 2814 |
|
| 2815 |
Radio buttons work in groups. Only one button in a group can be on at |
| 2816 |
at the same time. Typically you should add two or more buttons belonging |
| 2817 |
to a same radio button group. Each button should be passed a callback |
| 2818 |
function. This function will be called when a radio button in a group |
| 2819 |
is switched on, assuming it was not already on. |
| 2820 |
|
| 2821 |
Parameters |
| 2822 |
---------- |
| 2823 |
callback : callable |
| 2824 |
The method called when a radio button's state changes from off to |
| 2825 |
on. |
| 2826 |
|
| 2827 |
radio_button_group: str |
| 2828 |
Name of the group for the radio button. |
| 2829 |
|
| 2830 |
value : bool, default: False |
| 2831 |
The default state of the button. If multiple buttons in the same |
| 2832 |
group are initialized with to True state, only the last initialized |
| 2833 |
button will remain on. |
| 2834 |
|
| 2835 |
title: str, optional |
| 2836 |
String title to be displayed next to the radio button. |
| 2837 |
|
| 2838 |
position : sequence[float], default: (10.0, 10.0) |
| 2839 |
The absolute coordinates of the bottom left point of the button. |
| 2840 |
|
| 2841 |
size : int, default: 50 |
| 2842 |
The diameter of the button in number of pixels. |
| 2843 |
|
| 2844 |
border_size : int, default: 8 |
| 2845 |
The size of the borders of the button in pixels. |
| 2846 |
|
| 2847 |
color_on : ColorLike, default: ``'blue'`` |
| 2848 |
The color used when the button is checked. |
| 2849 |
|
| 2850 |
color_off : ColorLike, default: ``'grey'`` |
| 2851 |
The color used when the button is not checked. |
| 2852 |
|
| 2853 |
background_color : ColorLike, optional |
| 2854 |
The background color of the button. If not set, default will be set |
| 2855 |
as ``self._plotter.background_color``. |
| 2856 |
|
| 2857 |
Returns |
| 2858 |
------- |
| 2859 |
:vtk:`vtkButtonWidget` |
| 2860 |
The VTK button widget configured as a radio button. |
| 2861 |
|
| 2862 |
Examples |
| 2863 |
-------- |
| 2864 |
The following example creates a background color switcher. |
| 2865 |
|
| 2866 |
>>> import pyvista as pv |
| 2867 |
>>> pl = pv.Plotter() |
| 2868 |
>>> def set_bg(color): |
| 2869 |
... def wrapped_callback(): |
| 2870 |
... pl.background_color = color |
| 2871 |
... |
| 2872 |
... return wrapped_callback |
| 2873 |
>>> _ = pl.add_radio_button_widget( |
| 2874 |
... set_bg('white'), |
| 2875 |
... 'bgcolor', |
| 2876 |
... position=(10.0, 200.0), |
| 2877 |
... title='White', |
| 2878 |
... value=True, |
| 2879 |
... ) |
| 2880 |
>>> _ = pl.add_radio_button_widget( |
| 2881 |
... set_bg('lightblue'), |
| 2882 |
... 'bgcolor', |
| 2883 |
... position=(10.0, 140.0), |
| 2884 |
... title='Light Blue', |
| 2885 |
... ) |
| 2886 |
>>> _ = pl.add_radio_button_widget( |
| 2887 |
... set_bg('pink'), |
| 2888 |
... 'bgcolor', |
| 2889 |
... position=(10.0, 80.0), |
| 2890 |
... title='Pink', |
| 2891 |
... ) |
| 2892 |
>>> pl.show() |
| 2893 |
|
| 2894 |
""" |
| 2895 |
msg = 'Cannot add a widget to a closed plotter.' |
| 2896 |
self._plotter._get_iren_not_none(msg) |
| 2897 |
|
| 2898 |
if radio_button_group not in self.radio_button_widget_dict: |
| 2899 |
self.radio_button_widget_dict[radio_button_group] = [] |
| 2900 |
if title is not None: |
| 2901 |
if radio_button_group not in self.radio_button_title_dict: |
| 2902 |
self.radio_button_title_dict[radio_button_group] = [] |
| 2903 |
button_title = self._plotter.add_text( |
| 2904 |
title, |
| 2905 |
position=(position[0] + size + 10.0, position[1] + 7.5), |
| 2906 |
font_size=15, |
| 2907 |
) |
| 2908 |
self.radio_button_title_dict[radio_button_group].append(button_title) |
| 2909 |
|
| 2910 |
color_on = Color(color_on) |
| 2911 |
color_off = Color(color_off) |
| 2912 |
background_color = Color(background_color, default_color=self._plotter.background_color) |
| 2913 |
|
| 2914 |
def create_radio_button(fg_color, bg_color, size=size, smooth=2): # noqa: PLR0917 |
| 2915 |
fg_color = np.array(fg_color.int_rgb) |
| 2916 |
bg_color = np.array(bg_color.int_rgb) |
| 2917 |
|
| 2918 |
n_points = size**2 |
| 2919 |
button = pv.ImageData(dimensions=(size, size, 1)) |
| 2920 |
arr = np.array([bg_color] * n_points).reshape(size, size, 3) # fill background |
| 2921 |
|
| 2922 |
centre = size / 2 |
| 2923 |
rad_outer = centre |
| 2924 |
rad_inner = centre - border_size |
| 2925 |
# Paint radio button with simple anti-aliasing |
| 2926 |
for i, j in product(range(size), range(size)): |
| 2927 |
distance = np.sqrt((i - size / 2) ** 2 + (j - size / 2) ** 2) |
| 2928 |
if distance < rad_inner: |
| 2929 |
arr[i, j] = fg_color |
| 2930 |
elif rad_inner <= distance <= rad_inner + smooth: |
| 2931 |
blend = (distance - rad_inner) / smooth |
| 2932 |
arr[i, j] = (1 - blend) * fg_color + blend * bg_color |
| 2933 |
elif rad_outer - 2 * smooth <= distance <= rad_outer: |
| 2934 |
blend = abs(distance - rad_outer + smooth) / smooth |
| 2935 |
arr[i, j] = (1 - blend) * fg_color + blend * bg_color |
| 2936 |
|
| 2937 |
button.point_data['texture'] = arr.reshape(n_points, 3).astype(np.uint8) |
| 2938 |
return button |
| 2939 |
|
| 2940 |
button_on = create_radio_button(color_on, background_color) |
| 2941 |
button_off = create_radio_button(color_off, background_color) |
| 2942 |
|
| 2943 |
bounds = [ |
| 2944 |
position[0], |
| 2945 |
position[0] + size, |
| 2946 |
position[1], |
| 2947 |
position[1] + size, |
| 2948 |
0.0, |
| 2949 |
0.0, |
| 2950 |
] |
| 2951 |
|
| 2952 |
button_rep = _vtk.vtkTexturedButtonRepresentation2D() |
| 2953 |
button_rep.SetNumberOfStates(2) |
| 2954 |
button_rep.SetState(value) |
| 2955 |
button_rep.SetButtonTexture(0, button_off) |
| 2956 |
button_rep.SetButtonTexture(1, button_on) |
| 2957 |
button_rep.SetPlaceFactor(1) |
| 2958 |
button_rep.PlaceWidget(bounds) |
| 2959 |
button_rep.GetProperty().SetColor((1, 1, 1)) |
| 2960 |
|
| 2961 |
button_widget = _vtk.vtkButtonWidget() |
| 2962 |
button_widget.SetInteractor(self._plotter.iren.interactor) |
| 2963 |
button_widget.SetRepresentation(button_rep) |
| 2964 |
button_widget.SetCurrentRenderer(self._plotter.renderer) |
| 2965 |
button_widget.On() |
| 2966 |
|
| 2967 |
def toggle_other_buttons_off(widget): |
| 2968 |
other_buttons = [ |
| 2969 |
w for w in self.radio_button_widget_dict[radio_button_group] if w is not widget |
| 2970 |
] |
| 2971 |
for w in other_buttons: |
| 2972 |
w.GetRepresentation().SetState(0) |
| 2973 |
|
| 2974 |
def _the_callback(widget, _event): |
| 2975 |
widget_rep = widget.GetRepresentation() |
| 2976 |
state = widget_rep.GetState() |
| 2977 |
# Toggle back on, if button was already on, and was clicked off |
| 2978 |
if not state: |
| 2979 |
widget_rep.SetState(1) |
| 2980 |
state = True |
| 2981 |
else: |
| 2982 |
toggle_other_buttons_off(widget) |
| 2983 |
if callable(callback): |
| 2984 |
try_callback(callback) |
| 2985 |
|
| 2986 |
button_widget.AddObserver(_vtk.vtkCommand.StateChangedEvent, _the_callback) |
| 2987 |
self.radio_button_widget_dict[radio_button_group].append(button_widget) |
| 2988 |
if value: |
| 2989 |
toggle_other_buttons_off(button_widget) |
| 2990 |
return button_widget |
| 2991 |
|
| 2992 |
def clear_radio_button_widgets(self): |
| 2993 |
"""Remove all of the radio button widgets.""" |
| 2994 |
for widgets in self.radio_button_widget_dict.values(): |
| 2995 |
for widget in widgets: |
| 2996 |
widget.Off() |
| 2997 |
self.radio_button_widget_dict.clear() |
| 2998 |
for titles in self.radio_button_title_dict.values(): |
| 2999 |
for title in titles: |
| 3000 |
title.VisibilityOff() |
| 3001 |
self.radio_button_title_dict.clear() |
| 3002 |
|
| 3003 |
@_deprecate_positional_args |
| 3004 |
def add_camera_orientation_widget(self, animate: bool = True, n_frames=20): # noqa: FBT001, FBT002 |
| 3005 |
"""Add a camera orientation widget to the active renderer. |
| 3006 |
|
| 3007 |
Parameters |
| 3008 |
---------- |
| 3009 |
animate : bool, default: True |
| 3010 |
Enable or disable jump-to-axis-view animation. |
| 3011 |
|
| 3012 |
n_frames : int, default: 20 |
| 3013 |
The number of frames to animate the jump-to-axis-viewpoint feature. |
| 3014 |
|
| 3015 |
Returns |
| 3016 |
------- |
| 3017 |
:vtk:`vtkCameraOrientationWidget` |
| 3018 |
Camera orientation widget. |
| 3019 |
|
| 3020 |
See Also |
| 3021 |
-------- |
| 3022 |
:meth:`~pyvista.Plotter.add_axes` |
| 3023 |
Add arrow-style axes as an orientation widget. |
| 3024 |
|
| 3025 |
:meth:`~pyvista.Plotter.add_box_axes` |
| 3026 |
Add an axes box as an orientation widget. |
| 3027 |
|
| 3028 |
:ref:`axes_objects_example` |
| 3029 |
Example showing different axes objects. |
| 3030 |
|
| 3031 |
Examples |
| 3032 |
-------- |
| 3033 |
Add a camera orientation widget to the scene. |
| 3034 |
|
| 3035 |
>>> import pyvista as pv |
| 3036 |
>>> mesh = pv.Cube() |
| 3037 |
>>> pl = pv.Plotter() |
| 3038 |
>>> _ = pl.add_mesh(mesh, scalars=range(6), show_scalar_bar=False) |
| 3039 |
>>> _ = pl.add_camera_orientation_widget() |
| 3040 |
>>> pl.show() |
| 3041 |
|
| 3042 |
""" |
| 3043 |
widget = _vtk.vtkCameraOrientationWidget() |
| 3044 |
widget.SetParentRenderer(self._plotter.renderer) |
| 3045 |
widget.SetAnimate(animate) |
| 3046 |
widget.SetAnimatorTotalFrames(n_frames) |
| 3047 |
widget.On() |
| 3048 |
self.camera_widgets.append(widget) |
| 3049 |
return widget |
| 3050 |
|
| 3051 |
def clear_camera_widgets(self): |
| 3052 |
"""Remove all of the camera widgets.""" |
| 3053 |
for camera_widget in self.camera_widgets: |
| 3054 |
camera_widget.Off() |
| 3055 |
self.camera_widgets.clear() |
| 3056 |
|
| 3057 |
def clear_button_widgets(self): |
| 3058 |
"""Remove all of the button widgets.""" |
| 3059 |
for button_widget in self.button_widgets: |
| 3060 |
button_widget.Off() |
| 3061 |
self.button_widgets.clear() |
| 3062 |
|
| 3063 |
@_deprecate_positional_args(allowed=['logo']) |
| 3064 |
def add_logo_widget( # noqa: PLR0917 |
| 3065 |
self, |
| 3066 |
logo: ImageData | str | pathlib.Path | None = None, |
| 3067 |
position: VectorLike[float] = (0.75, 0.8), |
| 3068 |
size: VectorLike[float] = (0.2, 0.2), |
| 3069 |
opacity: float = 1.0, |
| 3070 |
): |
| 3071 |
"""Add a logo widget to the top of the viewport. |
| 3072 |
|
| 3073 |
If no logo is passed, the PyVista logo will be used. |
| 3074 |
|
| 3075 |
Parameters |
| 3076 |
---------- |
| 3077 |
logo : pyvista.ImageData or pathlib.Path, optional |
| 3078 |
The logo to display. If a pathlike is passed, it is assumed to be a |
| 3079 |
file path to an image. |
| 3080 |
|
| 3081 |
position : tuple(float), optional |
| 3082 |
The position of the logo in the viewport. The first value is the |
| 3083 |
horizontal position and the second value is the vertical position. |
| 3084 |
Both values must be between 0 and 1. |
| 3085 |
|
| 3086 |
size : tuple(float), optional |
| 3087 |
The size of the logo in the viewport. The first value is the |
| 3088 |
horizontal size and the second value is the vertical size. Both |
| 3089 |
values must be between 0 and 1. |
| 3090 |
|
| 3091 |
opacity : float, optional |
| 3092 |
The opacity of the logo. Must be between 0 and 1. |
| 3093 |
|
| 3094 |
Returns |
| 3095 |
------- |
| 3096 |
:vtk:`vtkLogoWidget` |
| 3097 |
The logo widget. |
| 3098 |
|
| 3099 |
Examples |
| 3100 |
-------- |
| 3101 |
Add a logo widget to the scene. |
| 3102 |
|
| 3103 |
>>> import pyvista as pv |
| 3104 |
>>> pl = pv.Plotter() |
| 3105 |
>>> _ = pl.add_logo_widget() |
| 3106 |
>>> _ = pl.add_mesh(pv.Sphere(), show_edges=True) |
| 3107 |
>>> pl.show() |
| 3108 |
|
| 3109 |
""" |
| 3110 |
if logo is None: |
| 3111 |
logo = pv.global_theme.logo_file |
| 3112 |
if logo is None: |
| 3113 |
# Fallback to PyVista logo |
| 3114 |
from pyvista import examples |
| 3115 |
|
| 3116 |
logo = examples.logofile |
| 3117 |
|
| 3118 |
if isinstance(logo, (str, pathlib.Path)): |
| 3119 |
logo = pv.read(logo, cls=pv.ImageData) |
| 3120 |
elif not isinstance(logo, pv.ImageData): |
| 3121 |
# Defensive runtime check: Python does not enforce type hints, |
| 3122 |
# so a caller may still pass something unexpected. |
| 3123 |
msg = 'Logo must be a pyvista.ImageData or a file path to an image.' # type: ignore[unreachable] |
| 3124 |
raise TypeError(msg) |
| 3125 |
|
| 3126 |
representation = _vtk.vtkLogoRepresentation() |
| 3127 |
representation.SetImage(logo) |
| 3128 |
representation.SetPosition(*position) |
| 3129 |
representation.SetPosition2(*size) |
| 3130 |
representation.GetImageProperty().SetOpacity(opacity) |
| 3131 |
widget = _vtk.vtkLogoWidget() |
| 3132 |
widget.SetInteractor(self._plotter.iren.interactor) |
| 3133 |
widget.SetRepresentation(representation) |
| 3134 |
widget.On() |
| 3135 |
self.logo_widgets.append(widget) |
| 3136 |
return widget |
| 3137 |
|
| 3138 |
def clear_logo_widgets(self): |
| 3139 |
"""Remove all of the logo widgets.""" |
| 3140 |
for logo_widget in self.logo_widgets: |
| 3141 |
logo_widget.Off() |
| 3142 |
self.logo_widgets.clear() |
| 3143 |
|
| 3144 |
def add_camera3d_widget(self): |
| 3145 |
"""Add a camera3d widget allow to move the camera. |
| 3146 |
|
| 3147 |
.. note:: |
| 3148 |
This widget requires ``vtk>=9.3.0``. |
| 3149 |
|
| 3150 |
Returns |
| 3151 |
------- |
| 3152 |
:vtk:`vtkCamera3DWidget` |
| 3153 |
The camera3d widget. |
| 3154 |
|
| 3155 |
Examples |
| 3156 |
-------- |
| 3157 |
Add a camera3d widget to the scene. |
| 3158 |
|
| 3159 |
>>> import pyvista as pv |
| 3160 |
>>> sphere = pv.Sphere() |
| 3161 |
>>> pl = pv.Plotter(shape=(1, 2)) |
| 3162 |
>>> _ = pl.add_mesh(sphere, show_edges=True) |
| 3163 |
>>> pl.subplot(0, 1) |
| 3164 |
>>> _ = pl.add_mesh(sphere, show_edges=True) |
| 3165 |
>>> _ = pl.add_camera3d_widget() |
| 3166 |
>>> pl.show(cpos=pl.camera_position) |
| 3167 |
|
| 3168 |
""" |
| 3169 |
if vtk_version_info < (9, 3, 0): # pragma: no cover |
| 3170 |
from pyvista.core.errors import VTKVersionError |
| 3171 |
|
| 3172 |
msg = 'vtkCamera3DWidget requires vtk>=9.3.0' |
| 3173 |
raise VTKVersionError(msg) |
| 3174 |
representation = _vtk.vtkCamera3DRepresentation() |
| 3175 |
representation.SetCamera(self._plotter.renderer.GetActiveCamera()) |
| 3176 |
widget = _vtk.vtkCamera3DWidget() |
| 3177 |
widget.SetInteractor(self._plotter.iren.interactor) |
| 3178 |
widget.SetRepresentation(representation) |
| 3179 |
widget.On() |
| 3180 |
self.camera3d_widgets.append(widget) |
| 3181 |
return widget |
| 3182 |
|
| 3183 |
def clear_camera3d_widgets(self): |
| 3184 |
"""Remove all of the camera3d widgets.""" |
| 3185 |
for camera3d_widget in self.camera3d_widgets: |
| 3186 |
camera3d_widget.Off() |
| 3187 |
self.camera3d_widgets.clear() |
| 3188 |
|
| 3189 |
def __plotter_close__(self) -> None: |
| 3190 |
"""Release widget state when the owning plotter closes.""" |
| 3191 |
self.clear_box_widgets() |
| 3192 |
self.clear_plane_widgets() |
| 3193 |
self.clear_line_widgets() |
| 3194 |
self.clear_slider_widgets() |
| 3195 |
self.clear_sphere_widgets() |
| 3196 |
self.clear_spline_widgets() |
| 3197 |
self.clear_button_widgets() |
| 3198 |
self.clear_radio_button_widgets() |
| 3199 |
self.clear_camera_widgets() |
| 3200 |
self.clear_measure_widgets() |
| 3201 |
self.clear_logo_widgets() |
| 3202 |
self.clear_camera3d_widgets() |