Debian Codegraph @

pyvista/plotting/plotter.py

raw
1 """PyVista plotting module."""
2
3 from __future__ import annotations
4
5 from collections.abc import Callable
6 from collections.abc import Iterable
7 from collections.abc import Iterator
8 from collections.abc import Mapping
9 from collections.abc import Sequence
10 import contextlib
11 from contextlib import contextmanager
12 from contextlib import suppress
13 from copy import deepcopy
14 import ctypes
15 from functools import wraps
16 import io
17 from itertools import cycle
18 import logging
19 import os
20 from pathlib import Path
21 import sys
22 import textwrap
23 from threading import Thread
24 import time
25 from typing import TYPE_CHECKING
26 from typing import Any
27 from typing import Literal
28 from typing import cast
29 import uuid
30 import warnings
31 import weakref
32
33 import numpy as np
34 import scooby
35
36 import pyvista as pv
37 from pyvista import _vtk
38 from pyvista._deprecate_positional_args import _deprecate_positional_args
39 from pyvista._warn_external import warn_external
40 from pyvista.core import _validation
41 from pyvista.core.errors import DeprecationError
42 from pyvista.core.errors import MissingDataError
43 from pyvista.core.errors import PyVistaDeprecationWarning
44 from pyvista.core.utilities.arrays import FieldAssociation
45 from pyvista.core.utilities.arrays import _coerce_pointslike_arg
46 from pyvista.core.utilities.arrays import convert_array
47 from pyvista.core.utilities.arrays import get_array
48 from pyvista.core.utilities.arrays import get_array_association
49 from pyvista.core.utilities.arrays import raise_not_matching
50 from pyvista.core.utilities.helpers import is_pyvista_dataset
51 from pyvista.core.utilities.helpers import wrap
52 from pyvista.core.utilities.misc import _BoundsSizeMixin
53 from pyvista.core.utilities.misc import _NoNewAttrMixin
54 from pyvista.core.utilities.misc import abstract_class
55 from pyvista.core.utilities.misc import assert_empty_kwargs
56
57 from ._plotting import _common_arg_parser
58 from ._plotting import _reduce_multicomponent_scalars_on_mesh
59 from ._plotting import _remap_scalars_through_topology_change
60 from ._plotting import _stamp_raw_numpy_scalars
61 from ._plotting import process_opacity
62 from ._property import Property
63 from .actor import Actor
64 from .camera import Camera
65 from .colors import Color
66 from .colors import get_cmap_safe
67 from .component_registry import register_plotter_component as _register_plotter_component
68 from .composite_mapper import CompositePolyDataMapper
69 from .errors import RenderWindowUnavailable
70 from .mapper import DataSetMapper
71 from .mapper import FixedPointVolumeRayCastMapper
72 from .mapper import GPUVolumeRayCastMapper
73 from .mapper import OpenGLGPUVolumeRayCastMapper
74 from .mapper import PointGaussianMapper
75 from .mapper import SmartVolumeMapper
76 from .mapper import UnstructuredGridVolumeRayCastMapper
77 from .mapper import _BaseMapper
78 from .mapper import _mapper_get_data_set_input
79 from .mapper import _mapper_has_data_set_input
80 from .opts import StereoType
81 from .picking import PickingComponent
82 from .render_window_interactor import RenderWindowInteractor
83 from .renderer import CameraPosition
84 from .renderer import Renderer
85 from .renderer import make_legend_face
86 from .renderers import Renderers
87 from .scalar_bars import ScalarBars
88 from .text import CornerAnnotation
89 from .text import Text
90 from .text import TextProperty
91 from .texture import numpy_to_texture
92 from .themes import Theme
93 from .utilities.algorithms import active_scalars_algorithm
94 from .utilities.algorithms import algorithm_to_mesh_handler
95 from .utilities.algorithms import callback_algorithm
96 from .utilities.algorithms import decimation_algorithm
97 from .utilities.algorithms import extract_surface_algorithm
98 from .utilities.algorithms import pointset_to_polydata_algorithm
99 from .utilities.algorithms import set_algorithm_input
100 from .utilities.algorithms import smooth_shading_algorithm
101 from .utilities.algorithms import triangulate_algorithm
102 from .utilities.gl_checks import uses_egl
103 from .utilities.regression import image_from_window
104 from .utilities.regression import run_image_filter
105 from .volume import Volume
106 from .volume_property import VolumeProperty
107 from .widgets import WidgetComponent
108
109 if TYPE_CHECKING:
110 import cycler
111 import imageio
112 from IPython.lib.display import IFrame
113 from PIL.Image import Image
114
115 from pyvista import DataSet
116 from pyvista import LookupTable
117 from pyvista import MultiBlock
118 from pyvista import PolyData
119 from pyvista import Texture
120 from pyvista import pyvista_ndarray
121 from pyvista.core._typing_core import BoundsTuple
122 from pyvista.core._typing_core import MatrixLike
123 from pyvista.core._typing_core import NumpyArray
124 from pyvista.core._typing_core import TransformLike
125 from pyvista.core._typing_core import VectorLike
126 from pyvista.core.utilities.arrays import CellLiteral
127 from pyvista.core.utilities.arrays import PointLiteral
128 from pyvista.jupyter import JupyterBackendOptions
129 from pyvista.plotting._typing import BackfaceArgs
130 from pyvista.plotting._typing import CameraPositionOptions
131 from pyvista.plotting._typing import Chart
132 from pyvista.plotting._typing import ColorLike
133 from pyvista.plotting._typing import ColormapOptions
134 from pyvista.plotting._typing import CullingOptions
135 from pyvista.plotting._typing import FontFamilyOptions
136 from pyvista.plotting._typing import LightingOptions
137 from pyvista.plotting._typing import OpacityOptions
138 from pyvista.plotting._typing import PlottableType
139 from pyvista.plotting._typing import ScalarBarArgs
140 from pyvista.plotting._typing import SilhouetteArgs
141 from pyvista.plotting._typing import StyleOptions
142 from pyvista.plotting.cube_axes_actor import CubeAxesActor
143 from pyvista.plotting.text import HorizontalOptions
144 from pyvista.plotting.text import VerticalOptions
145 from pyvista.trame.jupyter import EmbeddableWidget
146 from pyvista.trame.jupyter import Widget
147
148 from .opts import PointSpriteShape
149
150
151 SUPPORTED_FORMATS = ['.png', '.jpeg', '.jpg', '.bmp', '.tif', '.tiff']
152 FPS_1_OVER_60 = 1 / 60
153
154 if os.environ.get('PYVISTA_KILL_DISPLAY'): # pragma: no cover
155 from pyvista.core.errors import DeprecationError
156
157 msg = 'PYVISTA_KILL_DISPLAY has been deprecated'
158 DeprecationError(msg)
159
160
161 def close_all() -> bool:
162 """Close all open/active plotters and clean up memory.
163
164 Returns
165 -------
166 bool
167 ``True`` when all plotters have been closed.
168
169 """
170 for pl in list(_ALL_PLOTTERS.values()):
171 if not pl._closed:
172 pl.close()
173 _ALL_PLOTTERS.clear()
174 return True
175
176
177 log = logging.getLogger(__name__)
178 log.setLevel('CRITICAL')
179 log.addHandler(logging.StreamHandler())
180
181
182 def _attach_raw_scalars_via_callback( # noqa: PLR0917
183 algo: _vtk.vtkAlgorithm | _vtk.vtkAlgorithmOutput,
184 mesh: DataSet,
185 scalars: NumpyArray[float],
186 scalars_name: str,
187 preference: PointLiteral | CellLiteral,
188 ) -> tuple[_vtk.vtkAlgorithm | _vtk.vtkAlgorithmOutput, DataSet]:
189 """Splice a callback stage that attaches raw numpy scalars to the pipeline.
190
191 Used by :meth:`Plotter.add_mesh` when smooth shading is enabled on an
192 upstream :vtk:`vtkAlgorithm` input and the user passed a raw numpy
193 array. The scalars cannot be resolved by name on the pipeline output,
194 so we wrap ``algo`` in a :class:`CallbackFilterAlgorithm` that
195 shallow-copies each output and stamps the array on it.
196
197 Parameters
198 ----------
199 algo : :vtk:`vtkAlgorithm`
200 Upstream algorithm whose output should gain the scalars array.
201
202 mesh : pyvista.DataSet
203 Current pipeline-output mesh (used to preserve the output type).
204
205 scalars : numpy.ndarray
206 Array to attach. Captured by the callback closure.
207
208 scalars_name : str
209 Name under which to attach the array.
210
211 preference : str
212 Either ``'point'`` or ``'cell'``.
213
214 Returns
215 -------
216 algo : :vtk:`vtkAlgorithm`
217 The new wrapping algorithm.
218
219 mesh : pyvista.DataSet
220 The resolved pipeline-output mesh after wrapping.
221
222 """
223
224 def _attach(dataset: DataSet) -> DataSet:
225 output = dataset.copy(deep=False)
226 if preference == 'point':
227 output.point_data.set_array(scalars, scalars_name, deep_copy=False)
228 else:
229 output.cell_data.set_array(scalars, scalars_name, deep_copy=False)
230 return output
231
232 wrapped = callback_algorithm(algo, _attach, output_type=type(mesh))
233 resolved_mesh, resolved_algo = algorithm_to_mesh_handler(wrapped)
234 # ``algorithm_to_mesh_handler`` may return ``None`` for the algo slot
235 # when its input is a plain dataset; here we just wrapped a live algo,
236 # so this branch is unreachable.
237 assert resolved_algo is not None # noqa: S101
238 return resolved_algo, resolved_mesh
239
240
241 def _warn_xserver() -> None: # pragma: no cover
242 """Check if plotting is supported and persist this state.
243
244 Check once and cache this value between calls. Warn the user if
245 plotting is not supported. Configured to check on Linux and Mac
246 OS since the Windows check is not quick.
247
248 """
249 # disable windows check until we can get a fast way of verifying
250 # if windows has a windows manager (which it generally does)
251 if os.name == 'nt':
252 return
253
254 if not hasattr(_warn_xserver, 'has_support'):
255 _warn_xserver.has_support = pv.system_supports_plotting() # type: ignore[attr-defined]
256
257 if not _warn_xserver.has_support: # type: ignore[attr-defined]
258 # check if a display has been set
259 if 'DISPLAY' in os.environ:
260 return
261
262 # finally, check if using a backend that doesn't require an xserver
263 if pv.global_theme.jupyter_backend in [
264 'client',
265 'html',
266 ]:
267 return
268
269 # Check if VTK has EGL support
270 if uses_egl():
271 return
272
273 warn_external(
274 '\n'
275 'This system does not appear to be running an xserver.\n'
276 'PyVista will likely segfault when rendering.\n\n'
277 'Alternatively, an offscreen version using OSMesa libraries '
278 'and ``vtk`` is available as of VTK 9.5.\n',
279 )
280
281
282 @abstract_class
283 class BasePlotter(_BoundsSizeMixin):
284 """Base plotting class.
285
286 To be used by the :class:`pyvista.Plotter` and
287 :class:`pyvistaqt.QtInteractor` classes.
288
289 Parameters
290 ----------
291 shape : sequence[int] | str, optional
292 Two item sequence of sub-render windows inside of the main window.
293 Specify two across with ``shape=(2, 1)`` and a two by two grid
294 with ``shape=(2, 2)``. By default there is only one renderer.
295 Can also accept a string descriptor as shape. For example:
296
297 * ``shape="3|1"`` means 3 plots on the left and 1 on the right,
298 * ``shape="4/2"`` means 4 plots on top and 2 at the bottom.
299
300 border : bool, default: False
301 Draw a border around each render window.
302
303 border_color : ColorLike, default: 'k'
304 Either a string, rgb list, or hex color string. For example:
305
306 * ``color='white'``
307 * ``color='w'``
308 * ``color=[1.0, 1.0, 1.0]``
309 * ``color='#FFFFFF'``
310
311 border_width : float, default: 2.0
312 Width of the border in pixels when enabled.
313
314 title : str, optional
315 Window title.
316
317 splitting_position : float, optional
318 The splitting position of the renderers.
319
320 groups : tuple, optional
321 Grouping for renderers.
322
323 row_weights : tuple
324 Row weights for renderers.
325
326 col_weights : tuple, optional
327 Column weights for renderers.
328
329 lighting : str, default: 'light kit'
330 What lighting to set up for the plotter. Accepted options:
331
332 * ``'light_kit'``: a vtk Light Kit composed of 5 lights.
333 * ``'three lights'``: illumination using 3 lights.
334 * ``'none'``: no light sources at instantiation.
335
336 theme : pyvista.plotting.themes.Theme, optional
337 Plot-specific theme.
338
339 image_scale : int, optional
340 Scale factor when saving screenshots. Image sizes will be
341 the ``window_size`` multiplied by this scale factor.
342
343 **kwargs : dict, optional
344 Additional keyword arguments.
345
346 Examples
347 --------
348 Simple plotter example showing a blurred cube with a gradient background.
349
350 >>> import pyvista as pv
351 >>> pl = pv.Plotter()
352 >>> _ = pl.add_mesh(pv.Cube())
353 >>> pl.set_background('black', top='white')
354 >>> pl.add_blurring()
355 >>> pl.show()
356
357 """
358
359 mouse_position: tuple[int, int] | None = None
360 click_position: tuple[int, int] | None = None
361
362 @_deprecate_positional_args(allowed=['shape'])
363 def __init__( # noqa: PLR0917
364 self,
365 shape: Sequence[int] | str = (1, 1),
366 border: bool | None = None, # noqa: FBT001
367 border_color: ColorLike = 'k',
368 border_width: float = 2.0,
369 title: str | None = None,
370 splitting_position: float | None = None,
371 groups: Sequence[int] | None = None,
372 row_weights: Sequence[int] | None = None,
373 col_weights: Sequence[int] | None = None,
374 lighting: LightingOptions | None = 'light kit',
375 theme: Theme | None = None,
376 image_scale: int | None = None,
377 **kwargs,
378 ) -> None:
379 """Initialize base plotter."""
380 super().__init__(**kwargs) # cooperative multiple inheritance
381 log.debug('BasePlotter init start')
382 self._initialized = False
383
384 # Tracks plotter components (see
385 # ``pyvista.plotting.component_registry``) that have been
386 # constructed on this instance. ``close()`` walks this list in
387 # reverse to invoke each component's optional lifecycle hooks.
388 self._components: list[Any] = []
389
390 self.mapper: _BaseMapper | None = None
391 self.volume: Volume | None = None
392 self.text: CornerAnnotation | Text | None = None
393 self.iren: RenderWindowInteractor | None = None
394 self.mwriter: imageio.plugins.ffmpeg.Writer | None = None
395 self._gif_filename: Path | None = None
396 self.ren_win: _vtk.vtkRenderWindow | None = None
397
398 self._theme = Theme()
399 if theme is None:
400 # copy global theme to ensure local plot theme is fixed
401 # after creation.
402 self._theme.load_theme(pv.global_theme)
403 else:
404 if not isinstance(theme, Theme):
405 msg = ( # type: ignore[unreachable]
406 'Expected ``pyvista.plotting.themes.Theme`` for '
407 f'``theme``, not {type(theme).__name__}.'
408 )
409 raise TypeError(msg)
410 self._theme.load_theme(theme)
411
412 self.image_transparent_background = self._theme.transparent_background
413
414 # optional function to be called prior to closing
415 self.__before_close_callback = None
416 self.mesh: MultiBlock | DataSet | None = None
417 if title is None:
418 title = self._theme.title
419 self.title = str(title)
420
421 # add renderers
422 self.renderers = Renderers(
423 self,
424 shape=shape,
425 splitting_position=splitting_position,
426 row_weights=row_weights,
427 col_weights=col_weights,
428 groups=groups,
429 border=border,
430 border_color=border_color,
431 border_width=border_width,
432 )
433
434 # track if the camera has been set up
435 self._first_time = True
436 # Keep track of the scale
437
438 # track if render window has ever been rendered
439 self._rendered = False
440
441 self._on_render_callbacks: set[Callable[[BasePlotter], None]] = set()
442
443 # this helps managing closed plotters
444 self._closed = False
445
446 # lighting style; be forgiving with input (accept underscores
447 # and ignore case)
448 lighting_normalized = str(lighting).replace('_', ' ').lower()
449 if lighting_normalized == 'light kit':
450 self.enable_lightkit()
451 elif lighting_normalized == 'three lights':
452 self.enable_3_lights()
453 elif lighting_normalized != 'none':
454 msg = f'Invalid lighting option "{lighting}".'
455 raise ValueError(msg)
456
457 # Track all active plotters. This has the side effect of ensuring that plotters are not
458 # collected until `close()`. See https://github.com/pyvista/pyvista/pull/3245
459 # This variable should be safe as a variable name
460 self._id_name = f'P_{hex(id(self))}_{len(_ALL_PLOTTERS)}'
461 _ALL_PLOTTERS[self._id_name] = self
462
463 # Key bindings
464 self.reset_key_events()
465 log.debug('BasePlotter init stop')
466
467 self._image_depth_null: NumpyArray[bool] | None = None
468 self.last_image_depth: pv.pyvista_ndarray | None = None
469 self.last_image: pv.pyvista_ndarray | None = None
470 self.last_vtksz: str | Path | None = None
471 self._has_background_layer = False
472 if image_scale is None:
473 image_scale = self._theme.image_scale
474 self._image_scale = image_scale
475
476 # set hidden line removal based on theme
477 if self.theme.hidden_line_removal:
478 self.enable_hidden_line_removal()
479
480 self._initialized = True
481 self._suppress_rendering = False
482
483 def __getattr__(self, item: str) -> Any:
484 """Resolve plotter component plugin lookups on attribute miss.
485
486 Before falling through, check whether ``item`` matches a
487 pending ``pyvista.plotter_components`` entry point. A match
488 triggers a one-shot plugin import, after which normal attribute
489 resolution finds the newly-attached component descriptor.
490
491 Mirrors :meth:`pyvista.DataObject.__getattr__` so the plotter
492 and dataset extension points present the same lookup contract.
493 """
494 # Lazy import to avoid a circular dependency at module load time.
495 from pyvista.plotting.component_registry import _resolve_pending_component # noqa: PLC0415
496
497 if _resolve_pending_component(item):
498 return object.__getattribute__(self, item)
499 return super().__getattribute__(item)
500
501 def __dir__(self) -> list[str]:
502 """Include pending plotter-component names so tab completion surfaces them.
503
504 Plugin-contributed components registered via the
505 ``pyvista.plotter_components`` entry-point group are imported
506 lazily on first attribute access. Listing their names alongside
507 the normal attribute set lets IPython / Jupyter / REPL tab
508 completion surface them without paying the plugin import cost
509 ahead of time.
510 """
511 from pyvista.plotting.component_registry import _pending_component_names # noqa: PLC0415
512
513 return sorted({*super().__dir__(), *_pending_component_names()})
514
515 def _get_iren_not_none(self, msg: str | None = None) -> RenderWindowInteractor:
516 if (iren := self.iren) is None:
517 msg = msg if msg is not None else 'This plotting window is not interactive.'
518 raise RuntimeError(msg)
519 else:
520 return iren
521
522 def _get_mwriter_not_none(self, msg: str | None = None) -> imageio.plugins.ffmpeg.Writer:
523 if (mwriter := self.mwriter) is None:
524 msg = msg if msg is not None else 'This plotter has not opened a movie or GIF file.'
525 raise RuntimeError(msg)
526 else:
527 return mwriter
528
529 @property
530 def suppress_rendering(self) -> bool: # numpydoc ignore=RT01
531 """Get or set whether to suppress render calls.
532
533 Returns
534 -------
535 bool
536 ``True`` when rendering is suppressed.
537
538 """
539 return self._suppress_rendering
540
541 @suppress_rendering.setter
542 def suppress_rendering(self, value: bool) -> None:
543 self._suppress_rendering = bool(value)
544
545 @property
546 def render_window(self) -> _vtk.vtkRenderWindow | None: # numpydoc ignore=RT01
547 """Access the :vtk:`vtkRenderWindow` attached to this plotter.
548
549 If the plotter is closed, this will return ``None``.
550
551 Returns
552 -------
553 output : :vtk:`vtkRenderWindow` | None
554 Render window if the plotter is not closed.
555
556 Notes
557 -----
558 Subclass must set ``ren_win`` on initialization.
559
560 """
561 return self.ren_win
562
563 @property
564 def theme(self) -> Theme: # numpydoc ignore=RT01
565 """Return the theme used for this plotter.
566
567 Set the theme when initializing the plotter instance.
568
569 Returns
570 -------
571 pyvista.Theme
572 Theme of this plotter.
573
574 Examples
575 --------
576 Use the dark theme for a plotter.
577
578 >>> import pyvista as pv
579 >>> from pyvista import themes
580 >>> pl = pv.Plotter(theme=themes.DarkTheme())
581 >>> actor = pl.add_mesh(pv.Sphere())
582 >>> pl.show()
583
584 """
585 return self._theme
586
587 @theme.setter
588 def theme(self, theme: Theme) -> None: # noqa: ARG002
589 # Deprecated on 0.47.0, error in v0.49, estimated removal on v0.50
590 msg = (
591 'Assigning a theme for a plotter instance is deprecated '
592 'and will removed in a future version of PyVista. '
593 'Set the theme when initializing the plotter instance instead.'
594 )
595 raise DeprecationError(msg)
596
597 @_deprecate_positional_args(allowed=['filename'])
598 def import_gltf(self, filename: str | Path, set_camera: bool = True) -> None: # noqa: FBT001, FBT002
599 """Import a glTF file into the plotter.
600
601 See https://www.khronos.org/gltf/ for more information.
602
603 Parameters
604 ----------
605 filename : str | Path
606 Path to the glTF file.
607
608 set_camera : bool, default: True
609 Set the camera viewing angle to one compatible with the
610 default three.js perspective (``'xy'``).
611
612 Examples
613 --------
614 >>> import pyvista as pv
615 >>> from pyvista import examples
616 >>> helmet_file = examples.gltf.download_damaged_helmet() # doctest:+SKIP
617 >>> texture = examples.hdr.download_dikhololo_night() # doctest:+SKIP
618 >>> pl = pv.Plotter() # doctest:+SKIP
619 >>> pl.import_gltf(helmet_file) # doctest:+SKIP
620 >>> pl.set_environment_texture(cubemap) # doctest:+SKIP
621 >>> pl.camera.zoom(1.8) # doctest:+SKIP
622 >>> pl.show() # doctest:+SKIP
623
624 See :ref:`load_gltf_example` for a full example using this method.
625
626 """
627 filename = Path(filename).expanduser().resolve()
628 if not filename.is_file():
629 msg = f'Unable to locate {filename}'
630 raise FileNotFoundError(msg)
631
632 importer = _vtk.vtkGLTFImporter()
633 importer.SetFileName(filename) # type: ignore[arg-type]
634 importer.SetRenderWindow(self.render_window)
635 importer.Update()
636
637 # set camera position to a three.js viewing perspective
638 if set_camera:
639 self.camera_position = 'xy'
640
641 def import_vrml(self, filename: str | Path) -> None:
642 """Import a VRML file into the plotter.
643
644 Parameters
645 ----------
646 filename : str | Path
647 Path to the VRML file.
648
649 Examples
650 --------
651 >>> import pyvista as pv
652 >>> from pyvista import examples
653 >>> sextant_file = examples.vrml.download_sextant() # doctest:+SKIP
654 >>> pl = pv.Plotter() # doctest:+SKIP
655 >>> pl.import_vrml(sextant_file) # doctest:+SKIP
656 >>> pl.show() # doctest:+SKIP
657
658 See :ref:`load_vrml_example` for a full example using this method.
659
660 """
661 filename = Path(filename).expanduser().resolve()
662 if not filename.is_file():
663 msg = f'Unable to locate {filename}'
664 raise FileNotFoundError(msg)
665
666 importer = _vtk.vtkVRMLImporter()
667 importer.SetFileName(filename) # type: ignore[arg-type]
668 importer.SetRenderWindow(self.render_window)
669 importer.Update()
670
671 def import_3ds(self, filename: str | Path) -> None:
672 """Import a 3DS file into the plotter.
673
674 .. versionadded:: 0.44.0
675
676 Parameters
677 ----------
678 filename : str | Path
679 Path to the 3DS file.
680
681 Examples
682 --------
683 >>> import pyvista as pv
684 >>> from pyvista import examples
685 >>> download_3ds_file = examples.download_3ds.download_iflamigm()
686 >>> pl = pv.Plotter()
687 >>> pl.import_3ds(download_3ds_file)
688 >>> pl.show()
689
690 """
691 filename = Path(filename).expanduser().resolve()
692 if not Path(filename).is_file():
693 msg = f'Unable to locate {filename}'
694 raise FileNotFoundError(msg)
695
696 importer = _vtk.vtk3DSImporter()
697 importer.SetFileName(filename) # type: ignore[arg-type]
698 importer.SetRenderWindow(self.render_window)
699 importer.Update()
700
701 def import_obj(self, filename: str | Path, filename_mtl: str | Path | None = None) -> None:
702 """Import from .obj wavefront files.
703
704 .. versionadded:: 0.44.0
705
706 Parameters
707 ----------
708 filename : str | Path
709 Path to the .obj file.
710
711 filename_mtl : str | Path, optional
712 Path to the .mtl file.
713
714 Examples
715 --------
716 >>> import pyvista as pv
717 >>> from pyvista import examples
718 >>> download_obj_file = examples.download_room_surface_mesh(load=False)
719 >>> pl = pv.Plotter()
720 >>> pl.import_obj(download_obj_file)
721 >>> pl.show()
722
723 Import an .obj file with a texture.
724
725 >>> from pathlib import Path
726 >>> filename = examples.download_doorman(load=False)
727 >>> pl = pv.Plotter()
728 >>> pl.import_obj(filename)
729 >>> pl.show(cpos='xy')
730
731 """
732 filename = Path(filename).expanduser().resolve()
733 if not filename.is_file():
734 msg = f'Unable to locate {filename}'
735 raise FileNotFoundError(msg)
736
737 importer = _vtk.vtkOBJImporter()
738 importer.SetFileName(filename) # type:ignore[arg-type]
739 if filename_mtl is None:
740 filename_mtl_path = filename.with_suffix('.mtl')
741 else:
742 filename_mtl_path = Path(filename_mtl).expanduser().resolve()
743 if filename_mtl_path.is_file():
744 importer.SetFileNameMTL(str(filename_mtl_path))
745 importer.SetTexturePath(str(filename_mtl_path.parents[0]))
746 importer.SetRenderWindow(self.render_window)
747 importer.Update()
748
749 def export_html(self, filename: str | Path | None) -> io.StringIO | None:
750 """Export this plotter as an interactive scene to a HTML file.
751
752 Parameters
753 ----------
754 filename : str | Path
755 Path to export the html file to.
756
757 Returns
758 -------
759 StringIO
760 If filename is None, returns the HTML as a StringIO object.
761
762 Notes
763 -----
764 You will need ``trame`` installed.
765
766 Examples
767 --------
768 >>> import pyvista as pv
769 >>> from pyvista import examples
770 >>> mesh = examples.load_uniform()
771 >>> pl = pv.Plotter(shape=(1, 2))
772 >>> _ = pl.add_mesh(mesh, scalars='Spatial Point Data', show_edges=True)
773 >>> pl.subplot(0, 1)
774 >>> _ = pl.add_mesh(mesh, scalars='Spatial Cell Data', show_edges=True)
775 >>> pl.export_html('pv.html') # doctest:+SKIP
776
777 """
778 try:
779 from trame_vtk.tools.vtksz2html import write_html # noqa: PLC0415
780 except ImportError: # pragma: no cover
781 msg = 'Please install trame dependencies: pip install "pyvista[jupyter]"'
782 raise ImportError(msg)
783
784 data = self.export_vtksz(filename=None)
785 buffer = io.StringIO()
786 write_html(data, buffer)
787 buffer.seek(0)
788
789 if filename is None:
790 return buffer
791
792 filename = Path(filename)
793 if filename.suffix != '.html':
794 filename / '.html'
795
796 # Move to final destination
797 with filename.open('w', encoding='utf-8') as f:
798 f.write(buffer.read())
799 return None
800
801 def export_vtksz(
802 self,
803 filename: str | Path | None = 'scene-export.vtksz',
804 format: Literal['zip', 'json'] = 'zip', # noqa: A002
805 ) -> str | Path:
806 """Export this plotter as a VTK.js OfflineLocalView file.
807
808 The exported file can be viewed with the OfflineLocalView viewer
809 available at https://kitware.github.io/vtk-js/examples/OfflineLocalView.html
810
811 Parameters
812 ----------
813 filename : str | Path, optional
814 Path to export the file to. Defaults to ``'scene-export.vtksz'``.
815
816 format : str, optional
817 The format of the exported file. Defaults to ``'zip'``. Can be
818 either ``'zip'`` or ``'json'``.
819
820 Returns
821 -------
822 output : str | Path
823 The exported filename.
824
825 """
826 try:
827 from pyvista.trame import PyVistaLocalView # noqa: PLC0415
828 from pyvista.trame.jupyter import elegantly_launch # noqa: PLC0415
829 from pyvista.trame.views import get_server # noqa: PLC0415
830 except ImportError: # pragma: no cover
831 msg = 'Please install trame dependencies: pip install "pyvista[jupyter]"'
832 raise ImportError(msg)
833
834 # Ensure trame server is launched
835 server = get_server(pv.global_theme.trame.jupyter_server_name)
836 if not server.running:
837 elegantly_launch(pv.global_theme.trame.jupyter_server_name)
838
839 view = PyVistaLocalView(self, trame_server=server)
840
841 content = view.export(format=format)
842
843 view.release_resources()
844 # Make sure callbacks are unregistered
845 self._on_render_callbacks.remove(view._plotter_render_callback)
846
847 if filename is None:
848 return content
849
850 with Path(filename).open('wb') as f:
851 f.write(content)
852
853 return filename
854
855 @_deprecate_positional_args(allowed=['filename'])
856 def export_gltf( # noqa: PLR0917
857 self,
858 filename: str,
859 inline_data: bool = True, # noqa: FBT001, FBT002
860 rotate_scene: bool = True, # noqa: FBT001, FBT002
861 save_normals: bool = True, # noqa: FBT001, FBT002
862 ) -> None:
863 """Export the current rendering scene as a glTF file.
864
865 Visit https://gltf-viewer.donmccurdy.com/ for an online viewer.
866
867 See :vtk:`vtkGLTFExporter` for limitations regarding the exporter.
868
869 Parameters
870 ----------
871 filename : str
872 Path to export the gltf file to.
873
874 inline_data : bool, default: True
875 Sets if the binary data be included in the json file as a
876 base64 string. When ``True``, only one file is exported.
877
878 rotate_scene : bool, default: True
879 Rotate scene to be compatible with the glTF specifications.
880
881 save_normals : bool, default: True
882 Saves the point array ``'Normals'`` as ``'NORMAL'`` in
883 the outputted scene.
884
885 Notes
886 -----
887 The VTK exporter only supports :class:`pyvista.PolyData` datasets. If
888 the plotter contains any non-PolyData datasets, these will be converted
889 in the plotter, leading to a copy of the data internally.
890
891 Examples
892 --------
893 Output a simple point cloud represented as balls.
894
895 >>> import numpy as np
896 >>> import pyvista as pv
897 >>> rng = np.random.default_rng(seed=0)
898 >>> point_cloud = rng.random((100, 3))
899 >>> pdata = pv.PolyData(point_cloud)
900 >>> pdata['orig_sphere'] = np.arange(100)
901 >>> sphere = pv.Sphere(radius=0.02)
902 >>> pc = pdata.glyph(scale=False, geom=sphere, orient=False)
903 >>> pl = pv.Plotter()
904 >>> _ = pl.add_mesh(
905 ... pc,
906 ... cmap='reds',
907 ... smooth_shading=True,
908 ... show_scalar_bar=False,
909 ... )
910 >>> pl.export_gltf('balls.gltf') # doctest:+SKIP
911 >>> pl.show()
912
913 Output the orientation plotter.
914
915 >>> from pyvista import demos
916 >>> pl = demos.orientation_plotter()
917 >>> pl.export_gltf('orientation_plotter.gltf') # doctest:+SKIP
918 >>> pl.show()
919
920 """
921 if self.render_window is None:
922 msg = 'This plotter has been closed and is unable to export the scene.'
923 raise RuntimeError(msg)
924
925 # rotate scene to gltf compatible view
926 renamed_arrays = [] # any renamed normal arrays
927 if rotate_scene:
928 for renderer in self.renderers:
929 for actor in renderer.actors.values():
930 if hasattr(actor, 'RotateX'):
931 actor.RotateX(-90)
932 actor.RotateZ(-90)
933
934 if save_normals:
935 try:
936 mapper = actor.GetMapper()
937 if mapper is None:
938 continue
939 dataset = mapper.dataset
940 if not isinstance(dataset, pv.PolyData):
941 warn_external(
942 'Plotter contains non-PolyData datasets. These have been '
943 'overwritten with PolyData surfaces and are internally '
944 'copies of the original datasets.',
945 )
946
947 try:
948 dataset = dataset.extract_surface(
949 algorithm=None, pass_pointid=False, pass_cellid=False
950 )
951 mapper.SetInputData(dataset)
952 except (AttributeError, ValueError, TypeError): # pragma: no cover
953 warn_external(
954 'During gLTF export, failed to convert some '
955 'datasets to PolyData. Exported scene will not have '
956 'all datasets.',
957 )
958
959 if 'Normals' in dataset.point_data:
960 # By default VTK uses the 'Normals' point data for normals
961 # but gLTF uses NORMAL.
962 point_data = dataset.GetPointData()
963 array = point_data.GetArray('Normals')
964 array.SetName('NORMAL')
965 renamed_arrays.append(array)
966
967 except Exception as e: # noqa: BLE001 # pragma: no cover
968 log.debug('Failed to rename array during gLTF export: %s', e)
969
970 exporter = _vtk.vtkGLTFExporter()
971 exporter.SetRenderWindow(self.render_window)
972 exporter.SetFileName(filename)
973 exporter.SetInlineData(inline_data)
974 exporter.SetSaveNormal(save_normals)
975 exporter.Update()
976
977 # rotate back if applicable
978 if rotate_scene:
979 for renderer in self.renderers:
980 for actor in renderer.actors.values():
981 if hasattr(actor, 'RotateX'):
982 actor.RotateZ(90)
983 actor.RotateX(90)
984
985 # revert any renamed arrays
986 for array in renamed_arrays:
987 array.SetName('Normals')
988
989 def export_vrml(self, filename: str | Path) -> None:
990 """Export the current rendering scene as a VRML file.
991
992 See :vtk:`vtkVRMLExporter` for limitations regarding the exporter.
993
994 Parameters
995 ----------
996 filename : str | Path
997 Filename to export the scene to.
998
999 Examples
1000 --------
1001 >>> import pyvista as pv
1002 >>> from pyvista import examples
1003 >>> pl = pv.Plotter()
1004 >>> _ = pl.add_mesh(examples.load_hexbeam())
1005 >>> pl.export_vrml('sample') # doctest:+SKIP
1006
1007 """
1008 if self.render_window is None:
1009 msg = 'This plotter has been closed and cannot be shown.'
1010 raise RuntimeError(msg)
1011
1012 exporter = _vtk.vtkVRMLExporter()
1013 exporter.SetFileName(filename) # type: ignore[arg-type]
1014 exporter.SetRenderWindow(self.render_window)
1015 exporter.Write()
1016
1017 @_deprecate_positional_args
1018 def enable_hidden_line_removal(self, all_renderers: bool = True) -> None: # noqa: FBT001, FBT002
1019 """Enable hidden line removal.
1020
1021 Wireframe geometry will be drawn using hidden line removal if
1022 the rendering engine supports it.
1023
1024 Disable this with :func:`disable_hidden_line_removal
1025 <Plotter.disable_hidden_line_removal>`.
1026
1027 Parameters
1028 ----------
1029 all_renderers : bool, default: True
1030 If ``True``, applies to all renderers in subplots. If
1031 ``False``, then only applies to the active renderer.
1032
1033 Examples
1034 --------
1035 Create a side-by-side plotter and render a sphere in wireframe
1036 with hidden line removal enabled on the left and disabled on
1037 the right.
1038
1039 >>> import pyvista as pv
1040 >>> sphere = pv.Sphere(theta_resolution=20, phi_resolution=20)
1041 >>> pl = pv.Plotter(shape=(1, 2))
1042 >>> _ = pl.add_mesh(sphere, line_width=3, style='wireframe')
1043 >>> _ = pl.add_text('With hidden line removal')
1044 >>> pl.enable_hidden_line_removal(all_renderers=False)
1045 >>> pl.subplot(0, 1)
1046 >>> pl.disable_hidden_line_removal(all_renderers=False)
1047 >>> _ = pl.add_mesh(sphere, line_width=3, style='wireframe')
1048 >>> _ = pl.add_text('Without hidden line removal')
1049 >>> pl.show()
1050
1051 """
1052 if all_renderers:
1053 for renderer in self.renderers:
1054 renderer.enable_hidden_line_removal()
1055 else:
1056 self.renderer.enable_hidden_line_removal()
1057
1058 @_deprecate_positional_args
1059 def disable_hidden_line_removal(self, all_renderers: bool = True) -> None: # noqa: FBT001, FBT002
1060 """Disable hidden line removal.
1061
1062 Enable again with :func:`enable_hidden_line_removal
1063 <Plotter.enable_hidden_line_removal>`.
1064
1065 Parameters
1066 ----------
1067 all_renderers : bool, default: True
1068 If ``True``, applies to all renderers in subplots. If
1069 ``False``, then only applies to the active renderer.
1070
1071 Examples
1072 --------
1073 Enable and then disable hidden line removal.
1074
1075 >>> import pyvista as pv
1076 >>> pl = pv.Plotter()
1077 >>> pl.enable_hidden_line_removal()
1078 >>> pl.disable_hidden_line_removal()
1079
1080 """
1081 if all_renderers:
1082 for renderer in self.renderers:
1083 renderer.disable_hidden_line_removal()
1084 else:
1085 self.renderer.disable_hidden_line_removal()
1086
1087 @property
1088 def scalar_bar(self) -> _vtk.vtkScalarBarActor: # numpydoc ignore=RT01
1089 """First scalar bar (kept for backwards compatibility).
1090
1091 Returns
1092 -------
1093 :vtk:`vtkScalarBarActor`
1094 First scalar bar actor.
1095
1096 """
1097 return next(iter(self.scalar_bars.values()))
1098
1099 @property
1100 def _before_close_callback(self) -> Callable[[Plotter], None] | None:
1101 """Return the cached function (expecting a reference)."""
1102 if self.__before_close_callback is not None:
1103 return self.__before_close_callback()
1104 return None
1105
1106 @_before_close_callback.setter
1107 def _before_close_callback(self, func: Callable[[Plotter], None] | None) -> None:
1108 """Store a weakref.ref of the function being called."""
1109 if func is not None:
1110 self.__before_close_callback = weakref.ref(func)
1111 else:
1112 self.__before_close_callback = None
1113
1114 @property
1115 def shape(self) -> tuple[int] | tuple[int, int]:
1116 """Return the shape of the plotter.
1117
1118 Returns
1119 -------
1120 output : tuple[int] | tuple[int, int]
1121 Shape of the plotter.
1122
1123 Examples
1124 --------
1125 Return the plotter shape.
1126
1127 >>> import pyvista as pv
1128 >>> pl = pv.Plotter(shape=(2, 2))
1129 >>> pl.shape
1130 (2, 2)
1131
1132 >>> pl.show()
1133
1134 """
1135 return self.renderers.shape
1136
1137 @property
1138 def renderer(self) -> Renderer: # numpydoc ignore=RT01
1139 """Return the active renderer.
1140
1141 Returns
1142 -------
1143 pyvista.Renderer
1144 Active render.
1145
1146 Examples
1147 --------
1148 >>> import pyvista as pv
1149 >>> pl = pv.Plotter()
1150 >>> pl.renderer
1151 <Renderer(...) at ...>
1152
1153 """
1154 return self.renderers.active_renderer
1155
1156 def subplot(self, index_row: int, index_column: int | None = None) -> None:
1157 """Set the active subplot.
1158
1159 Parameters
1160 ----------
1161 index_row : int
1162 Index of the subplot to activate along the rows.
1163
1164 index_column : int, optional
1165 Index of the subplot to activate along the columns.
1166
1167 See Also
1168 --------
1169 link_views
1170 :ref:`multi_window_example`
1171 :ref:`sharing_scalar_bars_example`
1172
1173 Examples
1174 --------
1175 Create a 2 wide plot and set the background of right-hand plot
1176 to orange. Add a cube to the left plot and a sphere to the
1177 right.
1178
1179 >>> import pyvista as pv
1180 >>> pl = pv.Plotter(shape=(1, 2))
1181 >>> actor = pl.add_mesh(pv.Cube())
1182 >>> pl.subplot(0, 1)
1183 >>> actor = pl.add_mesh(pv.Sphere())
1184 >>> pl.set_background('orange', all_renderers=False)
1185 >>> pl.show()
1186
1187 """
1188 self.renderers.set_active_renderer(index_row, index_column)
1189
1190 @wraps(Renderer.add_ruler)
1191 def add_ruler(self, *args, **kwargs) -> _vtk.vtkAxisActor2D: # numpydoc ignore=PR01,RT01
1192 """Wrap ``Renderer.add_ruler``."""
1193 return self.renderer.add_ruler(*args, **kwargs)
1194
1195 @wraps(Renderer.add_legend_scale)
1196 def add_legend_scale(
1197 self, *args, **kwargs
1198 ) -> tuple[_vtk.vtkActor, _vtk.vtkProperty | None]: # numpydoc ignore=PR01,RT01
1199 """Wrap ``Renderer.add_legend_scale``."""
1200 return self.renderer.add_legend_scale(*args, **kwargs)
1201
1202 @wraps(Renderer.add_legend)
1203 def add_legend(self, *args, **kwargs) -> _vtk.vtkLegendBoxActor: # numpydoc ignore=PR01,RT01
1204 """Wrap ``Renderer.add_legend``."""
1205 return self.renderer.add_legend(*args, **kwargs)
1206
1207 @wraps(Renderer.remove_legend)
1208 def remove_legend(self, *args, **kwargs) -> None: # numpydoc ignore=PR01,RT01
1209 """Wrap ``Renderer.remove_legend``."""
1210 return self.renderer.remove_legend(*args, **kwargs)
1211
1212 @property
1213 def legend(self) -> _vtk.vtkLegendBoxActor | None: # numpydoc ignore=RT01
1214 """Legend actor.
1215
1216 There can only be one legend actor per renderer. If
1217 ``legend`` is ``None``, there is no legend actor.
1218
1219 Returns
1220 -------
1221 :vtk:`vtkLegendBoxActor`
1222 Legend actor.
1223
1224 """
1225 return self.renderer.legend
1226
1227 @wraps(Renderer.add_floor)
1228 def add_floor(self, *args, **kwargs) -> Actor: # numpydoc ignore=PR01,RT01
1229 """Wrap ``Renderer.add_floor``."""
1230 return self.renderer.add_floor(*args, **kwargs)
1231
1232 @wraps(Renderer.remove_floors)
1233 def remove_floors(self, *args, **kwargs) -> None: # numpydoc ignore=PR01,RT01
1234 """Wrap ``Renderer.remove_floors``."""
1235 return self.renderer.remove_floors(*args, **kwargs)
1236
1237 @_deprecate_positional_args
1238 def enable_3_lights(self, only_active: bool = False) -> None: # noqa: FBT001, FBT002
1239 """Enable 3-lights illumination.
1240
1241 This will replace all pre-existing lights in the scene.
1242
1243 Parameters
1244 ----------
1245 only_active : bool, default: False
1246 If ``True``, only change the active renderer. The default
1247 is that every renderer is affected.
1248
1249 Examples
1250 --------
1251 >>> from pyvista import demos
1252 >>> pl = demos.orientation_plotter()
1253 >>> pl.enable_3_lights()
1254 >>> pl.show()
1255
1256 Note how this varies from the default plotting.
1257
1258 >>> pl = demos.orientation_plotter()
1259 >>> pl.show()
1260
1261 """
1262
1263 def _to_pos(elevation: float, azimuth: float) -> tuple[float, float, float]:
1264 theta = azimuth * np.pi / 180.0
1265 phi = (90.0 - elevation) * np.pi / 180.0
1266 x = np.sin(theta) * np.sin(phi)
1267 y = np.cos(phi)
1268 z = np.cos(theta) * np.sin(phi)
1269 return x, y, z
1270
1271 renderers = [self.renderer] if only_active else self.renderers
1272 for renderer in renderers:
1273 renderer.remove_all_lights()
1274
1275 # Inspired from Mayavi's version of Raymond Maple 3-lights illumination
1276 intensities = [1, 0.6, 0.5]
1277 all_angles = [(45.0, 45.0), (-30.0, -60.0), (-30.0, 60.0)]
1278 for intensity, angles in zip(intensities, all_angles, strict=True):
1279 light = pv.Light(light_type='camera light')
1280 light.intensity = intensity
1281 light.position = _to_pos(*angles)
1282 for renderer in renderers:
1283 renderer.add_light(light)
1284
1285 def disable_3_lights(self) -> None:
1286 """Please use ``enable_lightkit``, this method has been deprecated."""
1287 from pyvista.core.errors import DeprecationError # noqa: PLC0415
1288
1289 msg = 'DEPRECATED: Please use ``enable_lightkit``'
1290 raise DeprecationError(msg)
1291
1292 @_deprecate_positional_args
1293 def enable_lightkit(self, only_active: bool = False) -> None: # noqa: FBT001, FBT002
1294 """Enable the default light-kit lighting.
1295
1296 See:
1297 https://www.researchgate.net/publication/2926068_LightKit_A_lighting_system_for_effective_visualization
1298
1299 This will replace all pre-existing lights in the renderer.
1300
1301 Parameters
1302 ----------
1303 only_active : bool, default: False
1304 If ``True``, only change the active renderer. The default is that
1305 every renderer is affected.
1306
1307 Examples
1308 --------
1309 Create a plotter without any lights and then enable the
1310 default light kit.
1311
1312 >>> import pyvista as pv
1313 >>> pl = pv.Plotter(lighting=None)
1314 >>> pl.enable_lightkit()
1315 >>> actor = pl.add_mesh(pv.Cube(), show_edges=True)
1316 >>> pl.show()
1317
1318 """
1319 renderers = [self.renderer] if only_active else self.renderers
1320
1321 light_kit = _vtk.vtkLightKit()
1322 for renderer in renderers:
1323 renderer.remove_all_lights()
1324 # Use the renderer as a vtkLightKit parser.
1325 # Feed it the LightKit, pop off the vtkLights, put back
1326 # pyvista Lights. This is the price we must pay for using
1327 # inheritance rather than composition.
1328 light_kit.AddLightsToRenderer(renderer)
1329 vtk_lights = renderer.lights
1330 renderer.remove_all_lights()
1331 for vtk_light in vtk_lights:
1332 light = pv.Light.from_vtk(vtk_light)
1333 renderer.add_light(light)
1334 renderer.LightFollowCameraOn()
1335
1336 @_deprecate_positional_args(allowed=['aa_type'])
1337 def enable_anti_aliasing(
1338 self,
1339 aa_type: Literal['ssaa', 'msaa', 'fxaa'] = 'ssaa',
1340 multi_samples: int | None = None,
1341 all_renderers: bool = True, # noqa: FBT001, FBT002
1342 ) -> None:
1343 """Enable anti-aliasing.
1344
1345 This tends to make edges appear softer and less pixelated.
1346
1347 Parameters
1348 ----------
1349 aa_type : str, default: "ssaa"
1350 Anti-aliasing type. See the notes below. One of the following:
1351
1352 * ``"ssaa"`` - Super-Sample Anti-Aliasing
1353 * ``"msaa"`` - Multi-Sample Anti-Aliasing
1354 * ``"fxaa"`` - Fast Approximate Anti-Aliasing
1355
1356 multi_samples : int, optional
1357 The number of multi-samples when ``aa_type`` is ``"msaa"``. Note
1358 that using this setting automatically enables this for all
1359 renderers. Defaults to the theme multi_samples.
1360
1361 all_renderers : bool, default: True
1362 If ``True``, applies to all renderers in subplots. If ``False``,
1363 then only applies to the active renderer.
1364
1365 Notes
1366 -----
1367 SSAA, or Super-Sample Anti-Aliasing is a brute force method of
1368 anti-aliasing. It results in the best image quality but comes at a
1369 tremendous resource cost. SSAA works by rendering the scene at a higher
1370 resolution. The final image is produced by downsampling the
1371 massive source image using an averaging filter. This acts as a low pass
1372 filter which removes the high frequency components that would cause
1373 jaggedness.
1374
1375 MSAA, or Multi-Sample Anti-Aliasing is an optimization of SSAA that
1376 reduces the amount of pixel shader evaluations that need to be computed
1377 by focusing on overlapping regions of the scene. The result is
1378 anti-aliasing along edges that is on par with SSAA and less
1379 anti-aliasing along surfaces as these make up the bulk of SSAA
1380 computations. MSAA is substantially less computationally expensive than
1381 SSAA and results in comparable image quality.
1382
1383 FXAA, or Fast Approximate Anti-Aliasing is an Anti-Aliasing technique
1384 that is performed entirely in post processing. FXAA operates on the
1385 rasterized image rather than the scene geometry. As a consequence,
1386 forcing FXAA or using FXAA incorrectly can result in the FXAA filter
1387 smoothing out parts of the visual overlay that are usually kept sharp
1388 for reasons of clarity as well as smoothing out textures. FXAA is
1389 inferior to MSAA but is almost free computationally and is thus
1390 desirable on low end platforms.
1391
1392 Examples
1393 --------
1394 Enable super-sample anti-aliasing (SSAA).
1395
1396 >>> import pyvista as pv
1397 >>> pl = pv.Plotter()
1398 >>> pl.enable_anti_aliasing('ssaa')
1399 >>> _ = pl.add_mesh(pv.Sphere(), show_edges=True)
1400 >>> pl.show()
1401
1402 See :ref:`anti_aliasing_example` for a full example demonstrating
1403 VTK's anti-aliasing approaches.
1404
1405 """
1406 # apply MSAA to entire render window
1407 if aa_type == 'msaa':
1408 if self.render_window is None:
1409 msg = 'The render window has been closed.'
1410 raise AttributeError(msg)
1411 if multi_samples is None:
1412 multi_samples = self._theme.multi_samples
1413 self.render_window.SetMultiSamples(multi_samples)
1414 return
1415 elif aa_type not in ['ssaa', 'fxaa']:
1416 msg = f'Invalid `aa_type` "{aa_type}". Should be either "fxaa", "ssaa", or "msaa"'
1417 raise ValueError(msg)
1418 else:
1419 # disable MSAA as SSAA or FXAA is being enabled
1420 self.render_window.SetMultiSamples(0) # type: ignore[union-attr]
1421
1422 if all_renderers:
1423 for renderer in self.renderers:
1424 renderer.enable_anti_aliasing(aa_type)
1425 else:
1426 self.renderer.enable_anti_aliasing(aa_type)
1427
1428 @_deprecate_positional_args
1429 def disable_anti_aliasing(self, all_renderers: bool = True) -> None: # noqa: FBT001, FBT002
1430 """Disable anti-aliasing.
1431
1432 Parameters
1433 ----------
1434 all_renderers : bool, default: True
1435 If ``True``, applies to all renderers in subplots. If ``False``,
1436 then only applies to the active renderer.
1437
1438 Examples
1439 --------
1440 >>> import pyvista as pv
1441 >>> pl = pv.Plotter()
1442 >>> pl.disable_anti_aliasing()
1443 >>> _ = pl.add_mesh(pv.Sphere(), show_edges=True)
1444 >>> pl.show()
1445
1446 See :ref:`anti_aliasing_example` for a full example demonstrating
1447 VTK's anti-aliasing approaches.
1448
1449 """
1450 self.render_window.SetMultiSamples(0) # type: ignore[union-attr]
1451
1452 if all_renderers:
1453 for renderer in self.renderers:
1454 renderer.disable_anti_aliasing()
1455 else:
1456 self.renderer.disable_anti_aliasing()
1457
1458 @wraps(Renderer.set_focus)
1459 def set_focus(self, *args, render: bool = True, **kwargs) -> None: # numpydoc ignore=PR01,RT01
1460 """Wrap ``Renderer.set_focus``."""
1461 log.debug('set_focus: %s, %s', str(args), str(kwargs))
1462 self.renderer.set_focus(*args, **kwargs)
1463 if render:
1464 self.render()
1465
1466 @wraps(Renderer.set_position)
1467 def set_position(
1468 self, *args, render: bool = True, **kwargs
1469 ) -> None: # numpydoc ignore=PR01,RT01
1470 """Wrap ``Renderer.set_position``."""
1471 self.renderer.set_position(*args, **kwargs)
1472 if render:
1473 self.render()
1474
1475 @wraps(Renderer.set_viewup)
1476 def set_viewup(
1477 self,
1478 *args,
1479 render: bool = True,
1480 **kwargs,
1481 ) -> None: # numpydoc ignore=PR01,RT01
1482 """Wrap ``Renderer.set_viewup``."""
1483 self.renderer.set_viewup(*args, **kwargs)
1484 if render:
1485 self.render()
1486
1487 @wraps(Renderer.add_orientation_widget)
1488 def add_orientation_widget(
1489 self, *args, **kwargs
1490 ) -> _vtk.vtkOrientationMarkerWidget: # numpydoc ignore=PR01,RT01
1491 """Wrap ``Renderer.add_orientation_widget``."""
1492 return self.renderer.add_orientation_widget(*args, **kwargs)
1493
1494 @wraps(Renderer.add_axes)
1495 def add_axes(
1496 self, *args, **kwargs
1497 ) -> (
1498 _vtk.vtkAxesActor | _vtk.vtkPropAssembly | _vtk.vtkAnnotatedCubeActor
1499 ): # numpydoc ignore=PR01,RT01
1500 """Wrap ``Renderer.add_axes``."""
1501 return self.renderer.add_axes(*args, **kwargs)
1502
1503 @wraps(Renderer.add_box_axes)
1504 def add_box_axes(
1505 self, *args, **kwargs
1506 ) -> _vtk.vtkAnnotatedCubeActor: # numpydoc ignore=PR01,RT01
1507 """Wrap ``Renderer.add_box_axes``."""
1508 return self.renderer.add_box_axes(*args, **kwargs)
1509
1510 @wraps(Renderer.add_north_arrow_widget)
1511 def add_north_arrow_widget(
1512 self, *args, **kwargs
1513 ) -> _vtk.vtkOrientationMarkerWidget: # numpydoc ignore=PR01,RT01
1514 """Wrap ``Renderer.add_north_arrow_widget``."""
1515 return self.renderer.add_north_arrow_widget(*args, **kwargs)
1516
1517 @wraps(Renderer.hide_axes)
1518 def hide_axes(self, *args, **kwargs) -> None: # numpydoc ignore=PR01,RT01
1519 """Wrap ``Renderer.hide_axes``."""
1520 return self.renderer.hide_axes(*args, **kwargs)
1521
1522 @wraps(Renderer.show_axes)
1523 def show_axes(self, *args, **kwargs) -> None: # numpydoc ignore=PR01,RT01
1524 """Wrap ``Renderer.show_axes``."""
1525 return self.renderer.show_axes(*args, **kwargs)
1526
1527 @wraps(Renderer.update_bounds_axes)
1528 def update_bounds_axes(self, *args, **kwargs) -> None: # numpydoc ignore=PR01,RT01
1529 """Wrap ``Renderer.update_bounds_axes``."""
1530 return self.renderer.update_bounds_axes(*args, **kwargs)
1531
1532 @wraps(Renderer.add_chart)
1533 def add_chart(self, *args, **kwargs) -> None: # numpydoc ignore=PR01,RT01
1534 """Wrap ``Renderer.add_chart``."""
1535 return self.renderer.add_chart(*args, **kwargs)
1536
1537 @wraps(Renderer.remove_chart)
1538 def remove_chart(self, *args, **kwargs) -> None: # numpydoc ignore=PR01,RT01
1539 """Wrap ``Renderer.remove_chart``."""
1540 return self.renderer.remove_chart(*args, **kwargs)
1541
1542 @wraps(Renderers.set_chart_interaction)
1543 def set_chart_interaction(self, *args, **kwargs) -> list[Chart]: # numpydoc ignore=PR01,RT01
1544 """Wrap ``Renderers.set_chart_interaction``."""
1545 return self.renderers.set_chart_interaction(*args, **kwargs)
1546
1547 @wraps(Renderer.add_actor)
1548 def add_actor(
1549 self, *args, **kwargs
1550 ) -> tuple[_vtk.vtkProp, _vtk.vtkProperty | None]: # numpydoc ignore=PR01,RT01
1551 """Wrap ``Renderer.add_actor``."""
1552 return self.renderer.add_actor(*args, **kwargs)
1553
1554 @wraps(Renderer.enable_parallel_projection)
1555 def enable_parallel_projection(self, *args, **kwargs) -> None: # numpydoc ignore=PR01,RT01
1556 """Wrap ``Renderer.enable_parallel_projection``."""
1557 return self.renderer.enable_parallel_projection(*args, **kwargs)
1558
1559 @wraps(Renderer.disable_parallel_projection)
1560 def disable_parallel_projection(self, *args, **kwargs) -> None: # numpydoc ignore=PR01,RT01
1561 """Wrap ``Renderer.disable_parallel_projection``."""
1562 return self.renderer.disable_parallel_projection(*args, **kwargs)
1563
1564 @wraps(Renderer.enable_ssao)
1565 def enable_ssao(self, *args, **kwargs) -> None: # numpydoc ignore=PR01,RT01
1566 """Wrap ``Renderer.enable_ssao``."""
1567 return self.renderer.enable_ssao(*args, **kwargs)
1568
1569 @wraps(Renderer.disable_ssao)
1570 def disable_ssao(self, *args, **kwargs) -> None: # numpydoc ignore=PR01,RT01
1571 """Wrap ``Renderer.disable_ssao``."""
1572 return self.renderer.disable_ssao(*args, **kwargs)
1573
1574 @wraps(Renderer.enable_shadows)
1575 def enable_shadows(self, *args, **kwargs) -> None: # numpydoc ignore=PR01,RT01
1576 """Wrap ``Renderer.enable_shadows``."""
1577 return self.renderer.enable_shadows(*args, **kwargs)
1578
1579 @wraps(Renderer.disable_shadows)
1580 def disable_shadows(self, *args, **kwargs) -> None: # numpydoc ignore=PR01,RT01
1581 """Wrap ``Renderer.disable_shadows``."""
1582 return self.renderer.disable_shadows(*args, **kwargs)
1583
1584 @property
1585 def parallel_projection(self) -> bool: # numpydoc ignore=RT01
1586 """Return or set parallel projection state of active render window."""
1587 return self.renderer.parallel_projection
1588
1589 @parallel_projection.setter
1590 def parallel_projection(self, state: bool) -> None:
1591 self.renderer.parallel_projection = state
1592
1593 @property
1594 def parallel_scale(self) -> float: # numpydoc ignore=RT01
1595 """Return or set parallel scale of active render window."""
1596 return self.renderer.parallel_scale
1597
1598 @parallel_scale.setter
1599 def parallel_scale(self, value: float) -> None:
1600 self.renderer.parallel_scale = value
1601
1602 @wraps(Renderer.add_axes_at_origin)
1603 def add_axes_at_origin(
1604 self, *args, **kwargs
1605 ) -> _vtk.vtkAxesActor: # numpydoc ignore=PR01,RT01
1606 """Wrap ``Renderer.add_axes_at_origin``."""
1607 return self.renderer.add_axes_at_origin(*args, **kwargs)
1608
1609 @wraps(Renderer.show_bounds)
1610 def show_bounds(self, *args, **kwargs) -> CubeAxesActor: # numpydoc ignore=PR01,RT01
1611 """Wrap ``Renderer.show_bounds``."""
1612 return self.renderer.show_bounds(*args, **kwargs)
1613
1614 @wraps(Renderer.add_bounding_box)
1615 def add_bounding_box(self, *args, **kwargs) -> Actor: # numpydoc ignore=PR01,RT01
1616 """Wrap ``Renderer.add_bounding_box``."""
1617 return self.renderer.add_bounding_box(*args, **kwargs)
1618
1619 @wraps(Renderer.remove_bounding_box)
1620 def remove_bounding_box(self, *args, **kwargs) -> None: # numpydoc ignore=PR01,RT01
1621 """Wrap ``Renderer.remove_bounding_box``."""
1622 return self.renderer.remove_bounding_box(*args, **kwargs)
1623
1624 @wraps(Renderer.remove_bounds_axes)
1625 def remove_bounds_axes(self, *args, **kwargs) -> None: # numpydoc ignore=PR01,RT01
1626 """Wrap ``Renderer.remove_bounds_axes``."""
1627 return self.renderer.remove_bounds_axes(*args, **kwargs)
1628
1629 @wraps(Renderer.show_grid)
1630 def show_grid(self, *args, **kwargs) -> CubeAxesActor: # numpydoc ignore=PR01,RT01
1631 """Wrap ``Renderer.show_grid``."""
1632 return self.renderer.show_grid(*args, **kwargs)
1633
1634 @wraps(Renderer.set_scale)
1635 def set_scale(self, *args, **kwargs) -> None: # numpydoc ignore=PR01,RT01
1636 """Wrap ``Renderer.set_scale``."""
1637 return self.renderer.set_scale(*args, **kwargs)
1638
1639 @wraps(Renderer.enable_depth_of_field)
1640 def enable_depth_of_field(self, *args, **kwargs) -> None: # numpydoc ignore=PR01,RT01
1641 """Wrap ``Renderer.enable_depth_of_field``."""
1642 return self.renderer.enable_depth_of_field(*args, **kwargs)
1643
1644 @wraps(Renderer.disable_depth_of_field)
1645 def disable_depth_of_field(self, *args, **kwargs) -> None: # numpydoc ignore=PR01,RT01
1646 """Wrap ``Renderer.disable_depth_of_field``."""
1647 return self.renderer.disable_depth_of_field(*args, **kwargs)
1648
1649 @wraps(Renderer.add_blurring)
1650 def add_blurring(self, *args, **kwargs) -> None: # numpydoc ignore=PR01,RT01
1651 """Wrap ``Renderer.add_blurring``."""
1652 return self.renderer.add_blurring(*args, **kwargs)
1653
1654 @wraps(Renderer.remove_blurring)
1655 def remove_blurring(self, *args, **kwargs) -> None: # numpydoc ignore=PR01,RT01
1656 """Wrap ``Renderer.remove_blurring``."""
1657 return self.renderer.remove_blurring(*args, **kwargs)
1658
1659 @wraps(Renderer.enable_eye_dome_lighting)
1660 def enable_eye_dome_lighting(self, *args, **kwargs) -> None: # numpydoc ignore=PR01,RT01
1661 """Wrap ``Renderer.enable_eye_dome_lighting``."""
1662 return self.renderer.enable_eye_dome_lighting(*args, **kwargs)
1663
1664 @wraps(Renderer.disable_eye_dome_lighting)
1665 def disable_eye_dome_lighting(self, *args, **kwargs) -> None: # numpydoc ignore=PR01,RT01
1666 """Wrap ``Renderer.disable_eye_dome_lighting``."""
1667 self.renderer.disable_eye_dome_lighting(*args, **kwargs)
1668
1669 @wraps(Renderer.reset_camera)
1670 def reset_camera(self, *args, **kwargs) -> None: # numpydoc ignore=PR01,RT01
1671 """Wrap ``Renderer.reset_camera``."""
1672 self.renderer.reset_camera(*args, **kwargs)
1673 self.render()
1674
1675 @wraps(Renderer.isometric_view)
1676 def isometric_view(self, *args, **kwargs) -> None: # numpydoc ignore=PR01,RT01
1677 """Wrap ``Renderer.isometric_view``."""
1678 self.renderer.isometric_view(*args, **kwargs)
1679
1680 @wraps(Renderer.view_isometric)
1681 def view_isometric(self, *args, **kwarg) -> None: # numpydoc ignore=PR01,RT01
1682 """Wrap ``Renderer.view_isometric``."""
1683 self.renderer.view_isometric(*args, **kwarg)
1684
1685 @wraps(Renderer.view_vector)
1686 def view_vector(self, *args, **kwarg) -> None: # numpydoc ignore=PR01,RT01
1687 """Wrap ``Renderer.view_vector``."""
1688 self.renderer.view_vector(*args, **kwarg)
1689
1690 @wraps(Renderer.view_xy)
1691 def view_xy(self, *args, **kwarg) -> None: # numpydoc ignore=PR01,RT01
1692 """Wrap ``Renderer.view_xy``."""
1693 self.renderer.view_xy(*args, **kwarg)
1694
1695 @wraps(Renderer.view_yx)
1696 def view_yx(self, *args, **kwarg) -> None: # numpydoc ignore=PR01,RT01
1697 """Wrap ``Renderer.view_yx``."""
1698 self.renderer.view_yx(*args, **kwarg)
1699
1700 @wraps(Renderer.view_xz)
1701 def view_xz(self, *args, **kwarg) -> None: # numpydoc ignore=PR01,RT01
1702 """Wrap ``Renderer.view_xz``."""
1703 self.renderer.view_xz(*args, **kwarg)
1704
1705 @wraps(Renderer.view_zx)
1706 def view_zx(self, *args, **kwarg) -> None: # numpydoc ignore=PR01,RT01
1707 """Wrap ``Renderer.view_zx``."""
1708 self.renderer.view_zx(*args, **kwarg)
1709
1710 @wraps(Renderer.view_yz)
1711 def view_yz(self, *args, **kwarg) -> None: # numpydoc ignore=PR01,RT01
1712 """Wrap ``Renderer.view_yz``."""
1713 self.renderer.view_yz(*args, **kwarg)
1714
1715 @wraps(Renderer.view_zy)
1716 def view_zy(self, *args, **kwarg) -> None: # numpydoc ignore=PR01,RT01
1717 """Wrap ``Renderer.view_zy``."""
1718 self.renderer.view_zy(*args, **kwarg)
1719
1720 @wraps(Renderer.disable)
1721 def disable(self, *args, **kwarg) -> None: # numpydoc ignore=PR01,RT01
1722 """Wrap ``Renderer.disable``."""
1723 self.renderer.disable(*args, **kwarg)
1724
1725 @wraps(Renderer.enable)
1726 def enable(self, *args, **kwarg) -> None: # numpydoc ignore=PR01,RT01
1727 """Wrap ``Renderer.enable``."""
1728 self.renderer.enable(*args, **kwarg)
1729
1730 @wraps(Renderer.enable_depth_peeling)
1731 def enable_depth_peeling(self, *args, **kwargs) -> bool | None: # numpydoc ignore=PR01,RT01
1732 """Wrap ``Renderer.enable_depth_peeling``."""
1733 if self.render_window is not None:
1734 result = self.renderer.enable_depth_peeling(*args, **kwargs)
1735 if result:
1736 self.render_window.AlphaBitPlanesOn()
1737 return result
1738 return None # pragma: no cover
1739
1740 @wraps(Renderer.disable_depth_peeling)
1741 def disable_depth_peeling(self) -> None: # numpydoc ignore=PR01,RT01
1742 """Wrap ``Renderer.disable_depth_peeling``."""
1743 if self.render_window is not None:
1744 self.render_window.AlphaBitPlanesOff()
1745 return self.renderer.disable_depth_peeling()
1746 return None # pragma: no cover
1747
1748 @wraps(Renderer.get_default_cam_pos)
1749 def get_default_cam_pos(self, *args, **kwargs) -> CameraPosition: # numpydoc ignore=PR01,RT01
1750 """Wrap ``Renderer.get_default_cam_pos``."""
1751 return self.renderer.get_default_cam_pos(*args, **kwargs)
1752
1753 @wraps(Renderer.remove_actor)
1754 def remove_actor(self, *args, **kwargs) -> bool: # numpydoc ignore=PR01,RT01
1755 """Wrap ``Renderer.remove_actor``."""
1756 for renderer in self.renderers:
1757 renderer.remove_actor(*args, **kwargs)
1758 return True
1759
1760 @wraps(Renderer.set_environment_texture)
1761 def set_environment_texture(self, *args, **kwargs) -> None: # numpydoc ignore=PR01,RT01
1762 """Wrap ``Renderer.set_environment_texture``."""
1763 return self.renderer.set_environment_texture(*args, **kwargs)
1764
1765 @wraps(Renderer.remove_environment_texture)
1766 def remove_environment_texture(self, *args, **kwargs) -> None: # numpydoc ignore=PR01,RT01
1767 """Wrap ``Renderer.remove_environment_texture``."""
1768 return self.renderer.remove_environment_texture(*args, **kwargs)
1769
1770 # Properties from Renderer ####
1771
1772 @property
1773 def actors(self) -> dict[str, _vtk.vtkProp]: # numpydoc ignore=RT01
1774 """Return the actors of the active renderer.
1775
1776 .. note::
1777
1778 This may include 2D actors such as :class:`~pyvista.Text`, 3D actors such
1779 as :class:`~pyvista.Actor`, and assemblies such as :class:`~pyvista.AxesAssembly`.
1780 The actors may also be unwrapped VTK objects.
1781
1782 Returns
1783 -------
1784 dict
1785 Dictionary of active actors.
1786
1787 """
1788 return self.renderer.actors
1789
1790 @property
1791 def camera(self) -> Camera: # numpydoc ignore=RT01
1792 """Return the active camera of the active renderer.
1793
1794 Returns
1795 -------
1796 pyvista.Camera
1797 Camera from the active renderer.
1798
1799 """
1800 if not self.renderer.camera.is_set:
1801 self.camera_position = self.get_default_cam_pos() # type: ignore[call-arg]
1802 self.reset_camera() # type: ignore[call-arg]
1803 self.renderer.camera.is_set = True
1804 return self.renderer.camera
1805
1806 @camera.setter
1807 def camera(self, camera: Camera) -> None:
1808 self.renderer.camera = camera
1809
1810 @property
1811 def camera_set(self) -> bool: # numpydoc ignore=RT01
1812 """Return or set if the camera of the active renderer has been set."""
1813 return self.renderer.camera.is_set
1814
1815 @camera_set.setter
1816 def camera_set(self, is_set: bool) -> None:
1817 self.renderer.camera.is_set = is_set
1818
1819 @property
1820 def bounds(self) -> BoundsTuple: # numpydoc ignore=RT01
1821 """Return the bounds of all VISIBLE actors present in the active rendering window.
1822
1823 Actors with ``visibility`` disabled or with ``use_bounds`` disabled are `not`
1824 included in the bounds.
1825
1826 .. versionchanged:: 0.45
1827
1828 Only the bounds of visible actors are now returned. Previously, the bounds
1829 of all actors was returned, regardless of visibility.
1830
1831 Returns
1832 -------
1833 BoundsTuple
1834 Bounds of all visible actors in the active renderer.
1835
1836 See Also
1837 --------
1838 compute_bounds
1839 Compute the bounds with options to enable or disable actor visibility.
1840
1841 Examples
1842 --------
1843 >>> import pyvista as pv
1844 >>> pl = pv.Plotter()
1845 >>> _ = pl.add_mesh(pv.Cube())
1846 >>> pl.bounds
1847 BoundsTuple(x_min = -0.5,
1848 x_max = 0.5,
1849 y_min = -0.5,
1850 y_max = 0.5,
1851 z_min = -0.5,
1852 z_max = 0.5)
1853
1854 """
1855 return self.renderer.bounds
1856
1857 @wraps(Renderer.compute_bounds)
1858 def compute_bounds(self, *args, **kwargs) -> BoundsTuple: # numpydoc ignore=PR01,RT01
1859 """Return the bounds of actors present in the renderer."""
1860 return self.renderer.compute_bounds(*args, **kwargs)
1861
1862 @property
1863 def length(self) -> float: # numpydoc ignore=RT01
1864 """Return the length of the diagonal of the bounding box of the scene."""
1865 return self.renderer.length
1866
1867 @property
1868 def center(self) -> tuple[float, float, float]:
1869 """Return the center of the active renderer.
1870
1871 Returns
1872 -------
1873 tuple[float, float, float]
1874 Center of the active renderer.
1875
1876 Examples
1877 --------
1878 >>> import pyvista as pv
1879 >>> pl = pv.Plotter()
1880 >>> _ = pl.add_mesh(pv.Cube())
1881 >>> pl.center
1882 (0.0, 0.0, 0.0)
1883
1884 """
1885 return self.renderer.center
1886
1887 @property
1888 def _scalar_bar_slots(self) -> set[int]:
1889 """Return the scalar bar slots of the active renderer."""
1890 return self.renderer._scalar_bar_slots
1891
1892 @_scalar_bar_slots.setter
1893 def _scalar_bar_slots(self, value: set[int]) -> None:
1894 """Set the scalar bar slots of the active renderer."""
1895 self.renderer._scalar_bar_slots = value
1896
1897 @property
1898 def _scalar_bar_slot_lookup(self) -> dict[str, int]:
1899 """Return the scalar bar slot lookup of the active renderer."""
1900 return self.renderer._scalar_bar_slot_lookup
1901
1902 @_scalar_bar_slot_lookup.setter
1903 def _scalar_bar_slot_lookup(self, value: dict[str, int]) -> None:
1904 self.renderer._scalar_bar_slot_lookup = value
1905
1906 @property
1907 def scale(self) -> list[float]: # numpydoc ignore=RT01
1908 """Return the scaling of the active renderer."""
1909 return self.renderer.scale
1910
1911 @scale.setter
1912 def scale(self, scale: list[float]) -> None:
1913 self.renderer.set_scale(*scale)
1914
1915 @property
1916 def camera_position(self) -> CameraPosition: # numpydoc ignore=RT01
1917 """Set or return the camera position of the active render window.
1918
1919 Examples
1920 --------
1921 Return the camera's position as a :class:`~pyvista.CameraPosition` object.
1922
1923 >>> import pyvista as pv
1924 >>> from pyvista import examples
1925 >>> mesh = examples.download_bunny_coarse()
1926 >>> pl = pv.Plotter()
1927 >>> _ = pl.add_mesh(mesh, show_edges=True, reset_camera=True)
1928 >>> cpos = pl.camera_position
1929
1930 Show the camera position. This implicitly calls ``repr(cpos)``.
1931
1932 >>> cpos
1933 CameraPosition(position=(0.02430, 0.0336, 0.9446),
1934 focal_point=(0.02430, 0.0336, -0.02225),
1935 viewup=(0.0, 1.0, 0.0))
1936
1937 Create a new :class:`~pyvista.CameraPosition` object by copy/pasting the repr and
1938 prepending the pyvista module, i.e. ``pv.``.
1939
1940 >>> new_cpos = pv.CameraPosition(
1941 ... position=(0.02430, 0.0336, 0.9446),
1942 ... focal_point=(0.02430, 0.0336, -0.02225),
1943 ... viewup=(0.0, 1.0, 0.0),
1944 ... )
1945
1946 Set the :attr:`camera_position` with this new object.
1947
1948 >>> pl.camera_position = new_cpos
1949
1950 Use ``print`` or ``str`` to obtain a list representation instead.
1951
1952 >>> print(cpos)
1953 [(0.02430, 0.0336, 0.9446),
1954 (0.02430, 0.0336, -0.02225),
1955 (0.0, 1.0, 0.0)]
1956
1957 Reposition it via a list of tuples.
1958
1959 >>> pl.camera_position = [
1960 ... (0.3914, 0.4542, 0.7670),
1961 ... (0.0243, 0.0336, -0.0222),
1962 ... (-0.2148, 0.8998, -0.3796),
1963 ... ]
1964 >>> pl.show()
1965
1966 Set the camera position using a string and look at the ``'xy'`` plane.
1967
1968 >>> pl = pv.Plotter()
1969 >>> _ = pl.add_mesh(mesh, show_edges=True)
1970 >>> pl.camera_position = 'xy'
1971 >>> pl.show()
1972
1973 Set the camera position using a string and look at the ``'zy'`` plane.
1974
1975 >>> pl = pv.Plotter()
1976 >>> _ = pl.add_mesh(mesh, show_edges=True)
1977 >>> pl.camera_position = 'zy'
1978 >>> pl.show()
1979
1980 For more examples, see :ref:`cameras_api`.
1981
1982 """
1983 return self.renderer.camera_position
1984
1985 @camera_position.setter
1986 def camera_position(self, camera_location: CameraPositionOptions) -> None:
1987 self.renderer.camera_position = camera_location
1988
1989 @property
1990 def background_color(self) -> Color: # numpydoc ignore=RT01
1991 """Return the background color of the active render window.
1992
1993 Examples
1994 --------
1995 Set the background color to ``"pink"`` and plot it.
1996
1997 >>> import pyvista as pv
1998 >>> pl = pv.Plotter()
1999 >>> _ = pl.add_mesh(pv.Cube(), show_edges=True)
2000 >>> pl.background_color = 'pink'
2001 >>> pl.background_color
2002 Color(name='pink', hex='#ffc0cbff', opacity=255)
2003 >>> pl.show()
2004
2005 """
2006 return self.renderers.active_renderer.background_color
2007
2008 @background_color.setter
2009 def background_color(self, color: Color) -> None:
2010 self.set_background(color) # type: ignore[arg-type]
2011
2012 @property
2013 def window_size(self) -> list[int]: # numpydoc ignore=RT01
2014 """Return the render window size in ``(width, height)``.
2015
2016 Examples
2017 --------
2018 Change the window size from ``200 x 200`` to ``400 x 400``.
2019
2020 >>> import pyvista as pv
2021 >>> pl = pv.Plotter(window_size=[200, 200])
2022 >>> pl.window_size
2023 [200, 200]
2024 >>> pl.window_size = [400, 400]
2025 >>> pl.window_size
2026 [400, 400]
2027
2028 """
2029 return list(self.render_window.GetSize()) # type: ignore[union-attr]
2030
2031 @window_size.setter
2032 def window_size(self, window_size: Sequence[int]) -> None:
2033 self.render_window.SetSize(window_size[0], window_size[1]) # type: ignore[union-attr]
2034 self._window_size_unset = False
2035 self.render()
2036
2037 @contextmanager
2038 def window_size_context(
2039 self, window_size: Sequence[int] | None = None
2040 ) -> Iterator[BasePlotter]:
2041 """Set the render window size in an isolated context.
2042
2043 Parameters
2044 ----------
2045 window_size : sequence[int], optional
2046 Window size in pixels. Defaults to :attr:`pyvista.Plotter.window_size`.
2047
2048 Examples
2049 --------
2050 Take two different screenshots with two different window sizes.
2051
2052 >>> import pyvista as pv
2053 >>> pl = pv.Plotter(off_screen=True)
2054 >>> _ = pl.add_mesh(pv.Cube())
2055 >>> with pl.window_size_context((400, 400)):
2056 ... pl.screenshot('/tmp/small_screenshot.png') # doctest:+SKIP
2057 >>> with pl.window_size_context((1000, 1000)):
2058 ... pl.screenshot('/tmp/big_screenshot.png') # doctest:+SKIP
2059
2060 """
2061 # No op if not set
2062 if window_size is None:
2063 yield self
2064 return
2065 # If render window is not current
2066 if self.render_window is None:
2067 warn_external('Attempting to set window_size on an unavailable render widow.')
2068 yield self
2069 return
2070 size_before = self.window_size
2071 if window_size is not None:
2072 self.window_size = window_size
2073 try:
2074 yield self
2075 finally:
2076 # Sometimes the render window is destroyed within the context
2077 # and re-setting will fail
2078 if self.render_window is not None:
2079 self.window_size = size_before
2080
2081 @property
2082 def image_depth(self) -> pv.pyvista_ndarray: # numpydoc ignore=RT01
2083 """Return a depth image representing current render window.
2084
2085 Helper attribute for ``get_image_depth``.
2086
2087 """
2088 return self.get_image_depth()
2089
2090 def _check_rendered(self) -> None:
2091 """Check if the render window has been shown and raise an exception if not."""
2092 if not self._rendered:
2093 msg = (
2094 '\nThis plotter has not yet been set up and rendered '
2095 'with ``show()``.\n'
2096 'Consider setting ``off_screen=True`` '
2097 'for off screen rendering.\n'
2098 )
2099 raise AttributeError(msg)
2100
2101 def _check_has_ren_win(self) -> None:
2102 """Check if render window attribute exists and raise an exception if not."""
2103 if self.render_window is None:
2104 msg = 'Render window is not available.'
2105 raise RenderWindowUnavailable(msg)
2106 if not self.render_window.IsCurrent():
2107 msg = 'Render window is not current.'
2108 raise RenderWindowUnavailable(msg)
2109
2110 def _make_render_window_current(self) -> None:
2111 if self.render_window is None:
2112 msg = 'Render window is not available.'
2113 raise RenderWindowUnavailable(msg)
2114 self.render_window.MakeCurrent() # pragma: no cover
2115
2116 def _enable_stereo_rendering(self, stereo_type: StereoType = StereoType.ANAGLYPH) -> None:
2117 """Enable stereo rendering.
2118
2119 This method must be called before the window is realized.
2120 """
2121 if self.render_window is None:
2122 msg = 'The render window has been closed.'
2123 raise AttributeError(msg)
2124 if not self.render_window.GetNeverRendered():
2125 msg = 'Stereo rendering must be enabled before the window is realized.'
2126 raise RuntimeError(msg)
2127 self.render_window.SetStereoCapableWindow(1)
2128 self.render_window.SetStereoType(stereo_type.value)
2129 self.render_window.SetStereoRender(1)
2130 self.render_window.StereoUpdate()
2131
2132 @property
2133 def image(self) -> pv.pyvista_ndarray: # numpydoc ignore=RT01
2134 """Return an image array of current render window.
2135
2136 Returns
2137 -------
2138 pyvista.pyvista_ndarray
2139 Image array of current render window.
2140
2141 Examples
2142 --------
2143 >>> import pyvista as pv
2144 >>> pl = pv.Plotter(off_screen=True)
2145 >>> _ = pl.add_mesh(pv.Cube())
2146 >>> pl.show()
2147 >>> pl.image # doctest:+SKIP
2148
2149 """
2150 if self.render_window is None and self.last_image is not None:
2151 return self.last_image
2152
2153 self._check_rendered()
2154 self._check_has_ren_win()
2155
2156 return image_from_window(
2157 self.render_window,
2158 scale=self.image_scale,
2159 ignore_alpha=not self.image_transparent_background,
2160 )
2161
2162 @property
2163 def image_scale(self) -> int: # numpydoc ignore=RT01
2164 """Get or set the scale factor when saving a screenshot.
2165
2166 This will scale up the screenshots taken of the render window to save a
2167 higher resolution image than what is rendered on screen.
2168
2169 Image sizes will be the :py:attr:`window_size
2170 <pyvista.Plotter.window_size>` multiplied by this scale factor.
2171
2172 Returns
2173 -------
2174 int
2175 Image scale factor.
2176
2177 Examples
2178 --------
2179 Double the resolution of a screenshot.
2180
2181 >>> import pyvista as pv
2182 >>> pl = pv.Plotter()
2183 >>> _ = pl.add_mesh(pv.Sphere())
2184 >>> pl.image_scale = 2
2185 >>> pl.screenshot('screenshot.png') # doctest:+SKIP
2186
2187 Set the image scale from ``Plotter``.
2188
2189 >>> import pyvista as pv
2190 >>> pl = pv.Plotter(image_scale=2)
2191 >>> _ = pl.add_mesh(pv.Sphere())
2192 >>> pl.screenshot('screenshot.png') # doctest:+SKIP
2193
2194 """
2195 return self._image_scale
2196
2197 @image_scale.setter
2198 def image_scale(self, value: int) -> None:
2199 value = int(value)
2200 if value < 1:
2201 msg = 'Scale factor must be a positive integer.'
2202 raise ValueError(msg)
2203 self._image_scale = value
2204
2205 @contextmanager
2206 def image_scale_context(self, scale: int | None = None) -> Iterator[BasePlotter]:
2207 """Set the image scale in an isolated context.
2208
2209 Parameters
2210 ----------
2211 scale : int, optional
2212 Integer scale factor. Defaults to :attr:`pyvista.Plotter.image_scale`.
2213
2214 """
2215 scale_before = self.image_scale
2216 if scale is not None:
2217 self.image_scale = scale
2218 try:
2219 yield self
2220 finally:
2221 self.image_scale = scale_before
2222
2223 def render(self) -> None:
2224 """Render the main window.
2225
2226 Will not render until ``show`` has been called.
2227
2228 Any render callbacks added with
2229 :func:`add_on_render_callback() <pyvista.Plotter.add_on_render_callback>`
2230 and the ``render_event=False`` option set will still execute on any call.
2231 """
2232 if (
2233 self.render_window is not None
2234 and not self._first_time
2235 and not self._suppress_rendering
2236 ):
2237 log.debug('Rendering')
2238 self.renderers.on_plotter_render()
2239 self.render_window.Render()
2240 self._rendered = True
2241 for callback in self._on_render_callbacks:
2242 callback(self)
2243
2244 @_deprecate_positional_args(allowed=['callback'])
2245 def add_on_render_callback(
2246 self,
2247 callback: Callable[[BasePlotter], None],
2248 render_event: bool = False, # noqa: FBT001, FBT002
2249 ) -> None:
2250 """Add a method to be called post-render.
2251
2252 Parameters
2253 ----------
2254 callback : callable
2255 The callback method to run post-render. This takes a single
2256 argument which is the plotter object.
2257
2258 render_event : bool, default: False
2259 If ``True``, associate with all VTK RenderEvents. Otherwise, the
2260 callback is only handled on a successful ``render()`` from the
2261 PyVista plotter directly.
2262
2263 """
2264 if render_event:
2265 for renderer in self.renderers:
2266 renderer.AddObserver(_vtk.vtkCommand.RenderEvent, lambda *_: callback(self))
2267 else:
2268 self._on_render_callbacks.add(callback)
2269
2270 def clear_on_render_callbacks(self) -> None:
2271 """Clear all callback methods previously registered with ``render()``."""
2272 for renderer in self.renderers:
2273 renderer.RemoveObservers(_vtk.vtkCommand.RenderEvent)
2274 self._on_render_callbacks = set()
2275
2276 @wraps(RenderWindowInteractor.add_key_event)
2277 def add_key_event(self, *args, **kwargs) -> None: # numpydoc ignore=PR01,RT01
2278 """Wrap RenderWindowInteractor.add_key_event."""
2279 if self.iren is not None:
2280 self.iren.add_key_event(*args, **kwargs)
2281
2282 @wraps(RenderWindowInteractor.add_timer_event)
2283 def add_timer_event(self, *args, **kwargs) -> None: # numpydoc ignore=PR01,RT01
2284 """Wrap RenderWindowInteractor.add_timer_event."""
2285 if self.iren is not None:
2286 self.iren.add_timer_event(*args, **kwargs)
2287
2288 @wraps(RenderWindowInteractor.clear_events_for_key)
2289 def clear_events_for_key(self, *args, **kwargs) -> None: # numpydoc ignore=PR01,RT01
2290 """Wrap RenderWindowInteractor.clear_events_for_key."""
2291 if self.iren is not None:
2292 self.iren.clear_events_for_key(*args, **kwargs)
2293
2294 def store_mouse_position(self, *args) -> None: # noqa: ARG002
2295 """Store mouse position."""
2296 self.mouse_position = self._get_iren_not_none().get_event_position()
2297
2298 def store_click_position(self, *args) -> None: # noqa: ARG002
2299 """Store click position in viewport coordinates."""
2300 self.click_position = self._get_iren_not_none().get_event_position()
2301 self.mouse_position = self.click_position
2302
2303 def track_mouse_position(self) -> None:
2304 """Keep track of the mouse position.
2305
2306 This will potentially slow down the interactor. No callbacks
2307 supported here - use
2308 :func:`pyvista.Plotter.track_click_position` instead.
2309
2310 """
2311 self._get_iren_not_none().track_mouse_position(self.store_mouse_position)
2312
2313 def untrack_mouse_position(self) -> None:
2314 """Stop tracking the mouse position."""
2315 self._get_iren_not_none().untrack_mouse_position()
2316
2317 @wraps(RenderWindowInteractor.track_click_position)
2318 def track_click_position(self, *args, **kwargs) -> None: # numpydoc ignore=PR01,RT01
2319 """Wrap RenderWindowInteractor.track_click_position."""
2320 self._get_iren_not_none().track_click_position(*args, **kwargs)
2321
2322 @wraps(RenderWindowInteractor.untrack_click_position)
2323 def untrack_click_position(self, *args, **kwargs) -> None: # numpydoc ignore=PR01,RT01
2324 """Stop tracking the click position."""
2325 self._get_iren_not_none().untrack_click_position(*args, **kwargs)
2326
2327 @property
2328 def pickable_actors(self) -> list[_vtk.vtkActor]: # numpydoc ignore=RT01
2329 """Return or set the pickable actors.
2330
2331 When setting, this will be the list of actors to make
2332 pickable. All actors not in the list will be made unpickable.
2333 If ``actors`` is ``None``, all actors will be made unpickable.
2334
2335 Returns
2336 -------
2337 list[:vtk:`vtkActor`]
2338 List of actors.
2339
2340 Examples
2341 --------
2342 Add two actors to a :class:`pyvista.Plotter`, make one
2343 pickable, and then list the pickable actors.
2344
2345 >>> import pyvista as pv
2346 >>> pl = pv.Plotter()
2347 >>> sphere_actor = pl.add_mesh(pv.Sphere())
2348 >>> cube_actor = pl.add_mesh(pv.Cube(), pickable=False, style='wireframe')
2349 >>> len(pl.pickable_actors)
2350 1
2351
2352 Set the pickable actors to both actors.
2353
2354 >>> pl.pickable_actors = [sphere_actor, cube_actor]
2355 >>> len(pl.pickable_actors)
2356 2
2357
2358 Set the pickable actors to ``None``.
2359
2360 >>> pl.pickable_actors = None
2361 >>> len(pl.pickable_actors)
2362 0
2363
2364 """
2365 return [
2366 actor
2367 for renderer in self.renderers
2368 for actor in renderer.actors.values()
2369 if actor.GetPickable()
2370 ]
2371
2372 @pickable_actors.setter
2373 def pickable_actors(self, actors: _vtk.vtkActor | list[_vtk.vtkActor] | None = None) -> None:
2374 actors = [] if actors is None else actors
2375 if isinstance(actors, _vtk.vtkActor):
2376 actors = [actors]
2377
2378 if not all(isinstance(actor, _vtk.vtkActor) for actor in actors):
2379 msg = (
2380 f'Expected a vtkActor instance or a list of vtkActors, got '
2381 f'{[type(actor) for actor in actors]} instead.'
2382 )
2383 raise TypeError(msg)
2384
2385 for renderer in self.renderers:
2386 for actor in renderer.actors.values():
2387 actor.SetPickable(actor in actors)
2388
2389 def _prep_for_close(self) -> None:
2390 """Make sure a screenshot is acquired before closing.
2391
2392 This doesn't actually close anything. It just preps the plotter for
2393 closing.
2394 """
2395 # Grab screenshot right before renderer closes
2396 self.last_image = self.screenshot(True, return_img=True)
2397 self.last_image_depth = self.get_image_depth()
2398
2399 def increment_point_size_and_line_width(self, increment: float) -> None:
2400 """Increment point size and line width of all actors.
2401
2402 For every actor in the scene, increment both its point size
2403 and line width by the given value.
2404
2405 Parameters
2406 ----------
2407 increment : float
2408 Amount to increment point size and line width.
2409
2410 """
2411 for renderer in self.renderers:
2412 for actor in renderer._actors:
2413 if hasattr(actor, 'GetProperty'):
2414 prop = actor.GetProperty()
2415 if hasattr(prop, 'SetPointSize'):
2416 prop.SetPointSize(prop.GetPointSize() + increment)
2417 if hasattr(prop, 'SetLineWidth'):
2418 prop.SetLineWidth(prop.GetLineWidth() + increment)
2419 self.render()
2420
2421 def zoom_camera(self, value: float | Literal['tight']) -> None:
2422 """Zoom of the camera and render.
2423
2424 Parameters
2425 ----------
2426 value : float or str
2427 Zoom of the camera. If a float, must be greater than 0. Otherwise,
2428 if a string, must be ``"tight"``. If tight, the plot will be zoomed
2429 such that the actors fill the entire viewport.
2430
2431 """
2432 self.camera.zoom(value)
2433 self.render()
2434
2435 def reset_key_events(self) -> None:
2436 """Reset all of the key press events to their defaults."""
2437 if self.iren is None:
2438 return
2439
2440 self.iren.clear_key_event_callbacks()
2441
2442 self.add_key_event('q', self._prep_for_close) # type: ignore[arg-type] # Add no matter what
2443 b_left_down_callback = lambda: self.iren.add_observer(
2444 'LeftButtonPressEvent',
2445 self.left_button_down,
2446 )
2447 self.add_key_event('b', b_left_down_callback) # type: ignore[arg-type]
2448 self.add_key_event('v', lambda: self.isometric_view_interactive()) # type: ignore[arg-type] # noqa: PLW0108
2449 self.add_key_event('C', lambda: self.enable_cell_picking()) # type: ignore[arg-type,call-arg] # noqa: PLW0108
2450 self.add_key_event('Up', lambda: self.zoom_camera(1.05)) # type: ignore[arg-type]
2451 self.add_key_event('Down', lambda: self.zoom_camera(0.95)) # type: ignore[arg-type]
2452 self.add_key_event('plus', lambda: self.increment_point_size_and_line_width(1)) # type: ignore[arg-type]
2453 self.add_key_event('minus', lambda: self.increment_point_size_and_line_width(-1)) # type: ignore[arg-type]
2454
2455 @wraps(RenderWindowInteractor.key_press_event)
2456 def key_press_event(self, *args, **kwargs) -> None: # numpydoc ignore=PR01,RT01
2457 """Wrap RenderWindowInteractor.key_press_event."""
2458 self._get_iren_not_none().key_press_event(*args, **kwargs)
2459
2460 def left_button_down(self, *args) -> None: # noqa: ARG002
2461 """Register the event for a left button down click."""
2462 attr = 'GetRenderFramebuffer'
2463 if (
2464 hasattr(renwin := self.render_window, attr)
2465 and not getattr(renwin, attr)().GetFBOIndex()
2466 ):
2467 # must raise a runtime error as this causes a segfault on VTK9
2468 msg = 'Invoking helper with no framebuffer'
2469 raise ValueError(msg)
2470
2471 # Get 2D click location on window
2472 click_pos = self._get_iren_not_none().get_event_position()
2473
2474 # Get corresponding click location in the 3D plot
2475 picker = _vtk.vtkWorldPointPicker()
2476 picker.Pick(click_pos[0], click_pos[1], 0, self.renderer)
2477 self.pickpoint = np.asarray(picker.GetPickPosition()).reshape((-1, 3))
2478 if np.any(np.isnan(self.pickpoint)):
2479 self.pickpoint[:] = 0
2480
2481 @wraps(RenderWindowInteractor.enable_trackball_style)
2482 def enable_trackball_style(self) -> None: # numpydoc ignore=PR01,RT01
2483 """Wrap RenderWindowInteractor.enable_trackball_style."""
2484 self._get_iren_not_none().enable_trackball_style()
2485
2486 @wraps(RenderWindowInteractor.enable_interactor_style)
2487 def enable_interactor_style(
2488 self, style: str | None = None
2489 ) -> None: # numpydoc ignore=PR01,RT01
2490 """Wrap RenderWindowInteractor.enable_interactor_style."""
2491 self._get_iren_not_none().enable_interactor_style(style)
2492
2493 @wraps(RenderWindowInteractor.enable_custom_trackball_style)
2494 def enable_custom_trackball_style(self, *args, **kwargs) -> None: # numpydoc ignore=PR01,RT01
2495 """Wrap RenderWindowInteractor.enable_custom_trackball_style."""
2496 self._get_iren_not_none().enable_custom_trackball_style(*args, **kwargs)
2497
2498 @wraps(RenderWindowInteractor.enable_trackball_actor_style)
2499 def enable_trackball_actor_style(self) -> None: # numpydoc ignore=PR01,RT01
2500 """Wrap RenderWindowInteractor.enable_trackball_actor_style."""
2501 self._get_iren_not_none().enable_trackball_actor_style()
2502
2503 @wraps(RenderWindowInteractor.enable_image_style)
2504 def enable_image_style(self) -> None: # numpydoc ignore=PR01,RT01
2505 """Wrap RenderWindowInteractor.enable_image_style."""
2506 self._get_iren_not_none().enable_image_style()
2507
2508 @wraps(RenderWindowInteractor.enable_joystick_style)
2509 def enable_joystick_style(self) -> None: # numpydoc ignore=PR01,RT01
2510 """Wrap RenderWindowInteractor.enable_joystick_style."""
2511 self._get_iren_not_none().enable_joystick_style()
2512
2513 @wraps(RenderWindowInteractor.enable_joystick_actor_style)
2514 def enable_joystick_actor_style(self) -> None: # numpydoc ignore=PR01,RT01
2515 """Wrap RenderWindowInteractor.enable_joystick_actor_style."""
2516 self._get_iren_not_none().enable_joystick_actor_style()
2517
2518 @wraps(RenderWindowInteractor.enable_zoom_style)
2519 def enable_zoom_style(self) -> None: # numpydoc ignore=PR01,RT01
2520 """Wrap RenderWindowInteractor.enable_zoom_style."""
2521 self._get_iren_not_none().enable_zoom_style()
2522
2523 @wraps(RenderWindowInteractor.enable_terrain_style)
2524 def enable_terrain_style(self, *args, **kwargs) -> None: # numpydoc ignore=PR01,RT01
2525 """Wrap RenderWindowInteractor.enable_terrain_style."""
2526 self._get_iren_not_none().enable_terrain_style(*args, **kwargs)
2527
2528 @wraps(RenderWindowInteractor.enable_rubber_band_style)
2529 def enable_rubber_band_style(self) -> None: # numpydoc ignore=PR01,RT01
2530 """Wrap RenderWindowInteractor.enable_rubber_band_style."""
2531 self._get_iren_not_none().enable_rubber_band_style()
2532
2533 @wraps(RenderWindowInteractor.enable_rubber_band_2d_style)
2534 def enable_rubber_band_2d_style(self) -> None: # numpydoc ignore=PR01,RT01
2535 """Wrap RenderWindowInteractor.enable_rubber_band_2d_style."""
2536 self._get_iren_not_none().enable_rubber_band_2d_style()
2537
2538 @wraps(RenderWindowInteractor.enable_2d_style)
2539 def enable_2d_style(self) -> None: # numpydoc ignore=PR01,RT01
2540 """Wrap RenderWindowInteractor.enable_2d_style."""
2541 self._get_iren_not_none().enable_2d_style()
2542
2543 def enable_stereo_render(self) -> None:
2544 """Enable anaglyph stereo rendering.
2545
2546 Disable this with :func:`disable_stereo_render
2547 <Plotter.disable_stereo_render>`
2548
2549 Examples
2550 --------
2551 Enable stereo rendering to show a cube as an anaglyph image.
2552
2553 >>> import pyvista as pv
2554 >>> pl = pv.Plotter()
2555 >>> _ = pl.add_mesh(pv.Cube())
2556 >>> pl.enable_stereo_render()
2557 >>> pl.show()
2558
2559 """
2560 if self.render_window is not None:
2561 self.render_window.SetStereoTypeToAnaglyph()
2562 self.render_window.StereoRenderOn()
2563
2564 def disable_stereo_render(self) -> None:
2565 """Disable anaglyph stereo rendering.
2566
2567 Enable again with :func:`enable_stereo_render
2568 <Plotter.enable_stereo_render>`
2569
2570 Examples
2571 --------
2572 Enable and then disable stereo rendering. It should show a simple cube.
2573
2574 >>> import pyvista as pv
2575 >>> pl = pv.Plotter()
2576 >>> _ = pl.add_mesh(pv.Cube())
2577 >>> pl.enable_stereo_render()
2578 >>> pl.disable_stereo_render()
2579 >>> pl.show()
2580
2581 """
2582 if self.render_window is not None:
2583 self.render_window.StereoRenderOff()
2584
2585 def hide_axes_all(self) -> None:
2586 """Hide the axes orientation widget in all renderers."""
2587 for renderer in self.renderers:
2588 renderer.hide_axes()
2589
2590 def show_axes_all(self) -> None:
2591 """Show the axes orientation widget in all renderers.
2592
2593 Examples
2594 --------
2595 >>> import pyvista as pv
2596 >>> from pyvista import examples
2597 >>>
2598 >>> mesh = examples.load_globe()
2599 >>> texture = examples.load_globe_texture()
2600 >>>
2601 >>> # create multi-window plot (1 row, 2 columns)
2602 >>> pl = pv.Plotter(shape=(1, 2))
2603 >>>
2604 >>> # activate subplot 1 and add a mesh
2605 >>> pl.subplot(0, 0)
2606 >>> _ = pl.add_mesh(mesh, texture=texture)
2607 >>>
2608 >>> # activate subplot 2 and add a mesh
2609 >>> pl.subplot(0, 1)
2610 >>> _ = pl.add_mesh(examples.load_airplane())
2611 >>>
2612 >>> # show the axes orientation widget in all subplots
2613 >>> pl.show_axes_all()
2614 >>>
2615 >>> # display the window
2616 >>> pl.show()
2617
2618 """
2619 for renderer in self.renderers:
2620 renderer.show_axes()
2621
2622 def isometric_view_interactive(self) -> None:
2623 """Set the current interactive render window to isometric view."""
2624 interactor = self._get_iren_not_none().get_interactor_style()
2625 renderer = interactor.GetCurrentRenderer()
2626 if renderer is None:
2627 renderer = self.renderer
2628 renderer.view_isometric()
2629
2630 @_deprecate_positional_args(allowed=['stime'])
2631 def update(self, stime: int = 1, force_redraw: bool = True) -> None: # noqa: FBT001, FBT002
2632 """Update window, redraw, process messages query.
2633
2634 Parameters
2635 ----------
2636 stime : int, default: 1
2637 Duration of timer that interrupt :vtk:`vtkRenderWindowInteractor`
2638 in milliseconds.
2639
2640 force_redraw : bool, default: True
2641 Call ``render`` immediately.
2642
2643 """
2644 if stime <= 0:
2645 stime = 1
2646
2647 curr_time = time.time()
2648 Plotter.last_update_time = min(Plotter.last_update_time, curr_time)
2649
2650 if self.iren is not None:
2651 update_rate = self.iren.get_desired_update_rate()
2652 if (curr_time - Plotter.last_update_time) > (1.0 / update_rate):
2653 # Allow interaction for a brief moment during interactive updating
2654 # Use the non-blocking ProcessEvents method.
2655 self.iren.process_events()
2656 # Rerender
2657 self.render()
2658 Plotter.last_update_time = curr_time
2659 return
2660
2661 if force_redraw:
2662 self.render()
2663
2664 @_deprecate_positional_args(allowed=['dataset'])
2665 def add_composite( # noqa: PLR0917
2666 self,
2667 dataset: MultiBlock,
2668 color: ColorLike | None = None,
2669 style: StyleOptions | None = None,
2670 scalars: str | None = None,
2671 clim: Sequence[float] | None = None,
2672 show_edges: bool | None = None, # noqa: FBT001
2673 edge_color: ColorLike | None = None,
2674 point_size: float | None = None,
2675 line_width: float | None = None,
2676 opacity: float | None = 1.0,
2677 flip_scalars: bool = False, # noqa: FBT001, FBT002
2678 lighting: bool | None = None, # noqa: FBT001
2679 n_colors: int = 256,
2680 interpolate_before_map: bool | None = True, # noqa: FBT001, FBT002
2681 cmap: ColormapOptions | LookupTable | None = None,
2682 label: str | None = None,
2683 reset_camera: bool | None = None, # noqa: FBT001
2684 scalar_bar_args: ScalarBarArgs | None = None,
2685 show_scalar_bar: bool | None = None, # noqa: FBT001
2686 multi_colors: bool | str | cycler.Cycler[str, ColorLike] | Sequence[ColorLike] = False, # noqa: FBT001, FBT002
2687 name: str | None = None,
2688 render_points_as_spheres: bool | None = None, # noqa: FBT001
2689 render_lines_as_tubes: bool | None = None, # noqa: FBT001
2690 smooth_shading: bool | None = None, # noqa: FBT001
2691 split_sharp_edges: bool | None = None, # noqa: FBT001
2692 ambient: float | None = None,
2693 diffuse: float | None = None,
2694 specular: float | None = None,
2695 specular_power: float | None = None,
2696 nan_color: ColorLike | None = None,
2697 nan_opacity: float = 1.0,
2698 culling: CullingOptions | bool | None = None, # noqa: FBT001
2699 rgb: bool | None = None, # noqa: FBT001
2700 below_color: ColorLike | None = None,
2701 above_color: ColorLike | None = None,
2702 annotations: dict[float, str] | None = None,
2703 pickable: bool = True, # noqa: FBT001, FBT002
2704 preference: PointLiteral | CellLiteral = 'point',
2705 log_scale: bool = False, # noqa: FBT001, FBT002
2706 pbr: bool | None = None, # noqa: FBT001
2707 metallic: float | None = None,
2708 roughness: float | None = None,
2709 render: bool = True, # noqa: FBT001, FBT002
2710 component: int | None = None,
2711 color_missing_with_nan: bool = False, # noqa: FBT001, FBT002
2712 copy_mesh: bool = False, # noqa: FBT001, FBT002
2713 show_vertices: bool | None = None, # noqa: FBT001
2714 edge_opacity: float | None = None,
2715 force_opaque: bool = False, # noqa: FBT001, FBT002
2716 **kwargs,
2717 ) -> tuple[Actor, CompositePolyDataMapper]:
2718 """Add a composite dataset to the plotter.
2719
2720 Parameters
2721 ----------
2722 dataset : pyvista.MultiBlock
2723 A :class:`pyvista.MultiBlock` dataset.
2724
2725 color : ColorLike, default: :attr:`pyvista.plotting.themes.Theme.color`
2726 Use to make the entire mesh have a single solid color.
2727 Either a string, RGB list, or hex color string. For example:
2728 ``color='white'``, ``color='w'``, ``color=[1.0, 1.0, 1.0]``, or
2729 ``color='#FFFFFF'``. Color will be overridden if scalars are
2730 specified. To color each element of the composite dataset
2731 individually, you will need to iteratively call ``add_mesh`` for
2732 each sub-dataset.
2733
2734 style : str, default: 'wireframe'
2735 Visualization style of the mesh. One of the following:
2736 ``style='surface'``, ``style='wireframe'``, ``style='points'``.
2737 Defaults to ``'surface'``. Note that ``'wireframe'`` only shows a
2738 wireframe of the outer geometry.
2739
2740 scalars : str, optional
2741 Scalars used to "color" the points or cells of the dataset.
2742 Accepts only a string name of an array that is present on the
2743 composite dataset.
2744
2745 clim : sequence[float], optional
2746 Two item color bar range for scalars. Defaults to minimum and
2747 maximum of scalars array. Example: ``[-1, 2]``. ``rng`` is
2748 also an accepted alias for this.
2749
2750 show_edges : bool, optional
2751 Shows the edges of a mesh. Does not apply to a wireframe
2752 representation.
2753
2754 Defaults to :attr:`pyvista.global_theme.show_edges
2755 <pyvista.plotting.themes.Theme.show_edges>`.
2756
2757 edge_color : ColorLike, optional
2758 The solid color to give the edges when ``show_edges=True``.
2759 Either a string, RGB list, or hex color string.
2760
2761 Defaults to :attr:`pyvista.global_theme.edge_color
2762 <pyvista.plotting.themes.Theme.edge_color>`.
2763
2764 point_size : float, default: 5.0
2765 Point size of any points in the dataset plotted. Also
2766 applicable when style='points'. Default ``5.0``.
2767
2768 line_width : float, optional
2769 Thickness of lines. Only valid for wireframe and surface
2770 representations.
2771
2772 opacity : float, default: 1.0
2773 Opacity of the mesh. A single float value that will be applied
2774 globally opacity of the mesh and uniformly
2775 applied everywhere - should be between 0 and 1.
2776
2777 flip_scalars : bool, default: False
2778 Flip direction of cmap. Most colormaps allow ``*_r``
2779 suffix to do this as well.
2780
2781 lighting : bool, default: True
2782 Enable or disable view direction lighting.
2783
2784 n_colors : int, default: 256
2785 Number of colors to use when displaying scalars. The scalar bar
2786 will also have this many colors.
2787
2788 interpolate_before_map : bool, default: True
2789 Enabling makes for a smoother scalars display. When ``False``,
2790 OpenGL will interpolate the mapped colors which can result in
2791 showing colors that are not present in the color map.
2792
2793 cmap : str | list | LookupTable, default: :attr:`pyvista.plotting.themes.Theme.cmap`
2794 If a string, this is the name of the ``matplotlib`` colormap to use
2795 when mapping the ``scalars``. See :ref:`named_colormaps` for supported
2796 colormaps.
2797 Only applicable for when displaying ``scalars``.
2798 ``colormap`` is also an accepted alias
2799 for this. If ``colorcet`` or ``cmocean`` are installed, their
2800 colormaps can be specified by name.
2801
2802 You can also specify a list of colors to override an existing
2803 colormap with a custom one. For example, to create a three color
2804 colormap you might specify ``['green', 'red', 'blue']``.
2805
2806 This parameter also accepts a :class:`pyvista.LookupTable`. If this
2807 is set, all parameters controlling the color map like ``n_colors``
2808 will be ignored.
2809
2810 label : str, optional
2811 String label to use when adding a legend to the scene with
2812 :func:`pyvista.Plotter.add_legend`.
2813
2814 reset_camera : bool, optional
2815 Reset the camera after adding this mesh to the scene. The default
2816 setting is ``None``, where the camera is only reset if this plotter
2817 has already been shown. If ``False``, the camera is not reset
2818 regardless of the state of the ``Plotter``. When ``True``, the
2819 camera is always reset.
2820
2821 scalar_bar_args : dict, optional
2822 Dictionary of keyword arguments to pass when adding the
2823 scalar bar to the scene. For options, see
2824 :func:`pyvista.Plotter.add_scalar_bar`.
2825
2826 show_scalar_bar : bool
2827 If ``False``, a scalar bar will not be added to the
2828 scene. Defaults to ``True`` unless ``rgba=True``.
2829
2830 multi_colors : bool | str | cycler.Cycler | sequence[ColorLike], default: False
2831 Color each block by a solid color using a custom cycler.
2832
2833 If ``True``, the default 'matplotlib' color cycler is used.
2834
2835 See :func:`set_color_cycler<Plotter.set_color_cycler>` for usage of
2836 custom color cyclers.
2837
2838 name : str, optional
2839 The name for the added mesh/actor so that it can be easily
2840 updated. If an actor of this name already exists in the
2841 rendering window, it will be replaced by the new actor.
2842
2843 render_points_as_spheres : bool, default: False
2844 Render points as spheres rather than dots.
2845
2846 render_lines_as_tubes : bool, default: False
2847 Show lines as thick tubes rather than flat lines. Control
2848 the width with ``line_width``.
2849
2850 smooth_shading : bool, default: :attr:`pyvista.plotting.themes.Theme.smooth_shading`
2851 Enable smooth shading when ``True`` using the Phong shading
2852 algorithm. When ``False``, uses flat shading. Automatically
2853 enabled when ``pbr=True``. See :ref:`shading_example`.
2854
2855 split_sharp_edges : bool, default: False
2856 Split sharp edges exceeding 30 degrees when plotting with smooth
2857 shading. Control the angle with the optional keyword argument
2858 ``feature_angle``. By default this is ``False`` unless overridden
2859 by the global or plotter theme. Note that enabling this will
2860 create a copy of the input mesh within the plotter. See
2861 :ref:`shading_example`.
2862
2863 ambient : float, default: 0.0
2864 When lighting is enabled, this is the amount of light in
2865 the range of 0 to 1 (default 0.0) that reaches the actor
2866 when not directed at the light source emitted from the
2867 viewer.
2868
2869 diffuse : float, default: 1.0
2870 The diffuse lighting coefficient.
2871
2872 specular : float, default: 0.0
2873 The specular lighting coefficient.
2874
2875 specular_power : float, default: 1.0
2876 The specular power. Between 0.0 and 128.0.
2877
2878 nan_color : ColorLike, default: :attr:`pyvista.plotting.themes.Theme.nan_color`
2879 The color to use for all ``NaN`` values in the plotted
2880 scalar array.
2881
2882 nan_opacity : float, default: 1.0
2883 Opacity of ``NaN`` values. Should be between 0 and 1.
2884
2885 culling : str, bool, default: False
2886 Does not render faces that are culled. This can be helpful for
2887 dense surface meshes, especially when edges are visible, but can
2888 cause flat meshes to be partially displayed. One of the following:
2889
2890 * ``True`` - Enable backface culling
2891 * ``"b"`` - Enable backface culling
2892 * ``"back"`` - Enable backface culling
2893 * ``"backface"`` - Enable backface culling
2894 * ``"f"`` - Enable frontface culling
2895 * ``"front"`` - Enable frontface culling
2896 * ``"frontface"`` - Enable frontface culling
2897 * ``False`` - Disable both backface and frontface culling
2898
2899 rgb : bool, default: False
2900 If an 2 dimensional array is passed as the scalars, plot
2901 those values as RGB(A) colors. ``rgba`` is also an
2902 accepted alias for this. Opacity (the A) is optional. If
2903 a scalars array ending with ``"_rgb"`` or ``"_rgba"`` is passed,
2904 the default becomes ``True``. This can be overridden by setting
2905 this parameter to ``False``.
2906
2907 below_color : ColorLike, optional
2908 Solid color for values below the scalars range
2909 (``clim``). This will automatically set the scalar bar
2910 ``below_label`` to ``'below'``.
2911
2912 above_color : ColorLike, optional
2913 Solid color for values below the scalars range
2914 (``clim``). This will automatically set the scalar bar
2915 ``above_label`` to ``'above'``.
2916
2917 annotations : dict, optional
2918 Pass a dictionary of annotations. Keys are the float
2919 values in the scalars range to annotate on the scalar bar
2920 and the values are the string annotations.
2921
2922 pickable : bool, default: True
2923 Set whether this actor is pickable.
2924
2925 preference : str, default: 'point'
2926 For each block, when ``block.n_points == block.n_cells`` and
2927 setting scalars, this parameter sets how the scalars will be mapped
2928 to the mesh. For example, when ``'point'`` the scalars will be
2929 associated with the mesh points if available. Can be either
2930 ``'point'`` or ``'cell'``.
2931
2932 log_scale : bool, default: False
2933 Use log scale when mapping data to colors. Scalars less
2934 than zero are mapped to the smallest representable
2935 positive float.
2936
2937 pbr : bool, default: False
2938 Enable physics based rendering (PBR) if the mesh is
2939 ``PolyData``. Use the ``color`` argument to set the base
2940 color.
2941
2942 metallic : float, default: 0.0
2943 Usually this value is either 0 or 1 for a real material
2944 but any value in between is valid. This parameter is only
2945 used by PBR interpolation.
2946
2947 roughness : float, default: 0.5
2948 This value has to be between 0 (glossy) and 1 (rough). A
2949 glossy material has reflections and a high specular
2950 part. This parameter is only used by PBR
2951 interpolation.
2952
2953 render : bool, default: True
2954 Force a render when ``True``.
2955
2956 component : int, optional
2957 Set component of vector valued scalars to plot. Must be
2958 nonnegative, if supplied. If ``None``, the magnitude of
2959 the vector is plotted.
2960
2961 color_missing_with_nan : bool, default: False
2962 Color any missing values with the ``nan_color``. This is useful
2963 when not all blocks of the composite dataset have the specified
2964 ``scalars``.
2965
2966 copy_mesh : bool, default: False
2967 If ``True``, a copy of the mesh will be made before adding it to
2968 the plotter. This is useful if e.g. you would like to add the same
2969 mesh to a plotter multiple times and display different
2970 scalars. Setting ``copy_mesh`` to ``False`` is necessary if you
2971 would like to update the mesh after adding it to the plotter and
2972 have these updates rendered, e.g. by changing the active scalars or
2973 through an interactive widget.
2974
2975 show_vertices : bool, optional
2976 When ``style`` is not ``'points'``, render the external surface
2977 vertices. The following optional keyword arguments may be used to
2978 control the style of the vertices:
2979
2980 * ``vertex_color`` - The color of the vertices
2981 * ``vertex_style`` - Change style to ``'points_gaussian'``
2982 * ``vertex_opacity`` - Control the opacity of the vertices
2983
2984 edge_opacity : float, optional
2985 Edge opacity of the mesh. A single float value that will be applied globally
2986 edge opacity of the mesh and uniformly applied everywhere - should be
2987 between 0 and 1.
2988
2989 .. note::
2990 `edge_opacity` uses ``SetEdgeOpacity`` as the underlying method which
2991 requires VTK version 9.3 or higher. If ``SetEdgeOpacity`` is not
2992 available, `edge_opacity` is set to 1.
2993
2994 force_opaque : bool, default: False
2995 Whether to force the returned actor to be opaque. Can be useful for web visualization
2996 with ``culling = "front"`` and ``opacity`` smaller than 1.
2997 See https://github.com/Kitware/trame-vtk/issues/105 for more details.
2998
2999 .. versionadded:: 0.48
3000
3001 **kwargs : dict, optional
3002 Optional keyword arguments.
3003
3004 Returns
3005 -------
3006 pyvista.Actor
3007 Actor of the composite dataset.
3008
3009 pyvista.CompositePolyDataMapper
3010 Composite PolyData mapper.
3011
3012 Examples
3013 --------
3014 Add a sphere and a cube as a multiblock dataset to a plotter and then
3015 change the visibility and color of the blocks.
3016
3017 Note index ``1`` and ``2`` are used to access the individual blocks of
3018 the composite dataset. This is because the :class:`pyvista.MultiBlock`
3019 is the root node of the "tree" and is index ``0``. This allows you to
3020 access individual blocks or the entire composite dataset itself in the
3021 case of multiple nested composite datasets.
3022
3023 >>> import pyvista as pv
3024 >>> dataset = pv.MultiBlock([pv.Cube(), pv.Sphere(center=(0, 0, 1))])
3025 >>> pl = pv.Plotter()
3026 >>> actor, mapper = pl.add_composite(dataset)
3027 >>> mapper.block_attr[1].color = 'b'
3028 >>> mapper.block_attr[1].opacity = 0.5
3029 >>> mapper.block_attr[2].color = 'r'
3030 >>> pl.show()
3031
3032 """
3033 if not isinstance(dataset, _vtk.vtkCompositeDataSet):
3034 msg = f'Invalid type ({type(dataset)}). Must be a composite dataset.' # type: ignore[unreachable]
3035 raise TypeError(msg)
3036 # always convert
3037 dataset = dataset.as_polydata_blocks(copy=copy_mesh)
3038 self.mesh = dataset # for legacy behavior
3039
3040 # Parse arguments
3041 (
3042 scalar_bar_args,
3043 split_sharp_edges,
3044 show_scalar_bar,
3045 feature_angle,
3046 render_points_as_spheres,
3047 _point_shape,
3048 smooth_shading,
3049 clim,
3050 cmap,
3051 culling,
3052 name,
3053 nan_color,
3054 _texture,
3055 rgb,
3056 interpolation,
3057 remove_existing_actor,
3058 vertex_color,
3059 vertex_style,
3060 vertex_opacity,
3061 ) = _common_arg_parser(
3062 dataset=dataset,
3063 theme=self._theme,
3064 n_colors=n_colors,
3065 scalar_bar_args=scalar_bar_args,
3066 split_sharp_edges=split_sharp_edges,
3067 show_scalar_bar=show_scalar_bar,
3068 render_points_as_spheres=render_points_as_spheres,
3069 point_shape=None,
3070 smooth_shading=smooth_shading,
3071 pbr=pbr,
3072 clim=clim,
3073 cmap=cmap,
3074 culling=culling,
3075 name=name,
3076 nan_color=nan_color,
3077 nan_opacity=nan_opacity,
3078 texture=None,
3079 rgb=rgb,
3080 style=style,
3081 **kwargs,
3082 )
3083 if show_vertices is None:
3084 show_vertices = self._theme.show_vertices
3085
3086 # Compute surface normals if using smooth shading
3087 if smooth_shading:
3088 dataset = dataset._compute_normals(
3089 cell_normals=False,
3090 split_vertices=True,
3091 feature_angle=feature_angle,
3092 )
3093
3094 mapper = CompositePolyDataMapper(
3095 dataset,
3096 theme=self._theme,
3097 color_missing_with_nan=color_missing_with_nan,
3098 interpolate_before_map=interpolate_before_map,
3099 )
3100 self.mapper = mapper
3101
3102 actor, _ = self.add_actor(mapper, render=False)
3103 actor = cast('Actor', actor)
3104 actor.force_opaque = force_opaque
3105
3106 prop = Property(
3107 self._theme,
3108 interpolation=interpolation,
3109 metallic=metallic,
3110 roughness=roughness,
3111 point_size=point_size,
3112 ambient=ambient,
3113 diffuse=diffuse,
3114 specular=specular,
3115 specular_power=specular_power,
3116 show_edges=show_edges,
3117 color=self.renderer.next_color if color is None or color is True else color, # type: ignore[comparison-overlap]
3118 style=style,
3119 edge_color=edge_color,
3120 render_points_as_spheres=render_points_as_spheres,
3121 render_lines_as_tubes=render_lines_as_tubes,
3122 lighting=lighting,
3123 line_width=line_width,
3124 opacity=opacity,
3125 culling=culling,
3126 edge_opacity=edge_opacity,
3127 )
3128 actor.SetProperty(prop)
3129
3130 if label is not None:
3131 self._add_legend_label(actor=actor, label=label, scalars=None, color=prop.color)
3132
3133 # check if there are any consistent active scalars
3134 if color is not None:
3135 self.mapper.scalar_visibility = False
3136 elif multi_colors:
3137 self.mapper.set_unique_colors(multi_colors)
3138 else:
3139 if scalars is None:
3140 point_name, cell_name = dataset._get_consistent_active_scalars()
3141 if point_name and cell_name:
3142 scalars = point_name if preference == 'point' else cell_name
3143 else:
3144 scalars = point_name if point_name is not None else cell_name
3145
3146 elif not isinstance(scalars, str):
3147 msg = f'`scalars` must be a string for `add_composite`, not ({type(scalars)})' # type: ignore[unreachable]
3148 raise TypeError(msg)
3149
3150 if scalars is not None:
3151 # enable rgb if the scalars name ends with rgb or rgba
3152 if rgb is None and scalars.endswith(('_rgb', '_rgba')):
3153 rgb = True
3154 show_scalar_bar = False
3155
3156 scalar_bar_args = self.mapper.set_scalars(
3157 scalars_name=scalars,
3158 preference=preference,
3159 component=component,
3160 annotations=annotations,
3161 rgb=rgb,
3162 scalar_bar_args=scalar_bar_args,
3163 n_colors=n_colors,
3164 nan_color=nan_color,
3165 above_color=above_color,
3166 below_color=below_color,
3167 clim=clim,
3168 cmap=cmap,
3169 flip_scalars=flip_scalars,
3170 log_scale=log_scale,
3171 )
3172 else:
3173 self.mapper.scalar_visibility = False
3174
3175 # Only show scalar bar if there are scalars
3176 if show_scalar_bar and scalars is not None and isinstance(scalar_bar_args, Mapping):
3177 self.add_scalar_bar(**scalar_bar_args) # type: ignore[call-arg]
3178
3179 # by default reset the camera if the plotting window has been rendered
3180 if reset_camera is None:
3181 reset_camera = not self._first_time and not self.camera_set
3182
3183 # add this immediately prior to adding the actor to ensure vertices
3184 # are rendered
3185 if show_vertices and style not in ['points', 'points_gaussian']:
3186 self.add_composite(
3187 dataset,
3188 style=vertex_style,
3189 point_size=point_size,
3190 color=vertex_color,
3191 render_points_as_spheres=render_points_as_spheres,
3192 name=f'{name}-vertices',
3193 opacity=vertex_opacity,
3194 lighting=lighting,
3195 render=False,
3196 show_vertices=False,
3197 )
3198
3199 self.add_actor(
3200 actor, # type: ignore[arg-type]
3201 reset_camera=reset_camera,
3202 name=name,
3203 pickable=pickable,
3204 render=render,
3205 remove_existing_actor=remove_existing_actor,
3206 )
3207
3208 return actor, mapper
3209
3210 @_deprecate_positional_args(allowed=['mesh'])
3211 def add_mesh( # noqa: PLR0917
3212 self,
3213 mesh: MatrixLike[float] | PlottableType | _vtk.vtkAlgorithm,
3214 color: ColorLike | None = None,
3215 style: StyleOptions | None = None,
3216 scalars: str | NumpyArray[float] | None = None,
3217 clim: Sequence[float] | None = None,
3218 show_edges: bool | None = None, # noqa: FBT001
3219 edge_color: ColorLike | None = None,
3220 point_size: float | None = None,
3221 line_width: float | None = None,
3222 opacity: float | OpacityOptions | Sequence[float] | None = None,
3223 flip_scalars: bool = False, # noqa: FBT001, FBT002
3224 lighting: bool | None = None, # noqa: FBT001
3225 n_colors: int = 256,
3226 interpolate_before_map: bool | None = None, # noqa: FBT001
3227 cmap: ColormapOptions | LookupTable | None = None,
3228 label: str | None = None,
3229 reset_camera: bool | None = None, # noqa: FBT001
3230 scalar_bar_args: ScalarBarArgs | None = None,
3231 show_scalar_bar: bool | None = None, # noqa: FBT001
3232 multi_colors: bool = False, # noqa: FBT001, FBT002
3233 name: str | None = None,
3234 texture: Texture | NumpyArray[float] | None = None,
3235 render_points_as_spheres: bool | None = None, # noqa: FBT001
3236 point_shape: PointSpriteShape | str | None = None,
3237 render_lines_as_tubes: bool | None = None, # noqa: FBT001
3238 smooth_shading: bool | None = None, # noqa: FBT001
3239 split_sharp_edges: bool | None = None, # noqa: FBT001
3240 ambient: float | None = None,
3241 diffuse: float | None = None,
3242 specular: float | None = None,
3243 specular_power: float | None = None,
3244 nan_color: ColorLike | None = None,
3245 nan_opacity: float = 1.0,
3246 culling: CullingOptions | bool | None = None, # noqa: FBT001
3247 rgb: bool | None = None, # noqa: FBT001
3248 categories: bool = False, # noqa: FBT001, FBT002
3249 silhouette: SilhouetteArgs | bool | None = None, # noqa: FBT001
3250 use_transparency: bool = False, # noqa: FBT001, FBT002
3251 below_color: ColorLike | None = None,
3252 above_color: ColorLike | None = None,
3253 annotations: dict[float, str] | None = None,
3254 pickable: bool = True, # noqa: FBT001, FBT002
3255 preference: PointLiteral | CellLiteral = 'point',
3256 log_scale: bool = False, # noqa: FBT001, FBT002
3257 pbr: bool | None = None, # noqa: FBT001
3258 metallic: float | None = None,
3259 roughness: float | None = None,
3260 render: bool = True, # noqa: FBT001, FBT002
3261 user_matrix: TransformLike | None = None,
3262 component: int | None = None,
3263 emissive: bool | None = None, # noqa: FBT001
3264 copy_mesh: bool = False, # noqa: FBT001, FBT002
3265 backface_params: BackfaceArgs | Property | None = None,
3266 show_vertices: bool | None = None, # noqa: FBT001
3267 edge_opacity: float | None = None,
3268 remove_existing_actor: bool | None = None, # noqa: FBT001
3269 force_opaque: bool = False, # noqa: FBT001, FBT002
3270 **kwargs,
3271 ) -> Actor:
3272 """Add any PyVista/VTK mesh or dataset that PyVista can wrap to the scene.
3273
3274 This method is using a mesh representation to view the surfaces
3275 and/or geometry of datasets. For volume rendering, see
3276 :func:`pyvista.Plotter.add_volume`.
3277
3278 To see the what most of the following parameters look like in action,
3279 please refer to :class:`pyvista.Property`.
3280
3281 Parameters
3282 ----------
3283 mesh : DataSet | MultiBlock | :vtk:`vtkAlgorithm` | str | Path
3284 Any PyVista or VTK mesh is supported. Also, any dataset
3285 that :func:`pyvista.wrap` can handle including NumPy
3286 arrays of XYZ points. Plotting also supports VTK algorithm
3287 objects (:vtk:`vtkAlgorithm` and :vtk:`vtkAlgorithmOutput`).
3288 When passing an algorithm, the rendering pipeline will be
3289 connected to the passed algorithm to dynamically update
3290 the scene (see :ref:`plotting_algorithms_example` for examples).
3291
3292 .. versionadded:: 0.47
3293
3294 Support adding a mesh directly from file.
3295
3296 color : ColorLike, optional
3297 Use to make the entire mesh have a single solid color.
3298 Either a string, RGB list, or hex color string. For example:
3299 ``color='white'``, ``color='w'``, ``color=[1.0, 1.0, 1.0]``, or
3300 ``color='#FFFFFF'``. Color will be overridden if scalars are
3301 specified.
3302
3303 Defaults to :attr:`pyvista.global_theme.color
3304 <pyvista.plotting.themes.Theme.color>`.
3305
3306 style : str, optional
3307 Visualization style of the mesh. One of the following:
3308 ``style='surface'``, ``style='wireframe'``, ``style='points'``,
3309 ``style='points_gaussian'``. Defaults to ``'surface'``. Note that
3310 ``'wireframe'`` only shows a wireframe of the outer geometry.
3311 ``'points_gaussian'`` can be modified with the ``emissive``,
3312 ``render_points_as_spheres`` options.
3313
3314 scalars : str | numpy.ndarray, optional
3315 Scalars used to "color" the mesh. Accepts a string name
3316 of an array that is present on the mesh or an array equal
3317 to the number of cells or the number of points in the
3318 mesh. Array should be sized as a single vector. If both
3319 ``color`` and ``scalars`` are ``None``, then the active
3320 scalars are used.
3321
3322 When a raw numpy array is passed, it is attached to
3323 ``mesh`` under a generated name (typically
3324 ``pyvista.DEFAULT_SCALARS_NAME`` or
3325 ``Data-<n>`` if that name is taken). This makes the
3326 array visible to downstream pipeline stages (for example
3327 smooth-shading surface extraction) and lets callers
3328 later mutate it via ``mesh[name] = ...`` to update the
3329 render. Mutation is scoped to raw-numpy inputs only.
3330 Passing ``scalars=<str>`` never modifies the mesh.
3331
3332 clim : sequence[float], optional
3333 Two item color bar range for scalars. Defaults to minimum and
3334 maximum of scalars array. Example: ``[-1, 2]``. ``rng`` is
3335 also an accepted alias for this.
3336
3337 show_edges : bool, optional
3338 Shows the edges of a mesh. Does not apply to a wireframe
3339 representation.
3340
3341 edge_color : ColorLike, optional
3342 The solid color to give the edges when ``show_edges=True``.
3343 Either a string, RGB list, or hex color string.
3344
3345 Defaults to :attr:`pyvista.global_theme.edge_color
3346 <pyvista.plotting.themes.Theme.edge_color>`.
3347
3348 point_size : float, optional
3349 Point size of any nodes in the dataset plotted. Also
3350 applicable when style='points'. Default ``5.0``.
3351
3352 line_width : float, optional
3353 Thickness of lines. Only valid for wireframe and surface
3354 representations. Default ``None``.
3355
3356 opacity : float | str | array_like
3357 Opacity of the mesh. If a single float value is given, it
3358 will be the global opacity of the mesh and uniformly
3359 applied everywhere - should be between 0 and 1. A string
3360 can also be specified to map the scalars range to a
3361 predefined opacity transfer function (options include:
3362 ``'linear'``, ``'linear_r'``, ``'geom'``, ``'geom_r'``).
3363 A string could also be used to map a scalars array from
3364 the mesh to the opacity (must have same number of elements
3365 as the ``scalars`` argument). Or you can pass a custom
3366 made transfer function that is an array either
3367 ``n_colors`` in length or shorter.
3368
3369 flip_scalars : bool, default: False
3370 Flip direction of cmap. Most colormaps allow ``*_r``
3371 suffix to do this as well.
3372
3373 lighting : bool, optional
3374 Enable or disable view direction lighting. Default ``False``.
3375
3376 n_colors : int, optional
3377 Number of colors to use when displaying scalars. Defaults to 256.
3378 The scalar bar will also have this many colors.
3379
3380 interpolate_before_map : bool, optional
3381 Enabling makes for a smoother scalars display. Default is
3382 ``True``. When ``False``, OpenGL will interpolate the
3383 mapped colors which can result is showing colors that are
3384 not present in the color map.
3385
3386 cmap : str | list | LookupTable, default: :attr:`pyvista.plotting.themes.Theme.cmap`
3387 If a string, this is the name of the ``matplotlib`` colormap to use
3388 when mapping the ``scalars``. See :ref:`named_colormaps` for supported
3389 colormaps.
3390
3391 Only applicable for when displaying ``scalars``.
3392 ``colormap`` is also an accepted alias
3393 for this. If ``colorcet`` or ``cmocean`` are installed, their
3394 colormaps can be specified by name.
3395
3396 You can also specify a list of colors to override an existing
3397 colormap with a custom one. For example, to create a three color
3398 colormap you might specify ``['green', 'red', 'blue']``.
3399
3400 This parameter also accepts a :class:`pyvista.LookupTable`. If this
3401 is set, all parameters controlling the color map like ``n_colors``
3402 will be ignored.
3403
3404 label : str, optional
3405 String label to use when adding a legend to the scene with
3406 :func:`pyvista.Plotter.add_legend`.
3407
3408 reset_camera : bool, optional
3409 Reset the camera after adding this mesh to the scene. The default
3410 setting is ``None``, where the camera is only reset if this plotter
3411 has already been shown. If ``False``, the camera is not reset
3412 regardless of the state of the ``Plotter``. When ``True``, the
3413 camera is always reset.
3414
3415 scalar_bar_args : dict, optional
3416 Dictionary of keyword arguments to pass when adding the
3417 scalar bar to the scene. For options, see
3418 :func:`pyvista.Plotter.add_scalar_bar`.
3419
3420 show_scalar_bar : bool, optional
3421 If ``False``, a scalar bar will not be added to the
3422 scene.
3423
3424 multi_colors : bool | str | cycler.Cycler | sequence[ColorLike], default: False
3425 If a :class:`pyvista.MultiBlock` dataset is given this will color
3426 each block by a solid color using a custom cycler.
3427
3428 If ``True``, the default 'matplotlib' color cycler is used.
3429
3430 See :func:`set_color_cycler<Plotter.set_color_cycler>` for usage of
3431 custom color cycles.
3432
3433 name : str, optional
3434 The name for the added mesh/actor so that it can be easily
3435 updated. If an actor of this name already exists in the
3436 rendering window, it will be replaced by the new actor.
3437
3438 texture : pyvista.Texture or np.ndarray, optional
3439 A texture to apply if the input mesh has texture
3440 coordinates. This will not work with MultiBlock
3441 datasets.
3442
3443 render_points_as_spheres : bool, optional
3444 Render points as spheres rather than dots.
3445
3446 point_shape : PointSpriteShape | str, optional
3447 Render points as a custom sprite shape instead of squares.
3448 Accepts a :class:`pyvista.plotting.opts.PointSpriteShape`
3449 enum value or a string. Must be one of ``'circle'``,
3450 ``'triangle'``, ``'hexagon'``, ``'diamond'``, ``'asterisk'``,
3451 or ``'star'``. Requires ``style='points'``. If
3452 ``render_points_as_spheres`` is ``True`` (explicitly or via
3453 theme), it will be automatically disabled with a warning.
3454
3455 .. versionadded:: 0.48
3456
3457 render_lines_as_tubes : bool, optional
3458 Show lines as thick tubes rather than flat lines. Control
3459 the width with ``line_width``.
3460
3461 smooth_shading : bool, optional
3462 Enable smooth shading when ``True`` using the Phong
3463 shading algorithm. When ``False``, use flat shading.
3464 Automatically enabled when ``pbr=True``. See
3465 :ref:`shading_example`.
3466
3467 split_sharp_edges : bool, optional
3468 Split sharp edges exceeding 30 degrees when plotting with smooth
3469 shading. Control the angle with the optional keyword argument
3470 ``feature_angle``. By default this is ``False`` unless overridden
3471 by the global or plotter theme. Note that enabling this will
3472 create a copy of the input mesh within the plotter. See
3473 :ref:`shading_example`.
3474
3475 ambient : float, optional
3476 When lighting is enabled, this is the amount of light in
3477 the range of 0 to 1 (default 0.0) that reaches the actor
3478 when not directed at the light source emitted from the
3479 viewer.
3480
3481 diffuse : float, optional
3482 The diffuse lighting coefficient. Default 1.0.
3483
3484 specular : float, optional
3485 The specular lighting coefficient. Default 0.0.
3486
3487 specular_power : float, optional
3488 The specular power. Between 0.0 and 128.0.
3489
3490 nan_color : ColorLike, optional
3491 The color to use for all ``NaN`` values in the plotted
3492 scalar array.
3493
3494 nan_opacity : float, optional
3495 Opacity of ``NaN`` values. Should be between 0 and 1.
3496 Default 1.0.
3497
3498 culling : str, optional
3499 Does not render faces that are culled. Options are
3500 ``'front'`` or ``'back'``. This can be helpful for dense
3501 surface meshes, especially when edges are visible, but can
3502 cause flat meshes to be partially displayed. Defaults to
3503 ``False``.
3504
3505 rgb : bool, optional
3506 If an 2 dimensional array is passed as the scalars, plot
3507 those values as RGB(A) colors. ``rgba`` is also an
3508 accepted alias for this. Opacity (the A) is optional. If
3509 a scalars array ending with ``"_rgba"`` is passed, the default
3510 becomes ``True``. This can be overridden by setting this
3511 parameter to ``False``.
3512
3513 categories : bool, optional
3514 If set to ``True``, then the number of unique values in
3515 the scalar array will be used as the ``n_colors``
3516 argument.
3517
3518 silhouette : dict, bool, optional
3519 If set to ``True``, plot a silhouette highlight for the
3520 mesh. This feature is only available for a triangulated
3521 ``PolyData``. As a ``dict``, it contains the properties
3522 of the silhouette to display:
3523
3524 * ``color``: ``ColorLike``, color of the silhouette
3525 * ``line_width``: ``float``, edge width
3526 * ``opacity``: ``float`` between 0 and 1, edge transparency
3527 * ``feature_angle``: If a ``float``, display sharp edges
3528 exceeding that angle in degrees.
3529 * ``decimate``: ``float`` between 0 and 1, level of decimation
3530
3531 use_transparency : bool, optional
3532 Invert the opacity mappings and make the values correspond
3533 to transparency.
3534
3535 below_color : ColorLike, optional
3536 Solid color for values below the scalars range
3537 (``clim``). This will automatically set the scalar bar
3538 ``below_label`` to ``'below'``.
3539
3540 above_color : ColorLike, optional
3541 Solid color for values below the scalars range
3542 (``clim``). This will automatically set the scalar bar
3543 ``above_label`` to ``'above'``.
3544
3545 annotations : dict, optional
3546 Pass a dictionary of annotations. Keys are the float
3547 values in the scalars range to annotate on the scalar bar
3548 and the values are the string annotations.
3549
3550 pickable : bool, optional
3551 Set whether this actor is pickable.
3552
3553 preference : str, default: "point"
3554 When ``mesh.n_points == mesh.n_cells`` and setting
3555 scalars, this parameter sets how the scalars will be
3556 mapped to the mesh. Default ``'point'``, causes the
3557 scalars will be associated with the mesh points. Can be
3558 either ``'point'`` or ``'cell'``.
3559
3560 log_scale : bool, default: False
3561 Use log scale when mapping data to colors. Scalars less
3562 than zero are mapped to the smallest representable
3563 positive float.
3564
3565 pbr : bool, optional
3566 Enable physics based rendering (PBR) if the mesh is
3567 ``PolyData``. Use the ``color`` argument to set the base
3568 color.
3569
3570 metallic : float, optional
3571 Usually this value is either 0 or 1 for a real material
3572 but any value in between is valid. This parameter is only
3573 used by PBR interpolation.
3574
3575 roughness : float, optional
3576 This value has to be between 0 (glossy) and 1 (rough). A
3577 glossy material has reflections and a high specular
3578 part. This parameter is only used by PBR
3579 interpolation.
3580
3581 render : bool, default: True
3582 Force a render when ``True``.
3583
3584 user_matrix : TransformLike, default: np.eye(4)
3585 Matrix passed to the Actor class before rendering. This affects the
3586 actor/rendering only, not the input volume itself. The user matrix is the
3587 last transformation applied to the actor before rendering. Defaults to the
3588 identity matrix.
3589
3590 component : int, optional
3591 Set component of vector valued scalars to plot. Must be
3592 nonnegative, if supplied. If ``None``, the magnitude of
3593 the vector is plotted. See :ref:`vector_component_example`
3594 for examples.
3595
3596 emissive : bool, optional
3597 Treat the points/splats as emissive light sources. Only valid for
3598 ``style='points_gaussian'`` representation.
3599
3600 copy_mesh : bool, default: False
3601 If ``True``, a copy of the mesh will be made before adding it to
3602 the plotter. This is useful if you would like to add the same
3603 mesh to a plotter multiple times and display different
3604 scalars. Setting ``copy_mesh`` to ``False`` is necessary if you
3605 would like to update the mesh after adding it to the plotter and
3606 have these updates rendered, e.g. by changing the active scalars or
3607 through an interactive widget. This should only be set to ``True``
3608 with caution. Defaults to ``False``. This is ignored if the input
3609 is a :vtk:`vtkAlgorithm` subclass.
3610
3611 backface_params : dict | Property, optional
3612 A :class:`pyvista.Property` or a dict of parameters to use for
3613 backface rendering. This is useful for instance when the inside of
3614 oriented surfaces has a different color than the outside. When a
3615 :class:`pyvista.Property`, this is directly used for backface
3616 rendering. When a dict, valid keys are :class:`pyvista.Property`
3617 attributes, and values are corresponding values to use for the
3618 given property. Omitted keys (or the default of
3619 ``backface_params=None``) default to the corresponding frontface
3620 properties.
3621
3622 show_vertices : bool, optional
3623 When ``style`` is not ``'points'``, render the external surface
3624 vertices. The following optional keyword arguments may be used to
3625 control the style of the vertices:
3626
3627 * ``vertex_color`` - The color of the vertices
3628 * ``vertex_style`` - Change style to ``'points_gaussian'``
3629 * ``vertex_opacity`` - Control the opacity of the vertices
3630
3631 See :ref:`vertices_example` for examples.
3632
3633 edge_opacity : float, optional
3634 Edge opacity of the mesh. A single float value that will be applied globally
3635 edge opacity of the mesh and uniformly applied everywhere - should be
3636 between 0 and 1.
3637
3638 .. note::
3639 `edge_opacity` uses ``SetEdgeOpacity`` as the underlying method which
3640 requires VTK version 9.3 or higher. If ``SetEdgeOpacity`` is not
3641 available, `edge_opacity` is set to 1.
3642
3643 remove_existing_actor : bool, optional
3644 Remove any existing actor in the renderer with the same name before adding
3645 this actor. By default, this is ``True`` when ``name`` is provided, and
3646 ``False`` when ``name`` is ``None``. Set to ``False`` to improve performance
3647 when adding multiple named actors, particularly during initial scene setup
3648 where no actors exist yet.
3649
3650 force_opaque : bool, default: False
3651 Whether to force the returned actor to be opaque. Can be useful for web visualization
3652 with ``culling = "front"`` and ``opacity`` smaller than 1.
3653 See https://github.com/Kitware/trame-vtk/issues/105 for more details.
3654
3655 .. versionadded:: 0.48
3656
3657 **kwargs : dict, optional
3658 Optional keyword arguments.
3659
3660 Returns
3661 -------
3662 pyvista.Actor
3663 Actor of the mesh.
3664
3665 Examples
3666 --------
3667 Add a sphere to the plotter and show it with a custom scalar
3668 bar title.
3669
3670 >>> import pyvista as pv
3671 >>> sphere = pv.Sphere()
3672 >>> sphere['Data'] = sphere.points[:, 2]
3673 >>> pl = pv.Plotter()
3674 >>> _ = pl.add_mesh(sphere, scalar_bar_args={'title': 'Z Position'})
3675 >>> pl.show()
3676
3677 Plot using RGB on a single cell. Note that since the number of
3678 points and the number of cells are identical, we have to pass
3679 ``preference='cell'``.
3680
3681 >>> import pyvista as pv
3682 >>> import numpy as np
3683 >>> vertices = np.array(
3684 ... [
3685 ... [0, 0, 0],
3686 ... [1, 0, 0],
3687 ... [0.5, 0.667, 0],
3688 ... [0.5, 0.33, 0.667],
3689 ... ]
3690 ... )
3691 >>> faces = np.hstack([[3, 0, 1, 2], [3, 0, 3, 2], [3, 0, 1, 3], [3, 1, 2, 3]])
3692 >>> mesh = pv.PolyData(vertices, faces)
3693 >>> mesh.cell_data['colors'] = [
3694 ... [255, 255, 255],
3695 ... [0, 255, 0],
3696 ... [0, 0, 255],
3697 ... [255, 0, 0],
3698 ... ]
3699 >>> pl = pv.Plotter()
3700 >>> _ = pl.add_mesh(
3701 ... mesh,
3702 ... scalars='colors',
3703 ... lighting=False,
3704 ... rgb=True,
3705 ... preference='cell',
3706 ... )
3707 >>> pl.camera_position = 'xy'
3708 >>> pl.show()
3709
3710 Note how this varies from ``preference=='point'``. This is
3711 because each point is now being individually colored, versus
3712 in ``preference=='point'``, each cell face is individually
3713 colored.
3714
3715 >>> pl = pv.Plotter()
3716 >>> _ = pl.add_mesh(
3717 ... mesh,
3718 ... scalars='colors',
3719 ... lighting=False,
3720 ... rgb=True,
3721 ... preference='point',
3722 ... )
3723 >>> pl.camera_position = 'xy'
3724 >>> pl.show()
3725
3726 Plot a plane with a constant color and vary its opacity by point.
3727
3728 >>> plane = pv.Plane()
3729 >>> plane.plot(
3730 ... color='b',
3731 ... opacity=np.linspace(0, 1, plane.n_points),
3732 ... show_edges=True,
3733 ... )
3734
3735 Plot the points of a sphere with Gaussian smoothing while coloring by z
3736 position.
3737
3738 >>> mesh = pv.Sphere()
3739 >>> mesh.plot(
3740 ... scalars=mesh.points[:, 2],
3741 ... style='points_gaussian',
3742 ... opacity=0.5,
3743 ... point_size=10,
3744 ... render_points_as_spheres=False,
3745 ... show_scalar_bar=False,
3746 ... )
3747
3748 Plot spheres using `points_gaussian` style and scale them by radius.
3749
3750 >>> N_SPHERES = 1_000_000
3751 >>> rng = np.random.default_rng(seed=0)
3752 >>> pos = rng.random((N_SPHERES, 3))
3753 >>> rad = rng.random(N_SPHERES) * 0.01
3754 >>> pdata = pv.PolyData(pos)
3755 >>> pdata['radius'] = rad
3756 >>> pdata.plot(
3757 ... style='points_gaussian',
3758 ... emissive=False,
3759 ... render_points_as_spheres=True,
3760 ... )
3761
3762 """
3763 if (
3764 pv.vtk_version_info == (9, 6, 0)
3765 and isinstance(mesh, pv.UnstructuredGrid)
3766 and (ghost_name := _vtk.vtkDataSetAttributes.GhostArrayName()) in mesh.cell_data.keys()
3767 ):
3768 # Ghost cells are not rendered properly in VTK 9.6.0 https://gitlab.kitware.com/vtk/vtk/-/issues/19922
3769 # As a workaround, extract non-hidden cells
3770 hidden_cells = mesh.cell_data[ghost_name] == _vtk.vtkDataSetAttributes.HIDDENCELL
3771 if np.any(hidden_cells):
3772 not_hidden = mesh.extract_cells(
3773 ~hidden_cells, pass_cell_ids=False, pass_point_ids=False
3774 )
3775 with contextlib.suppress(KeyError):
3776 del not_hidden.cell_data[ghost_name]
3777
3778 # Simulate the non-visible bounds by adding points at the corners
3779 xmin, xmax, ymin, ymax, zmin, zmax = mesh.bounds
3780 points = np.array(
3781 [
3782 [xmin, ymin, zmin],
3783 [xmax, ymin, zmin],
3784 [xmin, ymax, zmin],
3785 [xmax, ymax, zmin],
3786 [xmin, ymin, zmax],
3787 [xmax, ymin, zmax],
3788 [xmin, ymax, zmax],
3789 [xmax, ymax, zmax],
3790 ],
3791 dtype=float,
3792 )
3793
3794 # Create degenerate triangles at each point
3795 n_points = points.shape[0]
3796 cells = np.empty(n_points * 4, dtype=np.int64)
3797 celltypes = np.full(n_points, pv.CellType.TRIANGLE, dtype=np.uint8)
3798 for i in range(n_points):
3799 off = 4 * i
3800 cells[off] = 3
3801 cells[off + 1] = i
3802 cells[off + 2] = i
3803 cells[off + 3] = i
3804
3805 corners_grid = pv.UnstructuredGrid(cells, celltypes, points)
3806
3807 # Ensure we have data for the new points so we can merge the meshes
3808 # and keep the original mesh arrays
3809 for array in mesh.point_data.keys():
3810 corners_grid.point_data[array] = mesh.point_data[array][0]
3811 for array in mesh.cell_data.keys():
3812 corners_grid.cell_data[array] = mesh.cell_data[array][0]
3813
3814 # Combine meshes
3815 not_hidden = not_hidden + corners_grid
3816 association, name = mesh.active_scalars_info
3817 try:
3818 not_hidden.set_active_scalars(name, preference=association)
3819 except KeyError:
3820 not_hidden.set_active_scalars(None, preference=association)
3821 mesh = not_hidden
3822 copy_mesh = False
3823
3824 if user_matrix is None:
3825 user_matrix = np.eye(4)
3826 if style == 'points_gaussian':
3827 mapper: _BaseMapper = PointGaussianMapper(theme=self.theme, emissive=emissive)
3828 else:
3829 mapper = DataSetMapper(theme=self.theme)
3830 self.mapper = mapper
3831
3832 if render_lines_as_tubes and show_edges:
3833 warn_external(
3834 '`show_edges=True` not supported when `render_lines_as_tubes=True`. '
3835 'Ignoring `show_edges`.',
3836 UserWarning,
3837 )
3838 show_edges = False
3839
3840 if isinstance(mesh, (str, Path)):
3841 mesh = pv.read(mesh)
3842
3843 mesh, algo = algorithm_to_mesh_handler(mesh)
3844
3845 # Convert the VTK data object to a pyvista wrapped object if necessary
3846 if not is_pyvista_dataset(mesh):
3847 mesh = wrap(mesh) # type: ignore[unreachable]
3848 if not is_pyvista_dataset(mesh):
3849 msg = f'Object type ({type(mesh)}) not supported for plotting in PyVista.'
3850 raise TypeError(msg)
3851 if isinstance(mesh, pv.PointSet):
3852 # cast to PointSet to PolyData
3853 if algo is not None:
3854 algo = pointset_to_polydata_algorithm(algo)
3855 mesh, algo = algorithm_to_mesh_handler(algo)
3856 else:
3857 mesh = mesh.cast_to_polydata(deep=False)
3858 elif isinstance(mesh, (pv.MultiBlock, pv.PartitionedDataSet)): # type: ignore[unreachable]
3859 if not isinstance(mesh, pv.MultiBlock): # type: ignore[unreachable]
3860 mesh = mesh.cast_to_multiblock()
3861 if algo is not None:
3862 msg = (
3863 'Algorithms with `MultiBlock` output type are not supported by '
3864 '`add_mesh` at this time.'
3865 )
3866 raise TypeError(msg)
3867 _validation.check_instance(opacity, (float, int, type(None)), name='opacity')
3868 _validation.check_instance(scalars, (str, type(None)), name='scalars')
3869 actor, _ = self.add_composite(
3870 mesh,
3871 color=color,
3872 style=style,
3873 scalars=scalars,
3874 clim=clim,
3875 show_edges=show_edges,
3876 edge_color=edge_color,
3877 point_size=point_size,
3878 line_width=line_width,
3879 opacity=opacity,
3880 flip_scalars=flip_scalars,
3881 lighting=lighting,
3882 n_colors=n_colors,
3883 interpolate_before_map=interpolate_before_map,
3884 cmap=cmap,
3885 label=label,
3886 reset_camera=reset_camera,
3887 scalar_bar_args=scalar_bar_args,
3888 show_scalar_bar=show_scalar_bar,
3889 multi_colors=multi_colors,
3890 name=name,
3891 render_points_as_spheres=render_points_as_spheres,
3892 render_lines_as_tubes=render_lines_as_tubes,
3893 smooth_shading=smooth_shading,
3894 split_sharp_edges=split_sharp_edges,
3895 ambient=ambient,
3896 diffuse=diffuse,
3897 specular=specular,
3898 specular_power=specular_power,
3899 nan_color=nan_color,
3900 nan_opacity=nan_opacity,
3901 culling=culling,
3902 rgb=rgb,
3903 below_color=below_color,
3904 above_color=above_color,
3905 pickable=pickable,
3906 preference=preference,
3907 log_scale=log_scale,
3908 pbr=pbr,
3909 metallic=metallic,
3910 roughness=roughness,
3911 render=render,
3912 show_vertices=show_vertices,
3913 edge_opacity=edge_opacity,
3914 remove_existing_actor=remove_existing_actor,
3915 force_opaque=force_opaque,
3916 **kwargs,
3917 )
3918 return actor
3919 elif copy_mesh and algo is None:
3920 # A shallow copy of `mesh` is made here so when we set (or add) scalars
3921 # active, it doesn't modify the original input mesh.
3922 # We ignore `copy_mesh` if the input is an algorithm
3923 mesh = mesh.copy(deep=False)
3924 mesh = cast('pv.DataSet', mesh)
3925
3926 # Parse arguments
3927 (
3928 scalar_bar_args,
3929 split_sharp_edges,
3930 show_scalar_bar,
3931 feature_angle,
3932 render_points_as_spheres,
3933 point_shape,
3934 smooth_shading,
3935 clim,
3936 cmap,
3937 culling,
3938 name,
3939 nan_color,
3940 texture,
3941 rgb,
3942 interpolation,
3943 remove_existing_actor,
3944 vertex_color,
3945 vertex_style,
3946 vertex_opacity,
3947 ) = _common_arg_parser(
3948 dataset=mesh,
3949 theme=self._theme,
3950 n_colors=n_colors,
3951 scalar_bar_args=scalar_bar_args,
3952 split_sharp_edges=split_sharp_edges,
3953 show_scalar_bar=show_scalar_bar,
3954 render_points_as_spheres=render_points_as_spheres,
3955 point_shape=point_shape,
3956 smooth_shading=smooth_shading,
3957 pbr=pbr,
3958 clim=clim,
3959 cmap=cmap,
3960 culling=culling,
3961 name=name,
3962 nan_color=nan_color,
3963 nan_opacity=nan_opacity,
3964 texture=texture,
3965 rgb=rgb,
3966 style=style,
3967 remove_existing_actor=remove_existing_actor,
3968 **kwargs,
3969 )
3970
3971 if show_vertices is None:
3972 show_vertices = self._theme.show_vertices
3973
3974 if edge_opacity is None and pv.vtk_version_info >= (9, 3):
3975 edge_opacity = self._theme.edge_opacity
3976
3977 if silhouette is None:
3978 silhouette = self._theme.silhouette.enabled
3979 if silhouette:
3980 if isinstance(silhouette, dict):
3981 silhouette_actor = self.add_silhouette(algo or mesh, **silhouette)
3982 else:
3983 silhouette_actor = self.add_silhouette(algo or mesh)
3984 silhouette_actor.user_matrix = user_matrix
3985
3986 scalar_bar_args = cast('ScalarBarArgs', scalar_bar_args)
3987 # Try to plot something if no preference given
3988 if scalars is None and color is None and texture is None:
3989 # Make sure scalars components are not vectors/tuples
3990 scalars = mesh.active_scalars_name
3991 # Don't allow plotting of string arrays by default
3992 if scalars is not None: # and np.issubdtype(mesh.active_scalars.dtype, np.number):
3993 scalar_bar_args.setdefault('title', scalars)
3994 else:
3995 scalars = None
3996
3997 # Make sure scalars is a numpy array after this point
3998 original_scalar_name = None
3999 scalars_name = pv.DEFAULT_SCALARS_NAME
4000 if isinstance(scalars, str):
4001 mapper.array_name = scalars
4002
4003 # enable rgb if the scalars name ends with rgb or rgba
4004 if rgb is None and scalars.endswith(('_rgb', '_rgba')):
4005 rgb = True
4006
4007 original_scalar_name = scalars
4008 scalars = get_array(mesh, scalars, preference=preference, err=True)
4009 scalar_bar_args.setdefault('title', original_scalar_name)
4010 scalars_name = original_scalar_name
4011
4012 # Set the active scalars name here. If the name already exists in
4013 # the input mesh, it may not be set as the active scalars within
4014 # the mapper. This should be refactored by 0.36.0
4015 field = get_array_association(mesh, original_scalar_name, preference=preference)
4016 mapper.scalar_map_mode = field.name
4017
4018 # set preference for downstream use with actual
4019 if field == FieldAssociation.POINT:
4020 preference = 'point'
4021 elif field == FieldAssociation.CELL:
4022 preference = 'cell'
4023
4024 if algo is not None:
4025 # Ensures that the right scalars are set as active on
4026 # each pipeline request
4027 algo = active_scalars_algorithm(algo, original_scalar_name, preference=preference)
4028 mesh, algo = algorithm_to_mesh_handler(algo)
4029
4030 # Raw numpy scalars against a concrete mesh: stamp on the mesh so
4031 # pipeline stages (e.g. smooth shading) carry the array forward.
4032 # See ``_stamp_raw_numpy_scalars``. Skipped for 2D non-rgb arrays,
4033 # which are reduced to 1D by the smooth-shading block or by
4034 # ``mapper.set_scalars`` before being attached, to avoid leaving a
4035 # stale raw multi-component array on the mesh alongside the reduced
4036 # derivative.
4037 if (
4038 algo is None
4039 and isinstance(scalars, np.ndarray)
4040 and original_scalar_name is None
4041 and scalars.shape[0] in (mesh.n_points, mesh.n_cells)
4042 and (scalars.ndim == 1 or rgb)
4043 ):
4044 scalars_name, preference = _stamp_raw_numpy_scalars(
4045 mesh, scalars, scalars_name, preference
4046 )
4047 original_scalar_name = scalars_name
4048
4049 if smooth_shading:
4050 # Reduce 2D scalars ahead of the pipeline. The derived array
4051 # must exist on the mesh before smooth shading so subsequent
4052 # pipeline stages carry it forward. See docstring.
4053 if (
4054 isinstance(scalars, np.ndarray)
4055 and scalars.ndim == 2
4056 and not rgb
4057 and scalars.shape[0] in (mesh.n_points, mesh.n_cells)
4058 ):
4059 scalars, scalars_name, preference = _reduce_multicomponent_scalars_on_mesh(
4060 mesh, scalars, scalars_name, component, preference
4061 )
4062 original_scalar_name = scalars_name
4063 component = None
4064 mapper.array_name = scalars_name
4065
4066 input_n_points = mesh.n_points
4067 input_n_cells = mesh.n_cells
4068 algo = smooth_shading_algorithm(
4069 algo or mesh,
4070 split_sharp_edges=split_sharp_edges,
4071 feature_angle=feature_angle,
4072 )
4073 mesh, algo = algorithm_to_mesh_handler(algo)
4074
4075 if scalars is not None and (
4076 mesh.n_points != input_n_points or mesh.n_cells != input_n_cells
4077 ):
4078 scalars = _remap_scalars_through_topology_change(
4079 mesh, scalars, original_scalar_name, preference, input_n_points
4080 )
4081
4082 # Raw numpy scalars with an upstream algorithm do not exist on the
4083 # pipeline output by name. Splice a callback stage that attaches
4084 # them to a shallow copy so the downstream ActiveScalarsAlgorithm
4085 # can activate the mapper's live input, not just the cached
4086 # snapshot.
4087 if (
4088 algo is not None
4089 and original_scalar_name is None
4090 and isinstance(scalars, np.ndarray)
4091 and scalars.shape[0] in (mesh.n_points, mesh.n_cells)
4092 ):
4093 algo, mesh = _attach_raw_scalars_via_callback(
4094 algo, mesh, scalars, scalars_name, preference
4095 )
4096 original_scalar_name = scalars_name
4097
4098 if rgb:
4099 show_scalar_bar = False
4100 scalars = cast('NumpyArray[float]', scalars)
4101 if scalars.ndim != 2 or scalars.shape[1] < 3 or scalars.shape[1] > 4:
4102 msg = 'RGB array must be n_points/n_cells by 3/4 in shape.'
4103 raise ValueError(msg)
4104
4105 if algo is None and not self.theme.allow_empty_mesh and not mesh.n_points:
4106 # Algorithms may initialize with an empty mesh
4107 msg = (
4108 'Empty meshes cannot be plotted. Input mesh has zero points. '
4109 'To allow plotting empty meshes, set `pv.global_theme.allow_empty_mesh = True`'
4110 )
4111 raise ValueError(msg)
4112
4113 # set main values
4114 self.mesh = mesh
4115 mapper.dataset = self.mesh
4116 if interpolate_before_map is not None:
4117 mapper.interpolate_before_map = interpolate_before_map
4118 set_algorithm_input(mapper, algo or mesh)
4119
4120 actor = Actor(mapper=mapper)
4121 actor.user_matrix = user_matrix
4122 actor.force_opaque = force_opaque
4123
4124 if texture is not None:
4125 if isinstance(texture, np.ndarray):
4126 texture = numpy_to_texture(texture)
4127 if not isinstance(texture, (_vtk.vtkTexture, _vtk.vtkOpenGLTexture)):
4128 msg = f'Invalid texture type ({type(texture)})'
4129 raise TypeError(msg)
4130 if mesh.GetPointData().GetTCoords() is None:
4131 msg = 'Input mesh does not have texture coordinates to support the texture.'
4132 raise ValueError(msg)
4133 actor.texture = texture
4134 # Set color to white by default when using a texture
4135 if color is None:
4136 color = 'white'
4137 if scalars is None:
4138 show_scalar_bar = False
4139 mapper.scalar_visibility = False
4140
4141 # see https://github.com/pyvista/pyvista/issues/950
4142 mesh.set_active_scalars(None)
4143
4144 # Handle making opacity array
4145 custom_opac, opacity = process_opacity(
4146 mesh=mesh,
4147 opacity=opacity,
4148 preference=preference,
4149 n_colors=n_colors,
4150 scalars=scalars,
4151 use_transparency=use_transparency,
4152 )
4153
4154 # Scalars formatting ==================================================
4155 if scalars is not None:
4156 mapper.set_scalars(
4157 scalars=scalars,
4158 scalars_name=scalars_name,
4159 n_colors=n_colors,
4160 scalar_bar_args=scalar_bar_args,
4161 rgb=rgb,
4162 component=component,
4163 preference=preference,
4164 custom_opac=custom_opac,
4165 annotations=annotations,
4166 log_scale=log_scale,
4167 nan_color=nan_color,
4168 above_color=above_color,
4169 below_color=below_color,
4170 cmap=cmap,
4171 flip_scalars=flip_scalars,
4172 opacity=opacity,
4173 categories=categories,
4174 clim=clim,
4175 )
4176 mapper.scalar_visibility = True
4177 elif custom_opac: # no scalars but custom opacity
4178 mapper.set_custom_opacity(
4179 opacity,
4180 color=color,
4181 n_colors=n_colors,
4182 preference=preference,
4183 )
4184 mapper.scalar_visibility = True
4185 else:
4186 mapper.scalar_visibility = False
4187
4188 # Set actor properties ================================================
4189 prop_kwargs = dict(
4190 theme=self._theme,
4191 interpolation=interpolation,
4192 metallic=metallic,
4193 roughness=roughness,
4194 point_size=point_size,
4195 ambient=ambient,
4196 diffuse=diffuse,
4197 specular=specular,
4198 specular_power=specular_power,
4199 show_edges=show_edges,
4200 color=self.renderer.next_color if color is None or color is True else color, # type: ignore[comparison-overlap]
4201 style=style if style != 'points_gaussian' else 'points',
4202 edge_color=edge_color,
4203 render_lines_as_tubes=render_lines_as_tubes,
4204 lighting=lighting,
4205 line_width=line_width,
4206 culling=culling,
4207 edge_opacity=edge_opacity,
4208 )
4209
4210 if isinstance(opacity, (float, int)):
4211 prop_kwargs['opacity'] = opacity
4212 prop = Property(**prop_kwargs)
4213 actor.SetProperty(prop)
4214
4215 if style == 'points_gaussian' and mapper.dataset is not None:
4216 mapper.scale_factor = prop.point_size * mapper.dataset.length / 1300
4217 if not render_points_as_spheres and not mapper.emissive and prop.opacity >= 1.0:
4218 prop.opacity = 0.9999 # otherwise, weird triangles
4219
4220 if render_points_as_spheres is not None:
4221 if render_points_as_spheres and style == 'points_gaussian':
4222 mapper.use_circular_splat(prop.opacity)
4223 prop.opacity = 1.0
4224 else:
4225 prop.render_points_as_spheres = render_points_as_spheres
4226
4227 if point_shape is not None:
4228 actor.set_point_sprite_shape(point_shape)
4229
4230 if backface_params is not None:
4231 if isinstance(backface_params, Property):
4232 backface_prop = backface_params
4233 elif isinstance(backface_params, dict):
4234 # preserve omitted kwargs from frontface
4235 backface_kwargs = deepcopy(prop_kwargs)
4236 backface_kwargs.update(backface_params)
4237 backface_prop = Property(**backface_kwargs)
4238 else:
4239 msg = ( # type: ignore[unreachable]
4240 'Backface params must be a pyvista.Property or a dict, '
4241 f'not {type(backface_params).__name__}.'
4242 )
4243 raise TypeError(msg)
4244 actor.backface_prop = backface_prop
4245
4246 # legend label
4247 if label is not None:
4248 self._add_legend_label(
4249 actor=actor, label=label, scalars=scalars, color=actor.prop.color
4250 )
4251
4252 # by default reset the camera if the plotting window has been rendered
4253 if reset_camera is None:
4254 reset_camera = not self._first_time and not self.camera_set
4255
4256 # add this immediately prior to adding the actor to ensure vertices
4257 # are rendered
4258 if show_vertices and style not in ['points', 'points_gaussian']:
4259 self.add_mesh(
4260 extract_surface_algorithm(algo or mesh),
4261 style=vertex_style,
4262 point_size=point_size,
4263 color=vertex_color,
4264 render_points_as_spheres=render_points_as_spheres,
4265 name=f'{name}-vertices',
4266 opacity=vertex_opacity,
4267 lighting=lighting,
4268 render=False,
4269 show_vertices=False,
4270 )
4271
4272 self.add_actor(
4273 actor, # type:ignore[arg-type]
4274 reset_camera=reset_camera,
4275 name=name,
4276 pickable=pickable,
4277 render=render,
4278 remove_existing_actor=remove_existing_actor,
4279 )
4280
4281 # hide scalar bar if using special scalars
4282 if scalar_bar_args.get('title') == '__custom_rgba':
4283 show_scalar_bar = False
4284
4285 # Only show scalar bar if there are scalars
4286 if show_scalar_bar and scalars is not None:
4287 self.add_scalar_bar(**scalar_bar_args) # type: ignore[call-arg]
4288
4289 self.renderer.Modified()
4290
4291 return actor
4292
4293 def _add_legend_label(
4294 self,
4295 *,
4296 actor: Actor,
4297 label: str,
4298 scalars: str | NumpyArray[float] | None,
4299 color: Color,
4300 ) -> None:
4301 """Add a legend label based on an actor and its scalars."""
4302 if not isinstance(label, str):
4303 msg = 'Label must be a string' # type: ignore[unreachable]
4304 raise TypeError(msg)
4305
4306 if isinstance(self.mesh, pv.DataSet) and self.mesh._glyph_geom is not None:
4307 # Using only the first geometry
4308 geom: str | PolyData = pv.wrap(self.mesh._glyph_geom[0]).extract_surface(
4309 algorithm=None, pass_pointid=False, pass_cellid=False
4310 )
4311 else:
4312 geom = 'triangle' if scalars is None else 'rectangle'
4313
4314 poly = make_legend_face(geom)
4315
4316 addr = actor.GetAddressAsString('')
4317 self.renderer._labels[addr] = (poly, label, color)
4318
4319 @_deprecate_positional_args(allowed=['volume'])
4320 def add_volume( # noqa: PLR0917
4321 self,
4322 volume: DataSet | MultiBlock | NumpyArray[float],
4323 scalars: str | NumpyArray[float] | None = None,
4324 clim: float | tuple[float, float] | None = None,
4325 resolution: VectorLike[float] | None = None,
4326 opacity: OpacityOptions | NumpyArray[float] = 'linear',
4327 n_colors: int = 256,
4328 cmap: ColormapOptions | LookupTable | None = None,
4329 flip_scalars: bool = False, # noqa: FBT001, FBT002
4330 reset_camera: bool | None = None, # noqa: FBT001
4331 name: str | None = None,
4332 ambient: float | None = None,
4333 categories: bool | int = False, # noqa: FBT001, FBT002
4334 culling: CullingOptions | bool = False, # noqa: FBT001, FBT002
4335 multi_colors: bool = False, # noqa: FBT001, FBT002
4336 blending: Literal['additive', 'maximum', 'minimum', 'composite', 'average'] = 'composite',
4337 mapper: Literal['fixed_point', 'gpu', 'open_gl', 'smart', 'ugrid'] | None = None,
4338 scalar_bar_args: ScalarBarArgs | None = None,
4339 show_scalar_bar: bool | None = None, # noqa: FBT001
4340 annotations: dict[float, str] | None = None,
4341 pickable: bool = True, # noqa: FBT001, FBT002
4342 preference: PointLiteral | CellLiteral = 'point',
4343 opacity_unit_distance: float | None = None,
4344 shade: bool = False, # noqa: FBT001, FBT002
4345 diffuse: float = 0.7, # TODO: different default for volumes
4346 specular: float = 0.2, # TODO: different default for volumes
4347 specular_power: float = 10.0, # TODO: different default for volumes
4348 render: bool | None = True, # noqa: FBT001, FBT002
4349 user_matrix: TransformLike | None = None,
4350 log_scale: bool = False, # noqa: FBT001, FBT002
4351 **kwargs,
4352 ) -> Actor | list[Actor]:
4353 """Add a volume, rendered using a smart mapper by default.
4354
4355 Requires a 3D data type like :class:`numpy.ndarray`,
4356 :class:`pyvista.ImageData`, :class:`pyvista.RectilinearGrid`,
4357 or :class:`pyvista.UnstructuredGrid`.
4358
4359 Parameters
4360 ----------
4361 volume : 3D numpy.ndarray | DataSet
4362 The input volume to visualize. 3D numpy arrays are accepted.
4363
4364 .. warning::
4365 If the input is not :class:`numpy.ndarray`,
4366 :class:`pyvista.ImageData`, or :class:`pyvista.RectilinearGrid`,
4367 volume rendering will often have poor performance.
4368
4369 scalars : str | numpy.ndarray, optional
4370 Scalars used to "color" the mesh. Accepts a string name of an
4371 array that is present on the mesh or an array with length equal
4372 to the number of cells or the number of points in the
4373 mesh. If ``scalars`` is ``None``, then the active scalars are used.
4374
4375 Scalars may be 1 dimensional or 2 dimensional. If 1 dimensional,
4376 the scalars will be mapped to the lookup table. If 2 dimensional
4377 the scalars will be directly mapped to RGBA values, array should be
4378 shaped ``(N, 4)`` where ``N`` is the number of points, and of
4379 datatype ``np.uint8``.
4380
4381 clim : sequence[float] | float, optional
4382 Color bar range for scalars. For example: ``[-1, 2]``. Defaults to
4383 minimum and maximum of scalars array if the scalars dtype is not
4384 ``np.uint8``. ``rng`` is also an accepted alias for this parameter.
4385
4386 If the scalars datatype is ``np.uint8``, this parameter defaults to
4387 ``[0, 256]``.
4388
4389 If a single value is given, the range ``[-clim, clim]`` is used.
4390
4391 resolution : list, optional
4392 Block resolution. For example ``[1, 1, 1]``. Resolution must be
4393 non-negative. While VTK accepts negative spacing, this results in
4394 unexpected behavior. See:
4395 `pyvista #1967 <https://github.com/pyvista/pyvista/issues/1967>`_.
4396
4397 opacity : str | numpy.ndarray, optional
4398 Opacity mapping for the scalars array.
4399
4400 A string can also be specified to map the scalars range to a
4401 predefined opacity transfer function. Or you can pass a custom made
4402 transfer function that is an array either ``n_colors`` in length or
4403 array, or you can pass a string to select a built in transfer
4404 function. If a string, should be one of the following:
4405
4406 * ``'linear'`` - Linear
4407 * ``'linear_r'`` - Linear except reversed
4408 * ``'geom'`` - Evenly spaced on the log scale
4409 * ``'geom_r'`` - Evenly spaced on the log scale except reversed
4410 * ``'sigmoid'`` - Linear map between -10.0 and 10.0
4411 * ``'sigmoid_1'`` - Linear map between -1.0 and 1.0
4412 * ``'sigmoid_2'`` - Linear map between -2.0 and 2.0
4413 * ``'sigmoid_3'`` - Linear map between -3.0 and 3.0
4414 * ``'sigmoid_4'`` - Linear map between -4.0 and 4.0
4415 * ``'sigmoid_5'`` - Linear map between -5.0 and 5.0
4416 * ``'sigmoid_6'`` - Linear map between -6.0 and 6.0
4417 * ``'sigmoid_7'`` - Linear map between -7.0 and 7.0
4418 * ``'sigmoid_8'`` - Linear map between -8.0 and 8.0
4419 * ``'sigmoid_9'`` - Linear map between -9.0 and 9.0
4420 * ``'sigmoid_10'`` - Linear map between -10.0 and 10.0
4421 * ``'sigmoid_15'`` - Linear map between -15.0 and 15.0
4422 * ``'sigmoid_20'`` - Linear map between -20.0 and 20.0
4423 * ``'foreground'`` - Transparent background and opaque foreground.
4424 Intended for use with segmentation labels. Assumes the smallest
4425 scalar value of the array is the background value (e.g. 0).
4426
4427 If RGBA scalars are provided, this parameter is set to ``'linear'``
4428 to ensure the opacity transfer function has no effect on the input
4429 opacity values.
4430
4431 n_colors : int, optional
4432 Number of colors to use when displaying scalars. Defaults to 256.
4433 The scalar bar will also have this many colors.
4434
4435 cmap : str | list | LookupTable, default: :attr:`pyvista.plotting.themes.Theme.cmap`
4436 If a string, this is the name of the ``matplotlib`` colormap to use
4437 when mapping the ``scalars``. See :ref:`named_colormaps` for supported
4438 colormaps.
4439
4440 Only applicable for when displaying ``scalars``.
4441 ``colormap`` is also an accepted alias
4442 for this. If ``colorcet`` or ``cmocean`` are installed, their
4443 colormaps can be specified by name.
4444
4445 You can also specify a list of colors to override an existing
4446 colormap with a custom one. For example, to create a three color
4447 colormap you might specify ``['green', 'red', 'blue']``.
4448
4449 This parameter also accepts a :class:`pyvista.LookupTable`. If this
4450 is set, all parameters controlling the color map like ``n_colors``
4451 will be ignored.
4452
4453 flip_scalars : bool, optional
4454 Flip direction of cmap. Most colormaps allow ``*_r`` suffix to do
4455 this as well.
4456
4457 reset_camera : bool, optional
4458 Reset the camera after adding this mesh to the scene.
4459
4460 name : str, optional
4461 The name for the added actor so that it can be easily
4462 updated. If an actor of this name already exists in the
4463 rendering window, it will be replaced by the new actor.
4464
4465 ambient : float, optional
4466 When lighting is enabled, this is the amount of light from
4467 0 to 1 that reaches the actor when not directed at the
4468 light source emitted from the viewer. Default 0.0.
4469
4470 categories : bool, optional
4471 If set to ``True``, then the number of unique values in the scalar
4472 array will be used as the ``n_colors`` argument.
4473
4474 culling : str, optional
4475 Does not render faces that are culled. Options are ``'front'`` or
4476 ``'back'``. This can be helpful for dense surface meshes,
4477 especially when edges are visible, but can cause flat
4478 meshes to be partially displayed. Defaults ``False``.
4479
4480 multi_colors : bool, optional
4481 Whether or not to use multiple colors when plotting MultiBlock
4482 object. Blocks will be colored sequentially as 'Reds', 'Greens',
4483 'Blues', and 'Grays'.
4484
4485 blending : str, optional
4486 Blending mode for visualisation of the input object(s). Can be
4487 one of 'additive', 'maximum', 'minimum', 'composite', or
4488 'average'. Defaults to 'composite'.
4489
4490 mapper : str, optional
4491 Volume mapper to use given by name. Options include:
4492 ``'fixed_point'``, ``'gpu'``, ``'open_gl'``, ``'smart'``,
4493 and ``'ugrid'``. If ``None`` the ``"volume_mapper"`` in the
4494 ``self._theme`` is used. If using ``'fixed_point'``,
4495 only ``ImageData`` types can be used.
4496
4497 .. note::
4498 If a :class:`pyvista.UnstructuredGrid` is input, the 'ugrid'
4499 mapper (:vtk:`vtkUnstructuredGridVolumeRayCastMapper`) will be
4500 used regardless.
4501
4502 .. note::
4503 The ``'smart'`` mapper chooses one of the other listed
4504 mappers based on rendering parameters and available
4505 hardware. Most of the time the ``'smart'`` simply checks
4506 if a GPU is available and if so, uses the ``'gpu'``
4507 mapper, otherwise using the ``'fixed_point'`` mapper.
4508
4509 .. warning::
4510 The ``'fixed_point'`` mapper is CPU-based and will have
4511 lower performance than the ``'gpu'`` or ``'open_gl'``
4512 mappers.
4513
4514 scalar_bar_args : dict, optional
4515 Dictionary of keyword arguments to pass when adding the
4516 scalar bar to the scene. For options, see
4517 :func:`pyvista.Plotter.add_scalar_bar`.
4518
4519 show_scalar_bar : bool
4520 If ``False``, a scalar bar will not be added to the
4521 scene. Defaults to ``True``.
4522
4523 annotations : dict, optional
4524 Pass a dictionary of annotations. Keys are the float
4525 values in the scalars range to annotate on the scalar bar
4526 and the values are the string annotations.
4527
4528 pickable : bool, optional
4529 Set whether this mesh is pickable.
4530
4531 preference : str, optional
4532 When ``mesh.n_points == mesh.n_cells`` and setting
4533 scalars, this parameter sets how the scalars will be
4534 mapped to the mesh. Default ``'point'``, causes the
4535 scalars will be associated with the mesh points. Can be
4536 either ``'point'`` or ``'cell'``.
4537
4538 opacity_unit_distance : float, optional
4539 Set/Get the unit distance on which the scalar opacity
4540 transfer function is defined. Meaning that over that
4541 distance, a given opacity (from the transfer function) is
4542 accumulated. This is adjusted for the actual sampling
4543 distance during rendering. By default, this is the length
4544 of the diagonal of the bounding box of the volume divided
4545 by the dimensions.
4546
4547 shade : bool, default: False
4548 Default off. If shading is turned on, the mapper may
4549 perform shading calculations - in some cases shading does
4550 not apply (for example, in a maximum intensity projection)
4551 and therefore shading will not be performed even if this
4552 flag is on.
4553
4554 diffuse : float, default: 0.7
4555 The diffuse lighting coefficient.
4556
4557 specular : float, default: 0.2
4558 The specular lighting coefficient.
4559
4560 specular_power : float, default: 10.0
4561 The specular power. Between ``0.0`` and ``128.0``.
4562
4563 render : bool, default: True
4564 Force a render when True.
4565
4566 user_matrix : TransformLike, default: np.eye(4)
4567 Matrix passed to the Volume class before rendering. This affects the
4568 actor/rendering only, not the input volume itself. The user matrix is the
4569 last transformation applied to the actor before rendering. Defaults to the
4570 identity matrix.
4571
4572 log_scale : bool, default: False
4573 Use log scale when mapping data to colors. Scalars less
4574 than zero are mapped to the smallest representable
4575 positive float.
4576
4577 **kwargs : dict, optional
4578 Optional keyword arguments.
4579
4580 Returns
4581 -------
4582 pyvista.Actor
4583 Actor of the volume.
4584
4585 Examples
4586 --------
4587 Show a built-in volume example with the coolwarm colormap.
4588
4589 >>> from pyvista import examples
4590 >>> import pyvista as pv
4591 >>> bolt_nut = examples.download_bolt_nut()
4592 >>> pl = pv.Plotter()
4593 >>> _ = pl.add_volume(bolt_nut, cmap='coolwarm')
4594 >>> pl.show()
4595
4596 Create a volume from scratch and plot it using single vector of
4597 scalars.
4598
4599 >>> import pyvista as pv
4600 >>> grid = pv.ImageData(dimensions=(9, 9, 9))
4601 >>> grid['scalars'] = -grid.x
4602 >>> pl = pv.Plotter()
4603 >>> _ = pl.add_volume(grid, opacity='linear')
4604 >>> pl.show()
4605
4606 Plot a volume from scratch using RGBA scalars
4607
4608 >>> import pyvista as pv
4609 >>> import numpy as np
4610 >>> grid = pv.ImageData(dimensions=(5, 20, 20))
4611 >>> scalars = grid.points - (grid.origin)
4612 >>> scalars /= scalars.max()
4613 >>> opacity = np.linalg.norm(grid.points - grid.center, axis=1).reshape(-1, 1)
4614 >>> opacity /= opacity.max()
4615 >>> scalars = np.hstack((scalars, opacity**3))
4616 >>> scalars *= 255
4617 >>> pl = pv.Plotter()
4618 >>> vol = pl.add_volume(grid, scalars=scalars.astype(np.uint8))
4619 >>> vol.prop.interpolation_type = 'linear'
4620 >>> pl.show()
4621
4622 Plot an UnstructuredGrid.
4623
4624 >>> from pyvista import examples
4625 >>> import pyvista as pv
4626 >>> mesh = examples.download_letter_a()
4627 >>> mesh['scalars'] = mesh.points[:, 1]
4628 >>> pl = pv.Plotter()
4629 >>> _ = pl.add_volume(mesh, opacity_unit_distance=0.1)
4630 >>> pl.show()
4631
4632 """
4633 # Handle default arguments
4634
4635 if user_matrix is None:
4636 user_matrix = np.eye(4)
4637 # Supported aliases
4638 clim = kwargs.pop('rng', clim)
4639 cmap = kwargs.pop('colormap', cmap)
4640 culling = kwargs.pop('backface_culling', culling)
4641
4642 if 'scalar' in kwargs:
4643 msg = (
4644 '`scalar` is an invalid keyword argument for `add_mesh`. '
4645 'Perhaps you mean `scalars` with an s?'
4646 )
4647 raise TypeError(msg)
4648 assert_empty_kwargs(**kwargs)
4649
4650 if show_scalar_bar is None:
4651 show_scalar_bar = self._theme.show_scalar_bar or scalar_bar_args # type: ignore[assignment]
4652
4653 # Avoid mutating input
4654 scalar_bar_args = {} if scalar_bar_args is None else scalar_bar_args.copy()
4655
4656 if culling is True:
4657 culling = 'backface'
4658
4659 if mapper is None:
4660 # Default mapper choice. Overridden later if UnstructuredGrid
4661 mapper = self._theme.volume_mapper # type: ignore[assignment]
4662
4663 # only render when the plotter has already been shown
4664 if render is None:
4665 render = not self._first_time
4666
4667 # Convert the VTK data object to a pyvista wrapped object if necessary
4668 if not is_pyvista_dataset(volume):
4669 if isinstance(volume, np.ndarray):
4670 volume = cast('pv.ImageData', wrap(volume))
4671 if resolution is None:
4672 resolution = [1, 1, 1]
4673 elif len(resolution) != 3:
4674 msg = 'Invalid resolution dimensions.'
4675 raise ValueError(msg)
4676 volume.spacing = resolution
4677 _validation.check_instance(volume, (pv.DataSet, pv.MultiBlock), name='volume')
4678 else:
4679 # HACK: Make a copy so the original object is not altered.
4680 # Also, place all data on the nodes as issues arise when
4681 # volume rendering on the cells.
4682 volume = volume.cell_data_to_point_data()
4683 assert isinstance(volume, (pv.DataSet, pv.MultiBlock)) # noqa: S101
4684
4685 if name is None:
4686 name = f'{type(volume).__name__}({volume.memory_address})'
4687
4688 if isinstance(volume, pv.MultiBlock):
4689 cycler = cycle(['Reds', 'Greens', 'Blues', 'Greys', 'Oranges', 'Purples'])
4690 # Now iteratively plot each element of the multiblock dataset
4691 actors = []
4692 for idx, block in enumerate(volume):
4693 if block is None:
4694 continue
4695 # Get a good name to use
4696 next_name = f'{name}-{idx}'
4697 # Get the data object
4698 wrapped = wrap(block)
4699 if resolution is None:
4700 try:
4701 block_resolution = wrapped.GetSpacing()
4702 except AttributeError:
4703 block_resolution = resolution
4704 else:
4705 block_resolution = resolution
4706 color = next(cycler) if multi_colors else cmap
4707
4708 a = self.add_volume(
4709 wrapped,
4710 resolution=block_resolution,
4711 opacity=opacity,
4712 n_colors=n_colors,
4713 cmap=color, # type: ignore[arg-type]
4714 flip_scalars=flip_scalars,
4715 reset_camera=reset_camera,
4716 name=next_name,
4717 ambient=ambient,
4718 categories=categories,
4719 culling=culling,
4720 clim=clim,
4721 mapper=mapper,
4722 pickable=pickable,
4723 opacity_unit_distance=opacity_unit_distance,
4724 shade=shade,
4725 diffuse=diffuse,
4726 specular=specular,
4727 specular_power=specular_power,
4728 render=render,
4729 show_scalar_bar=show_scalar_bar,
4730 )
4731 a = cast('Actor', a)
4732
4733 actors.append(a)
4734 return actors
4735
4736 # Make sure structured grids are not less than 3D
4737 # ImageData and RectilinearGrid should be olay as <3D
4738 if isinstance(volume, pv.StructuredGrid) and any(d < 2 for d in volume.dimensions):
4739 msg = 'StructuredGrids must be 3D dimensional.'
4740 raise ValueError(msg)
4741
4742 if isinstance(volume, pv.PolyData):
4743 msg = f'Type {type(volume)} not supported for volume rendering as it is not 3D.'
4744 raise TypeError(msg)
4745 elif not isinstance(
4746 volume,
4747 (pv.ImageData, pv.RectilinearGrid, pv.UnstructuredGrid),
4748 ):
4749 volume = volume.cast_to_unstructured_grid()
4750
4751 # Override mapper choice for UnstructuredGrid
4752 if isinstance(volume, pv.UnstructuredGrid):
4753 # Unstructured grid must be all tetrahedrals
4754 if not (volume.celltypes == pv.CellType.TETRA).all():
4755 volume = volume.triangulate()
4756 mapper = 'ugrid'
4757
4758 if mapper == 'fixed_point' and not isinstance(volume, pv.ImageData):
4759 msg = (
4760 f'Type {type(volume)} not supported for volume rendering with the '
4761 f'`"fixed_point"` mapper. Use `pyvista.ImageData`.'
4762 )
4763 raise TypeError(msg)
4764 elif isinstance(volume, pv.UnstructuredGrid) and mapper != 'ugrid':
4765 msg = (
4766 f'Type {type(volume)} not supported for volume rendering with the '
4767 f'`{mapper}` mapper. Use the "ugrid" mapper or simply leave as None.'
4768 )
4769 raise TypeError(msg)
4770
4771 volume = cast('pv.DataSet', volume)
4772 if opacity_unit_distance is None and not isinstance(volume, pv.UnstructuredGrid):
4773 opacity_unit_distance = volume.length / (np.mean(volume.dimensions) - 1)
4774
4775 if scalars is None:
4776 # Make sure scalars components are not vectors/tuples
4777 scalars = volume.active_scalars
4778 # Don't allow plotting of string arrays by default
4779 if scalars is not None and np.issubdtype(scalars.dtype, np.number):
4780 scalar_bar_args.setdefault('title', volume.active_scalars_info[1]) # type: ignore[typeddict-item]
4781 else:
4782 msg = 'No scalars to use for volume rendering.'
4783 raise MissingDataError(msg)
4784
4785 title = 'Data'
4786 if isinstance(scalars, str):
4787 title = scalars
4788 scalars = get_array(volume, scalars, preference=preference, err=True)
4789 scalar_bar_args.setdefault('title', title)
4790 elif not isinstance(scalars, np.ndarray):
4791 scalars = np.asarray(scalars) # type: ignore[unreachable]
4792 scalars = cast('NumpyArray[float]', scalars)
4793
4794 if not np.issubdtype(scalars.dtype, np.number):
4795 msg = 'Non-numeric scalars are currently not supported for volume rendering.'
4796 raise TypeError(msg)
4797
4798 if scalars.ndim != 1:
4799 if scalars.ndim != 2:
4800 msg = '`add_volume` only supports scalars with 1 or 2 dimensions'
4801 raise ValueError(msg)
4802 if scalars.shape[1] != 4 or scalars.dtype != np.uint8:
4803 msg = (
4804 f'`add_volume` only supports scalars with 2 dimension that have '
4805 f'4 components of datatype np.uint8, scalars have shape {scalars.shape} '
4806 f'and datatype {scalars.dtype}'
4807 )
4808 raise ValueError(msg)
4809 if opacity != 'linear':
4810 opacity = 'linear'
4811 warn_external('Ignoring custom opacity due to RGBA scalars.')
4812
4813 # Define mapper, volume, and add the correct properties
4814 mappers_lookup = {
4815 'fixed_point': FixedPointVolumeRayCastMapper,
4816 'gpu': GPUVolumeRayCastMapper,
4817 'open_gl': OpenGLGPUVolumeRayCastMapper,
4818 'smart': SmartVolumeMapper,
4819 'ugrid': UnstructuredGridVolumeRayCastMapper,
4820 }
4821 if not isinstance(mapper, str) or mapper not in mappers_lookup.keys():
4822 msg = (
4823 f'Mapper ({mapper}) unknown. Available volume mappers include: '
4824 f'{", ".join(mappers_lookup.keys())}'
4825 )
4826 raise TypeError(msg)
4827 self.mapper = mappers_lookup[mapper](theme=self._theme)
4828
4829 # Set scalars range
4830 min_, max_ = None, None
4831 if clim is None:
4832 min_, max_ = np.nanmin(scalars), np.nanmax(scalars)
4833 clim = (min_, max_)
4834 elif isinstance(clim, (float, int)):
4835 clim = (-clim, clim)
4836
4837 if log_scale and clim[0] <= 0:
4838 clim = (sys.float_info.min, clim[1])
4839
4840 volume[title] = scalars
4841 volume.active_scalars_name = title
4842
4843 # Scalars interpolation approach
4844 if scalars.shape[0] == volume.n_points:
4845 self.mapper.scalar_map_mode = 'point'
4846 elif scalars.shape[0] == volume.n_cells:
4847 self.mapper.scalar_map_mode = 'cell'
4848 else:
4849 raise_not_matching(scalars, volume)
4850
4851 self.mapper.scalar_range = clim
4852
4853 if isinstance(cmap, pv.LookupTable):
4854 self.mapper.lookup_table = cmap
4855 else:
4856 if cmap is None:
4857 cmap = self._theme.cmap
4858
4859 cmap_obj = get_cmap_safe(cmap)
4860 if categories:
4861 if categories is True:
4862 n_colors = len(np.unique(scalars))
4863 elif isinstance(categories, int):
4864 n_colors = categories
4865
4866 if flip_scalars:
4867 cmap_obj = cmap_obj.reversed()
4868
4869 # Set colormap and build lookup table
4870 self.mapper.lookup_table.apply_cmap(cmap_obj, n_colors)
4871 self.mapper.lookup_table.apply_opacity(opacity)
4872 self.mapper.lookup_table.scalar_range = clim
4873 self.mapper.lookup_table.log_scale = log_scale
4874 if isinstance(annotations, dict):
4875 self.mapper.lookup_table.annotations = annotations
4876
4877 self.mapper.dataset = volume
4878 self.mapper.blend_mode = blending
4879 self.mapper.update()
4880
4881 self.volume = Volume()
4882 self.volume.mapper = self.mapper
4883 self.volume.user_matrix = user_matrix
4884
4885 self.volume.prop = VolumeProperty(
4886 lookup_table=self.mapper.lookup_table,
4887 ambient=ambient,
4888 shade=shade,
4889 specular=specular,
4890 specular_power=specular_power,
4891 diffuse=diffuse,
4892 opacity_unit_distance=opacity_unit_distance,
4893 )
4894
4895 if scalars.ndim == 2:
4896 self.volume.prop.independent_components = False
4897 show_scalar_bar = False
4898
4899 actor, _ = self.add_actor(
4900 self.volume, # type: ignore[arg-type]
4901 reset_camera=reset_camera,
4902 name=name,
4903 culling=culling,
4904 pickable=pickable,
4905 render=render,
4906 )
4907
4908 # Add scalar bar if scalars are available
4909 if show_scalar_bar and scalars is not None:
4910 self.add_scalar_bar(**scalar_bar_args) # type: ignore[call-arg]
4911
4912 self.renderer.Modified()
4913 return cast('Actor', actor)
4914
4915 @_deprecate_positional_args(allowed=['mesh'])
4916 def add_silhouette( # noqa: PLR0917
4917 self,
4918 mesh: NumpyArray[float]
4919 | DataSet
4920 | MultiBlock
4921 | _vtk.vtkAlgorithm
4922 | _vtk.vtkAlgorithmOutput,
4923 color: ColorLike | None = None,
4924 line_width: float | None = None,
4925 opacity: float | None = None,
4926 feature_angle: float | None = None,
4927 decimate: float | None = None,
4928 ) -> Actor:
4929 """Add a silhouette of a PyVista or VTK dataset to the scene.
4930
4931 A silhouette can also be generated directly in
4932 :func:`add_mesh <pyvista.Plotter.add_mesh>`. See also
4933 :ref:`silhouette_example`.
4934
4935 Parameters
4936 ----------
4937 mesh : DataSet | :vtk:`vtkAlgorithm`
4938 Mesh or mesh-producing algorithm for generating silhouette
4939 to plot.
4940
4941 color : ColorLike, optional
4942 Color of the silhouette lines.
4943
4944 line_width : float, optional
4945 Silhouette line width.
4946
4947 opacity : float, optional
4948 Line transparency between ``0`` and ``1``.
4949
4950 feature_angle : float, optional
4951 If set, display sharp edges exceeding that angle in degrees.
4952
4953 decimate : float, optional
4954 Level of decimation between ``0`` and ``1``. Decimating will
4955 improve rendering performance. A good rule of thumb is to
4956 try ``0.9`` first and decrease until the desired rendering
4957 performance is achieved.
4958
4959 Returns
4960 -------
4961 pyvista.Actor
4962 Actor of the silhouette.
4963
4964 Examples
4965 --------
4966 >>> import pyvista as pv
4967 >>> from pyvista import examples
4968 >>> bunny = examples.download_bunny()
4969 >>> pl = pv.Plotter()
4970 >>> _ = pl.add_mesh(bunny, color='lightblue')
4971 >>> _ = pl.add_silhouette(bunny, color='red', line_width=8.0)
4972 >>> pl.view_xy()
4973 >>> pl.show()
4974
4975 """
4976 mesh, algo = algorithm_to_mesh_handler(mesh)
4977 if not isinstance(mesh, pv.PolyData):
4978 algo = extract_surface_algorithm(algo or mesh)
4979 mesh, algo = algorithm_to_mesh_handler(algo)
4980
4981 silhouette_params = self._theme.silhouette.to_dict()
4982
4983 if color is None:
4984 color = silhouette_params['color']
4985 if line_width is None:
4986 line_width = silhouette_params['line_width']
4987 if opacity is None:
4988 opacity = silhouette_params['opacity']
4989 if feature_angle is None:
4990 feature_angle = silhouette_params['feature_angle']
4991 if decimate is None:
4992 decimate = silhouette_params['decimate']
4993
4994 # At this point we are dealing with a pipeline, so no `algo or mesh`
4995 if decimate:
4996 # Always triangulate as decimation filters needs it
4997 # and source mesh could have been any type
4998 algo = triangulate_algorithm(algo or mesh)
4999 algo = decimation_algorithm(algo, decimate)
5000 mesh, algo = algorithm_to_mesh_handler(algo)
5001
5002 alg = _vtk.vtkPolyDataSilhouette()
5003 set_algorithm_input(alg, algo or mesh)
5004 alg.SetCamera(self.renderer.camera)
5005 if feature_angle is not None:
5006 alg.SetEnableFeatureAngle(True)
5007 alg.SetFeatureAngle(feature_angle)
5008 else:
5009 alg.SetEnableFeatureAngle(False)
5010 mapper = DataSetMapper(theme=self._theme)
5011 mapper.SetInputConnection(alg.GetOutputPort())
5012 actor, prop = self.add_actor(mapper) # type: ignore[arg-type]
5013 prop = cast('Property', prop)
5014 prop.SetColor(Color(color).float_rgb) # type: ignore[call-overload]
5015 prop.SetOpacity(opacity)
5016 prop.SetLineWidth(line_width)
5017
5018 return cast('Actor', actor)
5019
5020 def update_scalar_bar_range(
5021 self, clim: float | Sequence[float], name: str | None = None
5022 ) -> None:
5023 """Update the value range of the active or named scalar bar.
5024
5025 Parameters
5026 ----------
5027 clim : sequence[float]
5028 The new range of scalar bar. For example ``[-1, 2]``.
5029
5030 name : str, optional
5031 The title of the scalar bar to update.
5032
5033 """
5034 if isinstance(clim, (float, int)):
5035 clim = (-clim, clim)
5036 if len(clim) != 2:
5037 msg = 'clim argument must be a length 2 iterable of values: (min, max).'
5038 raise TypeError(msg)
5039 if name is None:
5040 if self.mapper is None:
5041 msg = 'This plotter does not have an active mapper.'
5042 raise AttributeError(msg)
5043 self.mapper.scalar_range = clim
5044 return
5045
5046 try:
5047 # use the name to find the desired actor
5048 for mh in self.scalar_bars._scalar_bar_mappers[name]:
5049 mh.scalar_range = clim
5050 except KeyError:
5051 msg = f'Name ({name!r}) not valid/not found in this plotter.'
5052 raise ValueError(msg) from None
5053
5054 def clear_actors(self) -> None:
5055 """Clear actors from all renderers."""
5056 self.renderers.clear_actors()
5057
5058 def clear(self) -> None:
5059 """Clear plot by removing all actors and properties.
5060
5061 Examples
5062 --------
5063 >>> import pyvista as pv
5064 >>> pl = pv.Plotter()
5065 >>> actor = pl.add_mesh(pv.Sphere())
5066 >>> pl.clear()
5067 >>> pl.renderer.actors
5068 {}
5069
5070 """
5071 self.renderers.clear()
5072 self.scalar_bars.clear()
5073 self.mesh = None
5074 self.mapper = None
5075
5076 def link_views(self, views: int | Iterable[int] | None = 0) -> None:
5077 """Link the views' cameras.
5078
5079 Parameters
5080 ----------
5081 views : int | tuple | list, default: 0
5082 If ``views`` is int, link the views to the given view
5083 index or if ``views`` is a tuple or a list, link the given
5084 views cameras.
5085
5086 See Also
5087 --------
5088 subplot
5089
5090 Examples
5091 --------
5092 Not linked view case.
5093
5094 >>> import pyvista as pv
5095 >>> from pyvista import demos
5096 >>> ocube = demos.orientation_cube()
5097 >>> pl = pv.Plotter(shape=(1, 2))
5098 >>> pl.subplot(0, 0)
5099 >>> _ = pl.add_mesh(ocube['cube'], show_edges=True)
5100 >>> _ = pl.add_mesh(ocube['x_p'], color='blue')
5101 >>> _ = pl.add_mesh(ocube['x_n'], color='blue')
5102 >>> _ = pl.add_mesh(ocube['y_p'], color='green')
5103 >>> _ = pl.add_mesh(ocube['y_n'], color='green')
5104 >>> _ = pl.add_mesh(ocube['z_p'], color='red')
5105 >>> _ = pl.add_mesh(ocube['z_n'], color='red')
5106 >>> pl.camera_position = 'yz'
5107 >>> pl.subplot(0, 1)
5108 >>> _ = pl.add_mesh(ocube['cube'], show_edges=True)
5109 >>> _ = pl.add_mesh(ocube['x_p'], color='blue')
5110 >>> _ = pl.add_mesh(ocube['x_n'], color='blue')
5111 >>> _ = pl.add_mesh(ocube['y_p'], color='green')
5112 >>> _ = pl.add_mesh(ocube['y_n'], color='green')
5113 >>> _ = pl.add_mesh(ocube['z_p'], color='red')
5114 >>> _ = pl.add_mesh(ocube['z_n'], color='red')
5115 >>> pl.show_axes()
5116 >>> pl.show()
5117
5118 Linked view case.
5119
5120 >>> pl = pv.Plotter(shape=(1, 2))
5121 >>> pl.subplot(0, 0)
5122 >>> _ = pl.add_mesh(ocube['cube'], show_edges=True)
5123 >>> _ = pl.add_mesh(ocube['x_p'], color='blue')
5124 >>> _ = pl.add_mesh(ocube['x_n'], color='blue')
5125 >>> _ = pl.add_mesh(ocube['y_p'], color='green')
5126 >>> _ = pl.add_mesh(ocube['y_n'], color='green')
5127 >>> _ = pl.add_mesh(ocube['z_p'], color='red')
5128 >>> _ = pl.add_mesh(ocube['z_n'], color='red')
5129 >>> pl.camera_position = 'yz'
5130 >>> pl.subplot(0, 1)
5131 >>> _ = pl.add_mesh(ocube['cube'], show_edges=True)
5132 >>> _ = pl.add_mesh(ocube['x_p'], color='blue')
5133 >>> _ = pl.add_mesh(ocube['x_n'], color='blue')
5134 >>> _ = pl.add_mesh(ocube['y_p'], color='green')
5135 >>> _ = pl.add_mesh(ocube['y_n'], color='green')
5136 >>> _ = pl.add_mesh(ocube['z_p'], color='red')
5137 >>> _ = pl.add_mesh(ocube['z_n'], color='red')
5138 >>> pl.show_axes()
5139 >>> pl.link_views()
5140 >>> pl.show()
5141
5142 """
5143 if isinstance(views, (int, np.integer)):
5144 camera = self.renderers[views].camera
5145 camera_status = self.renderers[views].camera.is_set
5146 for renderer in self.renderers:
5147 renderer.camera = camera
5148 renderer.camera.is_set = camera_status
5149 return
5150 views = np.asarray(views)
5151 if np.issubdtype(views.dtype, np.integer):
5152 camera = self.renderers[views[0]].camera
5153 camera_status = self.renderers[views[0]].camera.is_set
5154 for view_index in views:
5155 self.renderers[view_index].camera = camera
5156 self.renderers[view_index].camera.is_set = camera_status
5157 else:
5158 msg = f'Expected type is int, list or tuple: {type(views)} is given'
5159 raise TypeError(msg)
5160
5161 def unlink_views(self, views: int | Iterable[int] | None = None) -> None:
5162 """Unlink the views' cameras.
5163
5164 Parameters
5165 ----------
5166 views : int | tuple | list, optional
5167 If ``views`` is None unlink all the views, if ``views``
5168 is int unlink the selected view's camera or if ``views``
5169 is a tuple or a list, unlink the given views cameras.
5170
5171 """
5172 if views is None:
5173 for renderer in self.renderers:
5174 renderer.camera = Camera()
5175 renderer.reset_camera()
5176 renderer.camera.is_set = False
5177 elif isinstance(views, int):
5178 self.renderers[views].camera = Camera()
5179 self.renderers[views].reset_camera()
5180 self.renderers[views].camera.is_set = False
5181 elif isinstance(views, Iterable):
5182 for view_index in views:
5183 self.renderers[view_index].camera = Camera()
5184 self.renderers[view_index].reset_camera()
5185 self.renderers[view_index].camera_set = False
5186 else:
5187 msg = f'Expected type is None, int, list or tuple: {type(views)} is given' # type: ignore[unreachable]
5188 raise TypeError(msg)
5189
5190 @wraps(ScalarBars.add_scalar_bar)
5191 def add_scalar_bar(
5192 self, title: str = '', **kwargs
5193 ) -> _vtk.vtkScalarBarActor: # numpydoc ignore=PR01,RT01
5194 """Wrap for ``ScalarBars.add_scalar_bar``."""
5195 # only render when the plotter has already been shown
5196 render = kwargs.get('render')
5197 if render is None:
5198 kwargs['render'] = not self._first_time
5199
5200 # check if maper exists
5201 mapper = kwargs.get('mapper')
5202 if mapper is None:
5203 if self.mapper is None:
5204 msg = 'Mapper does not exist. Add a mesh with scalars first.'
5205 raise AttributeError(msg)
5206 kwargs['mapper'] = self.mapper
5207
5208 interactive = kwargs.get('interactive')
5209 if interactive is None:
5210 interactive = self._theme.interactive
5211 if self.shape != (1, 1):
5212 interactive = False
5213 kwargs['interactive'] = interactive
5214 elif interactive and self.shape != (1, 1):
5215 msg = 'Interactive scalar bars disabled for multi-renderer plots'
5216 raise ValueError(msg)
5217 # by default, use the plotter local theme
5218 kwargs.setdefault('theme', self._theme)
5219 return self.scalar_bars.add_scalar_bar(title, **kwargs)
5220
5221 @_deprecate_positional_args(allowed=['scalars'])
5222 def update_scalars(self, scalars, mesh=None, render: bool = True) -> None: # noqa: ANN001, FBT001, FBT002
5223 """Update scalars of an object in the plotter.
5224
5225 .. deprecated:: 0.43.0
5226 This method is deprecated and will be removed in a future version of
5227 PyVista. It is functionally equivalent to directly modifying the
5228 scalars of a mesh in-place.
5229
5230 .. code-block:: python
5231
5232 # Modify the points in place
5233 mesh['my scalars'] = values
5234 # Explicitly call render if needed
5235 pl.render()
5236
5237 Parameters
5238 ----------
5239 scalars : sequence
5240 Scalars to replace existing scalars.
5241
5242 mesh : vtk.PolyData | vtk.UnstructuredGrid, optional
5243 Object that has already been added to the Plotter. If
5244 None, uses last added mesh.
5245
5246 render : bool, default: True
5247 Force a render when True.
5248
5249 """
5250 # Deprecated on 0.43.0, estimated removal on v0.46.0
5251 warn_external(
5252 'This method is deprecated and will be removed in a future version of '
5253 'PyVista. Directly modify the scalars of a mesh in-place instead.',
5254 PyVistaDeprecationWarning,
5255 )
5256
5257 if mesh is None:
5258 mesh = self.mesh
5259
5260 if isinstance(mesh, (Iterable, pv.MultiBlock)):
5261 # Recursive if need to update scalars on many meshes
5262 for m in mesh:
5263 self.update_scalars(scalars, mesh=m, render=False)
5264 if render:
5265 self.render()
5266 return
5267
5268 if isinstance(scalars, str):
5269 # Grab scalars array if name given
5270 scalars = get_array(mesh, scalars)
5271
5272 if scalars is None:
5273 if render:
5274 self.render()
5275 return
5276
5277 if scalars.shape[0] == mesh.GetNumberOfPoints():
5278 data = mesh.GetPointData()
5279 elif scalars.shape[0] == mesh.GetNumberOfCells():
5280 data = mesh.GetCellData()
5281 else:
5282 raise_not_matching(scalars, mesh)
5283
5284 vtk_scalars = data.GetScalars()
5285 if vtk_scalars is None:
5286 msg = 'No active scalars'
5287 raise ValueError(msg)
5288 s = convert_array(vtk_scalars)
5289 s[:] = scalars
5290 vtk_scalars.Modified()
5291 data.Modified()
5292 with contextlib.suppress(Exception):
5293 # Why are the points updated here? Not all datasets have points
5294 # and only the scalars array is modified by this function...
5295 mesh.GetPoints().Modified()
5296
5297 if render:
5298 self.render()
5299
5300 def _clear_ren_win(self) -> None:
5301 """Clear the render window."""
5302 # Not using `render_window` property here to enforce clean up
5303 if self.ren_win is not None:
5304 self.ren_win.Finalize()
5305 if (
5306 sys.platform == 'darwin'
5307 and self.iren is not None
5308 and self.iren.interactor is not None
5309 ):
5310 # Flush pending Cocoa events so the macOS window server
5311 # actually dismisses the window. Without this, the NSWindow
5312 # is removed from NSApp.windows() but the window server
5313 # still draws it as a frozen "zombie" window.
5314 self.iren.interactor.ProcessEvents()
5315 self.ren_win = None
5316
5317 def close(self) -> None:
5318 """Close the render window."""
5319 # optionally run just prior to exiting the plotter
5320 if self._before_close_callback is not None:
5321 self._before_close_callback(self) # type: ignore[arg-type]
5322 self._before_close_callback = None
5323
5324 # Tear down plotter components first (in reverse construction
5325 # order) so that widgets / pickers release their VTK observers
5326 # before the renderers and render window go away.
5327 for component in reversed(getattr(self, '_components', ())):
5328 hook = getattr(component, '__plotter_close__', None)
5329 if hook is not None:
5330 hook()
5331
5332 # Renderer has an axes widget, so close it.
5333 self.renderers.close()
5334 self.renderers.remove_all_lights()
5335
5336 # Grab screenshots of last render
5337 # self.last_image = self.screenshot(None, return_img=True)
5338 # self.last_image_depth = self.get_image_depth()
5339
5340 self.mesh = None
5341 self.mapper = None
5342 self.text = None
5343
5344 self._clear_ren_win()
5345 if self.iren is not None:
5346 self.iren.close()
5347 self.iren = None
5348
5349 # end movie
5350 if self.mwriter is not None:
5351 with suppress(BaseException):
5352 self.mwriter.close()
5353 self.mwriter = None
5354
5355 # Remove the global reference to this plotter unless building the
5356 # gallery to allow it to collect.
5357 if not pv.BUILDING_GALLERY and _ALL_PLOTTERS is not None:
5358 _ALL_PLOTTERS.pop(self._id_name, None)
5359
5360 # this helps managing closed plotters
5361 self._closed = True
5362
5363 def deep_clean(self) -> None:
5364 """Clean the plotter of the memory."""
5365 if hasattr(self, 'renderers'):
5366 self.renderers.deep_clean()
5367 # Run deep-clean hooks on constructed components in reverse order.
5368 for component in reversed(getattr(self, '_components', ())):
5369 hook = getattr(component, '__plotter_deep_clean__', None)
5370 if hook is not None:
5371 hook()
5372 self.mesh = None
5373 self.mapper = None
5374 self.volume = None
5375 self.text = None
5376
5377 @_deprecate_positional_args(allowed=['text'])
5378 def add_text( # noqa: PLR0917
5379 self,
5380 text: str,
5381 position: Literal[
5382 'lower_left',
5383 'lower_right',
5384 'upper_left',
5385 'upper_right',
5386 'lower_edge',
5387 'upper_edge',
5388 'right_edge',
5389 'left_edge',
5390 ]
5391 | Sequence[float]
5392 | None = 'upper_left',
5393 font_size: int | None = 18,
5394 color: ColorLike | None = None,
5395 font: FontFamilyOptions | None = None,
5396 shadow: bool = False, # noqa: FBT001, FBT002
5397 name: str | None = None,
5398 viewport: bool = False, # noqa: FBT001, FBT002
5399 orientation: float = 0.0,
5400 font_file: str | None = None,
5401 *,
5402 render: bool = True,
5403 ) -> CornerAnnotation | Text:
5404 """Add text to plot object in the top left corner by default.
5405
5406 Parameters
5407 ----------
5408 text : str
5409 The text to add the rendering.
5410
5411 position : str | sequence[float], default: "upper_left"
5412 Position to place the bottom left corner of the text box.
5413 If tuple is used, the position of the text uses the pixel
5414 coordinate system (default). In this case,
5415 it returns a more general :vtk:`vtkOpenGLTextActor`.
5416 If string name is used, it returns a :vtk:`vtkCornerAnnotation`
5417 object normally used for fixed labels (like title or xlabel).
5418 Default is to find the top left corner of the rendering window
5419 and place text box up there. Available position: ``'lower_left'``,
5420 ``'lower_right'``, ``'upper_left'``, ``'upper_right'``,
5421 ``'lower_edge'``, ``'upper_edge'``, ``'right_edge'``, and
5422 ``'left_edge'``.
5423
5424 font_size : float, default: 18
5425 Sets the size of the title font.
5426
5427 color : ColorLike, optional
5428 Either a string, RGB list, or hex color string. For example:
5429
5430 * ``color='white'``
5431 * ``color='w'``
5432 * ``color=[1.0, 1.0, 1.0]``
5433 * ``color='#FFFFFF'``
5434
5435 Defaults to
5436 :attr:`pyvista.global_theme.font.color <pyvista.plotting.themes._Font.color>`.
5437
5438 font : str, default: 'arial'
5439 Font name may be ``'courier'``, ``'times'``, or ``'arial'``.
5440 This is ignored if the `font_file` is set.
5441
5442 shadow : bool, default: False
5443 Adds a black shadow to the text.
5444
5445 name : str, optional
5446 The name for the added actor so that it can be easily updated.
5447 If an actor of this name already exists in the rendering window, it
5448 will be replaced by the new actor.
5449
5450 viewport : bool, default: False
5451 If ``True`` and position is a tuple of float, uses the
5452 normalized viewport coordinate system (values between 0.0
5453 and 1.0 and support for HiDPI).
5454
5455 orientation : float, default: 0.0
5456 Angle orientation of text counterclockwise in degrees. The text
5457 is rotated around an anchor point that may be on the edge or
5458 corner of the text. The default is horizontal (0.0 degrees).
5459
5460 font_file : str, default: None
5461 The absolute file path to a local file containing a freetype
5462 readable font.
5463
5464 render : bool, default: True
5465 Force a render when ``True``.
5466
5467 Returns
5468 -------
5469 output : CornerAnnotation | Text
5470 Text actor added to plot.
5471
5472 Examples
5473 --------
5474 Add blue text to the upper right of the plotter.
5475
5476 >>> import pyvista as pv
5477 >>> pl = pv.Plotter()
5478 >>> actor = pl.add_text(
5479 ... 'Sample Text',
5480 ... position='upper_right',
5481 ... color='blue',
5482 ... shadow=True,
5483 ... font_size=26,
5484 ... )
5485 >>> pl.show()
5486
5487 Add text and use a custom freetype readable font file.
5488
5489 >>> pl = pv.Plotter()
5490 >>> actor = pl.add_text(
5491 ... 'Text',
5492 ... font_file='/home/user/Mplus2-Regular.ttf',
5493 ... ) # doctest:+SKIP
5494
5495
5496 """
5497 if font_size is None:
5498 font_size = self._theme.font.size
5499 if position is None:
5500 # Set the position of the text to the top left corner
5501 window_size = self.window_size
5502 x = (window_size[0] * 0.02) / self.shape[0]
5503 y = (window_size[1] * 0.85) / self.shape[0]
5504 position = [x, y]
5505 text_prop = TextProperty(
5506 color=color,
5507 font_family=font,
5508 orientation=orientation,
5509 font_file=font_file,
5510 shadow=shadow,
5511 )
5512 if isinstance(position, (int, str, bool)):
5513 actor: CornerAnnotation | Text = CornerAnnotation(
5514 position, text, linear_font_scale_factor=font_size // 2
5515 )
5516 else:
5517 actor = Text(text=text, position=position)
5518 if viewport:
5519 actor.GetActualPositionCoordinate().SetCoordinateSystemToNormalizedViewport()
5520 actor.GetActualPosition2Coordinate().SetCoordinateSystemToNormalizedViewport()
5521 text_prop.font_size = int(font_size * 2)
5522 actor.prop = text_prop
5523 self.text = actor
5524 self.add_actor(actor, reset_camera=False, name=name, pickable=False, render=render) # type: ignore[arg-type]
5525 return actor
5526
5527 def open_movie(
5528 self, filename: str | Path, framerate: int = 24, quality: int = 5, **kwargs
5529 ) -> None:
5530 """Establish a connection to the ffmpeg writer.
5531
5532 Requires ``imageio`` to be installed.
5533
5534 Parameters
5535 ----------
5536 filename : str | Path
5537 Filename of the movie to open. Filename should end in mp4,
5538 but other filetypes may be supported. See :func:`imageio.get_writer()
5539 <imageio.v2.get_writer>`.
5540
5541 framerate : int, default: 24
5542 Frames per second.
5543
5544 quality : int, default: 5
5545 Quality 10 is the top possible quality for any codec. The
5546 range is ``0 - 10``. Higher quality leads to a larger file.
5547
5548 **kwargs : dict, optional
5549 See the documentation for :func:`imageio.get_writer()
5550 <imageio.v2.get_writer>` for additional kwargs.
5551
5552 Notes
5553 -----
5554 See the documentation for :func:`imageio.get_writer() <imageio.v2.get_writer>`.
5555
5556 Examples
5557 --------
5558 Open a MP4 movie and set the quality to maximum.
5559
5560 >>> import pyvista as pv
5561 >>> pl = pv.Plotter()
5562 >>> pl.open_movie('movie.mp4', quality=10) # doctest:+SKIP
5563
5564 """
5565 try:
5566 from imageio import get_writer # noqa: PLC0415
5567 except ModuleNotFoundError: # pragma: no cover
5568 msg = 'Install imageio to use `open_movie` with:\n\n pip install imageio'
5569 raise ModuleNotFoundError(msg) from None
5570
5571 if (
5572 isinstance(pv.FIGURE_PATH, str) and not Path(filename).is_absolute()
5573 ): # pragma: no cover
5574 filename = Path(pv.FIGURE_PATH) / filename
5575 self.mwriter = get_writer(filename, fps=framerate, quality=quality, **kwargs)
5576
5577 @_deprecate_positional_args(allowed=['filename'])
5578 def open_gif( # noqa: PLR0917
5579 self,
5580 filename: str | Path,
5581 loop: int = 0,
5582 fps: float = 10,
5583 palettesize: int = 256,
5584 subrectangles: bool = False, # noqa: FBT001, FBT002
5585 **kwargs,
5586 ) -> None:
5587 """Open a gif file.
5588
5589 Requires ``imageio`` to be installed.
5590
5591 Parameters
5592 ----------
5593 filename : str | Path
5594 Filename of the gif to open. Filename must end in ``"gif"``.
5595
5596 loop : int, default: 0
5597 The number of iterations. Default value of 0 loops indefinitely.
5598
5599 fps : float, default: 10
5600 The number of frames per second. If duration is not given, the
5601 duration for each frame is set to 1/fps.
5602
5603 palettesize : int, default: 256
5604 The number of colors to quantize the image to. Is rounded to the
5605 nearest power of two. Must be between 2 and 256.
5606
5607 subrectangles : bool, default: False
5608 If ``True``, will try and optimize the GIF by storing only the rectangular
5609 parts of each frame that change with respect to the previous.
5610
5611 .. note::
5612 Setting this to ``True`` may help reduce jitter in colorbars.
5613
5614 **kwargs : dict, optional
5615 See the documentation for :func:`imageio.get_writer() <imageio.v2.get_writer>`
5616 for additional kwargs.
5617
5618 Notes
5619 -----
5620 Consider using `pygifsicle
5621 <https://github.com/LucaCappelletti94/pygifsicle>`_ to reduce the final
5622 size of the gif. See `Optimizing a GIF using pygifsicle
5623 <https://imageio.readthedocs.io/en/stable/examples.html#optimizing-a-gif-using-pygifsicle>`_.
5624
5625 See Also
5626 --------
5627 :ref:`gif_example`
5628 :ref:`moving_cmap_example`
5629 :ref:`moving_isovalue_example`
5630
5631 Examples
5632 --------
5633 Open a gif file, setting the framerate to 8 frames per second and
5634 reducing the colorspace to 64.
5635
5636 >>> import pyvista as pv
5637 >>> pl = pv.Plotter()
5638 >>> pl.open_gif('movie.gif', fps=8, palettesize=64) # doctest:+SKIP
5639
5640 See :ref:`gif_example` for a full example using this method.
5641
5642 """
5643 try:
5644 from imageio import __version__ # noqa: PLC0415
5645 from imageio import get_writer # noqa: PLC0415
5646 except ModuleNotFoundError: # pragma: no cover
5647 msg = 'Install imageio to use `open_gif` with:\n\n pip install imageio'
5648 raise ModuleNotFoundError(msg) from None
5649
5650 filename = Path(filename)
5651 if filename.suffix != '.gif':
5652 msg = 'Unsupported filetype. Must end in .gif'
5653 raise ValueError(msg)
5654 if isinstance(pv.FIGURE_PATH, str) and not filename.is_absolute(): # pragma: no cover
5655 filename = Path(pv.FIGURE_PATH) / filename
5656 self._gif_filename = filename.resolve()
5657
5658 kwargs['mode'] = 'I'
5659 kwargs['loop'] = loop
5660 kwargs['palettesize'] = palettesize
5661 kwargs['subrectangles'] = subrectangles
5662 if scooby.knowledge.meets_version(__version__, '2.28.1'):
5663 kwargs['duration'] = 1000 * 1 / fps
5664 else: # pragma: no cover
5665 kwargs['fps'] = fps
5666
5667 self.mwriter = get_writer(filename, **kwargs)
5668
5669 def write_frame(self) -> None:
5670 """Write a single frame to the movie file.
5671
5672 Examples
5673 --------
5674 >>> import pyvista as pv
5675 >>> pl = pv.Plotter()
5676 >>> pl.open_movie(filename) # doctest:+SKIP
5677 >>> pl.add_mesh(pv.Sphere()) # doctest:+SKIP
5678 >>> pl.write_frame() # doctest:+SKIP
5679
5680 See :ref:`movie_example` for a full example using this method.
5681
5682 """
5683 # if off screen, show has not been called and we must render
5684 # before extracting an image
5685 if self._first_time:
5686 self._on_first_render_request()
5687 self.render()
5688
5689 mwriter = self._get_mwriter_not_none()
5690 self.update()
5691 mwriter.append_data(self.image)
5692
5693 @_deprecate_positional_args
5694 def get_image_depth(
5695 self,
5696 fill_value: float | None = np.nan,
5697 reset_camera_clipping_range: bool = True, # noqa: FBT001, FBT002
5698 ) -> pv.pyvista_ndarray:
5699 """Return a depth image representing current render window.
5700
5701 .. versionchanged:: 0.47
5702 The last image depth is no longer automatically stored. You must
5703 enable ``store_image_depth=True`` within :meth:`Plotter.show` to
5704 obtain the image depth after the :class:`pyvista.Plotter` has been
5705 closed.
5706
5707 Parameters
5708 ----------
5709 fill_value : float, default: numpy.nan
5710 Fill value for points in image that do not include objects in
5711 scene. To not use a fill value, pass ``None``.
5712
5713 reset_camera_clipping_range : bool, default: True
5714 Reset the camera clipping range to include data in view.
5715
5716 Returns
5717 -------
5718 pyvista.pyvista_ndarray
5719 Image of depth values from camera orthogonal to image
5720 plane.
5721
5722 Notes
5723 -----
5724 Values in ``image_depth`` are negative to adhere to a right-handed
5725 coordinate system.
5726
5727 See Also
5728 --------
5729 :ref:`image_depth_example`
5730
5731 Examples
5732 --------
5733 >>> import pyvista as pv
5734 >>> pl = pv.Plotter()
5735 >>> actor = pl.add_mesh(pv.Sphere())
5736 >>> pl.show(store_image_depth=True)
5737 >>> zval = pl.get_image_depth()
5738
5739 """
5740 # allow no render window
5741 if self.render_window is None and self.last_image_depth is not None:
5742 zval = self.last_image_depth.copy()
5743 if fill_value is not None and self._image_depth_null is not None:
5744 zval[self._image_depth_null] = fill_value
5745 return zval
5746
5747 self._check_rendered()
5748 if self.render_window is None and self.last_image_depth is None:
5749 msg = (
5750 'The `Plotter` was closed without storing image depth. Call `show` with '
5751 '`store_image_depth=True` when using `get_image_depth`.'
5752 )
5753 raise RuntimeError(msg)
5754 self._check_has_ren_win()
5755
5756 # Ensure points in view are within clipping range of renderer?
5757 if reset_camera_clipping_range:
5758 self.renderer.ResetCameraClippingRange()
5759
5760 # Get the z-buffer image
5761 ifilter = _vtk.vtkWindowToImageFilter()
5762 ifilter.SetInput(self.render_window)
5763 ifilter.SetScale(self.image_scale)
5764 ifilter.ReadFrontBufferOff()
5765 ifilter.SetInputBufferTypeToZBuffer()
5766 zbuff = run_image_filter(ifilter)[:, :, 0]
5767
5768 # Convert z-buffer values to depth from camera
5769 with warnings.catch_warnings():
5770 warnings.filterwarnings('ignore')
5771 near, far = self.camera.clipping_range
5772 if self.camera.parallel_projection:
5773 zval = -(zbuff * (far - near) + near)
5774 else:
5775 zval = 2 * near * far / ((zbuff - 0.5) * 2 * (far - near) - near - far)
5776
5777 # Consider image values outside clipping range as nans
5778 self._image_depth_null = np.logical_or(zval < -far, np.isclose(zval, -far))
5779
5780 if fill_value is not None:
5781 zval[self._image_depth_null] = fill_value
5782
5783 return zval
5784
5785 @_deprecate_positional_args(allowed=['lines'])
5786 def add_lines( # noqa: PLR0917
5787 self,
5788 lines: NumpyArray[float],
5789 color: ColorLike = 'w',
5790 width: float = 5,
5791 label: str | None = None,
5792 name: str | None = None,
5793 connected: bool = False, # noqa: FBT001, FBT002
5794 ) -> Actor:
5795 """Add lines to the plotting object.
5796
5797 Parameters
5798 ----------
5799 lines : np.ndarray
5800 Points representing line segments. For example, two line
5801 segments would be represented as ``np.array([[0, 1, 0],
5802 [1, 0, 0], [1, 1, 0], [2, 0, 0]])``.
5803
5804 color : ColorLike, default: 'w'
5805 Either a string, rgb list, or hex color string. For example:
5806
5807 * ``color='white'``
5808 * ``color='w'``
5809 * ``color=[1.0, 1.0, 1.0]``
5810 * ``color='#FFFFFF'``
5811
5812 width : float, default: 5
5813 Thickness of lines.
5814
5815 label : str, default: None
5816 String label to use when adding a legend to the scene with
5817 :func:`pyvista.Plotter.add_legend`.
5818
5819 name : str, default: None
5820 The name for the added actor so that it can be easily updated.
5821 If an actor of this name already exists in the rendering window, it
5822 will be replaced by the new actor.
5823
5824 connected : bool, default: False
5825 Treat ``lines`` as points representing a series of *connected* lines.
5826 For example, two connected line segments would be represented as
5827 ``np.array([[0, 0, 0], [1, 0, 0], [1, 1, 0]])``. If ``False``, an *even*
5828 number of points must be passed to ``lines``, and the lines need not be
5829 connected.
5830
5831
5832 Returns
5833 -------
5834 pyvista.Actor
5835 Lines actor.
5836
5837 Examples
5838 --------
5839 Plot two lines.
5840
5841 >>> import numpy as np
5842 >>> import pyvista as pv
5843 >>> pl = pv.Plotter()
5844 >>> points = np.array([[0, 1, 0], [1, 0, 0], [1, 1, 0], [2, 0, 0]])
5845 >>> actor = pl.add_lines(points, color='purple', width=3)
5846 >>> pl.camera_position = 'xy'
5847 >>> pl.show()
5848
5849 Adding lines with ``connected=True`` will add a series of connected
5850 line segments.
5851
5852 >>> pl = pv.Plotter()
5853 >>> points = np.array([[0, 1, 0], [1, 0, 0], [1, 1, 0], [2, 0, 0]])
5854 >>> actor = pl.add_lines(points, color='purple', width=3, connected=True)
5855 >>> pl.camera_position = 'xy'
5856 >>> pl.show()
5857
5858 """
5859 if not isinstance(lines, np.ndarray):
5860 msg = 'Input should be an array of point segments' # type: ignore[unreachable]
5861 raise TypeError(msg)
5862
5863 lines_polydata: pv.PolyData = (
5864 pv.lines_from_points(lines) if connected else pv.line_segments_from_points(lines)
5865 )
5866
5867 actor = Actor(mapper=DataSetMapper(lines_polydata))
5868 actor.prop.line_width = width
5869 actor.prop.show_edges = True
5870 actor.prop.edge_color = color
5871 actor.prop.color = color
5872 actor.prop.lighting = False
5873
5874 # legend label
5875 if label:
5876 if not isinstance(label, str):
5877 msg = 'Label must be a string' # type: ignore[unreachable]
5878 raise TypeError(msg)
5879 addr = actor.GetAddressAsString('')
5880 self.renderer._labels[addr] = (lines_polydata, label, Color(color))
5881
5882 # Add to renderer
5883 self.add_actor(actor, reset_camera=False, name=name, pickable=False) # type: ignore[arg-type]
5884 return actor
5885
5886 @wraps(ScalarBars.remove_scalar_bar)
5887 def remove_scalar_bar(self, *args, **kwargs) -> None: # numpydoc ignore=PR01,RT01
5888 """Remove the active scalar bar."""
5889 self.scalar_bars.remove_scalar_bar(*args, **kwargs)
5890
5891 @_deprecate_positional_args(allowed=['points', 'labels'])
5892 def add_point_labels( # noqa: PLR0917
5893 self,
5894 points: MatrixLike[float] | VectorLike[float] | DataSet | _vtk.vtkAlgorithm,
5895 labels: Sequence[str | int] | str,
5896 italic: bool = False, # noqa: FBT001, FBT002
5897 bold: bool = True, # noqa: FBT001, FBT002
5898 font_size: int | None = None,
5899 text_color: ColorLike | None = None,
5900 font_family: FontFamilyOptions | None = None,
5901 font_file: str | None = None,
5902 shadow: bool = False, # noqa: FBT001, FBT002
5903 show_points: bool = True, # noqa: FBT001, FBT002
5904 point_color: ColorLike | None = None,
5905 point_size: float | None = None,
5906 name: str | None = None,
5907 shape_color: ColorLike = 'grey',
5908 shape: Literal['rect', 'rounded_rect'] | None = 'rounded_rect',
5909 fill_shape: bool = True, # noqa: FBT001, FBT002
5910 margin: int = 3,
5911 shape_opacity: float = 1.0,
5912 pickable: bool = False, # noqa: FBT001, FBT002
5913 render_points_as_spheres: bool = False, # noqa: FBT001, FBT002
5914 tolerance: float = 0.001,
5915 reset_camera: bool | None = None, # noqa: FBT001
5916 always_visible: bool = False, # noqa: FBT001, FBT002
5917 render: bool = True, # noqa: FBT001, FBT002
5918 justification_horizontal: HorizontalOptions | None = None,
5919 justification_vertical: VerticalOptions | None = None,
5920 background_color: ColorLike | None = None,
5921 background_opacity: float | None = None,
5922 ) -> _vtk.vtkActor2D:
5923 """Create a point actor with one label from list labels assigned to each point.
5924
5925 Parameters
5926 ----------
5927 points : sequence | DataSet | :vtk:`vtkAlgorithm`
5928 An ``n x 3`` sequence points or :class:`pyvista.DataSet` with
5929 points or mesh-producing algorithm.
5930
5931 labels : list | str
5932 List of labels. Must be the same length as points. If a
5933 string name is given with a :class:`pyvista.DataSet` input for
5934 points, then these are fetched.
5935
5936 italic : bool, default: False
5937 Italicises title and bar labels.
5938
5939 bold : bool, default: True
5940 Bolds title and bar labels.
5941
5942 font_size : float, optional
5943 Sets the size of the title font.
5944
5945 text_color : ColorLike, optional
5946 Color of text. Either a string, RGB sequence, or hex color string.
5947
5948 * ``text_color='white'``
5949 * ``text_color='w'``
5950 * ``text_color=[1.0, 1.0, 1.0]``
5951 * ``text_color='#FFFFFF'``
5952
5953 font_family : str, optional
5954 Font family. Must be either ``'courier'``, ``'times'``,
5955 or ``'arial``. This is ignored if the `font_file` is set.
5956
5957 font_file : str, default: None
5958 The absolute file path to a local file containing a freetype
5959 readable font.
5960
5961 shadow : bool, default: False
5962 Adds a black shadow to the text.
5963
5964 show_points : bool, default: True
5965 Controls if points are visible.
5966
5967 point_color : ColorLike, optional
5968 Either a string, rgb list, or hex color string. One of
5969 the following.
5970
5971 * ``point_color='white'``
5972 * ``point_color='w'``
5973 * ``point_color=[1.0, 1.0, 1.0]``
5974 * ``point_color='#FFFFFF'``
5975
5976 point_size : float, optional
5977 Size of points if visible.
5978
5979 name : str, optional
5980 The name for the added actor so that it can be easily
5981 updated. If an actor of this name already exists in the
5982 rendering window, it will be replaced by the new actor.
5983
5984 shape_color : ColorLike, default: "grey"
5985 Color of shape (if visible). Either a string, rgb
5986 sequence, or hex color string.
5987
5988 shape : str, default: "rounded_rect"
5989 The string name of the shape to use. Options are ``'rect'`` or
5990 ``'rounded_rect'``. If you want no shape, pass ``None``.
5991
5992 fill_shape : bool, default: True
5993 Fill the shape with the ``shape_color``. Outlines if ``False``.
5994
5995 margin : int, default: 3
5996 The size of the margin on the label background shape.
5997
5998 shape_opacity : float, default: 1.0
5999 The opacity of the shape in the range of ``[0, 1]``.
6000
6001 pickable : bool, default: False
6002 Set whether this actor is pickable.
6003
6004 render_points_as_spheres : bool, default: False
6005 Render points as spheres rather than dots.
6006
6007 tolerance : float, default: 0.001
6008 A tolerance to use to determine whether a point label is
6009 visible. A tolerance is usually required because the
6010 conversion from world space to display space during
6011 rendering introduces numerical round-off.
6012
6013 reset_camera : bool, optional
6014 Reset the camera after adding the points to the scene.
6015
6016 always_visible : bool, default: False
6017 Skip adding the visibility filter.
6018
6019 render : bool, default: True
6020 Force a render when ``True``.
6021
6022 justification_horizontal : str, optional
6023 Text's horizontal justification.
6024 Should be either "left", "center" or "right".
6025
6026 .. warning::
6027 If the justification is not default,
6028 the shape will be out of alignment with the label.
6029 If you use other than default,
6030 Please use the background color.
6031 See: https://github.com/pyvista/pyvista/pull/5407
6032
6033 justification_vertical : str, optional
6034 Text's vertical justification.
6035 Should be either "bottom", "center" or "top".
6036
6037 .. warning::
6038 If the justification is not default,
6039 the shape will be out of alignment with the label.
6040 If you use other than default,
6041 Please use the background color.
6042 See: https://github.com/pyvista/pyvista/pull/5407
6043
6044 background_color : Color, optional
6045 Background color of text's property.
6046
6047 background_opacity : float, optional
6048 Background opacity of text's property.
6049
6050 Returns
6051 -------
6052 :vtk:`vtkActor2D`
6053 VTK label actor. Can be used to change properties of the labels.
6054
6055 See Also
6056 --------
6057 :ref:`point_labels_example`
6058
6059 Examples
6060 --------
6061 >>> import numpy as np
6062 >>> import pyvista as pv
6063 >>> pl = pv.Plotter()
6064 >>> points = np.array([[0.0, 0.0, 0.0], [1.0, 1.0, 0.0], [2.0, 0.0, 0.0]])
6065 >>> labels = ['Point A', 'Point B', 'Point C']
6066 >>> actor = pl.add_point_labels(
6067 ... points,
6068 ... labels,
6069 ... italic=True,
6070 ... font_size=20,
6071 ... point_color='red',
6072 ... point_size=20,
6073 ... render_points_as_spheres=True,
6074 ... always_visible=True,
6075 ... shadow=True,
6076 ... )
6077 >>> pl.camera_position = 'xy'
6078 >>> pl.show()
6079
6080 """
6081 if font_family is None:
6082 font_family = self._theme.font.family # type: ignore[assignment]
6083 if font_size is None:
6084 font_size = self._theme.font.size
6085 point_color = Color(point_color, default_color=self._theme.color)
6086
6087 if isinstance(points, (list, tuple)):
6088 points = np.array(points)
6089
6090 if isinstance(points, np.ndarray):
6091 points = pv.PolyData(points) # Cast to poly data
6092 elif not is_pyvista_dataset(points) and not isinstance(points, _vtk.vtkAlgorithm):
6093 msg = f'Points type not usable: {type(points)}'
6094 raise TypeError(msg)
6095 points, algo = algorithm_to_mesh_handler(points)
6096 if algo is not None:
6097 # Extract points filter
6098 pc_algo = _vtk.vtkConvertToPointCloud()
6099 set_algorithm_input(pc_algo, algo)
6100 algo = pc_algo
6101
6102 if name is None:
6103 name = f'{type(points).__name__}({points.memory_address})'
6104
6105 hier = _vtk.vtkPointSetToLabelHierarchy()
6106 if not isinstance(labels, str):
6107 if algo is not None:
6108 msg = (
6109 'If using a vtkAlgorithm input, the labels must be a named array '
6110 'on the dataset.'
6111 )
6112 raise TypeError(msg)
6113 points = pv.PolyData(points.points)
6114 if len(points.points) != len(labels):
6115 msg = 'There must be one label for each point'
6116 raise ValueError(msg)
6117 vtklabels = _vtk.vtkStringArray()
6118 vtklabels.SetName('labels')
6119 for item in labels:
6120 vtklabels.InsertNextValue(str(item))
6121 points.GetPointData().AddArray(vtklabels)
6122 hier.SetLabelArrayName('labels')
6123 else:
6124 # Make sure PointData
6125 if labels not in points.point_data:
6126 msg = f'Array {labels!r} not found in point data.'
6127 raise ValueError(msg)
6128 hier.SetLabelArrayName(labels)
6129
6130 if always_visible:
6131 set_algorithm_input(hier, algo or points)
6132 else:
6133 # Only show visible points
6134 vis_points = _vtk.vtkSelectVisiblePoints()
6135 set_algorithm_input(vis_points, algo or points)
6136 vis_points.SetRenderer(self.renderer)
6137 vis_points.SetTolerance(tolerance)
6138
6139 hier.SetInputConnection(vis_points.GetOutputPort())
6140
6141 # create label mapper
6142 label_mapper = _vtk.vtkLabelPlacementMapper()
6143 label_mapper.SetInputConnection(hier.GetOutputPort())
6144 if not isinstance(shape, str):
6145 label_mapper.SetShapeToNone()
6146 elif shape.lower() in 'rect':
6147 label_mapper.SetShapeToRect()
6148 elif shape.lower() in 'rounded_rect':
6149 label_mapper.SetShapeToRoundedRect()
6150 else:
6151 msg = f'Shape ({shape}) not understood'
6152 raise ValueError(msg)
6153 if fill_shape:
6154 label_mapper.SetStyleToFilled()
6155 else:
6156 label_mapper.SetStyleToOutline()
6157 label_mapper.SetBackgroundColor(Color(shape_color).float_rgb)
6158 label_mapper.SetBackgroundOpacity(shape_opacity)
6159 label_mapper.SetMargin(margin)
6160
6161 text_property = pv.TextProperty(
6162 italic=italic,
6163 bold=bold,
6164 font_size=font_size,
6165 font_family=font_family,
6166 font_file=font_file,
6167 color=text_color,
6168 shadow=shadow,
6169 justification_horizontal=justification_horizontal,
6170 justification_vertical=justification_vertical,
6171 background_color=background_color,
6172 background_opacity=background_opacity,
6173 )
6174 hier.SetTextProperty(text_property)
6175
6176 # Explicitly set render=False to avoid unnecessary renders
6177 self.remove_actor(f'{name}-points', reset_camera=False, render=False) # type: ignore[arg-type]
6178 self.remove_actor(f'{name}-labels', reset_camera=False, render=False) # type: ignore[arg-type]
6179
6180 # add points
6181 if show_points:
6182 # Explicitly set render=False to defer rendering to the final add_actor call
6183 self.add_mesh(
6184 algo or points,
6185 color=point_color,
6186 point_size=point_size,
6187 name=f'{name}-points',
6188 pickable=pickable,
6189 render_points_as_spheres=render_points_as_spheres,
6190 reset_camera=reset_camera,
6191 render=False,
6192 )
6193
6194 label_actor = _vtk.vtkActor2D()
6195 label_actor.SetMapper(label_mapper)
6196 self.add_actor(
6197 label_actor, # type: ignore[arg-type]
6198 reset_camera=False,
6199 name=f'{name}-labels',
6200 pickable=False,
6201 render=render,
6202 )
6203 return label_actor
6204
6205 @_deprecate_positional_args(allowed=['points', 'labels'])
6206 def add_point_scalar_labels( # noqa: PLR0917
6207 self,
6208 points: MatrixLike[float] | VectorLike[float] | DataSet,
6209 labels: list[str | int] | str,
6210 fmt: str | None = None,
6211 preamble: str = '',
6212 **kwargs,
6213 ) -> _vtk.vtkActor2D:
6214 """Label the points from a dataset with the values of their scalars.
6215
6216 Wrapper for :func:`pyvista.Plotter.add_point_labels`.
6217
6218 Parameters
6219 ----------
6220 points : sequence[float] | np.ndarray | DataSet
6221 An ``n x 3`` numpy.ndarray or pyvista dataset with points.
6222
6223 labels : list | str
6224 List of scalars of labels. Must be the same length as points. If a
6225 string name is given with a :class:`pyvista.DataSet` input for
6226 points, then these are fetched.
6227
6228 fmt : str, optional
6229 String formatter used to format numerical data.
6230
6231 preamble : str, default: ""
6232 Text before the start of each label.
6233
6234 **kwargs : dict, optional
6235 Keyword arguments passed to
6236 :func:`pyvista.Plotter.add_point_labels`.
6237
6238 Returns
6239 -------
6240 :vtk:`vtkActor2D`
6241 VTK label actor. Can be used to change properties of the labels.
6242
6243 """
6244 if not is_pyvista_dataset(points):
6245 points, _ = _coerce_pointslike_arg(points, copy=False)
6246 if not isinstance(labels, (str, list)):
6247 msg = 'labels must be a string name of the scalars array to use or list of scalars' # type: ignore[unreachable]
6248 raise TypeError(msg)
6249 if fmt is None:
6250 fmt = self._theme.font.fmt
6251 if fmt is None:
6252 fmt = '%.6e' if pv.vtk_version_info < (9, 6, 0) else '{:.6e}' # type: ignore[unreachable]
6253 if isinstance(points, np.ndarray):
6254 scalars = labels
6255 elif is_pyvista_dataset(points):
6256 scalars = points.point_data[labels] # type: ignore[assignment, index]
6257 phrase = f'{preamble} {fmt}'
6258
6259 if pv.vtk_version_info < (9, 6, 0): # pragma: no branch
6260 labels = [phrase % val for val in scalars]
6261 else:
6262 labels = [phrase.format(val) for val in scalars]
6263 return self.add_point_labels(points, labels, **kwargs)
6264
6265 def add_points(
6266 self,
6267 points: MatrixLike[float] | VectorLike[float] | DataSet,
6268 style: Literal['points', 'points_gaussian'] = 'points',
6269 **kwargs,
6270 ) -> Actor:
6271 """Add points to a mesh.
6272
6273 Parameters
6274 ----------
6275 points : numpy.ndarray or pyvista.DataSet
6276 Array of points or the points from a pyvista object.
6277
6278 style : str, default: 'points'
6279 Visualization style of the mesh. One of the following:
6280 ``style='points'``, ``style='points_gaussian'``.
6281 ``'points_gaussian'`` can be controlled with the ``emissive`` and
6282 ``render_points_as_spheres`` options.
6283
6284 **kwargs : dict, optional
6285 See :func:`pyvista.Plotter.add_mesh` for optional
6286 keyword arguments.
6287
6288 See Also
6289 --------
6290 :ref:`points_gaussian_scale_example`
6291
6292 Returns
6293 -------
6294 pyvista.Actor
6295 Actor of the mesh.
6296
6297 Examples
6298 --------
6299 Add a numpy array of points to a mesh.
6300
6301 >>> import numpy as np
6302 >>> import pyvista as pv
6303 >>> rng = np.random.default_rng(seed=0)
6304 >>> points = rng.random((10, 3))
6305 >>> pl = pv.Plotter()
6306 >>> actor = pl.add_points(
6307 ... points, render_points_as_spheres=True, point_size=100.0
6308 ... )
6309 >>> pl.show()
6310
6311 Plot using the ``'points_gaussian'`` style
6312
6313 >>> points = rng.random((10, 3))
6314 >>> pl = pv.Plotter()
6315 >>> actor = pl.add_points(points, style='points_gaussian')
6316 >>> pl.show()
6317
6318 """
6319 if style not in ['points', 'points_gaussian']:
6320 msg = (
6321 f'Invalid style {style} for add_points. Should be either "points" or '
6322 '"points_gaussian".'
6323 )
6324 raise ValueError(msg)
6325 return self.add_mesh(points, style=style, **kwargs)
6326
6327 def add_arrows(
6328 self, cent: NumpyArray[float], direction: NumpyArray[float], mag: float = 1.0, **kwargs
6329 ) -> Actor:
6330 """Add arrows to the plotter.
6331
6332 Parameters
6333 ----------
6334 cent : np.ndarray
6335 Array of centers.
6336
6337 direction : np.ndarray
6338 Array of direction vectors.
6339
6340 mag : float, optional
6341 Amount to scale the direction vectors.
6342
6343 **kwargs : dict, optional
6344 See :func:`pyvista.Plotter.add_mesh` for optional
6345 keyword arguments.
6346
6347 Returns
6348 -------
6349 pyvista.Actor
6350 Actor of the arrows.
6351
6352 Examples
6353 --------
6354 Plot a random field of vectors and save a screenshot of it.
6355
6356 >>> import numpy as np
6357 >>> import pyvista as pv
6358 >>> rng = np.random.default_rng(seed=0)
6359 >>> cent = rng.random((10, 3))
6360 >>> direction = rng.random((10, 3))
6361 >>> pl = pv.Plotter()
6362 >>> _ = pl.add_arrows(cent, direction, mag=2)
6363 >>> pl.show()
6364
6365 """
6366 if cent.shape != direction.shape: # pragma: no cover
6367 msg = 'center and direction arrays must have the same shape'
6368 raise ValueError(msg)
6369
6370 direction = direction.copy()
6371 if cent.ndim != 2:
6372 cent = cent.reshape((-1, 3))
6373
6374 if direction.ndim != 2:
6375 direction = direction.reshape((-1, 3))
6376
6377 if mag != 1:
6378 direction = direction * mag
6379
6380 pdata = pv.vector_poly_data(cent, direction)
6381 # Create arrow object
6382 arrow = _vtk.vtkArrowSource()
6383 arrow.Update()
6384 glyph3D = _vtk.vtkGlyph3D()
6385 glyph3D.SetSourceData(arrow.GetOutput())
6386 glyph3D.SetInputData(pdata)
6387 glyph3D.SetVectorModeToUseVector()
6388 glyph3D.Update()
6389
6390 arrows = wrap(glyph3D.GetOutput())
6391 return self.add_mesh(arrows, **kwargs)
6392
6393 @staticmethod
6394 def _save_image(
6395 image: pv.pyvista_ndarray,
6396 filename: str | Path | io.BytesIO | bool | None, # noqa: FBT001
6397 return_img: bool, # noqa: FBT001
6398 ) -> pv.pyvista_ndarray | None:
6399 """Save to file and/or return a NumPy image array.
6400
6401 This is an internal helper.
6402
6403 """
6404 if not image.size:
6405 msg = 'Empty image. Have you run plot() first?'
6406 raise ValueError(msg)
6407 # write screenshot to file if requested
6408 if isinstance(filename, (str, Path, io.BytesIO)):
6409 from PIL import Image # noqa: PLC0415
6410
6411 if isinstance(filename, (str, Path)):
6412 filename = Path(filename)
6413 if isinstance(pv.FIGURE_PATH, str) and not filename.is_absolute():
6414 filename = Path(pv.FIGURE_PATH) / filename
6415 if not filename.suffix:
6416 filename = filename.with_suffix('.png')
6417 elif filename.suffix not in SUPPORTED_FORMATS:
6418 msg = (
6419 f'Unsupported extension {filename.suffix}\n'
6420 f'Must be one of the following: {SUPPORTED_FORMATS}'
6421 )
6422 raise ValueError(msg)
6423 filename = filename.expanduser().resolve()
6424 Image.fromarray(image).save(filename)
6425 else:
6426 Image.fromarray(image).save(filename, format='PNG')
6427 # return image array if requested
6428 return image if return_img else None
6429
6430 @_deprecate_positional_args(allowed=['filename'])
6431 def save_graphic( # noqa: PLR0917
6432 self,
6433 filename: str | Path,
6434 title: str = 'PyVista Export',
6435 raster: bool = True, # noqa: FBT001, FBT002
6436 painter: bool = True, # noqa: FBT001, FBT002
6437 ) -> None:
6438 """Save a screenshot of the rendering window as a graphic file.
6439
6440 This can be helpful for publication documents.
6441
6442 The supported formats are:
6443
6444 * ``'.svg'``
6445 * ``'.eps'``
6446 * ``'.ps'``
6447 * ``'.pdf'``
6448 * ``'.tex'``
6449
6450 Parameters
6451 ----------
6452 filename : str | Path
6453 Path to save the graphic file to.
6454
6455 title : str, default: "PyVista Export"
6456 Title to use within the file properties.
6457
6458 raster : bool, default: True
6459 Attempt to write 3D properties as a raster image.
6460
6461 painter : bool, default: True
6462 Configure the exporter to expect a painter-ordered 2D
6463 rendering, that is, a rendering at a fixed depth where
6464 primitives are drawn from the bottom up.
6465
6466 Examples
6467 --------
6468 >>> import pyvista as pv
6469 >>> from pyvista import examples
6470 >>> pl = pv.Plotter()
6471 >>> _ = pl.add_mesh(examples.load_airplane(), smooth_shading=True)
6472 >>> _ = pl.add_background_image(examples.mapfile)
6473 >>> pl.save_graphic('img.svg') # doctest:+SKIP
6474
6475 """
6476 if self.render_window is None:
6477 msg = 'This plotter is closed and unable to save a screenshot.'
6478 raise AttributeError(msg)
6479 if self._first_time:
6480 self._on_first_render_request()
6481 self.render()
6482 filepath = Path(filename)
6483 if isinstance(pv.FIGURE_PATH, str) and not filepath.is_absolute(): # pragma: no cover
6484 filepath = Path(pv.FIGURE_PATH) / filepath
6485 filepath = filepath.expanduser().resolve()
6486 extension = pv.core.utilities.fileio.get_ext(filepath)
6487
6488 writer = _vtk.vtkGL2PSExporter()
6489 modes = {
6490 '.svg': writer.SetFileFormatToSVG,
6491 '.eps': writer.SetFileFormatToEPS,
6492 '.ps': writer.SetFileFormatToPS,
6493 '.pdf': writer.SetFileFormatToPDF,
6494 '.tex': writer.SetFileFormatToTeX,
6495 }
6496 if extension not in modes:
6497 msg = (
6498 f'Extension ({extension}) is an invalid choice.\n\n'
6499 f'Valid options include: {", ".join(modes.keys())}'
6500 )
6501 raise ValueError(msg)
6502 writer.CompressOff()
6503 writer.SetFilePrefix(filepath.with_suffix('')) # type: ignore[arg-type]
6504 writer.SetRenderWindow(self.render_window)
6505 modes[extension]()
6506 writer.SetTitle(title)
6507 writer.SetWrite3DPropsAsRasterImage(raster)
6508 if painter:
6509 writer.UsePainterSettings()
6510 writer.Update()
6511
6512 @_deprecate_positional_args(allowed=['filename'])
6513 def screenshot( # noqa: PLR0917
6514 self,
6515 filename: str | Path | io.BytesIO | bool | None = None, # noqa: FBT001
6516 transparent_background: bool | None = None, # noqa: FBT001
6517 return_img: bool = True, # noqa: FBT001, FBT002
6518 window_size: Sequence[int] | None = None,
6519 scale: int | None = None,
6520 ) -> pv.pyvista_ndarray | None:
6521 """Take screenshot at current camera position.
6522
6523 Parameters
6524 ----------
6525 filename : str | Path | io.BytesIO, optional
6526 Location to write image to. If ``None``, no image is written.
6527
6528 transparent_background : bool, optional
6529 Whether to make the background transparent. The default is
6530 looked up on the plotter's theme.
6531
6532 return_img : bool, default: True
6533 If ``True``, a :class:`numpy.ndarray` of the image will be
6534 returned.
6535
6536 window_size : sequence[int], optional
6537 Set the plotter's size to this ``(width, height)`` before
6538 taking the screenshot.
6539
6540 scale : int, optional
6541 Set the factor to scale the window size to make a higher
6542 resolution image. If ``None`` this will use the ``image_scale``
6543 property on this plotter which defaults to one.
6544
6545 Returns
6546 -------
6547 pyvista.pyvista_ndarray
6548 Array containing pixel RGB and alpha. Sized:
6549
6550 * [Window height x Window width x 3] if
6551 ``transparent_background`` is set to ``False``.
6552 * [Window height x Window width x 4] if
6553 ``transparent_background`` is set to ``True``.
6554
6555 See Also
6556 --------
6557 :ref:`screenshot_example`
6558
6559 Examples
6560 --------
6561 >>> import pyvista as pv
6562 >>> sphere = pv.Sphere()
6563 >>> pl = pv.Plotter(off_screen=True)
6564 >>> actor = pl.add_mesh(sphere)
6565 >>> pl.screenshot('screenshot.png') # doctest:+SKIP
6566
6567 """
6568 with self.window_size_context(window_size):
6569 # configure image filter
6570 if transparent_background is None:
6571 transparent_background = self._theme.transparent_background
6572 self.image_transparent_background = transparent_background
6573
6574 # This if statement allows you to save screenshots of closed plotters
6575 # This is needed for the sphinx-gallery to work
6576 if self.render_window is None:
6577 # If plotter has been closed...
6578 # check if last_image exists
6579 if self.last_image is not None:
6580 # Save last image
6581 if scale is not None:
6582 warn_external(
6583 'This plotter is closed and cannot be scaled. '
6584 'Using the last saved image. '
6585 'Try using the `image_scale` property directly.',
6586 )
6587 return self._save_image(self.last_image, filename, return_img)
6588 # Plotter hasn't been rendered or was improperly closed
6589 msg = 'This plotter is closed and unable to save a screenshot.'
6590 raise RuntimeError(msg)
6591
6592 if self._first_time and (
6593 hasattr(self, 'off_screen') and not self.off_screen
6594 ): # 'off_screen' attribute is specific to Plotter objects.
6595 msg = 'Nothing to screenshot - call .show first or use the off_screen argument'
6596 raise RuntimeError(msg)
6597
6598 # if off screen, show has not been called and we must render
6599 # before extracting an image
6600 if self._first_time:
6601 self._on_first_render_request()
6602 self.render()
6603
6604 with self.image_scale_context(scale):
6605 self._make_render_window_current()
6606 return self._save_image(self.image, filename, return_img)
6607
6608 def _repr_png_(self) -> bytes | None:
6609 """Return the last cached screenshot as PNG bytes for IPython display hooks.
6610
6611 Enables the plotter to render as a static image in IDE plot panes and
6612 rich notebook frontends (Positron, VS Code Jupyter, JupyterLab). Uses
6613 :attr:`last_image`, which is populated by :meth:`show` or
6614 :meth:`screenshot`. Returns ``None`` when no screenshot has been
6615 captured yet; this method never triggers a render, so IDE variable
6616 inspectors can probe a plotter without side effects.
6617
6618 Returns
6619 -------
6620 bytes or None
6621 PNG-encoded image of the most recent screenshot, or ``None`` if
6622 the plotter has not been rendered.
6623
6624 """
6625 import PIL.Image # noqa: PLC0415
6626
6627 if self.last_image is None:
6628 return None
6629 buf = io.BytesIO()
6630 PIL.Image.fromarray(self.last_image).save(buf, format='PNG')
6631 return buf.getvalue()
6632
6633 @wraps(Renderers.set_background)
6634 def set_background(self, *args, **kwargs) -> None: # numpydoc ignore=PR01,RT01
6635 """Wrap ``Renderers.set_background``."""
6636 self.renderers.set_background(*args, **kwargs)
6637
6638 @wraps(Renderers.set_color_cycler)
6639 def set_color_cycler(self, *args, **kwargs) -> None: # numpydoc ignore=PR01,RT01
6640 """Wrap ``Renderers.set_color_cycler``."""
6641 self.renderers.set_color_cycler(*args, **kwargs)
6642
6643 @_deprecate_positional_args
6644 def generate_orbital_path( # noqa: PLR0917
6645 self,
6646 factor: float = 3.0,
6647 n_points: int = 20,
6648 viewup: Sequence[float] | None = None,
6649 shift: float = 0.0,
6650 ) -> pv.PolyData:
6651 """Generate an orbital path around the data scene.
6652
6653 Parameters
6654 ----------
6655 factor : float, default: 3.0
6656 A scaling factor when building the orbital extent.
6657
6658 n_points : int, default: 20
6659 Number of points on the orbital path.
6660
6661 viewup : sequence[float], optional
6662 The normal to the orbital plane.
6663
6664 shift : float, default: 0.0
6665 Shift the plane up/down from the center of the scene by
6666 this amount.
6667
6668 Returns
6669 -------
6670 pyvista.PolyData
6671 PolyData containing the orbital path.
6672
6673 Examples
6674 --------
6675 Generate an orbital path around a sphere.
6676
6677 >>> import pyvista as pv
6678 >>> pl = pv.Plotter()
6679 >>> _ = pl.add_mesh(pv.Sphere())
6680 >>> viewup = [0, 0, 1]
6681 >>> orbit = pl.generate_orbital_path(
6682 ... factor=2.0, n_points=50, shift=0.0, viewup=viewup
6683 ... )
6684
6685 See :ref:`orbit_example` for a full example using this method.
6686
6687 """
6688 if viewup is None:
6689 viewup = self._theme.camera.viewup
6690 center = np.array(self.center)
6691 bnds = self.bounds
6692 radius = (bnds.x_max - bnds.x_min) * factor
6693 y = (bnds.y_max - bnds.y_min) * factor
6694 radius = max(y, radius)
6695 center += np.array(viewup) * shift
6696 return pv.Polygon(center=center, radius=radius, normal=viewup, n_sides=n_points)
6697
6698 def fly_to(self, point: Sequence[float]) -> None:
6699 """Move the current camera's focal point to a position point.
6700
6701 The movement is animated over the number of frames specified in
6702 NumberOfFlyFrames. The LOD desired frame rate is used.
6703
6704 Parameters
6705 ----------
6706 point : sequence[float]
6707 Point to fly to in the form of ``(x, y, z)``.
6708
6709 """
6710 self._get_iren_not_none().fly_to(self.renderer, point)
6711
6712 @_deprecate_positional_args(allowed=['path'])
6713 def orbit_on_path( # noqa: PLR0917
6714 self,
6715 path: pv.PolyData | None = None,
6716 focus: Sequence[float] | None = None,
6717 step: float = 0.5,
6718 viewup: Sequence[float] | None = None,
6719 write_frames: bool = False, # noqa: FBT001, FBT002
6720 threaded: bool = False, # noqa: FBT001, FBT002
6721 progress_bar: bool = False, # noqa: FBT001, FBT002
6722 ) -> None:
6723 """Orbit on the given path focusing on the focus point.
6724
6725 Parameters
6726 ----------
6727 path : pyvista.PolyData
6728 Path of orbital points. The order in the points is the order of
6729 travel.
6730
6731 focus : sequence[float], optional
6732 The point of focus the camera. For example ``(0.0, 0.0, 0.0)``.
6733
6734 step : float, default: 0.5
6735 The timestep between flying to each camera position. Ignored when
6736 ``plotter.off_screen = True``.
6737
6738 viewup : sequence[float], optional
6739 The normal to the orbital plane.
6740
6741 write_frames : bool, default: False
6742 Assume a file is open and write a frame on each camera
6743 view during the orbit.
6744
6745 threaded : bool, default: False
6746 Run this as a background thread. Generally used within a
6747 GUI (i.e. PyQt).
6748
6749 progress_bar : bool, default: False
6750 Show the progress bar when proceeding through the path.
6751 This can be helpful to show progress when generating
6752 movies with ``off_screen=True``.
6753
6754 Examples
6755 --------
6756 Plot an orbit around the earth. Save the gif as a temporary file.
6757
6758 >>> from pathlib import Path
6759 >>> from tempfile import mkdtemp
6760 >>> import pyvista as pv
6761 >>> from pyvista import examples
6762 >>> mesh = examples.load_globe()
6763 >>> texture = examples.load_globe_texture()
6764 >>> filename = Path(mkdtemp()) / 'orbit.gif'
6765 >>> pl = pv.Plotter(window_size=[300, 300])
6766 >>> _ = pl.add_mesh(mesh, texture=texture, smooth_shading=True)
6767 >>> pl.open_gif(filename)
6768 >>> viewup = [0, 0, 1]
6769 >>> orbit = pl.generate_orbital_path(
6770 ... factor=2.0, n_points=24, shift=0.0, viewup=viewup
6771 ... )
6772 >>> pl.orbit_on_path(orbit, write_frames=True, viewup=viewup, step=0.02)
6773
6774 See :ref:`orbit_example` for a full example using this method.
6775
6776 """
6777 if focus is None:
6778 focus = self.center
6779 if viewup is None:
6780 viewup = self._theme.camera.viewup
6781 if path is None:
6782 path = self.generate_orbital_path(viewup=viewup)
6783 if not is_pyvista_dataset(path):
6784 path = pv.PolyData(path) # type: ignore[unreachable]
6785 points = path.points
6786
6787 # Make sure the whole scene is visible
6788 self.camera.thickness = path.length
6789
6790 if progress_bar:
6791 try:
6792 from tqdm import tqdm # noqa: PLC0415
6793 except ImportError: # pragma: no cover
6794 msg = 'Please install `tqdm` to use ``progress_bar=True``'
6795 raise ImportError(msg)
6796
6797 def orbit() -> None:
6798 """Define the internal thread for running the orbit."""
6799 points_seq = tqdm(points) if progress_bar else points
6800
6801 for point in points_seq:
6802 tstart = time.time() # include the render time in the step time
6803 self.set_position(point, render=False)
6804 self.set_focus(focus, render=False) # type: ignore[arg-type]
6805 self.set_viewup(viewup, render=False) # type: ignore[arg-type]
6806 self.renderer.ResetCameraClippingRange()
6807 if write_frames:
6808 self.write_frame()
6809 else:
6810 self.render()
6811 sleep_time = step - (time.time() - tstart)
6812 if sleep_time > 0 and (
6813 hasattr(self, 'off_screen') and not self.off_screen
6814 ): # 'off_screen' attribute is specific to Plotter objects.
6815 time.sleep(sleep_time)
6816 if write_frames:
6817 self._get_mwriter_not_none().close()
6818
6819 if threaded:
6820 thread = Thread(target=orbit)
6821 thread.start()
6822 else:
6823 orbit()
6824
6825 def export_obj(self, filename: str | Path) -> None:
6826 """Export scene to OBJ format.
6827
6828 Parameters
6829 ----------
6830 filename : str | Path
6831 Filename to export the scene to. Must end in ``'.obj'``.
6832
6833 Examples
6834 --------
6835 Export the scene to "scene.obj"
6836
6837 >>> import pyvista as pv
6838 >>> pl = pv.Plotter()
6839 >>> _ = pl.add_mesh(pv.Sphere())
6840 >>> pl.export_obj('scene.obj') # doctest:+SKIP
6841
6842 """
6843 if self.render_window is None:
6844 msg = 'This plotter must still have a render window open.'
6845 raise RuntimeError(msg)
6846 if (
6847 isinstance(pv.FIGURE_PATH, str) and not Path(filename).is_absolute()
6848 ): # pragma: no cover
6849 filename = Path(pv.FIGURE_PATH) / filename
6850 else:
6851 filename = Path(filename).expanduser().resolve()
6852
6853 if filename.suffix != '.obj':
6854 msg = '`filename` must end with ".obj"'
6855 raise ValueError(msg)
6856
6857 exporter = _vtk.vtkOBJExporter()
6858 # remove the extension as VTK always adds it in
6859 exporter.SetFilePrefix(filename.with_suffix('')) # type: ignore[arg-type]
6860 exporter.SetRenderWindow(self.render_window)
6861 exporter.Write()
6862
6863 @property
6864 def _datasets(self) -> list[pv.DataSet]:
6865 """Return a list of all datasets associated with this plotter."""
6866 datasets = []
6867 for renderer in self.renderers:
6868 for actor in renderer.actors.values():
6869 mapper = actor.GetMapper()
6870
6871 # ignore any mappers whose inputs are not datasets
6872 if _mapper_has_data_set_input(mapper):
6873 if isinstance(mapper, _BaseMapper) and mapper.dataset is not None:
6874 datasets.append(mapper.dataset)
6875 else:
6876 datasets.append(wrap(_mapper_get_data_set_input(mapper)))
6877
6878 return datasets
6879
6880 def __del__(self) -> None:
6881 """Delete the plotter."""
6882 # We have to check here if the plotter was only partially initialized
6883 if self._initialized and not self._closed:
6884 self.close()
6885 self.deep_clean()
6886 if self._initialized:
6887 del self.renderers
6888
6889 @_deprecate_positional_args(allowed=['image_path'])
6890 def add_background_image( # noqa: PLR0917
6891 self,
6892 image_path: str | Path,
6893 scale: float = 1.0,
6894 auto_resize: bool = True, # noqa: FBT001, FBT002
6895 as_global: bool = True, # noqa: FBT001, FBT002
6896 ) -> None:
6897 """Add a background image to a plot.
6898
6899 Parameters
6900 ----------
6901 image_path : str
6902 Path to an image file.
6903
6904 scale : float, default: 1.0
6905 Scale the image larger or smaller relative to the size of
6906 the window. For example, a scale size of 2 will make the
6907 largest dimension of the image twice as large as the
6908 largest dimension of the render window.
6909
6910 auto_resize : bool, default: True
6911 Resize the background when the render window changes size.
6912
6913 as_global : bool, default: True
6914 When multiple render windows are present, setting
6915 ``as_global=False`` will cause the background to only
6916 appear in one window.
6917
6918 Examples
6919 --------
6920 >>> import pyvista as pv
6921 >>> from pyvista import examples
6922 >>> pl = pv.Plotter()
6923 >>> actor = pl.add_mesh(pv.Sphere())
6924 >>> pl.add_background_image(examples.mapfile)
6925 >>> pl.show()
6926
6927 """
6928 if self.renderers.has_active_background_renderer:
6929 msg = (
6930 'A background image already exists. '
6931 'Remove it with ``remove_background_image`` '
6932 'before adding one'
6933 )
6934 raise RuntimeError(msg)
6935
6936 # Need to change the number of layers to support an additional
6937 # background layer
6938 if not self._has_background_layer:
6939 self.render_window.SetNumberOfLayers(3) # type: ignore[union-attr]
6940 renderer = self.renderers.add_background_renderer(image_path, scale, as_global)
6941 self.render_window.AddRenderer(renderer) # type: ignore[union-attr]
6942
6943 # set up autoscaling of the image
6944 if auto_resize: # pragma: no cover
6945 self._get_iren_not_none().add_observer('ModifiedEvent', renderer.resize)
6946
6947 @wraps(Renderers.remove_background_image)
6948 def remove_background_image(self) -> None: # numpydoc ignore=PR01,RT01
6949 """Wrap ``Renderers.remove_background_image``."""
6950 self.renderers.remove_background_image()
6951
6952 # return the active renderer to the top, otherwise flat background
6953 # will not be rendered
6954 self.renderer.layer = 0
6955
6956 def _on_first_render_request(self) -> None:
6957 """Once an image or render is officially requested, run this routine.
6958
6959 For example on the show call or any screenshot producing code.
6960 """
6961 # reset unless camera for the first render unless camera is set
6962 if self._first_time:
6963 for renderer in self.renderers:
6964 if not renderer.camera.is_set:
6965 renderer.camera_position = renderer.get_default_cam_pos()
6966 renderer.ResetCamera()
6967 self._first_time = False
6968
6969 def reset_camera_clipping_range(self) -> None:
6970 """Reset camera clipping planes."""
6971 self.renderer.ResetCameraClippingRange()
6972
6973 @_deprecate_positional_args(allowed=['light'])
6974 def add_light(self, light: _vtk.vtkLight, only_active: bool = False) -> None: # noqa: FBT001, FBT002
6975 """Add a Light to the scene.
6976
6977 Parameters
6978 ----------
6979 light : Light | :vtk:`vtkLight`
6980 The light to be added.
6981
6982 only_active : bool, default: False
6983 If ``True``, only add the light to the active
6984 renderer. The default is that every renderer adds the
6985 light. To add the light to an arbitrary renderer, see
6986 :func:`pyvista.Renderer.add_light`.
6987
6988 Examples
6989 --------
6990 Create a plotter that we initialize with no lights, and add a
6991 cube and a single headlight to it.
6992
6993 >>> import pyvista as pv
6994 >>> pl = pv.Plotter(lighting='none')
6995 >>> _ = pl.add_mesh(pv.Cube())
6996 >>> light = pv.Light(color='cyan', light_type='headlight')
6997 >>> pl.add_light(light)
6998 >>> pl.show()
6999
7000 """
7001 renderers = [self.renderer] if only_active else self.renderers
7002 for renderer in renderers:
7003 renderer.add_light(light)
7004
7005 @_deprecate_positional_args
7006 def remove_all_lights(self, only_active: bool = False) -> None: # noqa: FBT001, FBT002
7007 """Remove all lights from the scene.
7008
7009 Parameters
7010 ----------
7011 only_active : bool, default: False
7012 If ``True``, only remove lights from the active
7013 renderer. The default is that lights are stripped from
7014 every renderer.
7015
7016 Examples
7017 --------
7018 Create a plotter and remove all lights after initialization.
7019 Note how the mesh rendered is completely flat
7020
7021 >>> import pyvista as pv
7022 >>> pl = pv.Plotter()
7023 >>> pl.remove_all_lights()
7024 >>> pl.renderer.lights
7025 []
7026 >>> _ = pl.add_mesh(pv.Sphere(), show_edges=True)
7027 >>> pl.show()
7028
7029 Note how this differs from a plot with default lighting
7030
7031 >>> pv.Sphere().plot(show_edges=True, lighting=True)
7032
7033 """
7034 renderers = [self.renderer] if only_active else self.renderers
7035 for renderer in renderers:
7036 renderer.remove_all_lights()
7037
7038 def where_is(self, name: str) -> list[tuple[int, int]]:
7039 """Return the subplot coordinates of a given actor.
7040
7041 Parameters
7042 ----------
7043 name : str
7044 Actor's name.
7045
7046 Returns
7047 -------
7048 list[tuple[int, int]]
7049 A list with the subplot coordinates of the actor.
7050
7051 Examples
7052 --------
7053 >>> import pyvista as pv
7054 >>> pl = pv.Plotter(shape=(2, 2))
7055 >>> pl.subplot(0, 0)
7056 >>> _ = pl.add_mesh(pv.Box(), name='box')
7057 >>> pl.subplot(0, 1)
7058 >>> _ = pl.add_mesh(pv.Sphere(), name='sphere')
7059 >>> pl.subplot(1, 0)
7060 >>> _ = pl.add_mesh(pv.Box(), name='box')
7061 >>> pl.subplot(1, 1)
7062 >>> _ = pl.add_mesh(pv.Cone(), name='cone')
7063 >>> pl.where_is('box')
7064 [(0, 0), (1, 0)]
7065
7066 >>> pl.show()
7067
7068 """
7069 return [
7070 tuple(self.renderers.index_to_loc(index).tolist())
7071 for index in range(len(self.renderers))
7072 if name in self.renderers[index]._actors.keys()
7073 ]
7074
7075 # =======================================================================
7076 # Picking — forwarding shims for plotter.picking component.
7077 # =======================================================================
7078
7079 @wraps(PickingComponent.disable_picking)
7080 def disable_picking(self, *args, **kwargs) -> Any: # numpydoc ignore=PR01,RT01
7081 """Forward to :meth:`~pyvista.plotting.picking.PickingComponent.disable_picking`."""
7082 return self.picking.disable_picking(*args, **kwargs)
7083
7084 @wraps(PickingComponent.get_pick_position)
7085 def get_pick_position(self, *args, **kwargs) -> Any: # numpydoc ignore=PR01,RT01
7086 """Forward to :meth:`~pyvista.plotting.picking.PickingComponent.get_pick_position`."""
7087 return self.picking.get_pick_position(*args, **kwargs)
7088
7089 @wraps(PickingComponent.pick_click_position)
7090 def pick_click_position(self, *args, **kwargs) -> Any: # numpydoc ignore=PR01,RT01
7091 """Forward to :meth:`~pyvista.plotting.picking.PickingComponent.pick_click_position`."""
7092 return self.picking.pick_click_position(*args, **kwargs)
7093
7094 @wraps(PickingComponent.pick_mouse_position)
7095 def pick_mouse_position(self, *args, **kwargs) -> Any: # numpydoc ignore=PR01,RT01
7096 """Forward to :meth:`~pyvista.plotting.picking.PickingComponent.pick_mouse_position`."""
7097 return self.picking.pick_mouse_position(*args, **kwargs)
7098
7099 @wraps(PickingComponent.enable_point_picking)
7100 def enable_point_picking(self, *args, **kwargs) -> Any: # numpydoc ignore=PR01,RT01
7101 """Forward to :meth:`~pyvista.plotting.picking.PickingComponent.enable_point_picking`."""
7102 return self.picking.enable_point_picking(*args, **kwargs)
7103
7104 @wraps(PickingComponent.enable_rectangle_picking)
7105 def enable_rectangle_picking(self, *args, **kwargs) -> Any: # numpydoc ignore=PR01,RT01
7106 """Forward to :meth:`~pyvista.plotting.picking.PickingComponent.enable_rectangle_picking`.
7107
7108 See the component method for full documentation.
7109
7110 """
7111 return self.picking.enable_rectangle_picking(*args, **kwargs)
7112
7113 @wraps(PickingComponent.enable_surface_point_picking)
7114 def enable_surface_point_picking(self, *args, **kwargs) -> Any: # numpydoc ignore=PR01,RT01
7115 """Forward to ``PickingComponent.enable_surface_point_picking``.
7116
7117 See :meth:`~pyvista.plotting.picking.PickingComponent.enable_surface_point_picking`.
7118
7119 """
7120 return self.picking.enable_surface_point_picking(*args, **kwargs)
7121
7122 @wraps(PickingComponent.enable_mesh_picking)
7123 def enable_mesh_picking(self, *args, **kwargs) -> Any: # numpydoc ignore=PR01,RT01
7124 """Forward to :meth:`~pyvista.plotting.picking.PickingComponent.enable_mesh_picking`."""
7125 return self.picking.enable_mesh_picking(*args, **kwargs)
7126
7127 @wraps(PickingComponent.enable_rectangle_through_picking)
7128 def enable_rectangle_through_picking(
7129 self, *args, **kwargs
7130 ) -> Any: # numpydoc ignore=PR01,RT01
7131 """Forward to ``PickingComponent.enable_rectangle_through_picking``.
7132
7133 See :meth:`~pyvista.plotting.picking.PickingComponent.enable_rectangle_through_picking`.
7134
7135 """
7136 return self.picking.enable_rectangle_through_picking(*args, **kwargs)
7137
7138 @wraps(PickingComponent.enable_rectangle_visible_picking)
7139 def enable_rectangle_visible_picking(
7140 self, *args, **kwargs
7141 ) -> Any: # numpydoc ignore=PR01,RT01
7142 """Forward to ``PickingComponent.enable_rectangle_visible_picking``.
7143
7144 See :meth:`~pyvista.plotting.picking.PickingComponent.enable_rectangle_visible_picking`.
7145
7146 """
7147 return self.picking.enable_rectangle_visible_picking(*args, **kwargs)
7148
7149 @wraps(PickingComponent.enable_cell_picking)
7150 def enable_cell_picking(self, *args, **kwargs) -> Any: # numpydoc ignore=PR01,RT01
7151 """Forward to :meth:`~pyvista.plotting.picking.PickingComponent.enable_cell_picking`."""
7152 return self.picking.enable_cell_picking(*args, **kwargs)
7153
7154 @wraps(PickingComponent.enable_element_picking)
7155 def enable_element_picking(self, *args, **kwargs) -> Any: # numpydoc ignore=PR01,RT01
7156 """Forward to :meth:`~pyvista.plotting.picking.PickingComponent.enable_element_picking`."""
7157 return self.picking.enable_element_picking(*args, **kwargs)
7158
7159 @wraps(PickingComponent.enable_block_picking)
7160 def enable_block_picking(self, *args, **kwargs) -> Any: # numpydoc ignore=PR01,RT01
7161 """Forward to :meth:`~pyvista.plotting.picking.PickingComponent.enable_block_picking`."""
7162 return self.picking.enable_block_picking(*args, **kwargs)
7163
7164 @wraps(PickingComponent.enable_fly_to_right_click)
7165 def enable_fly_to_right_click(self, *args, **kwargs) -> Any: # numpydoc ignore=PR01,RT01
7166 """Forward to :meth:`~pyvista.plotting.picking.PickingComponent.enable_fly_to_right_click`.
7167
7168 See the component method for full documentation.
7169
7170 """
7171 return self.picking.enable_fly_to_right_click(*args, **kwargs)
7172
7173 @wraps(PickingComponent.fly_to_mouse_position)
7174 def fly_to_mouse_position(self, *args, **kwargs) -> Any: # numpydoc ignore=PR01,RT01
7175 """Forward to :meth:`~pyvista.plotting.picking.PickingComponent.fly_to_mouse_position`."""
7176 return self.picking.fly_to_mouse_position(*args, **kwargs)
7177
7178 @wraps(PickingComponent.enable_path_picking)
7179 def enable_path_picking(self, *args, **kwargs) -> Any: # numpydoc ignore=PR01,RT01
7180 """Forward to :meth:`~pyvista.plotting.picking.PickingComponent.enable_path_picking`."""
7181 return self.picking.enable_path_picking(*args, **kwargs)
7182
7183 @wraps(PickingComponent.enable_geodesic_picking)
7184 def enable_geodesic_picking(self, *args, **kwargs) -> Any: # numpydoc ignore=PR01,RT01
7185 """Forward to :meth:`~pyvista.plotting.picking.PickingComponent.enable_geodesic_picking`.
7186
7187 See the component method for full documentation.
7188
7189 """
7190 return self.picking.enable_geodesic_picking(*args, **kwargs)
7191
7192 @wraps(PickingComponent.enable_horizon_picking)
7193 def enable_horizon_picking(self, *args, **kwargs) -> Any: # numpydoc ignore=PR01,RT01
7194 """Forward to :meth:`~pyvista.plotting.picking.PickingComponent.enable_horizon_picking`."""
7195 return self.picking.enable_horizon_picking(*args, **kwargs)
7196
7197 @property
7198 def picked_point(self) -> Any: # numpydoc ignore=RT01
7199 """Picked point.
7200
7201 Forwarded from :attr:`~pyvista.plotting.picking.PickingComponent.picked_point`.
7202
7203 """
7204 return self.picking.picked_point
7205
7206 @property
7207 def picked_actor(self) -> Any: # numpydoc ignore=RT01
7208 """Picked actor.
7209
7210 Forwarded from :attr:`~pyvista.plotting.picking.PickingComponent.picked_actor`.
7211
7212 """
7213 return self.picking.picked_actor
7214
7215 @property
7216 def picked_mesh(self) -> Any: # numpydoc ignore=RT01
7217 """Picked mesh.
7218
7219 Forwarded from :attr:`~pyvista.plotting.picking.PickingComponent.picked_mesh`.
7220
7221 """
7222 return self.picking.picked_mesh
7223
7224 @property
7225 def picked_cells(self) -> Any: # numpydoc ignore=RT01
7226 """Picked cells.
7227
7228 Forwarded from :attr:`~pyvista.plotting.picking.PickingComponent.picked_cells`.
7229
7230 """
7231 return self.picking.picked_cells
7232
7233 @property
7234 def picked_block_index(self) -> Any: # numpydoc ignore=RT01
7235 """Picked block index.
7236
7237 Forwarded from :attr:`~pyvista.plotting.picking.PickingComponent.picked_block_index`.
7238
7239 """
7240 return self.picking.picked_block_index
7241
7242 @property
7243 def picked_path(self) -> Any: # numpydoc ignore=RT01
7244 """Picked path polyline.
7245
7246 Forwarded from ``PickingComponent.picked_path``.
7247
7248 """
7249 return self.picking.picked_path
7250
7251 @property
7252 def picked_geodesic(self) -> Any: # numpydoc ignore=RT01
7253 """Picked geodesic polyline.
7254
7255 Forwarded from ``PickingComponent.picked_geodesic``.
7256
7257 """
7258 return self.picking.picked_geodesic
7259
7260 @property
7261 def picked_horizon(self) -> Any: # numpydoc ignore=RT01
7262 """Picked horizon ribbon surface.
7263
7264 Forwarded from ``PickingComponent.picked_horizon``.
7265
7266 """
7267 return self.picking.picked_horizon
7268
7269 # =======================================================================
7270 # Widgets — forwarding shims for plotter.widgets component.
7271 # =======================================================================
7272
7273 @wraps(WidgetComponent.add_box_widget)
7274 def add_box_widget(self, *args, **kwargs) -> Any: # numpydoc ignore=PR01,RT01
7275 """Forward to :meth:`~pyvista.plotting.widgets.WidgetComponent.add_box_widget`."""
7276 return self.widgets.add_box_widget(*args, **kwargs)
7277
7278 @wraps(WidgetComponent.clear_box_widgets)
7279 def clear_box_widgets(self, *args, **kwargs) -> Any: # numpydoc ignore=PR01,RT01
7280 """Forward to :meth:`~pyvista.plotting.widgets.WidgetComponent.clear_box_widgets`."""
7281 return self.widgets.clear_box_widgets(*args, **kwargs)
7282
7283 @wraps(WidgetComponent.add_mesh_clip_box)
7284 def add_mesh_clip_box(self, *args, **kwargs) -> Any: # numpydoc ignore=PR01,RT01
7285 """Forward to :meth:`~pyvista.plotting.widgets.WidgetComponent.add_mesh_clip_box`."""
7286 return self.widgets.add_mesh_clip_box(*args, **kwargs)
7287
7288 @wraps(WidgetComponent.add_plane_widget)
7289 def add_plane_widget(self, *args, **kwargs) -> Any: # numpydoc ignore=PR01,RT01
7290 """Forward to :meth:`~pyvista.plotting.widgets.WidgetComponent.add_plane_widget`."""
7291 return self.widgets.add_plane_widget(*args, **kwargs)
7292
7293 @wraps(WidgetComponent.clear_plane_widgets)
7294 def clear_plane_widgets(self, *args, **kwargs) -> Any: # numpydoc ignore=PR01,RT01
7295 """Forward to :meth:`~pyvista.plotting.widgets.WidgetComponent.clear_plane_widgets`."""
7296 return self.widgets.clear_plane_widgets(*args, **kwargs)
7297
7298 @wraps(WidgetComponent.add_mesh_clip_plane)
7299 def add_mesh_clip_plane(self, *args, **kwargs) -> Any: # numpydoc ignore=PR01,RT01
7300 """Forward to :meth:`~pyvista.plotting.widgets.WidgetComponent.add_mesh_clip_plane`."""
7301 return self.widgets.add_mesh_clip_plane(*args, **kwargs)
7302
7303 @wraps(WidgetComponent.add_volume_clip_plane)
7304 def add_volume_clip_plane(self, *args, **kwargs) -> Any: # numpydoc ignore=PR01,RT01
7305 """Forward to :meth:`~pyvista.plotting.widgets.WidgetComponent.add_volume_clip_plane`."""
7306 return self.widgets.add_volume_clip_plane(*args, **kwargs)
7307
7308 @wraps(WidgetComponent.add_mesh_slice)
7309 def add_mesh_slice(self, *args, **kwargs) -> Any: # numpydoc ignore=PR01,RT01
7310 """Forward to :meth:`~pyvista.plotting.widgets.WidgetComponent.add_mesh_slice`."""
7311 return self.widgets.add_mesh_slice(*args, **kwargs)
7312
7313 @wraps(WidgetComponent.add_mesh_slice_orthogonal)
7314 def add_mesh_slice_orthogonal(self, *args, **kwargs) -> Any: # numpydoc ignore=PR01,RT01
7315 """Forward to :meth:`~pyvista.plotting.widgets.WidgetComponent.add_mesh_slice_orthogonal`.
7316
7317 See the component method for full documentation.
7318
7319 """
7320 return self.widgets.add_mesh_slice_orthogonal(*args, **kwargs)
7321
7322 @wraps(WidgetComponent.add_line_widget)
7323 def add_line_widget(self, *args, **kwargs) -> Any: # numpydoc ignore=PR01,RT01
7324 """Forward to :meth:`~pyvista.plotting.widgets.WidgetComponent.add_line_widget`."""
7325 return self.widgets.add_line_widget(*args, **kwargs)
7326
7327 @wraps(WidgetComponent.clear_line_widgets)
7328 def clear_line_widgets(self, *args, **kwargs) -> Any: # numpydoc ignore=PR01,RT01
7329 """Forward to :meth:`~pyvista.plotting.widgets.WidgetComponent.clear_line_widgets`."""
7330 return self.widgets.clear_line_widgets(*args, **kwargs)
7331
7332 @wraps(WidgetComponent.add_text_slider_widget)
7333 def add_text_slider_widget(self, *args, **kwargs) -> Any: # numpydoc ignore=PR01,RT01
7334 """Forward to :meth:`~pyvista.plotting.widgets.WidgetComponent.add_text_slider_widget`."""
7335 return self.widgets.add_text_slider_widget(*args, **kwargs)
7336
7337 @wraps(WidgetComponent.add_slider_widget)
7338 def add_slider_widget(self, *args, **kwargs) -> Any: # numpydoc ignore=PR01,RT01
7339 """Forward to :meth:`~pyvista.plotting.widgets.WidgetComponent.add_slider_widget`."""
7340 return self.widgets.add_slider_widget(*args, **kwargs)
7341
7342 @wraps(WidgetComponent.clear_slider_widgets)
7343 def clear_slider_widgets(self, *args, **kwargs) -> Any: # numpydoc ignore=PR01,RT01
7344 """Forward to :meth:`~pyvista.plotting.widgets.WidgetComponent.clear_slider_widgets`."""
7345 return self.widgets.clear_slider_widgets(*args, **kwargs)
7346
7347 @wraps(WidgetComponent.add_mesh_threshold)
7348 def add_mesh_threshold(self, *args, **kwargs) -> Any: # numpydoc ignore=PR01,RT01
7349 """Forward to :meth:`~pyvista.plotting.widgets.WidgetComponent.add_mesh_threshold`."""
7350 return self.widgets.add_mesh_threshold(*args, **kwargs)
7351
7352 @wraps(WidgetComponent.add_mesh_isovalue)
7353 def add_mesh_isovalue(self, *args, **kwargs) -> Any: # numpydoc ignore=PR01,RT01
7354 """Forward to :meth:`~pyvista.plotting.widgets.WidgetComponent.add_mesh_isovalue`."""
7355 return self.widgets.add_mesh_isovalue(*args, **kwargs)
7356
7357 @wraps(WidgetComponent.add_spline_widget)
7358 def add_spline_widget(self, *args, **kwargs) -> Any: # numpydoc ignore=PR01,RT01
7359 """Forward to :meth:`~pyvista.plotting.widgets.WidgetComponent.add_spline_widget`."""
7360 return self.widgets.add_spline_widget(*args, **kwargs)
7361
7362 @wraps(WidgetComponent.clear_spline_widgets)
7363 def clear_spline_widgets(self, *args, **kwargs) -> Any: # numpydoc ignore=PR01,RT01
7364 """Forward to :meth:`~pyvista.plotting.widgets.WidgetComponent.clear_spline_widgets`."""
7365 return self.widgets.clear_spline_widgets(*args, **kwargs)
7366
7367 @wraps(WidgetComponent.add_mesh_slice_spline)
7368 def add_mesh_slice_spline(self, *args, **kwargs) -> Any: # numpydoc ignore=PR01,RT01
7369 """Forward to :meth:`~pyvista.plotting.widgets.WidgetComponent.add_mesh_slice_spline`."""
7370 return self.widgets.add_mesh_slice_spline(*args, **kwargs)
7371
7372 @wraps(WidgetComponent.add_measurement_widget)
7373 def add_measurement_widget(self, *args, **kwargs) -> Any: # numpydoc ignore=PR01,RT01
7374 """Forward to :meth:`~pyvista.plotting.widgets.WidgetComponent.add_measurement_widget`."""
7375 return self.widgets.add_measurement_widget(*args, **kwargs)
7376
7377 @wraps(WidgetComponent.clear_measure_widgets)
7378 def clear_measure_widgets(self, *args, **kwargs) -> Any: # numpydoc ignore=PR01,RT01
7379 """Forward to :meth:`~pyvista.plotting.widgets.WidgetComponent.clear_measure_widgets`."""
7380 return self.widgets.clear_measure_widgets(*args, **kwargs)
7381
7382 @wraps(WidgetComponent.add_sphere_widget)
7383 def add_sphere_widget(self, *args, **kwargs) -> Any: # numpydoc ignore=PR01,RT01
7384 """Forward to :meth:`~pyvista.plotting.widgets.WidgetComponent.add_sphere_widget`."""
7385 return self.widgets.add_sphere_widget(*args, **kwargs)
7386
7387 @wraps(WidgetComponent.clear_sphere_widgets)
7388 def clear_sphere_widgets(self, *args, **kwargs) -> Any: # numpydoc ignore=PR01,RT01
7389 """Forward to :meth:`~pyvista.plotting.widgets.WidgetComponent.clear_sphere_widgets`."""
7390 return self.widgets.clear_sphere_widgets(*args, **kwargs)
7391
7392 @wraps(WidgetComponent.add_affine_transform_widget)
7393 def add_affine_transform_widget(self, *args, **kwargs) -> Any: # numpydoc ignore=PR01,RT01
7394 """Forward to ``WidgetComponent.add_affine_transform_widget``.
7395
7396 See :meth:`~pyvista.plotting.widgets.WidgetComponent.add_affine_transform_widget`.
7397
7398 """
7399 return self.widgets.add_affine_transform_widget(*args, **kwargs)
7400
7401 @wraps(WidgetComponent.add_checkbox_button_widget)
7402 def add_checkbox_button_widget(self, *args, **kwargs) -> Any: # numpydoc ignore=PR01,RT01
7403 """Forward to :meth:`~pyvista.plotting.widgets.WidgetComponent.add_checkbox_button_widget`.
7404
7405 See the component method for full documentation.
7406
7407 """
7408 return self.widgets.add_checkbox_button_widget(*args, **kwargs)
7409
7410 @wraps(WidgetComponent.add_radio_button_widget)
7411 def add_radio_button_widget(self, *args, **kwargs) -> Any: # numpydoc ignore=PR01,RT01
7412 """Forward to :meth:`~pyvista.plotting.widgets.WidgetComponent.add_radio_button_widget`."""
7413 return self.widgets.add_radio_button_widget(*args, **kwargs)
7414
7415 @wraps(WidgetComponent.clear_radio_button_widgets)
7416 def clear_radio_button_widgets(self, *args, **kwargs) -> Any: # numpydoc ignore=PR01,RT01
7417 """Forward to :meth:`~pyvista.plotting.widgets.WidgetComponent.clear_radio_button_widgets`.
7418
7419 See the component method for full documentation.
7420
7421 """
7422 return self.widgets.clear_radio_button_widgets(*args, **kwargs)
7423
7424 @wraps(WidgetComponent.add_camera_orientation_widget)
7425 def add_camera_orientation_widget(self, *args, **kwargs) -> Any: # numpydoc ignore=PR01,RT01
7426 """Forward to ``WidgetComponent.add_camera_orientation_widget``.
7427
7428 See :meth:`~pyvista.plotting.widgets.WidgetComponent.add_camera_orientation_widget`.
7429
7430 """
7431 return self.widgets.add_camera_orientation_widget(*args, **kwargs)
7432
7433 @wraps(WidgetComponent.clear_camera_widgets)
7434 def clear_camera_widgets(self, *args, **kwargs) -> Any: # numpydoc ignore=PR01,RT01
7435 """Forward to :meth:`~pyvista.plotting.widgets.WidgetComponent.clear_camera_widgets`."""
7436 return self.widgets.clear_camera_widgets(*args, **kwargs)
7437
7438 @wraps(WidgetComponent.clear_button_widgets)
7439 def clear_button_widgets(self, *args, **kwargs) -> Any: # numpydoc ignore=PR01,RT01
7440 """Forward to :meth:`~pyvista.plotting.widgets.WidgetComponent.clear_button_widgets`."""
7441 return self.widgets.clear_button_widgets(*args, **kwargs)
7442
7443 @wraps(WidgetComponent.add_logo_widget)
7444 def add_logo_widget(self, *args, **kwargs) -> Any: # numpydoc ignore=PR01,RT01
7445 """Forward to :meth:`~pyvista.plotting.widgets.WidgetComponent.add_logo_widget`."""
7446 return self.widgets.add_logo_widget(*args, **kwargs)
7447
7448 @wraps(WidgetComponent.clear_logo_widgets)
7449 def clear_logo_widgets(self, *args, **kwargs) -> Any: # numpydoc ignore=PR01,RT01
7450 """Forward to :meth:`~pyvista.plotting.widgets.WidgetComponent.clear_logo_widgets`."""
7451 return self.widgets.clear_logo_widgets(*args, **kwargs)
7452
7453 @wraps(WidgetComponent.add_camera3d_widget)
7454 def add_camera3d_widget(self, *args, **kwargs) -> Any: # numpydoc ignore=PR01,RT01
7455 """Forward to :meth:`~pyvista.plotting.widgets.WidgetComponent.add_camera3d_widget`."""
7456 return self.widgets.add_camera3d_widget(*args, **kwargs)
7457
7458 @wraps(WidgetComponent.clear_camera3d_widgets)
7459 def clear_camera3d_widgets(self, *args, **kwargs) -> Any: # numpydoc ignore=PR01,RT01
7460 """Forward to :meth:`~pyvista.plotting.widgets.WidgetComponent.clear_camera3d_widgets`."""
7461 return self.widgets.clear_camera3d_widgets(*args, **kwargs)
7462
7463 # =======================================================================
7464 # Widgets — deprecated forwarding properties for state collections.
7465 # =======================================================================
7466
7467 @property
7468 def camera_widgets(self) -> list[Any]: # numpydoc ignore=RT01
7469 """Forward to ``WidgetComponent.camera_widgets``.
7470
7471 .. deprecated:: 0.48
7472 Use ``Plotter.widgets.camera_widgets`` instead.
7473
7474 """
7475 warn_external(
7476 '``Plotter.camera_widgets`` is deprecated; '
7477 'use ``Plotter.widgets.camera_widgets`` instead.',
7478 PyVistaDeprecationWarning,
7479 )
7480 return self.widgets.camera_widgets
7481
7482 @property
7483 def box_widgets(self) -> list[Any]: # numpydoc ignore=RT01
7484 """Forward to ``WidgetComponent.box_widgets``.
7485
7486 .. deprecated:: 0.48
7487 Use ``Plotter.widgets.box_widgets`` instead.
7488
7489 """
7490 warn_external(
7491 '``Plotter.box_widgets`` is deprecated; use ``Plotter.widgets.box_widgets`` instead.',
7492 PyVistaDeprecationWarning,
7493 )
7494 return self.widgets.box_widgets
7495
7496 @property
7497 def box_clipped_meshes(self) -> list[Any]: # numpydoc ignore=RT01
7498 """Forward to ``WidgetComponent.box_clipped_meshes``.
7499
7500 .. deprecated:: 0.48
7501 Use ``Plotter.widgets.box_clipped_meshes`` instead.
7502
7503 """
7504 warn_external(
7505 '``Plotter.box_clipped_meshes`` is deprecated; '
7506 'use ``Plotter.widgets.box_clipped_meshes`` instead.',
7507 PyVistaDeprecationWarning,
7508 )
7509 return self.widgets.box_clipped_meshes
7510
7511 @property
7512 def plane_widgets(self) -> list[Any]: # numpydoc ignore=RT01
7513 """Forward to ``WidgetComponent.plane_widgets``.
7514
7515 .. deprecated:: 0.48
7516 Use ``Plotter.widgets.plane_widgets`` instead.
7517
7518 """
7519 warn_external(
7520 '``Plotter.plane_widgets`` is deprecated; '
7521 'use ``Plotter.widgets.plane_widgets`` instead.',
7522 PyVistaDeprecationWarning,
7523 )
7524 return self.widgets.plane_widgets
7525
7526 @property
7527 def plane_clipped_meshes(self) -> list[Any]: # numpydoc ignore=RT01
7528 """Forward to ``WidgetComponent.plane_clipped_meshes``.
7529
7530 .. deprecated:: 0.48
7531 Use ``Plotter.widgets.plane_clipped_meshes`` instead.
7532
7533 """
7534 warn_external(
7535 '``Plotter.plane_clipped_meshes`` is deprecated; '
7536 'use ``Plotter.widgets.plane_clipped_meshes`` instead.',
7537 PyVistaDeprecationWarning,
7538 )
7539 return self.widgets.plane_clipped_meshes
7540
7541 @property
7542 def plane_sliced_meshes(self) -> list[Any]: # numpydoc ignore=RT01
7543 """Forward to ``WidgetComponent.plane_sliced_meshes``.
7544
7545 .. deprecated:: 0.48
7546 Use ``Plotter.widgets.plane_sliced_meshes`` instead.
7547
7548 """
7549 warn_external(
7550 '``Plotter.plane_sliced_meshes`` is deprecated; '
7551 'use ``Plotter.widgets.plane_sliced_meshes`` instead.',
7552 PyVistaDeprecationWarning,
7553 )
7554 return self.widgets.plane_sliced_meshes
7555
7556 @property
7557 def line_widgets(self) -> list[Any]: # numpydoc ignore=RT01
7558 """Forward to ``WidgetComponent.line_widgets``.
7559
7560 .. deprecated:: 0.48
7561 Use ``Plotter.widgets.line_widgets`` instead.
7562
7563 """
7564 warn_external(
7565 '``Plotter.line_widgets`` is deprecated; '
7566 'use ``Plotter.widgets.line_widgets`` instead.',
7567 PyVistaDeprecationWarning,
7568 )
7569 return self.widgets.line_widgets
7570
7571 @property
7572 def slider_widgets(self) -> list[Any]: # numpydoc ignore=RT01
7573 """Forward to ``WidgetComponent.slider_widgets``.
7574
7575 .. deprecated:: 0.48
7576 Use ``Plotter.widgets.slider_widgets`` instead.
7577
7578 """
7579 warn_external(
7580 '``Plotter.slider_widgets`` is deprecated; '
7581 'use ``Plotter.widgets.slider_widgets`` instead.',
7582 PyVistaDeprecationWarning,
7583 )
7584 return self.widgets.slider_widgets
7585
7586 @property
7587 def threshold_meshes(self) -> list[Any]: # numpydoc ignore=RT01
7588 """Forward to ``WidgetComponent.threshold_meshes``.
7589
7590 .. deprecated:: 0.48
7591 Use ``Plotter.widgets.threshold_meshes`` instead.
7592
7593 """
7594 warn_external(
7595 '``Plotter.threshold_meshes`` is deprecated; '
7596 'use ``Plotter.widgets.threshold_meshes`` instead.',
7597 PyVistaDeprecationWarning,
7598 )
7599 return self.widgets.threshold_meshes
7600
7601 @property
7602 def isovalue_meshes(self) -> list[Any]: # numpydoc ignore=RT01
7603 """Forward to ``WidgetComponent.isovalue_meshes``.
7604
7605 .. deprecated:: 0.48
7606 Use ``Plotter.widgets.isovalue_meshes`` instead.
7607
7608 """
7609 warn_external(
7610 '``Plotter.isovalue_meshes`` is deprecated; '
7611 'use ``Plotter.widgets.isovalue_meshes`` instead.',
7612 PyVistaDeprecationWarning,
7613 )
7614 return self.widgets.isovalue_meshes
7615
7616 @property
7617 def spline_widgets(self) -> list[Any]: # numpydoc ignore=RT01
7618 """Forward to ``WidgetComponent.spline_widgets``.
7619
7620 .. deprecated:: 0.48
7621 Use ``Plotter.widgets.spline_widgets`` instead.
7622
7623 """
7624 warn_external(
7625 '``Plotter.spline_widgets`` is deprecated; '
7626 'use ``Plotter.widgets.spline_widgets`` instead.',
7627 PyVistaDeprecationWarning,
7628 )
7629 return self.widgets.spline_widgets
7630
7631 @property
7632 def spline_sliced_meshes(self) -> list[Any]: # numpydoc ignore=RT01
7633 """Forward to ``WidgetComponent.spline_sliced_meshes``.
7634
7635 .. deprecated:: 0.48
7636 Use ``Plotter.widgets.spline_sliced_meshes`` instead.
7637
7638 """
7639 warn_external(
7640 '``Plotter.spline_sliced_meshes`` is deprecated; '
7641 'use ``Plotter.widgets.spline_sliced_meshes`` instead.',
7642 PyVistaDeprecationWarning,
7643 )
7644 return self.widgets.spline_sliced_meshes
7645
7646 @property
7647 def sphere_widgets(self) -> list[Any]: # numpydoc ignore=RT01
7648 """Forward to ``WidgetComponent.sphere_widgets``.
7649
7650 .. deprecated:: 0.48
7651 Use ``Plotter.widgets.sphere_widgets`` instead.
7652
7653 """
7654 warn_external(
7655 '``Plotter.sphere_widgets`` is deprecated; '
7656 'use ``Plotter.widgets.sphere_widgets`` instead.',
7657 PyVistaDeprecationWarning,
7658 )
7659 return self.widgets.sphere_widgets
7660
7661 @property
7662 def button_widgets(self) -> list[Any]: # numpydoc ignore=RT01
7663 """Forward to ``WidgetComponent.button_widgets``.
7664
7665 .. deprecated:: 0.48
7666 Use ``Plotter.widgets.button_widgets`` instead.
7667
7668 """
7669 warn_external(
7670 '``Plotter.button_widgets`` is deprecated; '
7671 'use ``Plotter.widgets.button_widgets`` instead.',
7672 PyVistaDeprecationWarning,
7673 )
7674 return self.widgets.button_widgets
7675
7676 @property
7677 def radio_button_widget_dict(self) -> dict[str, Any]: # numpydoc ignore=RT01
7678 """Forward to ``WidgetComponent.radio_button_widget_dict``.
7679
7680 .. deprecated:: 0.48
7681 Use ``Plotter.widgets.radio_button_widget_dict`` instead.
7682
7683 """
7684 warn_external(
7685 '``Plotter.radio_button_widget_dict`` is deprecated; '
7686 'use ``Plotter.widgets.radio_button_widget_dict`` instead.',
7687 PyVistaDeprecationWarning,
7688 )
7689 return self.widgets.radio_button_widget_dict
7690
7691 @property
7692 def radio_button_title_dict(self) -> dict[str, Any]: # numpydoc ignore=RT01
7693 """Forward to ``WidgetComponent.radio_button_title_dict``.
7694
7695 .. deprecated:: 0.48
7696 Use ``Plotter.widgets.radio_button_title_dict`` instead.
7697
7698 """
7699 warn_external(
7700 '``Plotter.radio_button_title_dict`` is deprecated; '
7701 'use ``Plotter.widgets.radio_button_title_dict`` instead.',
7702 PyVistaDeprecationWarning,
7703 )
7704 return self.widgets.radio_button_title_dict
7705
7706 @property
7707 def distance_widgets(self) -> list[Any]: # numpydoc ignore=RT01
7708 """Forward to ``WidgetComponent.distance_widgets``.
7709
7710 .. deprecated:: 0.48
7711 Use ``Plotter.widgets.distance_widgets`` instead.
7712
7713 """
7714 warn_external(
7715 '``Plotter.distance_widgets`` is deprecated; '
7716 'use ``Plotter.widgets.distance_widgets`` instead.',
7717 PyVistaDeprecationWarning,
7718 )
7719 return self.widgets.distance_widgets
7720
7721 @property
7722 def logo_widgets(self) -> list[Any]: # numpydoc ignore=RT01
7723 """Forward to ``WidgetComponent.logo_widgets``.
7724
7725 .. deprecated:: 0.48
7726 Use ``Plotter.widgets.logo_widgets`` instead.
7727
7728 """
7729 warn_external(
7730 '``Plotter.logo_widgets`` is deprecated; '
7731 'use ``Plotter.widgets.logo_widgets`` instead.',
7732 PyVistaDeprecationWarning,
7733 )
7734 return self.widgets.logo_widgets
7735
7736 @property
7737 def camera3d_widgets(self) -> list[Any]: # numpydoc ignore=RT01
7738 """Forward to ``WidgetComponent.camera3d_widgets``.
7739
7740 .. deprecated:: 0.48
7741 Use ``Plotter.widgets.camera3d_widgets`` instead.
7742
7743 """
7744 warn_external(
7745 '``Plotter.camera3d_widgets`` is deprecated; '
7746 'use ``Plotter.widgets.camera3d_widgets`` instead.',
7747 PyVistaDeprecationWarning,
7748 )
7749 return self.widgets.camera3d_widgets
7750
7751
7752 # Register built-in plotter components. Imperative (not decorator on
7753 # ``ScalarBars``) to avoid circular imports between ``plotter.py`` and
7754 # the component modules it imports.
7755 _register_plotter_component('scalar_bars', target_cls=BasePlotter)(ScalarBars)
7756 _register_plotter_component('picking', target_cls=BasePlotter)(PickingComponent)
7757 _register_plotter_component('widgets', target_cls=BasePlotter)(WidgetComponent)
7758
7759
7760 class Plotter(_NoNewAttrMixin, BasePlotter):
7761 """Plotting object to display vtk meshes or numpy arrays.
7762
7763 Parameters
7764 ----------
7765 off_screen : bool, optional
7766 Renders off screen when ``True``. Useful for automated
7767 screenshots.
7768
7769 notebook : bool, optional
7770 When ``True``, the resulting plot is placed inline a jupyter
7771 notebook. Assumes a jupyter console is active. Automatically
7772 enables ``off_screen``.
7773
7774 shape : sequence[int], optional
7775 Number of sub-render windows inside of the main window.
7776 Specify two across with ``shape=(2, 1)`` and a two by two grid
7777 with ``shape=(2, 2)``. By default there is only one render
7778 window. Can also accept a string descriptor as shape. E.g.:
7779
7780 * ``shape="3|1"`` means 3 plots on the left and 1 on the right,
7781 * ``shape="4/2"`` means 4 plots on top and 2 at the bottom.
7782
7783 border : bool, optional
7784 Draw a border around each render window.
7785
7786 border_color : ColorLike, default: "k"
7787 Either a string, rgb list, or hex color string. For example:
7788
7789 * ``color='white'``
7790 * ``color='w'``
7791 * ``color=[1.0, 1.0, 1.0]``
7792 * ``color='#FFFFFF'``
7793
7794 window_size : sequence[int], optional
7795 Window size in pixels. Defaults to ``[1024, 768]``, unless
7796 set differently in the relevant theme's ``window_size``
7797 property.
7798
7799 line_smoothing : bool, default: False
7800 If ``True``, enable line smoothing.
7801
7802 polygon_smoothing : bool, default: False
7803 If ``True``, enable polygon smoothing.
7804
7805 lighting : str, default: 'light kit"
7806 Lighting to set up for the plotter. Accepted options:
7807
7808 * ``'light kit'``: a vtk Light Kit composed of 5 lights.
7809 * ``'three lights'``: illumination using 3 lights.
7810 * ``'none'``: no light sources at instantiation.
7811
7812 The default is a ``'light kit'`` (to be precise, 5 separate
7813 lights that act like a Light Kit).
7814
7815 theme : pyvista.plotting.themes.Theme, optional
7816 Plot-specific theme.
7817
7818 image_scale : int, optional
7819 Scale factor when saving screenshots. Image sizes will be
7820 the ``window_size`` multiplied by this scale factor.
7821
7822 stereo : StereoType | bool, optional
7823 Enable stereo rendering. If True, defaults to Anaglyph.
7824
7825 Examples
7826 --------
7827 >>> import pyvista as pv
7828 >>> mesh = pv.Cube()
7829 >>> another_mesh = pv.Sphere()
7830 >>> pl = pv.Plotter()
7831 >>> actor = pl.add_mesh(mesh, color='red', style='wireframe', line_width=4)
7832 >>> actor = pl.add_mesh(another_mesh, color='blue')
7833 >>> pl.show()
7834
7835 """
7836
7837 last_update_time = 0.0
7838
7839 @_deprecate_positional_args
7840 def __init__( # noqa: PLR0917
7841 self,
7842 off_screen: bool | None = None, # noqa: FBT001
7843 notebook: bool | None = None, # noqa: FBT001
7844 shape: Sequence[int] | str = (1, 1),
7845 groups: Sequence[int] | None = None,
7846 row_weights: Sequence[int] | None = None,
7847 col_weights: Sequence[int] | None = None,
7848 border: bool | None = None, # noqa: FBT001
7849 border_color: ColorLike = 'k',
7850 border_width: float = 2.0,
7851 window_size: list[int] | None = None,
7852 line_smoothing: bool = False, # noqa: FBT001, FBT002
7853 point_smoothing: bool = False, # noqa: FBT001, FBT002
7854 polygon_smoothing: bool = False, # noqa: FBT001, FBT002
7855 splitting_position: float | None = None,
7856 title: str | None = None,
7857 lighting: LightingOptions | None = 'light kit',
7858 theme: Theme | None = None,
7859 image_scale: int | None = None,
7860 stereo: StereoType | bool = False, # noqa: FBT001, FBT002
7861 ) -> None:
7862 """Initialize a vtk plotting object."""
7863 super().__init__(
7864 shape=shape,
7865 border=border,
7866 border_color=border_color,
7867 border_width=border_width,
7868 groups=groups,
7869 row_weights=row_weights,
7870 col_weights=col_weights,
7871 splitting_position=splitting_position,
7872 title=title,
7873 lighting=lighting,
7874 theme=theme,
7875 image_scale=image_scale,
7876 )
7877 # reset partial initialization flag
7878 self._initialized = False
7879
7880 log.debug('Plotter init start')
7881
7882 # check if a plotting backend is enabled
7883 _warn_xserver()
7884
7885 if off_screen is None:
7886 off_screen = pv.OFF_SCREEN
7887
7888 if notebook is None:
7889 if self._theme.notebook is not None:
7890 notebook = self._theme.notebook
7891 else:
7892 notebook = scooby.in_ipykernel()
7893
7894 self.notebook = notebook
7895 if self.notebook or pv.ON_SCREENSHOT:
7896 off_screen = True
7897 self.off_screen = off_screen
7898
7899 # initialize render window
7900 self.ren_win = _vtk.vtkRenderWindow()
7901 self.render_window.SetMultiSamples(0) # type: ignore[union-attr]
7902 self.render_window.SetBorders(True) # type: ignore[union-attr]
7903 if line_smoothing:
7904 self.render_window.LineSmoothingOn() # type: ignore[union-attr]
7905 if point_smoothing:
7906 self.render_window.PointSmoothingOn() # type: ignore[union-attr]
7907 if polygon_smoothing:
7908 self.render_window.PolygonSmoothingOn() # type: ignore[union-attr]
7909
7910 for renderer in self.renderers:
7911 self.render_window.AddRenderer(renderer) # type: ignore[union-attr]
7912
7913 # Add the shadow renderer to allow us to capture interactions within
7914 # a given viewport
7915 # https://vtk.org/pipermail/vtkusers/2018-June/102030.html
7916 number_or_layers = self.render_window.GetNumberOfLayers() # type: ignore[union-attr]
7917 current_layer = self.renderer.GetLayer()
7918 self.render_window.SetNumberOfLayers(number_or_layers + 1) # type: ignore[union-attr]
7919 self.render_window.AddRenderer(self.renderers.shadow_renderer) # type: ignore[union-attr]
7920 self.renderers.shadow_renderer.SetLayer(current_layer + 1)
7921 self.renderers.shadow_renderer.SetInteractive(False) # never needs to capture
7922
7923 if self.off_screen:
7924 self.render_window.SetOffScreenRendering(1) # type: ignore[union-attr]
7925 # On macOS, vtkCocoaRenderWindow creates an NSWindow even for
7926 # off-screen rendering, which shows a dock icon and requires
7927 # the main thread. Disconnecting from NSView creates a
7928 # standalone CGL context instead — no dock icon, no
7929 # main-thread requirement, and enables background-thread rendering.
7930 if hasattr(self.render_window, 'SetConnectContextToNSView'):
7931 self.render_window.SetConnectContextToNSView(False) # type: ignore[union-attr]
7932 # vtkGenericRenderWindowInteractor has no event loop and
7933 # allows the display client to close on Linux when
7934 # off_screen. We still want an interactor for off screen
7935 # plotting since there are some widgets (like the axes
7936 # widget) that need an interactor
7937 interactor = _vtk.vtkGenericRenderWindowInteractor()
7938 else:
7939 interactor = None
7940
7941 # Add ren win and interactor
7942 self.iren = RenderWindowInteractor(self, light_follow_camera=False, interactor=interactor)
7943 self.iren.set_render_window(self.render_window)
7944 self.reset_key_events()
7945 self._get_iren_not_none().enable_interactor_style()
7946 self.iren.add_observer('KeyPressEvent', self.key_press_event)
7947
7948 # Set camera widget based on theme. This requires that an
7949 # interactor be present.
7950 if self.theme._enable_camera_orientation_widget:
7951 self.add_camera_orientation_widget() # type: ignore[call-arg]
7952
7953 # Set background
7954 self.set_background(self._theme.background) # type: ignore[arg-type]
7955
7956 # Set window size
7957 self._window_size_unset = False
7958 if window_size is None:
7959 self.window_size = self._theme.window_size
7960 if self.window_size == pv.plotting.themes.Theme().window_size:
7961 self._window_size_unset = True
7962 else:
7963 self.window_size = window_size
7964
7965 if self._theme.depth_peeling.enabled and self.enable_depth_peeling(): # type: ignore[call-arg]
7966 for renderer in self.renderers:
7967 renderer.enable_depth_peeling()
7968
7969 # set anti_aliasing based on theme
7970 if self.theme.anti_aliasing:
7971 self.enable_anti_aliasing(self.theme.anti_aliasing) # type: ignore[arg-type]
7972
7973 if self.theme.camera.parallel_projection:
7974 self.enable_parallel_projection() # type: ignore[call-arg]
7975
7976 self.parallel_scale = self.theme.camera.parallel_scale
7977
7978 if isinstance(stereo, StereoType):
7979 self._enable_stereo_rendering(stereo)
7980 elif stereo:
7981 self._enable_stereo_rendering()
7982
7983 # some cleanup only necessary for fully initialized plotters
7984 self._initialized = True
7985 log.debug('Plotter init stop')
7986
7987 @_deprecate_positional_args
7988 def show( # noqa: PLR0917
7989 self,
7990 title: str | None = None,
7991 window_size: Sequence[int] | None = None,
7992 interactive: bool = True, # noqa: FBT001, FBT002
7993 auto_close: bool | None = None, # noqa: FBT001
7994 interactive_update: bool = False, # noqa: FBT001, FBT002
7995 full_screen: bool | None = None, # noqa: FBT001
7996 screenshot: str | Path | io.BytesIO | bool = False, # noqa: FBT001, FBT002
7997 return_img: bool = False, # noqa: FBT001, FBT002
7998 cpos: CameraPositionOptions | None = None,
7999 jupyter_backend: JupyterBackendOptions | str | None = None,
8000 return_viewer: bool = False, # noqa: FBT001, FBT002
8001 return_cpos: bool | None = None, # noqa: FBT001
8002 before_close_callback: Callable[[Plotter], None] | None = None,
8003 store_image_depth: bool = False, # noqa: FBT001, FBT002
8004 **kwargs,
8005 ) -> (
8006 CameraPosition
8007 | pyvista_ndarray
8008 | EmbeddableWidget
8009 | Widget
8010 | IFrame
8011 | Image
8012 | tuple[
8013 CameraPosition | EmbeddableWidget | Widget | pyvista_ndarray | IFrame | Image,
8014 ...,
8015 ]
8016 | None
8017 ):
8018 """Display the plotting window.
8019
8020 .. versionchanged:: 0.47
8021 The last image depth is no longer automatically stored. You must
8022 enable ``store_image_depth=True`` within :meth:`show` to
8023 obtain the image depth after the :class:`pyvista.Plotter` has been
8024 closed.
8025
8026 .. versionadded:: 0.47
8027 Added the ``store_image_depth`` parameter to allow storing image depth
8028 for use with :meth:`get_image_depth`.
8029
8030 Parameters
8031 ----------
8032 title : str, optional
8033 Title of plotting window. Defaults to
8034 :attr:`pyvista.global_theme.title <pyvista.plotting.themes.Theme.title>`.
8035
8036 window_size : list[int], optional
8037 Window size in pixels. Defaults to
8038 :attr:`pyvista.global_theme.window_size <pyvista.plotting.themes.Theme.window_size>`.
8039
8040 interactive : bool, optional
8041 Enabled by default. Allows user to pan and move figure.
8042 Defaults to
8043 :attr:`pyvista.global_theme.interactive <pyvista.plotting.themes.Theme.interactive>`.
8044
8045 auto_close : bool, optional
8046 Exits plotting session when user closes the window when
8047 interactive is ``True``. Defaults to
8048 :attr:`pyvista.global_theme.auto_close <pyvista.plotting.themes.Theme.auto_close>`.
8049
8050 interactive_update : bool, default: False
8051 Allows user to non-blocking draw, user should call
8052 :func:`Plotter.update` in each iteration.
8053
8054 full_screen : bool, optional
8055 Opens window in full screen. When enabled, ignores
8056 ``window_size``. Defaults to
8057 :attr:`pyvista.global_theme.full_screen <pyvista.plotting.themes.Theme.full_screen>`.
8058
8059 screenshot : str | Path | io.BytesIO | bool, default: False
8060 Take a screenshot of the initial state of the plot. If a string,
8061 it specifies the path to which the screenshot is saved. If
8062 ``True``, the screenshot is returned as an array. For interactive
8063 screenshots it's recommended to first call ``show()`` with
8064 ``auto_close=False`` to set the scene, then save the screenshot in
8065 a separate call to ``show()`` or :func:`Plotter.screenshot`.
8066 See also the ``before_close_callback`` parameter for an
8067 alternative.
8068
8069 return_img : bool, default: False
8070 Returns a numpy array representing the last image along
8071 with the camera position.
8072
8073 cpos : sequence[sequence[float]], optional
8074 The camera position. You can also set this with
8075 :attr:`Plotter.camera_position`.
8076
8077 jupyter_backend : str, optional
8078 Jupyter notebook plotting backend to use. One of the
8079 following:
8080
8081 * ``'none'`` : Do not display in the notebook.
8082 * ``'static'`` : Display a static figure.
8083 * ``'trame'`` : Display a dynamic figure with Trame.
8084 * ``'html'`` : Use an ebeddable HTML scene.
8085
8086 This can also be set globally with
8087 :func:`pyvista.set_jupyter_backend`.
8088
8089 A dictionary ``jupyter_kwargs`` can also be passed to further
8090 configure how the backend displays.
8091
8092 return_viewer : bool, default: False
8093 Return the jupyterlab viewer, scene, or display object when
8094 plotting with Jupyter notebook. When ``False`` and within a Jupyter
8095 environment, the scene will be immediately shown within the
8096 notebook. Set this to ``True`` to return the scene instead.
8097
8098 return_cpos : bool, optional
8099 Return the last camera position from the render window
8100 when enabled. Default based on theme setting. See
8101 :attr:`pyvista.plotting.themes.Theme.return_cpos`.
8102
8103 before_close_callback : Callable, optional
8104 Callback that is called before the plotter is closed.
8105 The function takes a single parameter, which is the plotter object
8106 before it closes. An example of use is to capture a screenshot after
8107 interaction::
8108
8109 def fun(plotter):
8110 plotter.screenshot('file.png')
8111
8112 store_image_depth : bool, default: False
8113 Store image depth before closing. Necessary when calling
8114 :meth:`get_image_depth` after rendering.
8115
8116 **kwargs : dict, optional
8117 Developer keyword arguments.
8118
8119 Returns
8120 -------
8121 cpos : CameraPosition
8122 List of camera position, focal point, and view up.
8123 Returned only when ``return_cpos=True`` or set in the
8124 default global or plot theme.
8125
8126 image : np.ndarray
8127 Numpy array of the last image when either ``return_img=True``
8128 or ``screenshot=True`` is set. Optionally contains alpha
8129 values. Sized:
8130
8131 * [Window height x Window width x 3] if the theme sets
8132 ``transparent_background=False``.
8133 * [Window height x Window width x 4] if the theme sets
8134 ``transparent_background=True``.
8135
8136 widget : Widget | EmbeddableWidget | IFrame | Image
8137 IPython widget when ``return_viewer=True``.
8138
8139 Notes
8140 -----
8141 Please use the ``q``-key to close the plotter as some
8142 operating systems (namely Windows) will experience issues
8143 saving a screenshot if the exit button in the GUI is pressed.
8144
8145 Examples
8146 --------
8147 Simply show the plot of a mesh.
8148
8149 >>> import pyvista as pv
8150 >>> pl = pv.Plotter()
8151 >>> _ = pl.add_mesh(pv.Cube())
8152 >>> pl.show()
8153
8154 Take a screenshot interactively. Screenshot will be of the
8155 first image shown, so use the first call with
8156 ``auto_close=False`` to set the scene before taking the
8157 screenshot.
8158
8159 >>> pl = pv.Plotter()
8160 >>> _ = pl.add_mesh(pv.Cube())
8161 >>> pl.show(auto_close=False) # doctest:+SKIP
8162 >>> pl.show(screenshot='my_image.png') # doctest:+SKIP
8163
8164 Obtain the camera position when using ``show``.
8165
8166 >>> pl = pv.Plotter()
8167 >>> _ = pl.add_mesh(pv.Sphere())
8168 >>> pl.show(return_cpos=True) # doctest:+SKIP
8169 CameraPosition(position=(1.9264, 1.9264, 1.9264),
8170 focal_point=(0.0, 0.0, 0.0),
8171 viewup=(0.0, 0.0, 1.0))
8172
8173 """
8174 jupyter_kwargs = kwargs.pop('jupyter_kwargs', {})
8175 assert_empty_kwargs(**kwargs)
8176
8177 if before_close_callback is None:
8178 before_close_callback = pv.global_theme._before_close_callback
8179 self._before_close_callback = before_close_callback
8180
8181 if interactive_update and auto_close is None:
8182 auto_close = False
8183 elif interactive_update and auto_close:
8184 warn_external(
8185 textwrap.dedent(
8186 """
8187 The plotter will close immediately automatically since ``auto_close=True``.
8188 Either, do not specify ``auto_close``, or set it to ``False`` if you want to
8189 interact with the plotter interactively.
8190 """,
8191 ).strip(),
8192 )
8193 elif auto_close is None:
8194 auto_close = self._theme.auto_close
8195
8196 if self.render_window is None:
8197 msg = 'This plotter has been closed and cannot be shown.'
8198 raise RuntimeError(msg)
8199
8200 if full_screen is None:
8201 full_screen = self._theme.full_screen
8202
8203 if full_screen:
8204 self.render_window.SetFullScreen(True)
8205 self.render_window.BordersOn() # super buggy when disabled
8206 else:
8207 if window_size is None:
8208 window_size = self.window_size
8209 else:
8210 self._window_size_unset = False
8211 self.render_window.SetSize(window_size[0], window_size[1])
8212
8213 # reset unless camera for the first render unless camera is set
8214 self.camera_position = cpos # type: ignore[assignment]
8215 self._on_first_render_request()
8216
8217 # handle plotter notebook
8218 if jupyter_backend and not self.notebook:
8219 warn_external(
8220 'Not within a jupyter notebook environment.\nIgnoring ``jupyter_backend``.'
8221 )
8222
8223 jupyter_disp = None
8224 if self.notebook:
8225 from pyvista.jupyter.notebook import handle_plotter # noqa: PLC0415
8226
8227 if jupyter_backend is None:
8228 jupyter_backend = self._theme.jupyter_backend
8229
8230 if jupyter_backend is None or jupyter_backend.lower() != 'none':
8231 jupyter_disp = handle_plotter(self, backend=jupyter_backend, **jupyter_kwargs)
8232
8233 self.render()
8234
8235 # initial double render needed for certain passes when offscreen
8236 if self.off_screen and 'vtkDepthOfFieldPass' in self.renderer._render_passes._passes:
8237 self.render()
8238
8239 # This has to be after the first render for some reason
8240 if title is None:
8241 title = self.title
8242 if title:
8243 self.render_window.SetWindowName(title)
8244 self.title = title
8245
8246 # Keep track of image for sphinx-gallery
8247 if pv.BUILDING_GALLERY:
8248 # always save screenshots for sphinx_gallery
8249 self.last_image = self.screenshot(screenshot, return_img=True)
8250 with suppress(ImportError):
8251 self.last_vtksz = self.export_vtksz(filename=None)
8252
8253 # See: https://github.com/pyvista/pyvista/issues/186#issuecomment-550993270
8254 if interactive and not self.off_screen: # pragma: no cover
8255 try: # interrupts will be caught here
8256 log.debug('Starting iren')
8257 self.iren.update_style() # type: ignore[union-attr]
8258 if not interactive_update:
8259 # Workaround for Windows interactor unresponsiveness after focus changes.
8260 # See: https://github.com/pyvista/pyvista/issues/8383
8261 if os.name == 'nt':
8262 vtk_iren = self.iren.interactor # type: ignore[union-attr]
8263 while True:
8264 tstart_frame = time.time()
8265 vtk_iren.ProcessEvents()
8266 if vtk_iren.GetDone():
8267 break
8268 self.render_window.Render()
8269
8270 # target an update rate of 60 FPS
8271 telap = time.time() - tstart_frame
8272 sleep_ms = int((FPS_1_OVER_60 - telap) * 1000)
8273 if sleep_ms > 0:
8274 # instead of time.sleep use MsgWaitForMultipleObjects
8275 # to pump window messages to avoid the window appearing
8276 # unresponsive
8277 ctypes.windll.user32.MsgWaitForMultipleObjects( # type: ignore[attr-defined]
8278 0,
8279 None,
8280 False,
8281 sleep_ms,
8282 0x04FF, # QS_ALLINPUT
8283 )
8284 else:
8285 self.iren.start() # type: ignore[union-attr]
8286
8287 if pv.vtk_version_info < (9, 2, 3):
8288 self.iren.initialize() # type: ignore[union-attr]
8289
8290 except KeyboardInterrupt:
8291 log.debug('KeyboardInterrupt')
8292 self.close()
8293 raise KeyboardInterrupt
8294 # In the event that the user hits the exit-button on the GUI (on
8295 # Windows OS) then it must be finalized and deleted as accessing it
8296 # will kill the kernel.
8297 # Here we check for that and clean it up before moving on to any of
8298 # the closing routines that might try to still access that
8299 # render window.
8300 # Ignore if using a Jupyter display
8301 _ren_win = self.render_window
8302 _is_current = _ren_win is not None and _ren_win.IsCurrent() # type: ignore[redundant-expr]
8303 if _ren_win is None:
8304 # Render window was already cleaned up (e.g. plotter.close()
8305 # called from a key event callback). Nothing left to do.
8306 pass # type: ignore[unreachable] # pragma: no cover
8307 elif jupyter_disp is None and not _is_current:
8308 self._clear_ren_win() # The ren_win is deleted
8309 # proper screenshots cannot be saved if this happens
8310 if not auto_close: # pragma: no cover
8311 warn_external(
8312 '`auto_close` ignored: by clicking the exit button, '
8313 'you have destroyed the render window and we have to '
8314 'close it out.',
8315 )
8316 self.close()
8317 if screenshot:
8318 warn_external(
8319 'A screenshot is unable to be taken as the render window is not current or '
8320 'rendering is suppressed.',
8321 )
8322 if _is_current and self._rendered:
8323 if pv.ON_SCREENSHOT:
8324 filename = uuid.uuid4().hex
8325 self.last_image = self.screenshot(filename, return_img=True)
8326 else:
8327 self.last_image = self.screenshot(screenshot, return_img=True)
8328 if store_image_depth:
8329 self.last_image_depth = self.get_image_depth()
8330 # NOTE: after this point, nothing from the render window can be accessed
8331 # as if a user pressed the close button, then it destroys the
8332 # the render view and a stream of errors will kill the Python
8333 # kernel if code here tries to access that renderer.
8334 # See issues #135 and #186 for insight before editing the
8335 # remainder of this function.
8336
8337 # Close the render window if requested
8338 if jupyter_disp is None and auto_close:
8339 # Plotters are never auto-closed in Jupyter
8340 self.close()
8341
8342 if jupyter_disp is not None and not return_viewer:
8343 # Default behaviour is to display the Jupyter viewer
8344 try:
8345 from IPython import display # noqa: PLC0415
8346 except ImportError: # pragma: no cover
8347 msg = 'Install IPython to display an image in a notebook'
8348 raise ImportError(msg)
8349 display.display(jupyter_disp)
8350
8351 # Three possible return values: (cpos, image, widget)
8352 return_values = tuple(
8353 val
8354 for val in (
8355 self.camera_position if return_cpos else None,
8356 self.last_image if return_img or screenshot is True else None,
8357 jupyter_disp if return_viewer else None,
8358 )
8359 if val is not None
8360 )
8361 if len(return_values) == 1:
8362 return return_values[0]
8363 return return_values or None
8364
8365 @_deprecate_positional_args(allowed=['title'])
8366 def add_title( # noqa: PLR0917
8367 self,
8368 title: str,
8369 font_size: int = 18,
8370 color: ColorLike | None = None,
8371 font: FontFamilyOptions | None = None,
8372 shadow: bool = False, # noqa: FBT001, FBT002
8373 ) -> CornerAnnotation | Text:
8374 """Add text to the top center of the plot.
8375
8376 This is merely a convenience method that calls ``add_text``
8377 with ``position='upper_edge'``.
8378
8379 Parameters
8380 ----------
8381 title : str
8382 The text to add the rendering.
8383
8384 font_size : float, default: 18
8385 Sets the size of the title font.
8386
8387 color : ColorLike, optional
8388 Either a string, rgb list, or hex color string. Defaults
8389 to white or the value of the global theme if set. For
8390 example:
8391
8392 * ``color='white'``
8393 * ``color='w'``
8394 * ``color=[1.0, 1.0, 1.0]``
8395 * ``color='#FFFFFF'``
8396
8397 font : str, optional
8398 Font name may be ``'courier'``, ``'times'``, or ``'arial'``.
8399
8400 shadow : bool, default: False
8401 Adds a black shadow to the text.
8402
8403 Returns
8404 -------
8405 output : CornerAnnotation | Text
8406 Text actor added to plot.
8407
8408 Examples
8409 --------
8410 >>> import pyvista as pv
8411 >>> pl = pv.Plotter()
8412 >>> pl.background_color = 'grey'
8413 >>> actor = pl.add_title('Plot Title', font='courier', color='k', font_size=40)
8414 >>> pl.show()
8415
8416 """
8417 # add additional spacing from the top of the figure by default
8418 title = '\n' + title
8419 return self.add_text(
8420 title,
8421 position='upper_edge',
8422 font_size=font_size,
8423 color=color,
8424 font=font,
8425 shadow=shadow,
8426 name='title',
8427 viewport=False,
8428 )
8429
8430 def add_cursor(
8431 self,
8432 bounds: Sequence[float] = (-1.0, 1.0, -1.0, 1.0, -1.0, 1.0),
8433 focal_point: Sequence[float] = (0.0, 0.0, 0.0),
8434 color: ColorLike | None = None,
8435 ) -> _vtk.vtkActor:
8436 """Add a cursor of a PyVista or VTK dataset to the scene.
8437
8438 Parameters
8439 ----------
8440 bounds : sequence[float], default: (-1.0, 1.0, -1.0, 1.0, -1.0, 1.0)
8441 Specify the bounds in the format of:
8442
8443 - ``(x_min, x_max, y_min, y_max, z_min, z_max)``
8444
8445 focal_point : sequence[float], default: (0.0, 0.0, 0.0)
8446 The focal point of the cursor.
8447
8448 color : ColorLike, optional
8449 Either a string, RGB sequence, or hex color string. For one
8450 of the following.
8451
8452 * ``color='white'``
8453 * ``color='w'``
8454 * ``color=[1.0, 1.0, 1.0]``
8455 * ``color='#FFFFFF'``
8456
8457 Returns
8458 -------
8459 :vtk:`vtkActor`
8460 VTK actor of the 2D cursor.
8461
8462 Examples
8463 --------
8464 >>> import pyvista as pv
8465 >>> sphere = pv.Sphere()
8466 >>> pl = pv.Plotter()
8467 >>> _ = pl.add_mesh(sphere)
8468 >>> _ = pl.add_cursor()
8469 >>> pl.show()
8470
8471 """
8472 alg = _vtk.vtkCursor3D()
8473 alg.SetModelBounds(bounds)
8474 alg.SetFocalPoint(focal_point) # type: ignore[call-overload]
8475 alg.AllOn()
8476 mapper = DataSetMapper(theme=self._theme)
8477 mapper.SetInputConnection(alg.GetOutputPort())
8478 actor, prop = self.add_actor(mapper) # type: ignore[arg-type]
8479 cast('_vtk.vtkProperty', prop).SetColor(Color(color).float_rgb) # type: ignore[call-overload]
8480
8481 return cast('_vtk.vtkActor', actor)
8482
8483 @property
8484 def meshes(
8485 self,
8486 ) -> list[pv.DataSet | pv.MultiBlock]: # numpydoc ignore=RT01
8487 """Return plotter meshes.
8488
8489 Returns
8490 -------
8491 list[DataSet | MultiBlock]
8492 List of mesh objects such as pyvista.PolyData, pyvista.UnstructuredGrid, etc.
8493
8494 """
8495 return [
8496 actor.mapper.dataset
8497 for actor in self.actors.values()
8498 if hasattr(actor, 'mapper') and hasattr(actor.mapper, 'dataset')
8499 ]
8500
8501
8502 # Tracks created plotters. This is the end of the module as we need to
8503 # define ``BasePlotter`` before including it in the type definition.
8504 #
8505 # When pyvista.BUILDING_GALLERY = False, the objects will be ProxyType, and
8506 # when True, BasePlotter.
8507 _ALL_PLOTTERS: dict[str, BasePlotter] = {}