      and the entire indexing would be::

           [A, B, d, e, f, C, g, h, i]

        Note how the composite datasets themselves are capitalized and are
        accessible in the flat indexing, and not just the datasets.

        Examples
        --------
        Add a composite dataset to a plotter and access its block attributes.
        Note how the zero index is the entire multiblock and you can use ``1``
        and ``2`` to access the individual sub-blocks.

        >>> import pyvista as pv
        >>> dataset = pv.MultiBlock(
        ...     [pv.Cube(), pv.Sphere(center=(0, 0, 1))]
        ... )
        >>> pl = pv.Plotter()
        >>> actor, mapper = pl.add_composite(dataset)
        >>> mapper.block_attr.get_block(0)
        MultiBlock (...)
          N Blocks    2
          X Bounds    -0.500, 0.500
          Y Bounds    -0.500, 0.500
          Z Bounds    -0.500, 1.500

        Note this is the same as using ``__getitem__``

        >>> mapper.block_attr[0]
        Composite Block Addr=... Attributes
        Visible:   None
        Opacity:   None
        Color:     None
        Pickable   None

        """
        try:
            if vtk_version_info <= (9, 0, 3):  # pragma: no cover
                vtk_ref = _vtk.reference(0)  # needed for <=9.0.3
                block = self.DataObjectFromIndex(index, self._dataset, vtk_ref)
            else:
                block = self.DataObjectFromIndex(index, self._dataset)
        except OverflowError:
            raise KeyError(f'Invalid block key: {index}') from None
        if block is None:
            if index > len(self) - 1:
                raise KeyError(
                    f'index {index} is out of bounds. There are only {len(self)} blocks.'
                ) from None
        return block

    def __getitem__(self, index):
        """Return a block attribute by its flat index."""
        return BlockAttributes(self.get_block(index), self)

    def __len__(self):
        """Return the number of blocks in this dataset."""
        from pyvista import MultiBlock  # avoid circular

        # start with 1 as there is always a composite dataset and this is the
        # root of the tree
        cc = 1
        for dataset in self._dataset:
            if isinstance(dataset, MultiBlock):
                cc += len(dataset) + 1  # include the block itself
            else:
                cc += 1
        return cc

    def __iter__(self):
        """Return an iterator of all the block attributes."""
        for ii in range(len(self)):
            yield self[ii]


class CompositePolyDataMapper(_vtk.vtkCompositePolyDataMapper2, _BaseMapper):
    """Composite PolyData mapper.

    Parameters
    ----------
    dataset : pyvista.MultiBlock
        Multiblock dataset.

    theme : pyvista.plotting.themes.Theme, optional
        Plot-specific theme.

    color_missing_with_nan : bool, optional
        Color any missing values with the ``nan_color``. This is useful
        when not all blocks of the composite dataset have the specified
        ``scalars``.

    interpolate_before_map : bool, optional
        Enabling makes for a smoother scalars display.  Default is
        ``True``.  When ``False``, OpenGL will interpolate the
        mapped colors which can result is showing colors that are
        not present in the color map.

    """

    def __init__(
        self, dataset, theme=None, color_missing_with_nan=None, interpolate_before_map=None
    ):
        """Initialize this composite mapper."""
        super().__init__(theme=theme)
        self.SetInputDataObject(dataset)

        # this must be added to set the color, opacity, and visibility of
        # individual blocks
        self._attr = CompositeAttributes(self, dataset)
        self._dataset = dataset

        if color_missing_with_nan is not None:
            self.color_missing_with_nan = color_missing_with_nan
        if interpolate_before_map is not None:
            self.interpolate_before_map = interpolate_before_map

    @property
    def dataset(self) -> 'pv.MultiBlock':  # numpydoc ignore=RT01
        """Return the composite dataset assigned to this mapper.

        Examples
        --------
        >>> import pyvista as pv
        >>> dataset = pv.MultiBlock(
        ...     [pv.Cube(), pv.Sphere(center=(0, 0, 1))]
        ... )
        >>> pl = pv.Plotter()
        >>> actor, mapper = pl.add_composite(dataset)
        >>> mapper.dataset
        MultiBlock (...)
          N Blocks    2
          X Bounds    -0.500, 0.500
          Y Bounds    -0.500, 0.500
          Z Bounds    -0.500, 1.500

        """
        return self._dataset

    @property
    def block_attr(self) -> CompositeAttributes:  # numpydoc ignore=RT01
        """Return the block attributes.

        Notes
        -----
        ``block_attr`` employs VTK's flat indexing and allows for accessing
        both the blocks of a composite dataset as well as the entire composite
        dataset. If there is only one composite dataset, ``A``, which contains
        datasets ``[b, c]``, the indexing would be ``[A, b, c]``.

        If there are two composite datasets ``[B, C]`` in one composite
        dataset, ``A``, each of which containing three additional datasets
        ``[d, e, f]``, and ``[g, h, i]``, respectively, then the head node,
        ``A``, would be the zero index, followed by the first child, ``B``,
        followed by all the children of ``B``, ``[d, e, f]``. In data
        structures, this flat indexing would be known as "Depth-first search"
        and the entire indexing would be::

           [A, B, d, e, f, C, g, h, i]

        Examples
        --------
        Add a sphere and a cube as a multiblock dataset to a plotter and then
        change the visibility and color of the blocks.

        >>> import pyvista as pv
        >>> dataset = pv.MultiBlock(
        ...     [pv.Cube(), pv.Sphere(center=(0, 0, 1))]
        ... )
        >>> pl = pv.Plotter()
        >>> actor, mapper = pl.add_composite(dataset)
        >>> mapper.block_attr[1].color = 'b'
        >>> mapper.block_attr[1].opacity = 0.1
        >>> mapper.block_attr[1]
        Composite Block Addr=... Attributes
        Visible:   None
        Opacity:   0.1
        Color:     Color(name='blue', hex='#0000ffff', opacity=255)
        Pickable   None

        """
        return self._attr

    @property
    def color_missing_with_nan(self) -> bool:  # numpydoc ignore=RT01
        """Color missing arrays with the NaN color.

        Examples
        --------
        Enable coloring missing values with NaN.

        >>> import pyvista as pv
        >>> dataset = pv.MultiBlock(
        ...     [pv.Cube(), pv.Sphere(center=(0, 0, 1))]
        ... )
        >>> dataset[0].point_data['data'] = dataset[0].points[:, 2]
        >>> pl = pv.Plotter()
        >>> actor, mapper = pl.add_composite(
        ...     dataset, scalars='data', show_scalar_bar=False
        ... )
        >>> mapper.nan_color = 'r'
        >>> mapper.color_missing_with_nan = True
        >>> pl.show()

        """
        return self.GetColorMissingArraysWithNanColor()

    @color_missing_with_nan.setter
    def color_missing_with_nan(self, value: bool):  # numpydoc ignore=GL08
        self.SetColorMissingArraysWithNanColor(value)

    def set_unique_colors(self):
        """Set each block of the dataset to a unique color.

        This uses ``matplotlib``'s color cycler.

        Examples
        --------
        Set each block of the composite dataset to a unique color.

        >>> import pyvista as pv
        >>> dataset = pv.MultiBlock(
        ...     [pv.Cube(), pv.Sphere(center=(0, 0, 1))]
        ... )
        >>> pl = pv.Plotter()
        >>> actor, mapper = pl.add_composite(dataset)
        >>> mapper.set_unique_colors()
        >>> mapper.block_attr[1].color
        Color(name='tab:orange', hex='#ff7f0eff', opacity=255)
        >>> mapper.block_attr[2].color
        Color(name='tab:green', hex='#2ca02cff', opacity=255)
        """
        self.scalar_visibility = False
        colors = cycle(matplotlib.rcParams['axes.prop_cycle'])
        for attr in self.block_attr:
            attr.color = next(colors)['color']

    def set_scalars(
        self,
        scalars_name,
        preference,
        component,
        annotations,
        rgb,
        scalar_bar_args,
        n_colors,
        nan_color,
        above_color,
        below_color,
        clim,
        cmap,
        flip_scalars,
        log_scale,
    ):
        """Set the scalars of the mapper.

        Parameters
        ----------
        scalars_name : str
            Name of the scalars in the dataset. Must already exist in at least
            of the blocks.

        preference : str
            For each block, when ``block.n_points == block.n_cells`` and
            setting scalars, this parameter sets how the scalars will be mapped
            to the mesh.  Default ``'point'``, causes the scalars will be
            associated with the mesh points.  Can be either ``'point'`` or
            ``'cell'``.

        component : int
            Set component of vector valued scalars to plot.  Must be
            nonnegative, if supplied. If ``None``, the magnitude of
            the vector is plotted.

        annotations : dict
            Pass a dictionary of annotations. Keys are the float
            values in the scalars range to annotate on the scalar bar
            and the values are the string annotations.

        rgb : bool
            If the ``scalars_name`` corresponds to a 2 dimensional array, plot
            those values as RGB(A) colors.

        scalar_bar_args : dict
            Dictionary of keyword arguments to pass when adding the
            scalar bar to the scene. For options, see
            :func:`pyvista.Plotter.add_scalar_bar`.

        n_colors : int
            Number of colors to use when displaying scalars.

        nan_color : ColorLike
            The color to use for all ``NaN`` values in the plotted
            scalar array.

        above_color : ColorLike
            Solid color for values below the scalars range
            (``clim``). This will automatically set the scalar bar
            ``above_label`` to ``'above'``.

        below_color : ColorLike
            Solid color for values below the scalars range
            (``clim``). This will automatically set the scalar bar
            ``below_label`` to ``'below'``.

        clim : Sequence
            Color bar range for scalars.  Defaults to minimum and
            maximum of scalars array.  Example: ``[-1, 2]``. ``rng``
            is also an accepted alias for this.

        cmap : str, list, or pyvista.LookupTable
            Name of the Matplotlib colormap to use when mapping the
            ``scalars``.  See available Matplotlib colormaps.  Only applicable
            for when displaying ``scalars``.
            ``colormap`` is also an accepted alias for this. If
            ``colorcet`` or ``cmocean`` are installed, their colormaps can be
            specified by name.

            You can also specify a list of colors to override an existing
            colormap with a custom one.  For example, to create a three color
            colormap you might specify ``['green', 'red', 'blue']``.

            This parameter also accepts a :class:`pyvista.LookupTable`. If this
            is set, all parameters controlling the color map like ``n_colors``
            will be ignored.
            are installed, their colormaps can be specified by name.

        flip_scalars : bool
            Flip direction of cmap. Most colormaps allow ``*_r``
            suffix to do this as well.

        log_scale : bool
            Use log scale when mapping data to colors. Scalars less
            than zero are mapped to the smallest representable
            positive float.

        Returns
        -------
        dict
            Dictionary of scalar bar arguments.

        """
        self._orig_scalars_name = scalars_name

        field, scalars_name, dtype = self._dataset._activate_plotting_scalars(
            scalars_name, preference, component, rgb
        )

        self.scalar_visibility = True
        if rgb:
            self.scalar_mode = 'direct'
            return scalar_bar_args
        else:
            self.scalar_map_mode = field.name.lower()

        scalar_bar_args.setdefault('title', scalars_name)

        if clim is None:
            clim = self._dataset.get_data_range(scalars_name, allow_missing=True)
        self.scalar_range = clim

        if log_scale:
            if clim[0] <= 0:
                clim = [sys.float_info.min, clim[1]]

        if isinstance(cmap, pv.LookupTable):
            self.lookup_table = cmap
        else:
            if dtype == np.bool_:
                cats = np.array([b'False', b'True'], dtype='|S5')
                values = np.array([0, 1])
                n_colors = 2
                scalar_bar_args.setdefault('n_labels', 0)
                self.lookup_table.SetAnnotations(convert_array(values), convert_string_array(cats))
                clim = [-0.5, 1.5]

            self.lookup_table.log_scale = log_scale

            if isinstance(annotations, dict):
                self.lookup_table.annotations = annotations

            # self.lookup_table.SetNumberOfTableValues(n_colors)
            if nan_color:
                self.lookup_table.nan_color = nan_color
            if above_color:
                self.lookup_table.above_range_color = above_color
                scalar_bar_args.setdefault('above_label', 'above')
            if below_color:
                self.lookup_table.below_range_color = below_color
                scalar_bar_args.setdefault('below_label', 'below')

            if cmap is None:
                if self._theme is None:
                    cmap = pv.global_theme.cmap
                else:
                    cmap = self._theme.cmap

            if cmap is not None:
                self.lookup_table.apply_cmap(cmap, n_colors, flip_scalars)
            else:  # pragma: no cover
                if flip_scalars:
                    self.lookup_table.SetHueRange(0.0, 0.66667)
                else:
                    self.lookup_table.SetHueRange(0.66667, 0.0)

        return scalar_bar_args


# pyvista/plotting/cube_axes_actor.py

"""Module containing the wrapping of CubeAxesActor."""
from typing import List, Tuple

import numpy as np

import pyvista as pv
from pyvista.core._typing_core import BoundsLike
from pyvista.core.utilities.arrays import convert_string_array

from . import _vtk


def make_axis_labels(vmin, vmax, n, fmt):
    """
    Create axis labels as a vtkStringArray.

    Parameters
    ----------
    vmin : float
        The minimum value for the axis labels.
    vmax : float
        The maximum value for the axis labels.
    n : int
        The number of labels to create.
    fmt : str
        A format string for the labels. If the string starts with '%', the label will be formatted using the old-style string formatting method.
        Otherwise, the label will be formatted using the new-style string formatting method.

    Returns
    -------
    vtkStringArray
        The created labels as a vtkStringArray object.
    """
    labels = _vtk.vtkStringArray()
    for v in np.linspace(vmin, vmax, n):
        if fmt:
            if fmt.startswith('%'):
                label = fmt % v
            else:
                label = fmt.format(v)
        else:
            label = f'{v}'
        labels.InsertNextValue(label)
    return labels


class CubeAxesActor(_vtk.vtkCubeAxesActor):
    """Wrap vtkCubeAxesActor.

    This class is created to wrap vtkCubeAxesActor, which is used to draw axes
    and labels for the input data bounds. This wrapping aims to provide a
    user-friendly interface to use `vtkCubeAxesActor
    <https://vtk.org/doc/nightly/html/classvtkCubeAxesActor.html>`_.

    Parameters
    ----------
    camera : pyvista.Camera
        Camera to link to the axes actor.

    minor_ticks : bool, default: False
        If ``True``, also plot minor ticks on all axes.

    tick_location : str, optional
        Set how the ticks are drawn on the axes grid. Options include:
        ``'inside', 'outside', 'both'``.

    x_title : str, default: "X Axis"
        Title of the X axis.

    y_title : str, default: "Y Axis"
        Title of the Y axis.

    z_title : str, default: "Z Axis"
        Title of the Z axis.

    x_axis_visibility : bool, default: True
        Visibility of the X axis.

    y_axis_visibility : bool, default: True
        Visibility of the Y axis.

    z_axis_visibility : bool, default: True
        Visibility of the Z axis.

    x_label_format : str, optional
        A format string defining how tick labels are generated from tick
        positions for the X axis. Defaults to the theme format if set,
        otherwise ``'%.1f'``.

    y_label_format : str, optional
        A format string defining how tick labels are generated from tick
        positions for the Y axis. Defaults to the theme format if set,
        otherwise ``'%.1f'``.

    z_label_format : str, optional
        A format string defining how tick labels are generated from tick
        positions for the Z axis. Defaults to the theme format if set,
        otherwise ``'%.1f'``.

    x_label_visibility : bool, default: True
        The visibility of the X axis labels.

    y_label_visibility : bool, default: True
        The visibility of the Y axis labels.

    z_label_visibility : bool, default: True
        The visibility of the Z axis labels.

    n_xlabels : int, default: 5
        Number of labels along the X axis.

    n_ylabels : int, default: 5
        Number of labels along the Y axis.

    n_zlabels : int, default: 5
        Number of labels along the Z axis.

    Examples
    --------
    Create a 3D plotter and add a CubeAxesActor to it.

    >>> import pyvista as pv
    >>> mesh = pv.Cube()
    >>> pl = pv.Plotter()
    >>> actor = pl.add_mesh(mesh)
    >>> cube_axes_actor = pv.CubeAxesActor(pl.camera)
    >>> cube_axes_actor.bounds = mesh.bounds
    >>> actor, property = pl.add_actor(cube_axes_actor)
    >>> pl.show()

    """

    def __init__(
        self,
        camera,
        minor_ticks=False,
        tick_location=None,
        x_title='X Axis',
        y_title='Y Axis',
        z_title='Z Axis',
        x_axis_visibility=True,
        y_axis_visibility=True,
        z_axis_visibility=True,
        x_label_format=None,
        y_label_format=None,
        z_label_format=None,
        x_label_visibility=True,
        y_label_visibility=True,
        z_label_visibility=True,
        n_xlabels=5,
        n_ylabels=5,
        n_zlabels=5,
    ):
        """Initialize CubeAxesActor."""
        super().__init__()
        self.camera = camera

        # empty string used for clearing axis labels
        self._empty_str = _vtk.vtkStringArray()
        self._empty_str.InsertNextValue('')

        # stop labels from being generated several times during init
        self.x_axis_visibility = False
        self.y_axis_visibility = False
        self.z_axis_visibility = False

        if not minor_ticks:
            self.x_axis_minor_tick_visibility = minor_ticks
            self.y_axis_minor_tick_visibility = minor_ticks
            self.z_axis_minor_tick_visibility = minor_ticks

        if tick_location:
            self.tick_location = tick_location
        self.x_title = x_title
        self.y_title = y_title
        self.z_title = z_title

        self._x_label_visibility = x_label_visibility
        self._y_label_visibility = y_label_visibility
        self._z_label_visibility = z_label_visibility

        if x_label_format is None:
            x_label_format = pv.global_theme.font.fmt
            if x_label_format is None:
                x_label_format = '%.1f'
        if y_label_format is None:
            y_label_format = pv.global_theme.font.fmt
            if y_label_format is None:
                y_label_format = '%.1f'
        if z_label_format is None:
            z_label_format = pv.global_theme.font.fmt
            if z_label_format is None:
                z_label_format = '%.1f'

        self.x_label_format = x_label_format
        self.y_label_format = y_label_format
        self.z_label_format = z_label_format

        self.n_xlabels = n_xlabels
        self.n_ylabels = n_ylabels
        self.n_zlabels = n_zlabels

        self.x_axis_visibility = x_axis_visibility
        self.y_axis_visibility = y_axis_visibility
        self.z_axis_visibility = z_axis_visibility

    @property
    def tick_location(self) -> str:  # numpydoc ignore=RT01
        """Return or set how the ticks are drawn on the axes grid.

        Options include: ``'inside', 'outside', 'both'``.
        """
        tloc = self.GetTickLocation()
        if tloc == 0:
            return 'inside'
        if tloc == 1:
            return 'outside'
        return 'both'

    @tick_location.setter
    def tick_location(self, value: str):  # numpydoc ignore=GL08
        if not isinstance(value, str):
            raise TypeError(f'`tick_location` must be a string, not {type(value)}')
        value = value.lower()
        if value in ('inside'):
            self.SetTickLocationToInside()
        elif value in ('outside'):
            self.SetTickLocationToOutside()
        elif value in ('both'):
            self.SetTickLocationToBoth()
        else:
            raise ValueError(
                f'Value of tick_location ("{value}") should be either "inside", "outside", '
                'or "both".'
            )

    @property
    def bounds(self) -> BoundsLike:  # numpydoc ignore=RT01
        """Return or set the bounding box."""
        return self.GetBounds()

    @bounds.setter
    def bounds(self, bounds: BoundsLike):  # numpydoc ignore=GL08
        self.SetBounds(bounds)
        self._update_labels()
        self.x_axis_range = float(bounds[0]), float(bounds[1])
        self.y_axis_range = float(bounds[2]), float(bounds[3])
        self.z_axis_range = float(bounds[4]), float(bounds[5])

    @property
    def x_axis_range(self) -> Tuple[float, float]:  # numpydoc ignore=RT01
        """Return or set the X axis range."""
        return self.GetXAxisRange()

    @x_axis_range.setter
    def x_axis_range(self, value: Tuple[float, float]):  # numpydoc ignore=GL08
        self.SetXAxisRange(value)

    @property
    def y_axis_range(self) -> Tuple[float, float]:  # numpydoc ignore=RT01
        """Return or set the Y axis range."""
        return self.GetYAxisRange()

    @y_axis_range.setter
    def y_axis_range(self, value: Tuple[float, float]):  # numpydoc ignore=GL08
        self.SetYAxisRange(value)

    @property
    def z_axis_range(self) -> Tuple[float, float]:  # numpydoc ignore=RT01
        """Return or set the Z axis range."""
        return self.GetZAxisRange()

    @z_axis_range.setter
    def z_axis_range(self, value: Tuple[float, float]):  # numpydoc ignore=GL08
        self.SetZAxisRange(value)

    @property
    def label_offset(self) -> float:  # numpydoc ignore=RT01
        """Return or set the distance between labels and the axis."""
        return self.GetLabelOffset()

    @label_offset.setter
    def label_offset(self, offset: float):  # numpydoc ignore=GL08
        self.SetLabelOffset(offset)

    @property
    def title_offset(self) -> float:  # numpydoc ignore=RT01
        """Return or set the distance between title and labels."""
        return self.GetTitleOffset()

    @title_offset.setter
    def title_offset(self, offset: float):  # numpydoc ignore=GL08
        self.SetTitleOffset(offset)

    @property
    def camera(self) -> 'pv.Camera':  # numpydoc ignore=RT01
        """Return or set the camera that performs scaling and translation."""
        return self.GetCamera()

    @camera.setter
    def camera(self, camera: 'pv.Camera'):  # numpydoc ignore=GL08
        self.SetCamera(camera)

    @property
    def x_axis_minor_tick_visibility(self) -> bool:  # numpydoc ignore=RT01
        """Return or set visibility of the X axis minior tick."""
        return bool(self.GetXAxisMinorTickVisibility())

    @x_axis_minor_tick_visibility.setter
    def x_axis_minor_tick_visibility(self, value: bool):  # numpydoc ignore=GL08
        self.SetXAxisMinorTickVisibility(value)

    @property
    def y_axis_minor_tick_visibility(self) -> bool:  # numpydoc ignore=RT01
        """Return or set visibility of the Y axis minior tick."""
        return bool(self.GetYAxisMinorTickVisibility())

    @y_axis_minor_tick_visibility.setter
    def y_axis_minor_tick_visibility(self, value: bool):  # numpydoc ignore=GL08
        self.SetYAxisMinorTickVisibility(value)

    @property
    def z_axis_minor_tick_visibility(self) -> bool:  # numpydoc ignore=RT01
        """Return or set visibility of the Z axis minior tick."""
        return bool(self.GetZAxisMinorTickVisibility())

    @z_axis_minor_tick_visibility.setter
    def z_axis_minor_tick_visibility(self, value: bool):  # numpydoc ignore=GL08
        self.SetZAxisMinorTickVisibility(value)

    @property
    def x_label_visibility(self) -> bool:  # numpydoc ignore=RT01
        """Return or set the visibility of the X axis labels."""
        return self._x_label_visibility

    @x_label_visibility.setter
    def x_label_visibility(self, value: bool):  # numpydoc ignore=GL08
        self._x_label_visibility = bool(value)
        self._update_x_labels()

    @property
    def y_label_visibility(self) -> bool:  # numpydoc ignore=RT01
        """Return or set the visibility of the Y axis labels."""
        return self._y_label_visibility

    @y_label_visibility.setter
    def y_label_visibility(self, value: bool):  # numpydoc ignore=GL08
        self._y_label_visibility = bool(value)
        self._update_y_labels()

    @property
    def z_label_visibility(self) -> bool:  # numpydoc ignore=RT01
        """Return or set the visibility of the Z axis labels."""
        return self._z_label_visibility

    @z_label_visibility.setter
    def z_label_visibility(self, value: bool):  # numpydoc ignore=GL08
        self._z_label_visibility = bool(value)
        self._update_z_labels()

    @property
    def x_axis_visibility(self) -> bool:  # numpydoc ignore=RT01
        """Return or set the visibility of the X axis."""
        return bool(self.GetXAxisVisibility())

    @x_axis_visibility.setter
    def x_axis_visibility(self, value: bool):  # numpydoc ignore=GL08
        self.SetXAxisVisibility(value)

    @property
    def y_axis_visibility(self) -> bool:  # numpydoc ignore=RT01
        """Return or set the visibility of the Y axis."""
        return bool(self.GetYAxisVisibility())

    @y_axis_visibility.setter
    def y_axis_visibility(self, value: bool):  # numpydoc ignore=GL08
        self.SetYAxisVisibility(value)

    @property
    def z_axis_visibility(self) -> bool:  # numpydoc ignore=RT01
        """Return or set the visibility of the Y axis."""
        return bool(self.GetZAxisVisibility())

    @z_axis_visibility.setter
    def z_axis_visibility(self, value: bool):  # numpydoc ignore=GL08
        self.SetZAxisVisibility(value)

    @property
    def x_label_format(self) -> str:  # numpydoc ignore=RT01
        """Return or set the label of the X axis."""
        return self.GetXLabelFormat()

    @x_label_format.setter
    def x_label_format(self, value: str):  # numpydoc ignore=GL08
        self.SetXLabelFormat(value)
        self._update_x_labels()

    @property
    def y_label_format(self) -> str:  # numpydoc ignore=RT01
        """Return or set the label of the Y axis."""
        return self.GetYLabelFormat()

    @y_label_format.setter
    def y_label_format(self, value: str):  # numpydoc ignore=GL08
        self.SetYLabelFormat(value)
        self._update_y_labels()

    @property
    def z_label_format(self) -> str:  # numpydoc ignore=RT01
        """Return or set the label of the Z axis."""
        return self.GetZLabelFormat()

    @z_label_format.setter
    def z_label_format(self, value: str):  # numpydoc ignore=GL08
        self.SetZLabelFormat(value)
        self._update_z_labels()

    @property
    def x_title(self) -> str:  # numpydoc ignore=RT01
        """Return or set the title of the X axis."""
        return self._x_title

    @x_title.setter
    def x_title(self, value: str):  # numpydoc ignore=GL08
        self._x_title = value
        self._update_x_labels()

    @property
    def y_title(self) -> str:  # numpydoc ignore=RT01
        """Return or set the title of the Y axis."""
        return self._y_title

    @y_title.setter
    def y_title(self, value: str):  # numpydoc ignore=GL08
        self._y_title = value
        self._update_y_labels()

    @property
    def z_title(self) -> str:  # numpydoc ignore=RT01
        """Return or set the title of the Z axis."""
        return self._z_title

    @z_title.setter
    def z_title(self, value: str):  # numpydoc ignore=GL08
        self._z_title = value
        self._update_z_labels()

    @property
    def use_2d_mode(self) -> bool:  # numpydoc ignore=RT01
        """Use the 2d render mode.

        This can be enabled for smoother plotting.
        """
        return bool(self.GetUse2DMode())

    @use_2d_mode.setter
    def use_2d_mode(self, value: bool):  # numpydoc ignore=GL08
        self.SetUse2DMode(value)

    @property
    def n_xlabels(self):  # numpydoc ignore=RT01
        """Number of labels on the X axis."""
        return self._n_xlabels

    @n_xlabels.setter
    def n_xlabels(self, value: int):  # numpydoc ignore=GL08
        self._n_xlabels = value
        self._update_x_labels()

    @property
    def n_ylabels(self):  # numpydoc ignore=RT01
        """Number of labels on the Y axis."""
        return self._n_ylabels

    @n_ylabels.setter
    def n_ylabels(self, value: int):  # numpydoc ignore=GL08
        self._n_ylabels = value
        self._update_y_labels()

    @property
    def n_zlabels(self):  # numpydoc ignore=RT01
        """Number of labels on the Z axis."""
        return self._n_zlabels

    @n_zlabels.setter
    def n_zlabels(self, value: int):  # numpydoc ignore=GL08
        self._n_zlabels = value
        self._update_z_labels()

    def _update_labels(self):
        """Update all labels."""
        self._update_x_labels()
        self._update_y_labels()
        self._update_z_labels()

    def _update_x_labels(self):
        """Regenerate X axis labels."""
        if self.x_axis_visibility:
            self.SetXTitle(self._x_title)
            if self._x_label_visibility:
                self.SetAxisLabels(
                    0, make_axis_labels(*self.bounds[0:2], self.n_xlabels, self.x_label_format)
                )
            else:
                self.SetAxisLabels(0, self._empty_str)
        else:
            self.SetXTitle('')
            self.SetAxisLabels(0, self._empty_str)

    def _update_y_labels(self):
        """Regenerate Y axis labels."""
        if self.y_axis_visibility:
            self.SetYTitle(self._y_title)
            if self._y_label_visibility:
                self.SetAxisLabels(
                    1, make_axis_labels(*self.bounds[2:4], self.n_ylabels, self.y_label_format)
                )
            else:
                self.SetAxisLabels(1, self._empty_str)
        else:
            self.SetYTitle('')
            self.SetAxisLabels(1, self._empty_str)

    def _update_z_labels(self):
        """Regenerate Z axis labels."""
        if self.z_axis_visibility:
            self.SetZTitle(self._z_title)
            if self._z_label_visibility:
                self.SetAxisLabels(
                    2, make_axis_labels(*self.bounds[4:6], self.n_zlabels, self.z_label_format)
                )
            else:
                self.SetAxisLabels(2, self._empty_str)
        else:
            self.SetZTitle('')
            self.SetAxisLabels(2, self._empty_str)

    @property
    def x_labels(self) -> List[str]:  # numpydoc ignore=RT01
        """Return the x axis labels."""
        return convert_string_array(self.GetAxisLabels(0))

    @property
    def y_labels(self) -> List[str]:  # numpydoc ignore=RT01
        """Return the y axis labels."""
        return convert_string_array(self.GetAxisLabels(1))

    @property
    def z_labels(self) -> List[str]:  # numpydoc ignore=RT01
        """Return the z axis labels."""
        return convert_string_array(self.GetAxisLabels(2))

    def update_bounds(self, bounds):
        """Update the bounds of this actor.

        Unlike the :attr:`CubeAxesActor.bounds` attribute, updating the bounds
        also updates the axis labels.

        Parameters
        ----------
        bounds : sequence[float]
            Bounds in the form of ``[xmin, xmax, ymin, ymax, zmin, zmax]``.

        """
        self.bounds = bounds


# pyvista/plotting/errors.py

"""Plotting errors."""

CAMERA_ERROR_MESSAGE = """Invalid camera description
Camera description must be one of the following:

Iterable containing position, focal_point, and view up.  For example:
[(2.0, 5.0, 13.0), (0.0, 0.0, 0.0), (-0.7, -0.5, 0.3)]

Iterable containing a view vector.  For example:
[-1.0, 2.0, -5.0]

A string containing the plane orthogonal to the view direction.  For example:
'xy'
"""


class InvalidCameraError(ValueError):  # numpydoc ignore=PR01
    """Exception when passed an invalid camera."""

    def __init__(self, message=CAMERA_ERROR_MESSAGE):
        """Call the base class constructor with the custom message."""
        super().__init__(message)


class RenderWindowUnavailable(RuntimeError):  # numpydoc ignore=PR01
    """Exception when the render window is not available."""

    def __init__(self, message="Render window is not available."):
        """Call the base class constructor with the custom message."""
        super().__init__(message)


class PyVistaPickingError(RuntimeError):
    """General picking error class."""

    pass


# pyvista/plotting/helpers.py

"""This module contains some convenience helper functions."""

from typing import Tuple

import numpy as np

import pyvista
from pyvista.core.utilities.helpers import is_pyvista_dataset


def plot_arrows(cent, direction, **kwargs):
    """Plot arrows as vectors.

    Parameters
    ----------
    cent : array_like[float]
        Accepts a single 3d point or array of 3d points.

    direction : array_like[float]
        Accepts a single 3d point or array of 3d vectors.
        Must contain the same number of items as ``cent``.

    **kwargs : dict, optional
        See :func:`pyvista.plot`.

    Returns
    -------
    tuple
        See the returns of :func:`pyvista.plot`.

    See Also
    --------
    pyvista.plot

    Examples
    --------
    Plot a single random arrow.

    >>> import numpy as np
    >>> import pyvista
    >>> cent = np.random.random(3)
    >>> direction = np.random.random(3)
    >>> pyvista.plot_arrows(cent, direction)

    Plot 100 random arrows.

    >>> import numpy as np
    >>> import pyvista
    >>> cent = np.random.random((100, 3))
    >>> direction = np.random.random((100, 3))
    >>> pyvista.plot_arrows(cent, direction)

    """
    return pyvista.plot([cent, direction], **kwargs)


def plot_compare_four(
    data_a,
    data_b,
    data_c,
    data_d,
    display_kwargs=None,
    plotter_kwargs=None,
    show_kwargs=None,
    screenshot=None,
    camera_position=None,
    outline=None,
    outline_color='k',
    labels=('A', 'B', 'C', 'D'),
    link=True,
    notebook=None,
):
    """Plot a 2 by 2 comparison of data objects.

    Parameters
    ----------
    data_a : pyvista.DataSet
        The data object to display in the top-left corner.
    data_b : pyvista.DataSet
        The data object to display in the top-right corner.
    data_c : pyvista.DataSet
        The data object to display in the bottom-left corner.
    data_d : pyvista.DataSet
        The data object to display in the bottom-right corner.
    display_kwargs : dict, default: None
        Additional keyword arguments to pass to the ``add_mesh`` method.
    plotter_kwargs : dict, default: None
        Additional keyword arguments to pass to the ``Plotter`` constructor.
    show_kwargs : dict, default: None
        Additional keyword arguments to pass to the ``show`` method.
    screenshot : str or bool, default: None
        File name or path to save screenshot of the plot, or ``True`` to return
        a screenshot array.
    camera_position : list, default: None
        The camera position to use in the plot.
    outline : pyvista.DataSet, default: None
        An outline to plot around the data objects.
    outline_color : str, default: 'k'
        The color of the outline.
    labels : tuple of str, default: ('A', 'B', 'C', 'D')
        The labels to display for each data object.
    link : bool, default: True
        If ``True``, link the views of the subplots.
    notebook : bool, default: None
        If ``True``, display the plot in a Jupyter notebook.

    Returns
    -------
    pyvista.Plotter
        The plotter object.
    """
    datasets = [[data_a, data_b], [data_c, data_d]]
    labels = [labels[0:2], labels[2:4]]

    if plotter_kwargs is None:
        plotter_kwargs = {}
    if display_kwargs is None:
        display_kwargs = {}
    if show_kwargs is None:
        show_kwargs = {}

    plotter_kwargs['notebook'] = notebook

    pl = pyvista.Plotter(shape=(2, 2), **plotter_kwargs)

    for i in range(2):
        for j in range(2):
            pl.subplot(i, j)
            pl.add_mesh(datasets[i][j], **display_kwargs)
            pl.add_text(labels[i][j])
            if is_pyvista_dataset(outline):
                pl.add_mesh(outline, color=outline_color)
            if camera_position is not None:
                pl.camera_position = camera_position

    if link:
        pl.link_views()
        # when linked, camera must be reset such that the view range
        # of all subrender windows matches
        pl.reset_camera()

    return pl.show(screenshot=screenshot, **show_kwargs)


def view_vectors(view: str, negative: bool = False) -> Tuple[np.ndarray, np.ndarray]:
    """Given a plane to view, return vectors for setting up camera.

    Parameters
    ----------
    view : {'xy', 'yx', 'xz', 'zx', 'yz', 'zy'}
        Plane to return vectors for.

    negative : bool, default: False
        Whether to view from opposite direction.

    Returns
    -------
    vec : numpy.ndarray
        ``[x, y, z]`` vector that points in the viewing direction.

    viewup : numpy.ndarray
        ``[x, y, z]`` vector that points to the viewup direction.

    """
    if view == 'xy':
        vec = np.array([0, 0, 1])
        viewup = np.array([0, 1, 0])
    elif view == 'yx':
        vec = np.array([0, 0, -1])
        viewup = np.array([1, 0, 0])
    elif view == 'xz':
        vec = np.array([0, -1, 0])
        viewup = np.array([0, 0, 1])
    elif view == 'zx':
        vec = np.array([0, 1, 0])
        viewup = np.array([1, 0, 0])
    elif view == 'yz':
        vec = np.array([1, 0, 0])
        viewup = np.array([0, 0, 1])
    elif view == 'zy':
        vec = np.array([-1, 0, 0])
        viewup = np.array([0, 1, 0])
    else:
        raise ValueError(
            f"Unexpected value for direction {view}\n"
            "    Expected: 'xy', 'yx', 'xz', 'zx', 'yz', 'zy'"
        )

    if negative:
        vec *= -1
    return vec, viewup


# pyvista/plotting/lights.py

"""Module containing pyvista implementation of vtk.vtkLight."""

from enum import IntEnum

import numpy as np

# imports here rather than in _vtk to avoid circular imports
try:
    from vtkmodules.vtkCommonMath import vtkMatrix4x4
    from vtkmodules.vtkRenderingCore import vtkLight, vtkLightActor
except ImportError:  # pragma: no cover
    from vtk import vtkLight, vtkLightActor, vtkMatrix4x4

from pyvista.core.utilities.arrays import vtkmatrix_from_array

from .colors import Color, ColorLike


class LightType(IntEnum):
    """An enumeration for the light types."""

    HEADLIGHT = 1
    CAMERA_LIGHT = 2
    SCENE_LIGHT = 3

    def __str__(self):
        """Pretty name for a light type."""
        return self.name.replace('_', ' ').title()


class Light(vtkLight):
    """Light class.

    Parameters
    ----------
    position : sequence[float], optional
        The position of the light. The interpretation of the position
        depends on the type of the light and whether the light has a
        transformation matrix.  See also the :py:attr:`position`
        property.

    focal_point : sequence[float], optional
        The focal point of the light. The interpretation of the focal
        point depends on the type of the light and whether the light
        has a transformation matrix.  See also the
        :py:attr:`focal_point` property.

    color : ColorLike, optional
        The color of the light. The ambient, diffuse and specular
        colors will all be set to this color on creation.

    light_type : str | int, default: 'scene light'
        The type of the light. If a string, one of ``'headlight'``,
        ``'camera light'`` or ``'scene light'``. If an int, one of 1,
        2 or 3, respectively. The class constants ``Light.HEADLIGHT``,
        ``Light.CAMERA_LIGHT`` and ``Light.SCENE_LIGHT`` are also
        available, respectively.

            - A headlight is attached to the camera, looking at its
              focal point along the axis of the camera.

            - A camera light also moves with the camera, but it can
              occupy a general position with respect to it.

            - A scene light is stationary with respect to the scene,
              as it does not follow the camera. This is the default.

    intensity : float, optional
        The brightness of the light (between 0 and 1).

    positional : bool, optional
        Set if the light is positional.

        The default is a directional light, i.e. an infinitely distant
        point source. A positional light with a cone angle of at least
        90 degrees acts like a spherical point source. A positional
        light with a cone angle that is less than 90 degrees is known
        as a spotlight.

    cone_angle : float, optional
        Cone angle of a positional light in degrees.

    show_actor : bool, default: False
        Show an actor for a spotlight that depicts the geometry of the
        beam.

    exponent : float, optional
        The exponent of the cosine used for spotlights. See also the
        :py:attr:`exponent` property.

    shadow_attenuation : float, optional
        The value of shadow attenuation.

        By default a light will be completely blocked when in shadow.
        By setting this value to less than 1.0 you can control how
        much light is attenuated when in shadow. Note that changing
        the :py:attr:`attenuation_values` of the light can make it pass
        through objects even if its shadow attenuation is 1.

    attenuation_values : sequence, optional
        Quadratic attenuation constants.

        The values are a 3-length sequence which specifies the constant,
        linear and quadratic constants in this order. These parameters
        only have an effect for positional lights.

    Examples
    --------
    Create a light at (10, 10, 10) and set its diffuse color to red.

    >>> import pyvista as pv
    >>> light = pv.Light(position=(10, 10, 10))
    >>> light.diffuse_color = 1.0, 0.0, 0.0

    Create a positional light at (0, 0, 3) with a cone angle of
    30, exponent of 20, and a visible actor.

    >>> light = pv.Light(
    ...     position=(0, 0, 3),
    ...     show_actor=True,
    ...     positional=True,
    ...     cone_angle=30,
    ...     exponent=20,
    ... )

    """

    # pull in light type enum values as class constants
    HEADLIGHT = LightType.HEADLIGHT
    CAMERA_LIGHT = LightType.CAMERA_LIGHT
    SCENE_LIGHT = LightType.SCENE_LIGHT

    def __init__(
        self,
        position=None,
        focal_point=None,
        color=None,
        light_type='scene light',
        intensity=None,
        positional=None,
        cone_angle=None,
        show_actor=False,
        exponent=None,
        shadow_attenuation=None,
        attenuation_values=None,
    ):
        """Initialize the light."""
        super().__init__()
        self._renderers = []
        self.actor = None

        if position is not None:
            self.position = position
        if focal_point is not None:
            self.focal_point = focal_point

        if color is not None:
            self.ambient_color = color
            self.diffuse_color = color
            self.specular_color = color

        if isinstance(light_type, str):
            # be forgiving: ignore spaces and case
            light_type_orig = light_type
            type_normalized = light_type.replace(' ', '').lower()
            mapping = {
                'headlight': LightType.HEADLIGHT,
                'cameralight': LightType.CAMERA_LIGHT,
                'scenelight': LightType.SCENE_LIGHT,
            }
            try:
                light_type = mapping[type_normalized]
            except KeyError:
                light_keys = ', '.join(mapping)
                msg = (
                    f'Invalid light_type "{light_type_orig}"\n'
                    f'Choose from one of the following: {light_keys}'
                )
                raise ValueError(msg) from None
        elif not isinstance(light_type, int):
            raise TypeError(
                f'Parameter light_type must be int or str, not {type(light_type).__name__}.'
            )
        # LightType is an int subclass

        self.light_type = light_type

        if intensity is not None:
            self.intensity = intensity

        if cone_angle is not None:
            self.cone_angle = cone_angle

        if exponent is not None:
            self.exponent = exponent

        if positional is not None:
            self.positional = positional

        if shadow_attenuation is not None:
            self.shadow_attenuation = shadow_attenuation

        if attenuation_values is not None:
            self.attenuation_values = attenuation_values

        # Add the light actor
        self.actor = vtkLightActor()
        self.actor.SetLight(self)
        self.actor.SetVisibility(show_actor)

    def __repr__(self):
        """Print a repr specifying the id of the light and its light type."""
        return f'<{self.__class__.__name__} ({self.light_type}) at {hex(id(self))}>'

    def __eq__(self, other):
        """Compare whether the relevant attributes of two lights are equal."""
        # attributes which are native python types and thus implement __eq__
        native_attrs = [
            'light_type',
            'position',
            'focal_point',
            'ambient_color',
            'diffuse_color',
            'specular_color',
            'intensity',
            'on',
            'positional',
            'exponent',
            'cone_angle',
            'attenuation_values',
            'shadow_attenuation',
        ]
        for attr in native_attrs:
            if getattr(self, attr) != getattr(other, attr):
                return False

        # check transformation matrix element by element (if it exists)
        this_trans = self.transform_matrix
        that_trans = other.transform_matrix
        trans_count = sum(1 for trans in [this_trans, that_trans] if trans is not None)
        if trans_count == 1:
            # either but not both are None
            return False
        if trans_count == 2:
            for i in range(4):
                for j in range(4):
                    if this_trans.GetElement(i, j) != that_trans.GetElement(i, j):
                        return False
        return True

    def __del__(self):
        """Clean up when the light is being destroyed."""
        self.actor = None
        self._renderers.clear()

    @property
    def shadow_attenuation(self):  # numpydoc ignore=RT01
        """Return or set the value of shadow attenuation.

        By default a light will be completely blocked when in shadow.
        By setting this value to less than 1.0 you can control how
        much light is attenuated when in shadow. Note that changing
        the :py:attr:`attenuation_values` of the light can make it pass
        through objects even if its shadow attenuation is 1.

        Examples
        --------
        Set the shadow attenuation to 0.5

        >>> import pyvista as pv
        >>> light = pv.Light()
        >>> light.shadow_attenuation = 0.5
        >>> light.shadow_attenuation
        0.5

        """
        return self.GetShadowAttenuation()

    @shadow_attenuation.setter
    def shadow_attenuation(self, value):  # numpydoc ignore=GL08
        self.SetShadowAttenuation(value)

    @property
    def ambient_color(self):  # numpydoc ignore=RT01
        """Return or set the ambient color of the light.

        When setting, the color must be a 3-length sequence or a string.
        For example:

            * ``color='white'``
            * ``color='w'``
            * ``color=[1.0, 1.0, 1.0]``
            * ``color='#FFFFFF'``

        Examples
        --------
        Create a light and set its ambient color to red.

        >>> import pyvista
        >>> light = pyvista.Light()
        >>> light.ambient_color = 'red'
        >>> light.ambient_color
        Color(name='red', hex='#ff0000ff', opacity=255)

        """
        return Color(self.GetAmbientColor())

    @ambient_color.setter
    def ambient_color(self, color: ColorLike):  # numpydoc ignore=GL08
        self.SetAmbientColor(Color(color).float_rgb)

    @property
    def diffuse_color(self):  # numpydoc ignore=RT01
        """Return or set the diffuse color of the light.

        When setting, the color must be a 3-length sequence or a string.
        For example:

            * ``color='white'``
            * ``color='w'``
            * ``color=[1.0, 1.0, 1.0]``
            * ``color='#FFFFFF'``

        Examples
        --------
        Create a light and set its diffuse color to blue.

        >>> import pyvista as pv
        >>> light = pv.Light()
        >>> light.diffuse_color = (0.0, 0.0, 1.0)
        >>> light.diffuse_color
        Color(name='blue', hex='#0000ffff', opacity=255)

        """
        return Color(self.GetDiffuseColor())

    @diffuse_color.setter
    def diffuse_color(self, color: ColorLike):  # numpydoc ignore=GL08
        self.SetDiffuseColor(Color(color).float_rgb)

    @property
    def specular_color(self):  # numpydoc ignore=RT01
        """Return or set the specular color of the light.

        When setting, the color must be a 3-length sequence or a string.
        For example:

            * ``color='white'``
            * ``color='w'``
            * ``color=[1.0, 1.0, 1.0]``
            * ``color='#FFFFFF'``

        Examples
        --------
        Create a light and set its specular color to bright green.

        >>> import pyvista as pv
        >>> light = pv.Light()
        >>> light.specular_color = '#00FF00'
        >>> light.specular_color
        Color(name='lime', hex='#00ff00ff', opacity=255)

        """
        return Color(self.GetSpecularColor())

    @specular_color.setter
    def specular_color(self, color: ColorLike):  # numpydoc ignore=GL08
        self.SetSpecularColor(Color(color).float_rgb)

    @property
    def position(self):  # numpydoc ignore=RT01
        """Return the position of the light.

        Note: the position is defined in the coordinate space
        indicated by the light's transformation matrix (if it
        exists). To get the light's world space position, use the
        (read-only) :py:attr:`world_position` property.

        Examples
        --------
        Create a light positioned at ``(10, 10, 10)`` after
        initialization, and note how the position is unaffected by a
        non-trivial transform matrix.

        >>> import numpy as np
        >>> import pyvista as pv
        >>> light = pv.Light()
        >>> light.position = (10, 10, 10)
        >>> # set a "random" transformation matrix
        >>> light.transform_matrix = np.arange(4 * 4).reshape(4, 4)
        >>> light.position
        (10.0, 10.0, 10.0)

        """
        return self.GetPosition()

    @position.setter
    def position(self, pos):  # numpydoc ignore=GL08
        self.SetPosition(pos)

    @property
    def world_position(self):  # numpydoc ignore=RT01
        """Return the world space position of the light.

        The world space position is the :py:attr:`position` property
        transformed by the light's transform matrix if it exists. The
        value of this read-only property corresponds to the
        ``vtk.vtkLight.GetTransformedPosition()`` method.

        Examples
        --------
        Create a light with a transformation matrix that corresponds to a
        90-degree rotation around the z axis and a shift by (0, 0, -1), and
        check that the light's position transforms as expected.

        >>> import numpy as np
        >>> import pyvista as pv
        >>> light = pv.Light(position=(1, 0, 3))
        >>> trans = np.zeros((4, 4))
        >>> trans[:-1, :-1] = [[0, -1, 0], [1, 0, 0], [0, 0, 1]]
        >>> trans[:-1, -1] = [0, 0, -1]
        >>> light.transform_matrix = trans
        >>> light.position
        (1.0, 0.0, 3.0)
        >>> light.world_position
        (0.0, 1.0, 2.0)

        """
        return self.GetTransformedPosition()

    @property
    def focal_point(self):  # numpydoc ignore=RT01
        """Return the focal point of the light.

        Note: the focal point is defined in the coordinate space
        indicated by the light's transformation matrix (if it
        exists). To get the light's world space focal point, use the
        (read-only) :py:attr:`world_focal_point` property.

        Examples
        --------
        Create a light at (10, 10, 10) shining at (0, 0, 1).

        >>> import pyvista as pv
        >>> light = pv.Light(position=(10, 10, 10))
        >>> light.focal_point = (0, 0, 1)

        """
        return self.GetFocalPoint()

    @focal_point.setter
    def focal_point(self, pos):  # numpydoc ignore=GL08
        self.SetFocalPoint(pos)

    @property
    def world_focal_point(self):  # numpydoc ignore=RT01
        """Return the world space focal point of the light.

        The world space focal point is the :py:attr:`focal_point`
        property transformed by the light's transform matrix if it
        exists. The value of this read-only property corresponds to
        the ``vtk.vtkLight.GetTransformedFocalPoint()`` method.

        Examples
        --------
        Create a light with a transformation matrix that corresponds
        to a 90-degree rotation around the z axis and a shift by (0,
        0, -1), and check that the light's focal point transforms as
        expected.

        >>> import numpy as np
        >>> import pyvista as pv
        >>> light = pv.Light(focal_point=(1, 0, 3))
        >>> trans = np.zeros((4, 4))
        >>> trans[:-1, :-1] = [[0, -1, 0], [1, 0, 0], [0, 0, 1]]
        >>> trans[:-1, -1] = [0, 0, -1]
        >>> light.transform_matrix = trans
        >>> light.focal_point
        (1.0, 0.0, 3.0)
        >>> light.world_focal_point
        (0.0, 1.0, 2.0)

        """
        return self.GetTransformedFocalPoint()

    @property
    def intensity(self):  # numpydoc ignore=RT01
        """Return or set the brightness of the light (between 0 and 1).

        Examples
        --------
        Light the two sides of a cube with lights of different
        brightness.

        >>> import pyvista as pv
        >>> plotter = pv.Plotter(lighting='none')
        >>> _ = plotter.add_mesh(pv.Cube(), color='cyan')
        >>> light_bright = pv.Light(
        ...     position=(3, 0, 0), light_type='scene light'
        ... )
        >>> light_dim = pv.Light(
        ...     position=(0, 3, 0), light_type='scene light'
        ... )
        >>> light_dim.intensity = 0.5
        >>> for light in light_bright, light_dim:
        ...     light.positional = True
        ...     plotter.add_light(light)
        ...
        >>> plotter.show()

        """
        return self.GetIntensity()

    @intensity.setter
    def intensity(self, intensity):  # numpydoc ignore=GL08
        self.SetIntensity(intensity)

    @property
    def on(self):  # numpydoc ignore=RT01
        """Return or set whether the light is on.

        This corresponds to the Switch state of the ``vtk.vtkLight`` class.

        Examples
        --------
        Create a light, check if it's on by default, and turn it off.

        >>> import pyvista as pv
        >>> light = pv.Light()
        >>> light.on
        True
        >>> light.on = False

        """
        return bool(self.GetSwitch())

    @on.setter
    def on(self, state):  # numpydoc ignore=GL08
        self.SetSwitch(state)

    @property
    def positional(self):  # numpydoc ignore=RT01
        """Return or set whether the light is positional.

        The default is a directional light, i.e. an infinitely distant
        point source. A positional light with a cone angle of at least
        90 degrees acts like a spherical point source. A positional
        light with a cone angle that is less than 90 degrees is known
        as a spotlight.

        Attenuation and cone angles are only used for positional
        lights.  The :py:attr:`exponent` property is only used for
        spotlights.  Positional lights with a cone angle of at least
        90 degrees don't show angular dependence of their beams, but
        they display attenuation.

        If the light is changed to directional, its actor (if previously
        shown) is automatically hidden.

        Examples
        --------
        Create a spotlight shining on the origin.

        >>> import pyvista as pv
        >>> light = pv.Light(position=(1, 1, 1))
        >>> light.positional = True
        >>> light.cone_angle = 30

        """
        return bool(self.GetPositional())

    @positional.setter
    def positional(self, state):  # numpydoc ignore=GL08
        if not state:
            self.hide_actor()
        self.SetPositional(state)
        self._check_actor()

    def _check_actor(self):
        """Check if the light actor should be added or removed from attached renderers.

        This should be called whenever positional state or cone angle
        are changed.

        """
        if self.actor is None:
            # only should occur on __init__
            return

        actor_state = self.cone_angle < 90 and self.positional
        actor_name = self.actor.GetAddressAsString("")

        # add or remove the actor from the renderer
        for renderer in self._renderers:
            if actor_state:
                if actor_name not in renderer.actors:
                    renderer.add_actor(self.actor, render=False)
            else:
                if actor_name in renderer.actors:
                    renderer.remove_actor(self.actor, render=False)

    @property
    def exponent(self):  # numpydoc ignore=RT01
        """Return or set the exponent of the cosine used for spotlights.

        With a spotlight (a positional light with cone angle less than
        90 degrees) the shape of the light beam within the light cone
        varies with the angle from the light's axis, and the variation
        of the intensity depends as the cosine of this angle raised to
        an exponent, which is 1 by default. Increasing the exponent
        makes the beam sharper (more focused around the axis),
        decreasing it spreads the beam out.

        Note that since the angular dependence defined by this
        property and the truncation performed by the
        :py:attr:`cone_angle` are independent, for spotlights with
        narrow beams (small :py:attr:`cone_angle`) it is harder to see
        the angular variation of the intensity, and a lot higher
        exponent might be necessary to visibly impact the angular
        distribution of the beam.

        Examples
        --------
        Plot three planes lit by three spotlights with exponents of 1,
        2 and 5.  The one with the lowest exponent has the broadest
        beam.

        >>> import pyvista as pv
        >>> plotter = pv.Plotter(lighting='none')
        >>> for offset, exponent in zip([0, 1.5, 3], [1, 2, 5]):
        ...     _ = plotter.add_mesh(
        ...         pv.Plane((offset, 0, 0)), color='white'
        ...     )
        ...     light = pv.Light(
        ...         position=(offset, 0, 0.1),
        ...         focal_point=(offset, 0, 0),
        ...     )
        ...     light.exponent = exponent
        ...     light.positional = True
        ...     light.cone_angle = 80
        ...     plotter.add_light(light)
        ...
        >>> plotter.view_xy()
        >>> plotter.show()

        """
        return self.GetExponent()

    @exponent.setter
    def exponent(self, exp):  # numpydoc ignore=GL08
        self.SetExponent(exp)

    @property
    def cone_angle(self):  # numpydoc ignore=RT01
        """Return or set the cone angle of a positional light.

        The angle is in degrees and is measured between the axis of
        the cone and an extremal ray of the cone. A value smaller than
        90 has spot lighting effects, anything equal to and above 90
        is just a positional light, i.e. a spherical point source.

        Regarding the angular distribution of the light, the cone
        angle merely truncates the beam, the shape of which is defined
        by the :py:attr:`exponent`.  If the cone angle is at least 90
        degrees then there is no angular dependence.

        If the light's cone angle is increased to 90 degrees or above,
        its actor (if previously shown) is automatically hidden.

        Examples
        --------
        Plot three planes lit by three spotlights with varying cone
        angles.  Use a large exponent to cause a visible angular
        variation of the intensity of the beams.

        >>> import pyvista as pv
        >>> plotter = pv.Plotter(lighting='none')
        >>> for offset, angle in zip([0, 1.5, 3], [70, 30, 20]):
        ...     _ = plotter.add_mesh(
        ...         pv.Plane((offset, 0, 0)), color='white'
        ...     )
        ...     light = pv.Light(
        ...         position=(offset, 0, 1), focal_point=(offset, 0, 0)
        ...     )
        ...     light.exponent = 15
        ...     light.positional = True
        ...     light.cone_angle = angle
        ...     plotter.add_light(light)
        ...
        >>> plotter.view_xy()
        >>> plotter.show()

        """
        return self.GetConeAngle()

    @cone_angle.setter
    def cone_angle(self, angle):  # numpydoc ignore=GL08
        if angle >= 90:
            self.hide_actor()
        self.SetConeAngle(angle)
        self._check_actor()

    @property
    def attenuation_values(self):  # numpydoc ignore=RT01
        """Return or set the quadratic attenuation constants.

        The values are 3-length sequences which specify the constant,
        linear and quadratic constants in this order. These parameters
        only have an effect for positional lights.

        Attenuation refers to the dampening of a beam of light as it
        gets further away from the point source. The three constants
        describe three different profiles for dampening with
        distance. A larger attenuation constant corresponds to more
        rapid decay with distance.

        Examples
        --------
        Plot three cubes lit by two lights with different attenuation
        profiles.  The blue light has slower linear attenuation, the
        green one has quadratic attenuation that makes it decay
        faster. Note that there are no shadow effects included so each
        box gets lit by both lights.

        >>> import pyvista as pv
        >>> plotter = pv.Plotter(lighting='none')
        >>> for offset in 1, 2.5, 4:
        ...     _ = plotter.add_mesh(
        ...         pv.Cube(center=(offset, offset, 0)), color='white'
        ...     )
        ...
        >>> colors = ['b', 'g']
        >>> all_attenuations = [(0, 0.1, 0), (0, 0, 0.1)]
        >>> centers = [(0, 1, 0), (1, 0, 0)]
        >>> for color, attenuation_constants, center in zip(
        ...     colors, all_attenuations, centers
        ... ):
        ...     light = pv.Light(position=center, color=color)
        ...     light.focal_point = (1 + center[0], 1 + center[1], 0)
        ...     light.cone_angle = 90
        ...     light.positional = True
        ...     light.attenuation_values = attenuation_constants
        ...     plotter.add_light(light)
        >>> plotter.view_vector((-1, -1, 1))
        >>> plotter.show()

        """
        return self.GetAttenuationValues()

    @attenuation_values.setter
    def attenuation_values(self, values):  # numpydoc ignore=GL08
        self.SetAttenuationValues(values)

    @property
    def transform_matrix(self):  # numpydoc ignore=RT01
        """Return (if any) or set the transformation matrix of the light.

        The transformation matrix is ``None`` by default, and it is
        stored as a ``vtk.vtkMatrix4x4`` object when set. If set, the
        light's parameters (position and focal point) are transformed
        by the matrix before being rendered. See also the
        :py:attr:`world_position` and :py:attr:`world_focal_point`
        read-only properties that can differ from :py:attr:`position`
        and :py:attr:`focal_point`, respectively.

        The 4-by-4 transformation matrix is a tool to encode a general
        linear transformation and a translation (an affine
        transform). The 3-by-3 principal submatrix (the top left
        corner of the matrix) encodes a three-dimensional linear
        transformation (e.g. some rotation around the origin). The top
        three elements in the last column of the matrix encode a
        three-dimensional translation. The last row of the matrix is
        redundant.

        Examples
        --------
        Create a light with a transformation matrix that corresponds
        to a 90-degree rotation around the z axis and a shift by (0,
        0, -1), and check that the light's position transforms as
        expected.

        >>> import numpy as np
        >>> import pyvista as pv
        >>> light = pv.Light(position=(1, 0, 3))
        >>> trans = np.zeros((4, 4))
        >>> trans[:-1, :-1] = [[0, -1, 0], [1, 0, 0], [0, 0, 1]]
        >>> trans[:-1, -1] = [0, 0, -1]
        >>> light.transform_matrix = trans
        >>> light.position
        (1.0, 0.0, 3.0)
        >>> light.world_position
        (0.0, 1.0, 2.0)

        """
        return self.GetTransformMatrix()

    @transform_matrix.setter
    def transform_matrix(self, matrix):  # numpydoc ignore=GL08
        if matrix is None or isinstance(matrix, vtkMatrix4x4):
            trans = matrix
        else:
            try:
                trans = vtkmatrix_from_array(matrix)
            except ValueError:
                raise ValueError(
                    'Transformation matrix must be a 4-by-4 matrix or array-like.'
                ) from None
        self.SetTransformMatrix(trans)

    @property
    def light_type(self):  # numpydoc ignore=RT01
        """Return or set the light type.

        The default light type is a scene light which lives in world
        coordinate space.

        A headlight is attached to the camera and always points at the
        camera's focal point.

        A camera light also moves with the camera, but it can have an
        arbitrary relative position to the camera. Camera lights are
        defined in a coordinate space where the camera is located at
        (0, 0, 1), looking towards (0, 0, 0) at a distance of 1, with
        up being (0, 1, 0). Camera lights use the transform matrix to
        establish this space, i.e. they have a fixed :py:attr:`position`
        with respect to the camera, and moving the camera only
        affects the :py:attr:`world_position` via changes in the
        :py:attr:`transform_matrix` (and the same goes for the focal
        point).

        The property returns class constant values from an enum:

            - ``Light.HEADLIGHT == 1``
            - ``Light.CAMERA_LIGHT == 2``
            - ``Light.SCENE_LIGHT == 3``

        If setting the value, either an integer code or a class constant enum
        value must be used.

        Examples
        --------
        Check the type of lights for the first two lights of the default
        light kit of plotters.

        >>> import pyvista as pv
        >>> plotter = pv.Plotter()
        >>> lights = plotter.renderer.lights[:2]
        >>> [light.light_type for light in lights]
        [<LightType.HEADLIGHT: 1>, <LightType.CAMERA_LIGHT: 2>]

        Change the light type of the default light kit's headlight to a scene light.

        >>> import pyvista as pv
        >>> plotter = pv.Plotter()
        >>> lights = plotter.renderer.lights[:2]
        >>> lights[0].light_type = pv.Light.SCENE_LIGHT
        >>> [light.light_type for light in lights]
        [<LightType.SCENE_LIGHT: 3>, <LightType.CAMERA_LIGHT: 2>]

        """
        return LightType(self.GetLightType())

    @light_type.setter
    def light_type(self, ltype):  # numpydoc ignore=GL08
        if not isinstance(ltype, int):
            # note that LightType is an int subclass
            raise TypeError(
                f'Light type must be an integer subclass instance, got {ltype} instead.'
            )
        self.SetLightType(ltype)

    @property
    def is_headlight(self):  # numpydoc ignore=RT01
        """Return whether the light is a headlight.

        Examples
        --------
        Verify that the first light of the default light kit is a headlight.

        >>> import pyvista as pv
        >>> plotter = pv.Plotter()
        >>> lights = plotter.renderer.lights
        >>> [light.is_headlight for light in lights]
        [True, False, False, False, False]

        """
        return bool(self.LightTypeIsHeadlight())

    @property
    def is_camera_light(self):  # numpydoc ignore=RT01
        """Return whether the light is a camera light.

        Examples
        --------
        Verify that four out of five lights of the default light kit
        are camera lights.

        >>> import pyvista as pv
        >>> plotter = pv.Plotter()
        >>> lights = plotter.renderer.lights
        >>> [light.is_camera_light for light in lights]
        [False, True, True, True, True]

        """
        return bool(self.LightTypeIsCameraLight())

    @property
    def is_scene_light(self):  # numpydoc ignore=RT01
        """Return whether the light is a scene light.

        Examples
        --------
        Verify that none of the lights of the default light kit are
        scene lights.

        >>> import pyvista as pv
        >>> plotter = pv.Plotter()
        >>> lights = plotter.renderer.lights
        >>> [light.is_scene_light for light in lights]
        [False, False, False, False, False]

        """
        return bool(self.LightTypeIsSceneLight())

    def switch_on(self):
        """Switch on the light.

        Examples
        --------
        Create a light, switch it off and switch it back on again.

        >>> import pyvista as pv
        >>> light = pv.Light()
        >>> light.on = False
        >>> light.switch_on()

        """
        self.SwitchOn()

    def switch_off(self):
        """Switch off the light.

        Examples
        --------
        Create a light and switch it off.

        >>> import pyvista as pv
        >>> light = pv.Light()
        >>> light.switch_off()

        """
        self.SwitchOff()

    def set_direction_angle(self, elev, azim):
        """Set the position and focal point of a directional light.

        The light is switched to directional (non-positional). The
        focal point is set to the origin. The position is defined in
        terms of an elevation and an azimuthal angle, both in degrees.

        Note that the equivalent ``vtk.vtkLight.SetDirectionAngle()`` method
        uses a surprising coordinate system where the (x', y', z') axes of
        the method correspond to the (z, x, y) axes of the renderer.
        This method reimplements the functionality in a way that ``elev``
        is the conventional elevation and ``azim`` is the conventional azimuth.
        In particular:

          * ``elev = 0``, ``azim = 0`` is the +x direction
          * ``elev = 0``, ``azim = 90`` is the +y direction
          * ``elev = 90``, ``azim = 0`` is the +z direction

        Parameters
        ----------
        elev : float
            The elevation of the directional light.

        azim : float
            The azimuthal angle of the directional light.

        Examples
        --------
        Create a light that shines on the origin from a 30-degree
        elevation in the xz plane.

        >>> import pyvista as pv
        >>> light = pv.Light()
        >>> light.set_direction_angle(30, 0)

        """
        self.positional = False
        self.focal_point = (0, 0, 0)
        theta = np.radians(90 - elev)
        phi = np.radians(azim)
        self.position = (np.sin(theta) * np.cos(phi), np.sin(theta) * np.sin(phi), np.cos(theta))

    def copy(self, deep=True):
        """Return a shallow or a deep copy of the light.

        The only mutable attribute of :class:`pyvista.Light` is the
        transformation matrix (if it exists). Thus asking for a
        shallow copy merely implies that the returned light and the
        original share the transformation matrix instance.

        Parameters
        ----------
        deep : bool, default: True
            Whether to return a deep copy rather than a shallow
            one.

        Returns
        -------
        pyvista.Light
            Copied light.

        Examples
        --------
        Create a light and check that it shares a transformation
        matrix with its shallow copy.

        >>> import pyvista as pv
        >>> light = pv.Light()
        >>> light.transform_matrix = [
        ...     [1, 0, 0, 0],
        ...     [0, 1, 0, 0],
        ...     [0, 0, 1, 0],
        ...     [0, 0, 0, 1],
        ... ]
        >>> shallow_copied = light.copy(deep=False)
        >>> shallow_copied == light
        True
        >>> shallow_copied.transform_matrix is light.transform_matrix
        True

        """
        immutable_attrs = [
            'light_type',
            'position',
            'focal_point',
            'ambient_color',
            'diffuse_color',
            'specular_color',
            'intensity',
            'on',
            'positional',
            'exponent',
            'cone_angle',
            'attenuation_values',
            'shadow_attenuation',
        ]
        new_light = Light()

        for attr in immutable_attrs:
            value = getattr(self, attr)
            setattr(new_light, attr, value)

        if deep and self.transform_matrix is not None:
            new_light.transform_matrix = vtkMatrix4x4()
            new_light.transform_matrix.DeepCopy(self.transform_matrix)
        else:
            new_light.transform_matrix = self.transform_matrix

        # light actors are private, always copy, but copy visibility state as well
        new_light.actor.SetVisibility(self.actor.GetVisibility())

        return new_light

    def set_headlight(self):
        """Set the light to be a headlight.

        Headlights are fixed to the camera and always point to the
        focal point of the camera. Calling this method will reset the
        light's transformation matrix.

        Examples
        --------
        >>> import pyvista
        >>> light = pyvista.Light()
        >>> light.set_headlight()
        >>> light.light_type
        <LightType.HEADLIGHT: 1>

        """
        self.SetLightTypeToHeadlight()

    def set_camera_light(self):
        """Set the light to be a camera light.

        A camera light moves with the camera, but it can have an
        arbitrary relative position to the camera. Camera lights are
        defined in a coordinate space where the camera is located at
        (0, 0, 1), looking towards (0, 0, 0) at a distance of 1, with
        up being (0, 1, 0).  Camera lights use the transformation
        matrix to establish this space.  Calling this method will
        reset the light's transformation matrix.

        Examples
        --------
        >>> import pyvista
        >>> light = pyvista.Light()
        >>> light.set_camera_light()
        >>> light.light_type
        <LightType.CAMERA_LIGHT: 2>

        """
        self.SetLightTypeToCameraLight()

    def set_scene_light(self):
        """Set the light to be a scene light.

        Scene lights are stationary with respect to the scene.
        Calling this method will reset the light's transformation
        matrix.

        Examples
        --------
        >>> import pyvista
        >>> light = pyvista.Light()
        >>> light.set_scene_light()
        >>> light.light_type
        <LightType.SCENE_LIGHT: 3>

        """
        self.SetLightTypeToSceneLight()

    @classmethod
    def from_vtk(cls, vtk_light):
        """Create a light from a ``vtk.vtkLight``, resulting in a copy.

        Parameters
        ----------
        vtk_light : vtk.vtkLight
            The ``vtk.vtkLight`` to be copied.

        Returns
        -------
        pyvista.Light
            Wrapped light.

        """
        if not isinstance(vtk_light, vtkLight):
            raise TypeError(
                f'Expected vtk.vtkLight object, got {type(vtk_light).__name__} instead.'
            )

        light = cls()
        light.light_type = vtk_light.GetLightType()  # resets transformation matrix
        light.position = vtk_light.GetPosition()
        light.focal_point = vtk_light.GetFocalPoint()
        light.ambient_color = vtk_light.GetAmbientColor()
        light.diffuse_color = vtk_light.GetDiffuseColor()
        light.specular_color = vtk_light.GetSpecularColor()
        light.intensity = vtk_light.GetIntensity()
        light.on = vtk_light.GetSwitch()
        light.positional = vtk_light.GetPositional()
        light.exponent = vtk_light.GetExponent()
        light.cone_angle = vtk_light.GetConeAngle()
        light.attenuation_values = vtk_light.GetAttenuationValues()
        trans = vtk_light.GetTransformMatrix()
        light.transform_matrix = trans
        light.shadow_attenuation = vtk_light.GetShadowAttenuation()

        return light

    def show_actor(self):
        """Show an actor for a spotlight that depicts the geometry of the beam.

        For a directional light or a positional light with
        :py:attr:`cone_angle` of at least 90 degrees the method
        doesn't do anything. If the light is changed so that it
        becomes a spotlight, this method has to be called again for
        the actor to show. To hide the actor see :func:`hide_actor`.

        Examples
        --------
        Create a scene containing a cube lit with a cyan spotlight and
        visualize the light using an actor.

        >>> import pyvista as pv
        >>> plotter = pv.Plotter()
        >>> _ = plotter.add_mesh(pv.Cube(), color='white')
        >>> for light in plotter.renderer.lights:
        ...     light.intensity /= 5
        ...
        >>> spotlight = pv.Light(position=(-1, 1, 1), color='cyan')
        >>> spotlight.positional = True
        >>> spotlight.cone_angle = 20
        >>> spotlight.intensity = 10
        >>> spotlight.exponent = 40
        >>> spotlight.show_actor()
        >>> plotter.add_light(spotlight)
        >>> plotter.show()

        """
        if not self.positional or self.cone_angle >= 90:
            return
        self.actor.VisibilityOn()

    def hide_actor(self):
        """Hide the actor for a positional light that depicts the geometry of the beam.

        For a directional light the function doesn't do anything.

        Examples
        --------
        >>> import pyvista
        >>> light = pyvista.Light()
        >>> light.hide_actor()

        """
        if not self.positional:
            return
        self.actor.VisibilityOff()

    @property
    def renderers(self):  # numpydoc ignore=RT01
        """Return the renderers associated with this light."""
        return self._renderers

    def add_renderer(self, renderer):
        """Attach a renderer to this light.

        Parameters
        ----------
        renderer : vtk.vtkRenderer
            Renderer.

        """
        # quick check to avoid adding twice
        if renderer not in self.renderers:
            self.renderers.append(renderer)

        # verify that the renderer has the light actor if applicable
        self._check_actor()


# pyvista/plotting/lookup_table.py

"""Wrap vtkLookupTable."""
from typing import Any, Optional, Tuple, Union

import numpy as np

import pyvista as pv
from pyvista.core.utilities.arrays import convert_array
from pyvista.core.utilities.misc import no_new_attr

from . import _vtk
from ._typing import ColorLike
from .colors import Color, get_cmap_safe
from .tools import opacity_transfer_function

RAMP_MAP = {0: 'linear', 1: 's-curve', 2: 'sqrt'}
RAMP_MAP_INV = {k: v for v, k in RAMP_MAP.items()}


class lookup_table_ndarray(np.ndarray):
    """An ndarray which references the owning table and the underlying vtkArray.

    This class is used to ensure that the internal vtkLookupTable updates when
    the values array is updated.

    """

    def __new__(
        cls,
        array,
        table=None,
    ):
        """Allocate the array."""
        obj = convert_array(array).view(cls)
        obj.VTKObject = array

        obj.table = _vtk.vtkWeakReference()
        obj.table.Set(table)

        return obj

    def __array_finalize__(self, obj):
        """Finalize array (associate with parent metadata)."""
        _vtk.VTKArray.__array_finalize__(self, obj)
        if np.shares_memory(self, obj):
            self.table = getattr(obj, 'table', None)
            self.VTKObject = getattr(obj, 'VTKObject', None)
        else:
            self.table = None
            self.VTKObject = None

    def __setitem__(self, key, value):
        """Implement [] set operator.

        When the array is changed it triggers "Modified()" which updates
        all upstream objects, including any render windows holding the
        object.
        """
        super().__setitem__(key, value)
        if self.VTKObject is not None:
            self.VTKObject.Modified()

        # the associated dataset should also be marked as modified
        if self.table is not None and self.table.Get():
            # this creates a new shallow copy and is necessary to update the
            # internal VTK array
            self.table.Get().values = self

    def __array_wrap__(self, out_arr, context=None):
        """Return a numpy scalar if array is 0d.

        See https://github.com/numpy/numpy/issues/5819

        """
        if out_arr.ndim:
            return np.ndarray.__array_wrap__(self, out_arr, context)

        # Match numpy's behavior and return a numpy dtype scalar
        return out_arr[()]

    __getattr__ = _vtk.VTKArray.__getattr__


@no_new_attr
class LookupTable(_vtk.vtkLookupTable):
    """Scalar to RGBA mapping table.

    A lookup table is an array that maps input values to output values. When
    plotting data over a dataset, it is necessary to map those scalars to
    colors (in the RGBA format), and this class provides the functionality to
    do so.

    See `vtkLookupTable
    <https://vtk.org/doc/nightly/html/classvtkLookupTable.html>`_ for more
    details regarding the underlying VTK API.

    Parameters
    ----------
    cmap : str | colors.Colormap, optional
        Color map from ``matplotlib``, ``colorcet``, or ``cmocean``. Either
        ``cmap`` or ``values`` can be set, but not both.

    n_values : int, default: 256
        Number of colors in the color map.

    flip : bool, default: False
        Flip the direction of cmap. Most colormaps allow ``*_r`` suffix to do this
        as well.

    values : array_like[float], optional
        Lookup table values. Either ``values`` or ``cmap`` can be set, but not
        both.

    value_range : tuple, optional
        The range of the brightness of the mapped lookup table. This range is
        only used when creating custom color maps and will be ignored if
        ``cmap`` is set.

    hue_range : tuple, optional
        Lookup table hue range. This range is only used when creating custom
        color maps and will be ignored if ``cmap`` is set.

    alpha_range : tuple, optional
        Lookup table alpha (transparency) range. This range is only used when
        creating custom color maps and will be ignored if ``cmap`` is set.

    scalar_range : tuple, optional
        The range of scalars which will be mapped to colors. Values outside of
        this range will be colored according to
        :attr`LookupTable.below_range_color` and
        :attr`LookupTable.above_range_color`.

    log_scale : bool, optional
        Use a log scale when mapping scalar values.

    nan_color : ColorLike, optional
        Color to render any values that are NANs.

    above_range_color : ColorLike, optional
        Color to render any values above :attr:`LookupTable.scalar_range`.

    below_range_color : ColorLike, optional
        Color to render any values below :attr:`LookupTable.scalar_range`.

    ramp : str, optional
        The shape of the table ramp. This range is only used when creating
        custom color maps and will be ignored if ``cmap`` is set.

    annotations : dict, optional
        A dictionary of annotations. Keys are the float values in the scalars
        range to annotate on the scalar bar and the values are the string
        annotations.

    Examples
    --------
    Plot the lookup table with the default VTK color map.

    >>> import pyvista as pv
    >>> lut = pv.LookupTable()
    >>> lut
    LookupTable (...)
      Table Range:                (0.0, 1.0)
      N Values:                   256
      Above Range Color:          None
      Below Range Color:          None
      NAN Color:                  Color(name='maroon', hex='#800000ff', opacity=255)
      Log Scale:                  False
      Color Map:                  "PyVista Lookup Table"
        Alpha Range:              (1.0, 1.0)
        Hue Range:                (0.0, 0.66667)
        Saturation Range          (1.0, 1.0)
        Value Range               (1.0, 1.0)
        Ramp                      s-curve
    >>> lut.plot()

    Plot the lookup table with the ``'inferno'`` color map.

    >>> import pyvista as pv
    >>> lut = pv.LookupTable('inferno', n_values=32)
    >>> lut
    LookupTable (...)
      Table Range:                (0.0, 1.0)
      N Values:                   32
      Above Range Color:          None
      Below Range Color:          None
      NAN Color:                  Color(name='maroon', hex='#800000ff', opacity=255)
      Log Scale:                  False
      Color Map:                  "inferno"
    >>> lut.plot()

    """

    _nan_color_set = False
    _cmap = None
    _values_manual = False
    _opacity_parm: Tuple[Any, bool, str] = (None, False, 'quadratic')

    def __init__(
        self,
        cmap=None,
        n_values=256,
        flip=False,
        values=None,
        value_range=None,
        hue_range=None,
        alpha_range=None,
        scalar_range=None,
        log_scale=None,
        nan_color=None,
        above_range_color=None,
        below_range_color=None,
        ramp=None,
        annotations=None,
    ):
        """Initialize the lookup table."""
        if cmap is not None and values is not None:
            raise ValueError('Cannot set both `cmap` and `values`.')

        if cmap is not None:
            self.apply_cmap(cmap, n_values=n_values, flip=flip)
        elif values is not None:
            self.values = values
        else:
            self.n_values = n_values
            if value_range is not None:
                self.value_range = value_range
            if hue_range is not None:
                self.hue_range = hue_range
            if alpha_range is not None:
                self.alpha_range = alpha_range
            if ramp is not None:
                self.ramp = ramp

        if nan_color is not None:
            self.nan_color = nan_color
        if above_range_color is not None:
            self.above_range_color = above_range_color
        if below_range_color is not None:
            self.below_range_color = below_range_color
        if scalar_range is not None:
            self.scalar_range = scalar_range
        if log_scale is not None:
            self.log_scale = log_scale
        if annotations is not None:
            self.annotations = annotations

    @property
    def value_range(self) -> Optional[tuple]:  # numpydoc ignore=RT01
        """Return or set the brightness of the mapped lookup table.

        This range is only used when creating custom color maps and will return
        ``None`` when a color map has been set with :attr:`LookupTable.cmap`.

        This will clear any existing color map and create new values for the
        lookup table when set.

        Examples
        --------
        Show the effect of setting the value range on the default color
        map.

        >>> import pyvista as pv
        >>> lut = pv.LookupTable()
        >>> lut.value_range = (0, 1.0)
        >>> lut.plot()

        Demonstrate a different value range.

        >>> import pyvista as pv
        >>> lut = pv.LookupTable()
        >>> lut.value_range = (0.5, 0.8)
        >>> lut.plot()

        """
        if self._cmap:
            return
        return self.GetValueRange()

    @value_range.setter
    def value_range(self, value: tuple):  # numpydoc ignore=GL08
        self.SetValueRange(value)
        self.rebuild()

    @property
    def hue_range(self) -> Optional[tuple]:  # numpydoc ignore=RT01
        """Return or set the hue range.

        This range is only used when creating custom color maps and will return
        ``None`` when a color map has been set with :attr:`LookupTable.cmap`.

        This will clear any existing color map and create new values for the
        lookup table when set.

        Examples
        --------
        Set the hue range. This allows you to create a lookup table
        without setting a color map.

        >>> import pyvista as pv
        >>> lut = pv.LookupTable()
        >>> lut.hue_range = (0, 0.1)
        >>> lut.plot()

        Create a different color map.

        >>> import pyvista as pv
        >>> lut = pv.LookupTable()
        >>> lut.hue_range = (0.5, 0.8)
        >>> lut.plot()

        """
        if self._cmap:
            return
        return self.GetHueRange()

    @hue_range.setter
    def hue_range(self, value: tuple):  # numpydoc ignore=GL08
        self.SetHueRange(value)
        self.rebuild()

    @property
    def cmap(self) -> Optional[str]:  # numpydoc ignore=RT01
        """Return or set the color map used by this lookup table.

        Examples
        --------
        Apply the single Matplotlib color map ``"Oranges"``.

        >>> import pyvista as pv
        >>> lut = pv.LookupTable()
        >>> lut.cmap = 'Oranges'
        >>> lut.plot()

        Apply a list of colors as a colormap.

        >>> import pyvista as pv
        >>> lut = pv.LookupTable()
        >>> lut.cmap = ['black', 'red', 'orange']
        >>> lut.plot()

        """
        return self._cmap

    @cmap.setter
    def cmap(self, value):  # numpydoc ignore=GL08
        self.apply_cmap(value, self.n_values)

    @property
    def log_scale(self) -> bool:  # numpydoc ignore=RT01
        """Use log scale.

        When ``True`` the lookup table is a log scale to
        :attr:`LookupTable.scalar_range`. Otherwise, it is linear scale.

        Examples
        --------
        Use log scale for the lookup table.

        >>> import pyvista as pv
        >>> lut = pv.LookupTable()
        >>> lut.log_scale = True
        >>> lut.scalar_range = (1, 100)
        >>> lut.plot()

        """
        return bool(self.GetScale())

    @log_scale.setter
    def log_scale(self, value: bool):  # numpydoc ignore=GL08
        self.SetScale(value)

    def __repr__(self):
        """Return the representation."""
        lines = [f'{type(self).__name__} ({hex(id(self))})']
        lines.append(f'  Table Range:                {self.scalar_range}')
        lines.append(f'  N Values:                   {self.n_values}')
        lines.append(f'  Above Range Color:          {self.above_range_color}')
        lines.append(f'  Below Range Color:          {self.below_range_color}')
        lines.append(f'  NAN Color:                  {self.nan_color}')
        lines.append(f'  Log Scale:                  {self.log_scale}')

        lines.append(f'  Color Map:                  "{self._lookup_type}"')
        if not (self.cmap or self._values_manual):
            lines.append(f'    Alpha Range:              {self.alpha_range}')
            lines.append(f'    Hue Range:                {self.hue_range}')
            lines.append(f'    Saturation Range          {self.saturation_range}')
            lines.append(f'    Value Range               {self.value_range}')
            lines.append(f'    Ramp                      {self.ramp}')

        return '\n'.join(lines)

    @property
    def scalar_range(self) -> tuple:  # numpydoc ignore=RT01
        """Return or set the table range.

        This is the range of scalars which will be mapped to colors. Values
        outside of this range will be colored according to
        :attr`LookupTable.below_range_color` and
        :attr`LookupTable.above_range_color`.

        Examples
        --------
        >>> import pyvista as pv
        >>> lut = pv.LookupTable()
        >>> lut.scalar_range = (0, 10)
        >>> lut.scalar_range
        (0.0, 10.0)

        """
        return self.GetTableRange()

    @scalar_range.setter
    def scalar_range(self, value: tuple):  # numpydoc ignore=GL08
        self.SetTableRange(value)

    @property
    def alpha_range(self) -> tuple:  # numpydoc ignore=RT01
        """Return or set the alpha range.

        This range is only used when creating custom color maps and will return
        ``None`` when a color map has been set with :attr:`LookupTable.cmap`.

        This will clear any existing color map and create new values for the
        lookup table when set.

        Examples
        --------
        Create a custom "blues" lookup table that decreases in opacity.

        >>> import pyvista as pv
        >>> lut = pv.LookupTable()
        >>> lut.hue_range = (0.7, 0.7)
        >>> lut.alpha_range = (1.0, 0.0)
        >>> lut.plot(background='grey')

        """
        if self._cmap:
            return None
        return self.GetAlphaRange()

    @alpha_range.setter
    def alpha_range(self, value: tuple):  # numpydoc ignore=GL08
        self.SetAlphaRange(value)
        self.rebuild()

    @property
    def saturation_range(self) -> tuple:  # numpydoc ignore=RT01
        """Return or set the saturation range.

        This range is only used when creating custom color maps and will return
        ``None`` when a color map has been set with :attr:`LookupTable.cmap`.

        This will clear any existing color map and create new values for the
        lookup table when set.

        Examples
        --------
        Create a custom "blues" lookup table that increases in saturation.

        >>> import pyvista as pv
        >>> lut = pv.LookupTable()
        >>> lut.hue_range = (0.7, 0.7)
        >>> lut.saturation_range = (0.0, 1.0)
        >>> lut.plot(background='grey')

        """
        if self._cmap:
            return None
        return self.GetSaturationRange()

    @saturation_range.setter
    def saturation_range(self, value: tuple):  # numpydoc ignore=GL08
        self.SetSaturationRange(value)
        self.rebuild()

    def rebuild(self):
        """Clear the color map and recompute the values table.

        This is called automatically when setting values like
        :attr:`LookupTable.value_range`.

        Notes
        -----
        This will reset any colormap set with :func:`LookupTable.apply_cmap` or
        :attr:`LookupTable.values`.

        """
        self._cmap = None
        self._values_manual = False
        self.ForceBuild()

    @property
    def nan_color(self) -> Optional[Color]:  # numpydoc ignore=RT01
        """Return or set the not a number (NAN) color.

        Any values that are NANs will be rendered with this color.

        Examples
        --------
        Set the NAN color to ``'grey'``.

        >>> import pyvista as pv
        >>> lut = pv.LookupTable()
        >>> lut.nan_color = 'grey'
        >>> lut.plot()

        """
        return Color(self.GetNanColor())

    @nan_color.setter
    def nan_color(self, value):  # numpydoc ignore=GL08
        # NAN value is always set, but make it explicit for example plotting
        self._nan_color_set = True
        self.SetNanColor(*Color(value).float_rgba)

    @property
    def nan_opacity(self):  # numpydoc ignore=RT01
        """Return or set the not a number (NAN) opacity.

        Any values that are NANs will be rendered with this opacity.

        Examples
        --------
        Set the NAN opacity to ``0.5``.

        >>> import pyvista as pv
        >>> lut = pv.LookupTable()
        >>> lut.nan_color = 'grey'
        >>> lut.nan_opacity = 0.5
        >>> lut.plot()

        """
        color = self.nan_color
        return color.opacity

    @nan_opacity.setter
    def nan_opacity(self, value):  # numpydoc ignore=GL08
        # Hacky check to prevent auto activation
        if not self._nan_color_set and (value == 1.0 or value == 255):
            return
        color = self.nan_color
        if color is None:
            color = Color(pv.global_theme.nan_color)
        self.nan_color = Color(self.nan_color, opacity=value)

    @property
    def ramp(self) -> str:  # numpydoc ignore=RT01
        """Set the shape of the table ramp.

        This attribute is only used when creating custom color maps and will
        return ``None`` when a color map has been set with
        :attr:`LookupTable.cmap`. This will clear any existing color map and
        create new values for the lookup table when set.

        This value may be either ``"s-curve"``, ``"linear"``, or ``"sqrt"``.

        * The default is S-curve, which tails off gradually at either end.
        * The equation used for ``"s-curve"`` is ``y = (sin((x - 1/2)*pi) +
          1)/2``, For an S-curve greyscale ramp, you should set
          :attr:`pyvista.LookupTable.n_values`` to 402 (which is ``256*pi/2``) to provide
          room for the tails of the ramp.

        * The equation for the ``"linear"`` is simply ``y = x``.
        * The equation for the ``"sqrt"`` is ``y = sqrt(x)``.

        Examples
        --------
        Show the default s-curve ramp.

        >>> import pyvista as pv
        >>> lut = pv.LookupTable()
        >>> lut.hue_range = (0.0, 0.33)
        >>> lut.ramp = 's-curve'
        >>> lut.plot()

        Plot the linear ramp.

        >>> import pyvista as pv
        >>> lut = pv.LookupTable()
        >>> lut.hue_range = (0.0, 0.33)
        >>> lut.ramp = 'linear'
        >>> lut.plot()

        Plot the ``"sqrt"`` ramp.

        >>> import pyvista as pv
        >>> lut = pv.LookupTable()
        >>> lut.hue_range = (0.0, 0.33)
        >>> lut.ramp = 'sqrt'
        >>> lut.plot()

        """
        return RAMP_MAP[self.GetRamp()]

    @ramp.setter
    def ramp(self, value: str):  # numpydoc ignore=GL08
        try:
            self.SetRamp(RAMP_MAP_INV[value])
        except KeyError:
            raise ValueError(f'`ramp` must be one of the following:\n{list(RAMP_MAP_INV.keys())}')
        self.rebuild()

    @property
    def above_range_color(self) -> Optional[Color]:  # numpydoc ignore=RT01
        """Return or set the above range color.

        Any values above :attr:`LookupTable.scalar_range` will be rendered with this
        color.

        Examples
        --------
        Enable the usage of the above range color.

        >>> import pyvista as pv
        >>> lut = pv.LookupTable()
        >>> lut.above_range_color = 'blue'
        >>> lut.plot()

        Disable the usage of the above range color.

        >>> import pyvista as pv
        >>> lut = pv.LookupTable()
        >>> lut.above_range_color = None
        >>> lut.plot()

        """
        if self.GetUseAboveRangeColor():
            return Color(self.GetAboveRangeColor())
        return None

    @above_range_color.setter
    def above_range_color(self, value: Union[bool, ColorLike]):  # numpydoc ignore=GL08
        if value in (None, False):
            self.SetUseAboveRangeColor(False)
        elif value is True:
            self.SetAboveRangeColor(*Color(pv.global_theme.above_range_color).float_rgba)
            self.SetUseAboveRangeColor(True)
        else:
            self.SetAboveRangeColor(*Color(value).float_rgba)
            self.SetUseAboveRangeColor(True)

    @property
    def above_range_opacity(self):  # numpydoc ignore=RT01
        """Return or set the above range opacity.

        Examples
        --------
        Set the above range opacity to ``0.5``.

        >>> import pyvista as pv
        >>> lut = pv.LookupTable()
        >>> lut.above_range_color = 'grey'
        >>> lut.above_range_opacity = 0.5
        >>> lut.plot()

        """
        color = self.above_range_color
        return color.opacity

    @above_range_opacity.setter
    def above_range_opacity(self, value):  # numpydoc ignore=GL08
        color = self.above_range_color
        if color is None:
            color = Color(pv.global_theme.above_range_color)
        self.above_range_color = Color(color, opacity=value)

    @property
    def below_range_color(self) -> Optional[Color]:  # numpydoc ignore=RT01
        """Return or set the below range color.

        Any values below :attr:`LookupTable.scalar_range` will be rendered with this
        color.

        Examples
        --------
        Enable the usage of the below range color.

        >>> import pyvista as pv
        >>> lut = pv.LookupTable()
        >>> lut.below_range_color = 'blue'
        >>> lut.plot()

        Disable the usage of the below range color.

        >>> import pyvista as pv
        >>> lut = pv.LookupTable()
        >>> lut.below_range_color = None
        >>> lut.plot()

        """
        if self.GetUseBelowRangeColor():
            return Color(self.GetBelowRangeColor())
        return None

    @below_range_color.setter
    def below_range_color(self, value: Union[bool, ColorLike]):  # numpydoc ignore=GL08
        if value in (None, False):
            self.SetUseBelowRangeColor(False)
        elif value is True:
            self.SetBelowRangeColor(*Color(pv.global_theme.below_range_color).float_rgba)
            self.SetUseBelowRangeColor(True)
        else:
            self.SetBelowRangeColor(*Color(value).float_rgba)
            self.SetUseBelowRangeColor(True)

    @property
    def below_range_opacity(self):  # numpydoc ignore=RT01
        """Return or set the below range opacity.

        Examples
        --------
        Set the below range opacity to ``0.5``.

        >>> import pyvista as pv
        >>> lut = pv.LookupTable()
        >>> lut.below_range_color = 'grey'
        >>> lut.below_range_opacity = 0.5
        >>> lut.plot()

        """
        color = self.below_range_color
        return color.opacity

    @below_range_opacity.setter
    def below_range_opacity(self, value):  # numpydoc ignore=GL08
        color = self.below_range_color
        if color is None:
            color = Color(pv.global_theme.below_range_color)
        self.below_range_color = Color(color, opacity=value)

    def apply_cmap(self, cmap, n_values: int = 256, flip: bool = False):
        """Assign a colormap to this lookup table.

        This can be used instead of :attr:`LookupTable.cmap` when you need to
        set the number of values at the same time as the color map.

        Parameters
        ----------
        cmap : str, list, colors.Colormap
            Colormap from Matplotlib, colorcet, or cmocean.

        n_values : int, default: 256
            Number of colors in the color map.

        flip : bool, default: False
            Flip direction of cmap. Most colormaps allow ``*_r`` suffix to do
            this as well.

        Examples
        --------
        Apply ``matplotlib``'s ``'cividis'`` color map.

        >>> import pyvista as pv
        >>> lut = pv.LookupTable()
        >>> lut.apply_cmap('cividis', n_values=32)
        >>> lut.plot()

        """
        if isinstance(cmap, list):
            n_values = len(cmap)

        cmap = get_cmap_safe(cmap)
        values = cmap(np.linspace(0, 1, n_values)) * 255

        if flip:
            values = values[::-1]

        self.values = values
        self._values_manual = False

        # reapply the opacity
        if self._opacity_parm[0] is not None:
            self.apply_opacity(*self._opacity_parm)

        self._cmap = cmap

    def apply_opacity(self, opacity, interpolate: bool = True, kind: str = 'quadratic'):
        """Assign custom opacity to this lookup table.

        Parameters
        ----------
        opacity : float | array_like[float] | str
            The opacity mapping to use. Can be a ``str`` name of a predefined
            mapping including ``'linear'``, ``'geom'``, ``'sigmoid'``,
            ``'sigmoid_3-10'``.  Append an ``'_r'`` to any of those names to
            reverse that mapping.  This can also be a custom array or list of
            values that will be interpolated across the ``n_color`` range for
            user defined mappings. Values must be between 0 and 1.

            If a ``float``, simply applies the same opacity across the entire
            colormap and must be between 0 and 1. Note that ``int`` values are
            interpreted as if they were floats.

        interpolate : bool, default: True
            Flag on whether or not to interpolate the opacity mapping for all
            colors.

        kind : str, default: 'quadratic'
            The interpolation kind if ``interpolate`` is ``True`` and ``scipy``
            is available. See :class:`scipy.interpolate.interp1d` for the
            available interpolation kinds.

            If ``scipy`` is not available, ``'linear'`` interpolation is used.

        Examples
        --------
        Apply a user defined custom opacity to a lookup table and plot the
        random hills example.

        >>> import pyvista as pv
        >>> from pyvista import examples
        >>> mesh = examples.load_random_hills()
        >>> lut = pv.LookupTable(cmap='viridis')
        >>> lut.apply_opacity([1.0, 0.4, 0.0, 0.4, 0.9])
        >>> lut.scalar_range = (
        ...     mesh.active_scalars.min(),
        ...     mesh.active_scalars.max(),
        ... )
        >>> pl = pv.Plotter()
        >>> _ = pl.add_mesh(mesh, cmap=lut)
        >>> pl.show()

        """
        if isinstance(opacity, (float, int)):
            if not 0 <= opacity <= 1:
                raise ValueError(f'Opacity must be between 0 and 1, got {opacity}')
            self.values[:, -1] = opacity * 255
        elif len(opacity) == self.n_values:
            # no interpolation is necessary
            self.values[:, -1] = np.array(opacity)
        else:
            self.values[:, -1] = opacity_transfer_function(
                opacity, self.n_values, interpolate=interpolate, kind=kind
            )
        self._opacity_parm = (opacity, interpolate, kind)

    @property
    def values(self) -> lookup_table_ndarray:  # numpydoc ignore=RT01
        """Return or set the lookup table values.

        This attribute is used when creating a custom lookup table. The table
        must be a RGBA array shaped ``(n, 4)``.

        Examples
        --------
        Create a simple four value lookup table ranging from black to red.

        >>> import pyvista as pv
        >>> lut = pv.LookupTable()
        >>> lut.values = [
        ...     [0, 0, 0, 255],
        ...     [85, 0, 0, 255],
        ...     [170, 0, 0, 255],
        ...     [255, 0, 0, 255],
        ... ]
        >>> lut.values
        lookup_table_ndarray([[  0,   0,   0, 255],
                              [ 85,   0,   0, 255],
                              [170,   0,   0, 255],
                              [255,   0,   0, 255]], dtype=uint8)
        >>> lut.plot()

        """
        return lookup_table_ndarray(self.GetTable(), table=self)

    @values.setter
    def values(self, new_values):  # numpydoc ignore=GL08
        self._values_manual = True
        self._cmap = None
        new_values = np.array(new_values, copy=False).astype(np.uint8, copy=False)
        self.SetTable(_vtk.numpy_to_vtk(new_values))

    @property
    def n_values(self) -> int:  # numpydoc ignore=RT01
        """Return or set the number of values in the lookup table.

        Examples
        --------
        Plot the ``"reds"`` colormap with 10 values.

        >>> import pyvista as pv
        >>> lut = pv.LookupTable('reds')
        >>> lut.n_values = 10
        >>> lut.plot()

        Plot the default colormap with 1024 values.

        >>> import pyvista as pv
        >>> lut = pv.LookupTable()
        >>> lut.n_values = 1024
        >>> lut.plot()

        """
        return self.GetNumberOfColors()

    @n_values.setter
    def n_values(self, value: int):  # numpydoc ignore=GL08
        if self._cmap is not None:
            self.apply_cmap(self._cmap, value)
            self.SetNumberOfTableValues(value)
        elif self._values_manual:
            raise RuntimeError(
                'Number of values cannot be set when the values array has been manually set. Reassign the values array if you wish to change the number of values.'
            )
        else:
            self.SetNumberOfColors(value)
            self.ForceBuild()

    @property
    def annotations(self) -> dict:  # numpydoc ignore=RT01
        """Return or set annotations.

        Pass a dictionary of annotations. Keys are the float values in the
        scalars range to annotate on the scalar bar and the values are the
        string annotations.

        Examples
        --------
        Assign annotations to the lookup table.

        >>> import pyvista as pv
        >>> lut = pv.LookupTable('magma')
        >>> lut.annotations = {0: 'low', 0.5: 'medium', 1: 'high'}
        >>> lut.plot()

        """
        vtk_values = self.GetAnnotatedValues()
        if vtk_values is None:
            return {}
        n_items = vtk_values.GetSize()
        keys = [vtk_values.GetValue(ii).ToFloat() for ii in range(n_items)]

        vtk_str = self.GetAnnotations()
        values = [str(vtk_str.GetValue(ii)) for ii in range(n_items)]
        return dict(zip(keys, values))

    @annotations.setter
    def annotations(self, values: Optional[dict]):  # numpydoc ignore=GL08
        self.ResetAnnotations()
        if values is not None:
            for val, anno in values.items():
                self.SetAnnotation(float(val), str(anno))

    @property
    def _lookup_type(self) -> str:
        """Return the lookup type."""
        if self.cmap:
            if hasattr(self.cmap, 'name'):
                return f'{self.cmap.name}'  # type: ignore
            else:  # pragma: no cover
                return f'{self.cmap}'
        elif self._values_manual:
            return 'From values array'
        else:
            return 'PyVista Lookup Table'

    def plot(self, **kwargs):
        """Plot this lookup table.

        Parameters
        ----------
        **kwargs : dict, optional
            Optional keyword arguments passed to :func:`pyvista.Plotter.show`.

        Examples
        --------
        Plot the ``"viridis"`` colormap with the below and above colors.

        >>> import pyvista as pv
        >>> lut = pv.LookupTable('viridis', n_values=8)
        >>> lut.below_range_color = 'black'
        >>> lut.above_range_color = 'grey'
        >>> lut.nan_color = 'r'
        >>> lut.plot()

        Plot only ``"blues"`` colormap.

        >>> import pyvista as pv
        >>> lut = pv.LookupTable('blues', n_values=1024)
        >>> lut.plot()

        """
        # need a trivial polydata for this
        mesh = pv.PolyData(np.zeros((2, 3)))
        mesh['Lookup Table'] = self.scalar_range

        pl = pv.Plotter(window_size=(800, 230), off_screen=kwargs.pop('off_screen', None))
        actor = pl.add_mesh(mesh, scalars=None, show_scalar_bar=False)
        actor.mapper.lookup_table = self
        actor.visibility = False

        scalar_bar_kwargs = {
            'color': 'k',
            'title': self._lookup_type + '\n',
            'outline': False,
            'title_font_size': 40,
        }
        label_level = 0
        if self.below_range_color:
            scalar_bar_kwargs['below_label'] = 'below'
            label_level = 1
        if self.above_range_color:
            scalar_bar_kwargs['above_label'] = 'above'
            label_level = 1

        label_level += self._nan_color_set

        scalar_bar = pl.add_scalar_bar(**scalar_bar_kwargs)
        scalar_bar.SetLookupTable(self)
        scalar_bar.SetMaximumNumberOfColors(self.n_values)
        scalar_bar.SetPosition(0.03, 0.1 + label_level * 0.1)
        scalar_bar.SetPosition2(0.95, 0.9 - label_level * 0.1)
        # scalar_bar.SetTextPad(-10)
        if self._nan_color_set and self.nan_opacity > 0:
            scalar_bar.SetDrawNanAnnotation(self._nan_color_set)

        pl.background_color = kwargs.pop('background', 'w')
        pl.show(**kwargs)

    def to_color_tf(self) -> _vtk.vtkColorTransferFunction:
        """Return the VTK color transfer function of this table.

        Returns
        -------
        vtk.vtkColorTransferFunction
            VTK color transfer function.

        Examples
        --------
        >>> import pyvista
        >>> lut = pyvista.LookupTable()
        >>> tf = lut.to_color_tf()
        >>> tf
        <vtkmodules.vtkRenderingCore.vtkColorTransferFunction(...) at ...>

        """
        color_tf = _vtk.vtkColorTransferFunction()
        mn, mx = self.scalar_range
        for ii, value in enumerate(np.linspace(mn, mx, self.n_values)):
            color_tf.AddRGBPoint(ii, *self.map_value(value, False))
        return color_tf

    def to_opacity_tf(self):
        """Return the opacity transfer function of this table.

        Returns
        -------
        vtk.vtkPiecewiseFunction
            Piecewise function of the opacity of this color table.

        Examples
        --------
        >>> import pyvista
        >>> lut = pyvista.LookupTable()
        >>> tf = lut.to_opacity_tf()
        >>> tf
        <vtkmodules.vtkCommonDataModel.vtkPiecewiseFunction(...) at ...>

        """
        opacity_tf = _vtk.vtkPiecewiseFunction()
        for ii, value in enumerate(self.values[:, 3]):
            opacity_tf.AddPoint(ii, value / self.n_values)
        return opacity_tf

    def map_value(self, value: float, opacity: bool = True) -> tuple:
        """Map a single value through the lookup table, returning an RBG(A) color.

        Parameters
        ----------
        value : float
            Scalar value to map to an RGB(A) color.

        opacity : bool, default: True
            Map the opacity as well.

        Returns
        -------
        tuple
            Mapped RGB(A) color.

        Examples
        --------
        >>> import pyvista
        >>> lut = pyvista.LookupTable()
        >>> rgba_color = lut.map_value(0.0)
        >>> rgba_color
        (1.0, 0.0, 0.0, 1.0)

        """
        color = [0.0, 0.0, 0.0]
        self.GetColor(value, color)
        if opacity:
            color.append(self.GetOpacity(value))
        return tuple(color)

    def __call__(self, value):
        """Implement a Matplotlib colormap-like call."""
        if isinstance(value, (int, float)):
            return self.map_value(value)
        else:
            try:
                return np.array([self.map_value(item) for item in value])
            except:
                raise TypeError('LookupTable __call__ expects a single value or an iterable.')


# pyvista/plotting/mapper.py

"""An internal module for wrapping the use of mappers."""
import sys
from typing import Optional, Union

import numpy as np

import pyvista as pv
from pyvista.core._typing_core import BoundsLike
from pyvista.core.utilities.arrays import (
    FieldAssociation,
    convert_array,
    convert_string_array,
    raise_not_matching,
)
from pyvista.core.utilities.helpers import wrap
from pyvista.core.utilities.misc import abstract_class, no_new_attr

from . import _vtk
from .colors import Color, get_cmap_safe
from .lookup_table import LookupTable
from .tools import normalize
from .utilities.algorithms import set_algorithm_input


@abstract_class
class _BaseMapper(_vtk.vtkAbstractMapper):
    """Base Mapper with methods common to other mappers."""

    _new_attr_exceptions = ('_theme',)

    def __init__(self, theme=None, **kwargs):
        self._theme = pv.themes.Theme()
        if theme is None:
            # copy global theme to ensure local property theme is fixed
            # after creation.
            self._theme.load_theme(pv.global_theme)
        else:
            self._theme.load_theme(theme)
        self.lookup_table = LookupTable()

        self.interpolate_before_map = kwargs.get(
            'interpolate_before_map', self._theme.interpolate_before_map
        )

    @property
    def bounds(self) -> BoundsLike:  # numpydoc ignore=RT01
        """Return the bounds of this mapper.

        Examples
        --------
        >>> import pyvista as pv
        >>> mapper = pv.DataSetMapper(dataset=pv.Cube())
        >>> mapper.bounds
        (-0.5, 0.5, -0.5, 0.5, -0.5, 0.5)

        """
        return self.GetBounds()

    def copy(self) -> '_BaseMapper':
        """Create a copy of this mapper.

        Returns
        -------
        pyvista.DataSetMapper
            A copy of this dataset mapper.

        Examples
        --------
        >>> import pyvista as pv
        >>> mapper = pv.DataSetMapper(dataset=pv.Cube())
        >>> mapper_copy = mapper.copy()

        """
        new_mapper = type(self)(theme=self._theme)
        # even though this uses ShallowCopy, the new mapper no longer retains
        # any connection with the original
        new_mapper.ShallowCopy(self)
        if hasattr(self, 'dataset'):
            new_mapper.dataset = self.dataset
        return new_mapper

    @property
    def scalar_range(self) -> tuple:  # numpydoc ignore=RT01
        """Return or set the scalar range.

        Examples
        --------
        Return the scalar range of a mapper.

        >>> import pyvista as pv
        >>> mesh = pv.Sphere()
        >>> pl = pv.Plotter()
        >>> actor = pl.add_mesh(mesh, scalars=mesh.points[:, 2])
        >>> actor.mapper.scalar_range
        (-0.5, 0.5)
        >>> pl.close()

        Return the scalar range of a composite dataset. In this example it's
        set to its default value of ``(0.0, 1.0)``.

        >>> import pyvista as pv
        >>> dataset = pv.MultiBlock(
        ...     [pv.Cube(), pv.Sphere(center=(0, 0, 1))]
        ... )
        >>> pl = pv.Plotter()
        >>> actor, mapper = pl.add_composite(dataset)
        >>> mapper.scalar_range
        (0.0, 1.0)
        >>> pl.close()

        """
        return self.GetScalarRange()

    @scalar_range.setter
    def scalar_range(self, clim):  # numpydoc ignore=GL08
        self.SetScalarRange(*clim)

    @property
    def lookup_table(self) -> 'pv.LookupTable':  # numpydoc ignore=RT01
        """Return or set the lookup table.

        Examples
        --------
        Return the lookup table of a dataset mapper.

        >>> import pyvista as pv
        >>> mesh = pv.Sphere()
        >>> pl = pv.Plotter()
        >>> actor = pl.add_mesh(
        ...     mesh, scalars=mesh.points[:, 2], cmap='bwr'
        ... )
        >>> actor.mapper.lookup_table
        LookupTable (...)
          Table Range:                (-0.5, 0.5)
          N Values:                   256
          Above Range Color:          None
          Below Range Color:          None
          NAN Color:                  Color(name='darkgray', hex='#a9a9a9ff', opacity=255)
          Log Scale:                  False
          Color Map:                  "bwr"

        Return the lookup table of a composite dataset mapper.

        >>> import pyvista as pv
        >>> dataset = pv.MultiBlock(
        ...     [pv.Cube(), pv.Sphere(center=(0, 0, 1))]
        ... )
        >>> pl = pv.Plotter()
        >>> actor, mapper = pl.add_composite(dataset)
        >>> mapper.lookup_table  # doctest:+SKIP
        <vtkmodules.vtkCommonCore.vtkLookupTable(...) at ...>

        """
        return self.GetLookupTable()

    @lookup_table.setter
    def lookup_table(self, table):  # numpydoc ignore=GL08
        self.SetLookupTable(table)

    @property
    def color_mode(self) -> str:  # numpydoc ignore=RT01
        """Return or set the color mode.

        Either ``'direct'``, or ``'map'``.

        * ``'direct'`` - All integer types are treated as colors with values in
          the range 0-255 and floating types are treated as colors with values
          in the range 0.0-1.0
        * ``'map'`` - All scalar data will be mapped through the lookup table.

        """
        mode = self.GetColorModeAsString().lower()
        if mode == 'mapscalars':
            return 'map'
        return 'direct'

    @color_mode.setter
    def color_mode(self, value: str):  # numpydoc ignore=GL08
        if value == 'direct':
            self.SetColorModeToDirectScalars()
        elif value == 'map':
            self.SetColorModeToMapScalars()
        else:
            raise ValueError('Color mode must be either "default", "direct" or "map"')

    @property
    def interpolate_before_map(self) -> bool:  # numpydoc ignore=RT01
        """Return or set the interpolation of scalars before mapping.

        Enabling makes for a smoother scalars display.  When ``False``,
        OpenGL will interpolate the mapped colors which can result in
        showing colors that are not present in the color map.

        Examples
        --------
        Disable interpolation before mapping.

        >>> import pyvista as pv
        >>> dataset = pv.MultiBlock(
        ...     [pv.Cube(), pv.Sphere(center=(0, 0, 1))]
        ... )
        >>> dataset[0].point_data['data'] = dataset[0].points[:, 2]
        >>> dataset[1].point_data['data'] = dataset[1].points[:, 2]
        >>> pl = pv.Plotter()
        >>> actor, mapper = pl.add_composite(
        ...     dataset,
        ...     show_scalar_bar=False,
        ...     n_colors=3,
        ...     cmap='bwr',
        ... )
        >>> mapper.interpolate_before_map = False
        >>> pl.show()

        Enable interpolation before mapping.

        >>> pl = pv.Plotter()
        >>> actor, mapper = pl.add_composite(
        ...     dataset,
        ...     show_scalar_bar=False,
        ...     n_colors=3,
        ...     cmap='bwr',
        ... )
        >>> mapper.interpolate_before_map = True
        >>> pl.show()

        See :ref:`interpolate_before_mapping_example` for additional
        explanation regarding this attribute.

        """
        return bool(self.GetInterpolateScalarsBeforeMapping())

    @interpolate_before_map.setter
    def interpolate_before_map(self, value: bool):  # numpydoc ignore=GL08
        self.SetInterpolateScalarsBeforeMapping(value)

    @property
    def array_name(self) -> str:  # numpydoc ignore=RT01
        """Return or set the array name or number and component to color by.

        Examples
        --------
        Show the name of the active scalars in the mapper.

        >>> import pyvista as pv
        >>> mesh = pv.Sphere()
        >>> mesh['my_scalars'] = mesh.points[:, 2]
        >>> pl = pv.Plotter()
        >>> actor = pl.add_mesh(mesh, scalars='my_scalars')
        >>> actor.mapper.array_name
        'my_scalars'
        >>> pl.close()

        """
        return self.GetArrayName()

    @array_name.setter
    def array_name(self, name: str):  # numpydoc ignore=GL08
        """Return or set the array name or number and component to color by."""
        self.SetArrayName(name)

    @property
    def scalar_map_mode(self) -> str:  # numpydoc ignore=RT01
        """Return or set the scalar map mode.

        Examples
        --------
        Show that the scalar map mode is set to ``'point'`` when setting the
        active scalars to point data.

        >>> import pyvista as pv
        >>> dataset = pv.MultiBlock(
        ...     [pv.Cube(), pv.Sphere(center=(0, 0, 1))]
        ... )
        >>> dataset[0].point_data['data'] = dataset[0].points[:, 2]
        >>> dataset[1].point_data['data'] = dataset[1].points[:, 2]
        >>> pl = pv.Plotter()
        >>> actor, mapper = pl.add_composite(
        ...     dataset, scalars='data', show_scalar_bar=False
        ... )
        >>> mapper.scalar_map_mode
        'point'
        >>> pl.close()

        """
        # map vtk strings to more sensible strings
        vtk_to_pv = {
            'Default': 'default',
            'UsePointData': 'point',
            'UseCellData': 'cell',
            'UsePointFieldData': 'point_field',
            'UseCellFieldData': 'cell_field',
            'UseFieldData': 'field',
        }
        return vtk_to_pv[self.GetScalarModeAsString()]

    @scalar_map_mode.setter
    def scalar_map_mode(self, scalar_mode: Union[str, FieldAssociation]):  # numpydoc ignore=GL08
        if isinstance(scalar_mode, FieldAssociation):
            scalar_mode = scalar_mode.name
        scalar_mode = scalar_mode.lower()  # type: ignore
        if scalar_mode == 'default':
            self.SetScalarModeToDefault()
        elif scalar_mode == 'point':
            self.SetScalarModeToUsePointData()
        elif scalar_mode == 'cell':
            self.SetScalarModeToUseCellData()
        elif scalar_mode == 'point_field':
            self.SetScalarModeToUsePointFieldData()
        elif scalar_mode == 'cell_field':
            self.SetScalarModeToUseCellFieldData()
        elif scalar_mode == 'field':
            self.SetScalarModeToUseFieldData()
        else:
            raise ValueError(
                f'Invalid `scalar_map_mode` "{scalar_mode}". Should be either '
                '"default", "point", "cell", "point_field", "cell_field" or "field".'
            )

    @property
    def scalar_visibility(self) -> bool:  # numpydoc ignore=RT01
        """Return or set the scalar visibility.

        Examples
        --------
        Show that scalar visibility is ``False``.

        >>> import pyvista as pv
        >>> mesh = pv.Sphere()
        >>> pl = pv.Plotter()
        >>> actor = pl.add_mesh(mesh)
        >>> actor.mapper.scalar_visibility
        False
        >>> pl.close()

        Show that scalar visibility is ``True``.

        >>> import pyvista as pv
        >>> dataset = pv.MultiBlock(
        ...     [pv.Cube(), pv.Sphere(center=(0, 0, 1))]
        ... )
        >>> dataset[0].point_data['data'] = dataset[0].points[:, 2]
        >>> dataset[1].point_data['data'] = dataset[1].points[:, 2]
        >>> pl = pv.Plotter()
        >>> actor, mapper = pl.add_composite(dataset, scalars='data')
        >>> mapper.scalar_visibility
        True
        >>> pl.close()

        """
        return bool(self.GetScalarVisibility())

    @scalar_visibility.setter
    def scalar_visibility(self, value: bool):  # numpydoc ignore=GL08
        return self.SetScalarVisibility(value)

    def update(self):
        """Update this mapper."""
        self.Update()


@no_new_attr
class DataSetMapper(_vtk.vtkDataSetMapper, _BaseMapper):
    """Wrap _vtk.vtkDataSetMapper.

    Parameters
    ----------
    dataset : pyvista.DataSet, optional
        Dataset to assign to this mapper.

    theme : pyvista.plotting.themes.Theme, optional
        Plot-specific theme.

    Examples
    --------
    Create a mapper outside :class:`pyvista.Plotter` and assign it to an
    actor.

    >>> import pyvista as pv
    >>> mesh = pv.Cube()
    >>> mapper = pv.DataSetMapper(dataset=mesh)
    >>> actor = pv.Actor(mapper=mapper)
    >>> actor.plot()

    """

    _cmap = None

    def __init__(
        self,
        dataset: Optional['pv.DataSet'] = None,
        theme: Optional['pv.themes.Theme'] = None,
    ):
        """Initialize this class."""
        super().__init__(theme=theme)
        if dataset is not None:
            self.dataset = dataset

    @property
    def dataset(self) -> Optional['pv.core.dataset.DataSet']:  # numpydoc ignore=RT01
        """Return or set the dataset assigned to this mapper."""
        return wrap(self.GetInputAsDataSet())

    @dataset.setter
    def dataset(
        self, obj: Union['pv.core.dataset.DataSet', _vtk.vtkAlgorithm, _vtk.vtkAlgorithmOutput]
    ):  # numpydoc ignore=GL08
        set_algorithm_input(self, obj)

    def as_rgba(self):  # numpydoc ignore=GL08
        """Convert the active scalars to RGBA.

        This method is used to convert the active scalars to a fixed RGBA array
        and is used for certain mappers that do not support the "map" color
        mode.

        """
        if self.color_mode == 'direct':
            return

        self.dataset.point_data.pop('__rgba__', None)
        self._configure_scalars_mode(
            self.lookup_table(self.dataset.active_scalars),
            '__rgba__',
            self.scalar_map_mode,
            True,
        )

    def _configure_scalars_mode(
        self,
        scalars,
        scalars_name,
        preference,
        direct_scalars_color_mode,
    ):
        """Configure scalar mode.

        Parameters
        ----------
        scalars : numpy.ndarray
            Array of scalars to assign to the mapper.

        scalars_name : str
            If the name of this array exists, scalars is ignored. Otherwise,
            the scalars will be added to the existing dataset and this
            parameter is the name to assign the scalars.

        preference : str
            Either ``'point'`` or ``'cell'``.

        direct_scalars_color_mode : bool
            When ``True``, scalars are treated as RGB colors. When
            ``False``, scalars are mapped to the color table.

        """
        if scalars.shape[0] == self.dataset.n_points and scalars.shape[0] == self.dataset.n_cells:
            use_points = preference == 'point'
            use_cells = not use_points
        else:
            use_points = scalars.shape[0] == self.dataset.n_points
            use_cells = scalars.shape[0] == self.dataset.n_cells

        # Scalars interpolation approach
        if use_points:
            if (
                scalars_name not in self.dataset.point_data
                or scalars_name == pv.DEFAULT_SCALARS_NAME
            ):
                self.dataset.point_data.set_array(scalars, scalars_name, False)
            self.dataset.active_scalars_name = scalars_name
            self.scalar_map_mode = 'point'
        elif use_cells:
            if (
                scalars_name not in self.dataset.cell_data
                or scalars_name == pv.DEFAULT_SCALARS_NAME
            ):
                self.dataset.cell_data.set_array(scalars, scalars_name, False)
            self.dataset.active_scalars_name = scalars_name
            self.scalar_map_mode = 'cell'
        else:
            raise_not_matching(scalars, self.dataset)

        self.color_mode = 'direct' if direct_scalars_color_mode else 'map'

    def set_scalars(
        self,
        scalars,
        scalars_name,
        n_colors=256,
        scalar_bar_args=None,
        rgb=None,
        component=None,
        preference='point',
        custom_opac=False,
        annotations=None,
        log_scale=False,
        nan_color=None,
        above_color=None,
        below_color=None,
        cmap=None,
        flip_scalars=False,
        opacity=None,
        categories=False,
        clim=None,
    ):
        """Set the scalars on this mapper.

        Parameters
        ----------
        scalars : numpy.ndarray
            Array of scalars to assign to the mapper.

        scalars_name : str
            If the name of this array exists, scalars is ignored. Otherwise,
            the scalars will be added to the existing dataset and this
            parameter is the name to assign the scalars.

        n_colors : int, default: 256
            Number of colors to use when displaying scalars.

        scalar_bar_args : dict, optional
            Dictionary of keyword arguments to pass when adding the
            scalar bar to the scene. For options, see
            :func:`pyvista.Plotter.add_scalar_bar`.

        rgb : bool, default: False
            If an 2 dimensional array is passed as the scalars, plot
            those values as RGB(A) colors. ``rgba`` is also an
            accepted alias for this.  Opacity (the A) is optional.  If
            a scalars array ending with ``"_rgba"`` is passed, the default
            becomes ``True``.  This can be overridden by setting this
            parameter to ``False``.

        component : int, optional
            Set component of vector valued scalars to plot.  Must be
            nonnegative, if supplied. If ``None``, the magnitude of
            the vector is plotted.

        preference : str, default: 'Point'
            When ``dataset.n_points == dataset.n_cells`` and setting scalars,
            this parameter sets how the scalars will be mapped to the mesh.
            Can be either ``'point'`` or ``'cell'``.

        custom_opac : bool, default: False
            Use custom opacity.

        annotations : dict, optional
            Pass a dictionary of annotations. Keys are the float
            values in the scalars range to annotate on the scalar bar
            and the values are the string annotations.

        log_scale : bool, default: False
            Use log scale when mapping data to colors. Scalars less
            than zero are mapped to the smallest representable
            positive float.

        nan_color : pyvista.ColorLike, optional
            The color to use for all ``NaN`` values in the plotted
            scalar array.

        above_color : pyvista.ColorLike, optional
            Solid color for values below the scalars range
            (``clim``). This will automatically set the scalar bar
            ``above_label`` to ``'above'``.

        below_color : pyvista.ColorLike, optional
            Solid color for values below the scalars range
            (``clim``). This will automatically set the scalar bar
            ``below_label`` to ``'below'``.

        cmap : str, list, or pyvista.LookupTable
            Name of the Matplotlib colormap to use when mapping the
            ``scalars``.  See available Matplotlib colormaps.  Only applicable
            for when displaying ``scalars``.
            ``colormap`` is also an accepted alias for this. If
            ``colorcet`` or ``cmocean`` are installed, their colormaps can be
            specified by name.

            You can also specify a list of colors to override an existing
            colormap with a custom one.  For example, to create a three color
            colormap you might specify ``['green', 'red', 'blue']``.

            This parameter also accepts a :class:`pyvista.LookupTable`. If this
            is set, all parameters controlling the color map like ``n_colors``
            will be ignored.

        flip_scalars : bool, default: False
            Flip direction of cmap. Most colormaps allow ``*_r`` suffix to do
            this as well.

        opacity : str or numpy.ndarray, optional
            Opacity mapping for the scalars array.
            A string can also be specified to map the scalars range to a
            predefined opacity transfer function (options include: 'linear',
            'linear_r', 'geom', 'geom_r'). Or you can pass a custom made
            transfer function that is an array either ``n_colors`` in length or
            shorter.

        categories : bool, default: False
            If set to ``True``, then the number of unique values in the scalar
            array will be used as the ``n_colors`` argument.

        clim : Sequence, optional
            Color bar range for scalars.  Defaults to minimum and
            maximum of scalars array.  Example: ``(-1, 2)``.

        """
        if scalar_bar_args is None:
            scalar_bar_args = {'n_colors': n_colors}

        if not isinstance(scalars, np.ndarray):
            scalars = np.asarray(scalars)

        # Set the array title for when it is added back to the mesh
        if custom_opac:
            scalars_name = '__custom_rgba'

        if not np.issubdtype(scalars.dtype, np.number) and not isinstance(cmap, pv.LookupTable):
            # we can rapidly handle bools
            if scalars.dtype == np.bool_:
                cats = np.array([b'False', b'True'], dtype='|S5')
                values = np.array([0, 1])
                clim = [-0.5, 1.5]
            else:
                # If str array, digitize and annotate
                cats, scalars = np.unique(scalars.astype('|S'), return_inverse=True)
                values = np.unique(scalars)
                clim = [np.min(values) - 0.5, np.max(values) + 0.5]
                scalars_name = f'{scalars_name}-digitized'

            n_colors = len(cats)
            scalar_bar_args.setdefault('n_labels', 0)

            self.lookup_table.SetAnnotations(convert_array(values), convert_string_array(cats))

        # Use only the real component if an array is complex
        if np.issubdtype(scalars.dtype, np.complexfloating):
            scalars = scalars.astype(float)
            scalars_name = f'{scalars_name}-real'

        if scalars.ndim != 1:
            if rgb:
                pass
            elif scalars.ndim == 2 and (
                scalars.shape[0] == self.dataset.n_points
                or scalars.shape[0] == self.dataset.n_cells
            ):
                if not isinstance(component, (int, type(None))):
                    raise TypeError('component must be either None or an integer')
                if component is None:
                    scalars = np.linalg.norm(scalars.copy(), axis=1)
                    scalars_name = f'{scalars_name}-normed'
                elif component < scalars.shape[1] and component >= 0:
                    scalars = np.array(scalars[:, component]).copy()
                    scalars_name = f'{scalars_name}-{component}'
                else:
                    raise ValueError(
                        'Component must be nonnegative and less than the '
                        f'dimensionality of the scalars array: {scalars.shape[1]}'
                    )
            else:
                scalars = scalars.ravel()

        if scalars.dtype == np.bool_:
            scalars = scalars.astype(np.float_)

        # Set scalars range
        if clim is None:
            clim = [np.nanmin(scalars), np.nanmax(scalars)]
        elif isinstance(clim, (int, float)):
            clim = [-clim, clim]

        if log_scale:
            if clim[0] <= 0:
                clim = [sys.float_info.min, clim[1]]

        if np.any(clim) and not rgb:
            self.scalar_range = clim[0], clim[1]

        if isinstance(cmap, pv.LookupTable):
            self.lookup_table = cmap
            self.scalar_range = self.lookup_table.scalar_range
        else:
            self.lookup_table.scalar_range = self.scalar_range
            # Set default map
            if cmap is None:
                if self._theme is None:
                    cmap = pv.global_theme.cmap
                else:
                    cmap = self._theme.cmap

            # have to add the attribute to pass it onward to some classes
            if isinstance(cmap, str):
                self._cmap = cmap
            if categories:
                if categories is True:
                    n_colors = len(np.unique(scalars))
                elif isinstance(categories, int):
                    n_colors = categories

            self.lookup_table.apply_cmap(cmap, n_colors)

            # Set opactities
            if isinstance(opacity, np.ndarray) and not custom_opac:
                self.lookup_table.apply_opacity(opacity)

            if flip_scalars:
                self.lookup_table.values[:] = self.lookup_table.values[::-1]

            if custom_opac:
                # need to round the colors here since we're
                # directly displaying the colors
                hue = normalize(scalars, minimum=clim[0], maximum=clim[1])
                scalars = np.round(hue * n_colors) / n_colors
                scalars = get_cmap_safe(cmap)(scalars) * 255
                scalars[:, -1] *= opacity
                scalars = scalars.astype(np.uint8)

            # configure the lookup table
            if nan_color:
                self.lookup_table.nan_color = nan_color
            if above_color:
                self.lookup_table.above_range_color = above_color
                scalar_bar_args.setdefault('above_label', 'above')
            if below_color:
                self.lookup_table.below_range_color = below_color
                scalar_bar_args.setdefault('below_label', 'below')
            if isinstance(annotations, dict):
                self.lookup_table.annotations = annotations
            self.lookup_table.log_scale = log_scale

        self._configure_scalars_mode(
            scalars,
            scalars_name,
            preference,
            rgb or custom_opac,
        )

        if isinstance(self, PointGaussianMapper):
            self.as_rgba()

    @property
    def cmap(self) -> Optional[str]:  # numpydoc ignore=RT01
        """Colormap assigned to this mapper."""
        return self._cmap

    def set_custom_opacity(self, opacity, color, n_colors, preference='point'):
        """Set custom opacity.

        Parameters
        ----------
        opacity : numpy.ndarray
            Opacity array to color the dataset. Array length must match either
            the number of points or cells.

        color : pyvista.ColorLike
            The color to use with the opacity array.

        n_colors : int
            Number of colors to use.

        preference : str, default: 'point'
            Either ``'point'`` or ``'cell'``. Used when the number of cells
            matches the number of points.

        """
        # Create a custom RGBA array to supply our opacity to
        if opacity.size == self.dataset.n_points:
            rgba = np.empty((self.dataset.n_points, 4), np.uint8)
        elif opacity.size == self.dataset.n_cells:
            rgba = np.empty((self.dataset.n_cells, 4), np.uint8)
        else:  # pragma: no cover
            raise ValueError(
                f"Opacity array size ({opacity.size}) does not equal "
                f"the number of points ({self.dataset.n_points}) or the "
                f"number of cells ({self.dataset.n_cells})."
            )

        if self._theme is not None:
            default_color = self._theme.color
        else:
            default_color = pv.global_theme.color

        rgba[:, :-1] = Color(color, default_color=default_color).int_rgb
        rgba[:, -1] = np.around(opacity * 255)

        self.color_mode = 'direct'
        self.lookup_table.n_values = n_colors
        self._configure_scalars_mode(rgba, '', preference, True)

    def __repr__(self):
        """Representation of the mapper."""
        mapper_attr = [
            f'{type(self).__name__} ({hex(id(self))})',
            f'  Scalar visibility:           {self.scalar_visibility}',
            f'  Scalar range:                {self.scalar_range}',
            f'  Interpolate before mapping:  {self.interpolate_before_map}',
            f'  Scalar map mode:             {self.scalar_map_mode}',
            f'  Color mode:                  {self.color_mode}',
            '',
        ]

        mapper_attr.append('Attached dataset:')
        mapper_attr.append(str(self.dataset))

        return '\n'.join(mapper_attr)


@no_new_attr
class PointGaussianMapper(_vtk.vtkPointGaussianMapper, DataSetMapper):
    """Wrap vtkPointGaussianMapper.

    Parameters
    ----------
    theme : pyvista.Theme, optional
        The theme to be used.
    emissive : bool, optional
        Whether or not the point should appear emissive. Default is set by the
        theme's ``lighting_params.emissive``.
    scale_factor : float, default: 1.0
        Scale factor applied to the point size.

    """

    def __init__(self, theme=None, emissive=None, scale_factor=1.0) -> None:
        super().__init__(theme=theme)
        if emissive is None:
            emissive = self._theme.lighting_params.emissive
        self.emissive = emissive
        self.scale_factor = scale_factor

    @property
    def emissive(self) -> bool:  # numpydoc ignore=RT01
        """Set or return emissive.

        This treats points as emissive light sources. Two points that overlap
        will have their brightness combined.
        """
        return bool(self.GetEmissive())

    @emissive.setter
    def emissive(self, value: bool):  # numpydoc ignore=GL08
        return self.SetEmissive(value)

    @property
    def scale_factor(self) -> float:  # numpydoc ignore=RT01
        """Set or return the scale factor.

        Ranges from 0 to 1. A value of 0 will cause the splats to be rendered
        as simple points. Defaults to 1.0.

        """
        return self.GetScaleFactor()

    @scale_factor.setter
    def scale_factor(self, value: float):  # numpydoc ignore=GL08
        return self.SetScaleFactor(value)

    def use_circular_splat(self, opacity: float = 1.0):
        """Set the fragment shader code to create a circular splat.

        Parameters
        ----------
        opacity : float, default: 1.0
            Desired opacity between 0 and 1.

        Notes
        -----
        This very close to ParaView's PointGaussianMapper, but uses opacity to
        modify the scale as the opacity cannot be set from the actor's property.
        """
        self.SetSplatShaderCode(
            "//VTK::Color::Impl\n"
            "float dist = dot(offsetVCVSOutput.xy,offsetVCVSOutput.xy);\n"
            "if (dist > 1.0) {\n"
            "  discard;\n"
            "} else {\n"
            f"  float scale = ({opacity} - dist);\n"
            "  ambientColor *= scale;\n"
            "  diffuseColor *= scale;\n"
            "}\n"
        )
        # maintain consistency with the default style
        self.emissive = True
        self.scale_factor *= 1.5

    def use_default_splat(self):
        """Clear the fragment shader and use the default splat."""
        self.SetSplatShaderCode(None)
        self.scale_factor /= 1.5

    def __repr__(self):
        """Representation of the Gaussian mapper."""
        mapper_attr = [
            f'{type(self).__name__} ({hex(id(self))})',
            f'  Scalar visibility:           {self.scalar_visibility}',
            f'  Scalar range:                {self.scalar_range}',
            f'  Emissive:                    {self.emissive}',
            f'  Scale Factor:                {self.scale_factor}',
            f'  Using custom splat:          {self.GetSplatShaderCode() is None}',
            '',
        ]

        mapper_attr.append('Attached dataset:')
        mapper_attr.append(str(self.dataset))

        return '\n'.join(mapper_attr)


@abstract_class
class _BaseVolumeMapper(_BaseMapper):
    """Volume mapper class to override methods and attributes for to volume mappers."""

    def __init__(self, theme=None):
        """Initialize this class."""
        super().__init__(theme=theme)
        self._lut = LookupTable()
        self._scalar_range = (0.0, 256.0)

    @property
    def interpolate_before_map(self):  # numpydoc ignore=RT01
        """Interpolate before map is not supported with volume mappers."""
        return None

    @interpolate_before_map.setter
    def interpolate_before_map(self, *args):  # numpydoc ignore=GL08
        pass

    @property
    def dataset(self):  # numpydoc ignore=RT01
        """Return or set the dataset assigned to this mapper."""
        # GetInputAsDataSet unavailable on volume mappers
        return wrap(self.GetDataSetInput())

    @dataset.setter
    def dataset(
        self, obj: Union['pv.core.dataset.DataSet', _vtk.vtkAlgorithm, _vtk.vtkAlgorithmOutput]
    ):
        set_algorithm_input(self, obj)

    @property
    def lookup_table(self):  # numpydoc ignore=GL08  # numpydoc ignore=RT01
        return self._lut

    @lookup_table.setter
    def lookup_table(self, lut):  # numpydoc ignore=GL08
        self._lut = lut

    @property
    def scalar_range(self) -> tuple:  # numpydoc ignore=RT01
        """Return or set the scalar range."""
        return self._scalar_range

    @scalar_range.setter
    def scalar_range(self, clim):  # numpydoc ignore=GL08
        if self.lookup_table is not None:
            self.lookup_table.SetRange(*clim)
        self._scalar_range = tuple(clim)

    @property
    def blend_mode(self) -> str:  # numpydoc ignore=RT01
        """Return or set the blend mode.

        One of the following:

        * ``"composite"``
        * ``"maximum"``
        * ``"minimum"``
        * ``"average"``
        * ``"additive"``

        Also accepts integer values corresponding to
        ``vtk.vtkVolumeMapper.BlendModes``. For example
        ``vtk.vtkVolumeMapper.COMPOSITE_BLEND``.

        """
        value = self.GetBlendMode()
        if value == 0:
            return 'composite'
        elif value == 1:
            return 'maximum'
        elif value == 2:
            return 'minimum'
        elif value == 3:
            return 'average'
        elif value == 4:
            return 'additive'

        raise NotImplementedError(
            f'Unsupported blend mode return value {value}'
        )  # pragma: no cover

    @blend_mode.setter
    def blend_mode(self, value: Union[str, int]):  # numpydoc ignore=GL08
        if isinstance(value, int):
            self.SetBlendMode(value)
        elif isinstance(value, str):
            value = value.lower()
            if value in ['additive', 'add', 'sum']:
                self.SetBlendModeToAdditive()
            elif value in ['average', 'avg', 'average_intensity']:
                self.SetBlendModeToAverageIntensity()
            elif value in ['composite', 'comp']:
                self.SetBlendModeToComposite()
            elif value in ['maximum', 'max', 'maximum_intensity']:
                self.SetBlendModeToMaximumIntensity()
            elif value in ['minimum', 'min', 'minimum_intensity']:
                self.SetBlendModeToMinimumIntensity()
            else:
                raise ValueError(
                    f'Blending mode {value!r} invalid. '
                    'Please choose either "additive", '
                    '"composite", "minimum" or "maximum".'
                )
        else:
            raise TypeError(f'`blend_mode` should be either an int or str, not `{type(value)}`')

    def __del__(self):
        self._lut = None


class FixedPointVolumeRayCastMapper(_vtk.vtkFixedPointVolumeRayCastMapper, _BaseVolumeMapper):
    """Wrap _vtk.vtkFixedPointVolumeRayCastMapper."""

    pass


class GPUVolumeRayCastMapper(_vtk.vtkGPUVolumeRayCastMapper, _BaseVolumeMapper):
    """Wrap _vtk.vtkGPUVolumeRayCastMapper."""

    pass


class OpenGLGPUVolumeRayCastMapper(_vtk.vtkOpenGLGPUVolumeRayCastMapper, _BaseVolumeMapper):
    """Wrap _vtk.vtkOpenGLGPUVolumeRayCastMapper."""

    pass


class SmartVolumeMapper(_vtk.vtkSmartVolumeMapper, _BaseVolumeMapper):
    """Wrap _vtk.vtkSmartVolumeMapper."""

    pass


class UnstructuredGridVolumeRayCastMapper(
    _vtk.vtkUnstructuredGridVolumeRayCastMapper, _BaseVolumeMapper
):
    """Wrap _vtk.vtkUnstructuredGridVolumeMapper."""

    pass


# pyvista/plotting/opts.py

"""Module with enum options classes for plotting."""
from pyvista.core.utilities.misc import AnnotatedIntEnum


class InterpolationType(AnnotatedIntEnum):
    """Lighting interpolation types.

    Attributes
    ----------
    FLAT : (int, str)
        Flat interpolation type.
    GOURAUD : (int, str)
        Gouraud interpolation type.
    PHONG : (int, str)
        Phong interpolation type.
    PBR : (int, str)
        Physically based rendering interpolation type.

    """

    FLAT = (0, 'Flat')
    GOURAUD = (1, 'Gouraud')
    PHONG = (2, 'PHONG')
    PBR = (3, 'Physically based rendering')

    @classmethod
    def from_str(cls, input_str):
        """Create from string.

        Create an instance of InterpolationType from a string.

        Parameters
        ----------
        input_str : str
            The string representation of the interpolation type.  Accepts
            aliases such as ``'pbr'`` for ``'Physically based rendering'``.

        Returns
        -------
        InterpolationType
            Interpolation type as defined by the input string.

        """
        aliases = {
            'pbr': 'Physically based rendering',
        }
        if input_str in aliases:
            input_str = aliases[input_str]
        return super().from_str(input_str)


class RepresentationType(AnnotatedIntEnum):
    """Types of representations the models can have."""

    POINTS = (0, 'Points')
    WIREFRAME = (1, 'Wireframe')
    SURFACE = (2, 'Surface')


class ElementType(AnnotatedIntEnum):
    """Types of elemental geometries."""

    MESH = (0, 'Mesh')
    CELL = (1, 'Cell')
    FACE = (2, 'Face')
    EDGE = (3, 'Edge')
    POINT = (4, 'Point')


class PickerType(AnnotatedIntEnum):
    """Types of pickers."""

    AREA = (0, 'Area')
    CELL = (1, 'Cell')
    HARDWARE = (2, 'Hardware')
    POINT = (3, 'Point')
    PROP = (4, 'Prop')
    RENDERED = (5, 'Rendered')
    RESLICE = (6, 'Reslice')
    SCENE = (7, 'Scene')
    VOLUME = (8, 'Volume')
    WORLD = (9, 'World')


# pyvista/plotting/picking.py

"""Module managing picking events."""
from functools import partial, wraps
from typing import Tuple
import warnings
import weakref

import numpy as np

import pyvista
from pyvista.core.errors import PyVistaDeprecationWarning
from pyvista.core.utilities.misc import try_callback

from . import _vtk
from .composite_mapper import CompositePolyDataMapper
from .errors import PyVistaPickingError
from .opts import ElementType, PickerType

PICKED_REPRESENTATION_NAMES = {
    'point': '_picked_point',
    'mesh': '_picked_mesh',
    'through': '_picked_through_selection',
    'visible': '_picked_visible_selection',
    'element': '_picked_element',
    'path': '_picked_path',
    'horizon': '_picked_horizon',
    'frustum': '_rectangle_selection_frustum',
}


def _launch_pick_event(interactor, event):
    """Create a Pick event based on coordinate or left-click."""
    click_x, click_y = interactor.GetEventPosition()
    click_z = 0

    picker = interactor.GetPicker()
    renderer = interactor.GetInteractorStyle()._parent()._plotter.iren.get_poked_renderer()
    picker.Pick(click_x, click_y, click_z, renderer)


def _poked_context_callback(plotter, *args, **kwargs):
    """Use _poked_context_callback in a poked renderer context."""
    with plotter.iren.poked_subplot():
        try_callback(*args, **kwargs)


class RectangleSelection:
    """Internal data structure for rectangle based selections.

    Parameters
    ----------
    frustum : _vtk.vtkPlanes
        Frustum that defines the selection.
    viewport : Tuple[float, float, float, float]
        The selected viewport coordinates, given as ``(x0, y0, x1, y1)``.

    """

    def __init__(self, frustum, viewport):
        self._frustum = frustum
        self._viewport = viewport

    @property
    def frustum(self) -> _vtk.vtkPlanes:  # numpydoc ignore=RT01
        """Get the selected frustum through the scene."""
        return self._frustum

    @property
    def frustum_mesh(self) -> 'pyvista.PolyData':  # numpydoc ignore=RT01
        """Get the frustum as a PyVista mesh."""
        frustum_source = _vtk.vtkFrustumSource()
        frustum_source.ShowLinesOff()
        frustum_source.SetPlanes(self.frustum)
        frustum_source.Update()
        return pyvista.wrap(frustum_source.GetOutput())

    @property
    def viewport(self) -> Tuple[float, float, float, float]:  # numpydoc ignore=RT01
        """Get the selected viewport coordinates.

        Coordinates are given as: ``(x0, y0, x1, y1)``
        """
        return self._viewport


class PointPickingElementHandler:
    """Internal picking handler for element-based picking.

    This handler is only valid for single point picking operations.

    Parameters
    ----------
    mode : ElementType, optional
        The element type to pick.
    callback : callable, optional
        A callback function to be executed on picking events.
    """

    def __init__(self, mode: ElementType = ElementType.CELL, callback=None):
        self._picker_ = None
        self.callback = callback
        self.mode = ElementType.from_any(mode)

    @property
    def picker(self):  # numpydoc ignore=RT01
        """Get or set the picker instance."""
        return self._picker_()

    @picker.setter
    def picker(self, picker):  # numpydoc ignore=GL08
        self._picker_ = weakref.ref(picker)

    def get_mesh(self):
        """Get the picked mesh.

        Returns
        -------
        pyvista.DataSet
            Picked mesh.

        """
        ds = self.picker.GetDataSet()
        if ds is not None:
            return pyvista.wrap(ds)

    def get_cell(self, picked_point):
        """Get the picked cell of the picked mesh.

        Parameters
        ----------
        picked_point : sequence[float]
            Coordinates of the picked point.

        Returns
        -------
        pyvista.UnstructuredGrid
            UnstructuredGrid containing the picked cell.

        """
        mesh = self.get_mesh()
        # cell_id = self.picker.GetCellId()
        cell_id = mesh.find_containing_cell(picked_point)  # more accurate
        if cell_id < 0:
            return  # TODO: this happens but shouldn't
        cell = mesh.extract_cells(cell_id)
        cell.cell_data['vtkOriginalCellIds'] = np.array([cell_id])
        return cell

    def get_face(self, picked_point):
        """Get the picked face of the picked cell.

        Parameters
        ----------
        picked_point : sequence[float]
            Coordinates of the picked point.

        Returns
        -------
        pyvista.UnstructuredGrid
            UnstructuredGrid containing the picked face.

        """
        cell = self.get_cell(picked_point).get_cell(0)
        if cell.n_faces > 1:
            for i, face in enumerate(cell.faces):
                contains = face.cast_to_unstructured_grid().find_containing_cell(picked_point)
                if contains > -1:
                    break
            if contains < 0:
                # this shouldn't happen
                raise RuntimeError('Trouble aligning point with face.')
            face = face.cast_to_unstructured_grid()
            face.field_data['vtkOriginalFaceIds'] = np.array([i])
        else:
            face = cell.cast_to_unstructured_grid()
            face.field_data['vtkOriginalFaceIds'] = np.array([0])

        return face

    def get_edge(self, picked_point):
        """Get the picked edge of the picked cell.

        Parameters
        ----------
        picked_point : sequence[float]
            Coordinates of the picked point.

        Returns
        -------
        pyvista.UnstructuredGrid
            UnstructuredGrid containing the picked edge.

        """
        cell = self.get_cell(picked_point).get_cell(0)
        if cell.n_edges > 1:
            ei = (
                cell.cast_to_unstructured_grid().extract_all_edges().find_closest_cell(picked_point)
            )
            edge = cell.edges[ei].cast_to_unstructured_grid()
            edge.field_data['vtkOriginalEdgeIds'] = np.array([ei])
        else:
            edge = cell.cast_to_unstructured_grid()

        return edge

    def get_point(self, picked_point):
        """Get the picked point of the picked mesh.

        Parameters
        ----------
        picked_point : sequence[float]
            Coordinates of the picked point.

        Returns
        -------
        pyvista.PolyData
            Picked mesh containing the point.

        """
        mesh = self.get_mesh()
        pid = mesh.find_closest_point(picked_point)
        picked = pyvista.PolyData(mesh.points[pid])
        picked.point_data['vtkOriginalPointIds'] = np.array([pid])
        return picked

    def __call__(self, picked_point, picker):
        """Perform the pick."""
        self.picker = picker
        mesh = self.get_mesh()
        if mesh is None:
            return  # No selected mesh (point not on surface of mesh)

        if self.mode == ElementType.MESH:
            picked = mesh
        elif self.mode == ElementType.CELL:
            picked = self.get_cell(picked_point)
            if picked is None:
                return  # TODO: handle
        elif self.mode == ElementType.FACE:
            picked = self.get_face(picked_point)
        elif self.mode == ElementType.EDGE:
            picked = self.get_edge(picked_point)
        elif self.mode == ElementType.POINT:
            picked = self.get_point(picked_point)

        if self.callback:
            try_callback(self.callback, picked)


class PickingInterface:  # numpydoc ignore=PR01
    """An internal class to hold core picking related features."""

    def __init__(self, *args, **kwargs):
        """Initialize the picking interface."""
        super().__init__(*args, **kwargs)
        self._picking_left_clicking_observer = None
        self._picking_right_clicking_observer = None
        self._picker_in_use = False
        self._picked_point = None

    def _clear_picking_representations(self):
        """Clear all picking representations."""
        for name in PICKED_REPRESENTATION_NAMES.values():
            self.remove_actor(name)

    @property
    def picked_point(self):  # numpydoc ignore=RT01
        """Return the picked point.

        This returns the picked point after selecting a point.

        Returns
        -------
        numpy.ndarray or None
            Picked point if available.

        """
        return self._picked_point

    def get_pick_position(self):
        """Get the pick position or area.

        Returns
        -------
        sequence
            Picked position or area as ``(x0, y0, x1, y1)``.

        """
        renderer = self.iren.get_poked_renderer()
        return renderer.get_pick_position()

    def pick_click_position(self):
        """Get corresponding click location in the 3D plot.

        Returns
        -------
        tuple
            Three item tuple with the 3D picked position.

        """
        if self.click_position is None:
            self.store_click_position()
        renderer = self.iren.get_poked_renderer()
        self.iren.picker.Pick(self.click_position[0], self.click_position[1], 0, renderer)
        return self.iren.picker.GetPickPosition()

    def pick_mouse_position(self):
        """Get corresponding mouse location in the 3D plot.

        Returns
        -------
        tuple
            Three item tuple with the 3D picked position.

        """
        if self.mouse_position is None:
            self.store_mouse_position()
        renderer = self.iren.get_poked_renderer()
        self.iren.picker.Pick(self.mouse_position[0], self.mouse_position[1], 0, renderer)
        return self.iren.picker.GetPickPosition()

    def _init_click_picking_callback(self, left_clicking=False):
        if left_clicking:
            self._picking_left_clicking_observer = self.iren.add_observer(
                "LeftButtonPressEvent",
                partial(try_callback, _launch_pick_event),
            )
        else:
            self._picking_right_clicking_observer = self.iren.add_observer(
                "RightButtonPressEvent",
                partial(try_callback, _launch_pick_event),
            )

    def disable_picking(self):
        """Disable any active picking and remove observers.

        Examples
        --------
        Enable and then disable picking.

        >>> import pyvista as pv
        >>> mesh = pv.Sphere(center=(1, 0, 0))
        >>> cube = pv.Cube()
        >>> pl = pv.Plotter()
        >>> _ = pl.add_mesh(mesh)
        >>> _ = pl.add_mesh(cube)
        >>> _ = pl.enable_mesh_picking()
        >>> pl.disable_picking()

        """
        # remove left and right clicking observer if available
        if getattr(self, 'iren', None):
            self.iren.remove_observer(self._picking_left_clicking_observer)
            self.iren.remove_observer(self._picking_right_clicking_observer)
            # Reset to default picker
            self.iren.reset_picker()
        self._picking_left_clicking_observer = None
        self._picking_right_clicking_observer = None

        self._picker_in_use = False

    def _validate_picker_not_in_use(self):
        if self._picker_in_use:
            raise PyVistaPickingError(
                'Picking is already enabled, please disable previous picking with `disable_picking()`.'
            )

    def enable_point_picking(
        self,
        callback=None,
        tolerance=0.025,
        left_clicking=False,
        picker=PickerType.POINT,
        show_message=True,
        font_size=18,
        color='pink',
        point_size=10,
        show_point=True,
        use_picker=False,
        pickable_window=False,
        clear_on_no_selection=True,
        **kwargs,
    ):
        """Enable picking at points under the cursor.

        Enable picking a point at the mouse location in the render
        view using the right mouse button. This point is saved to the
        ``.picked_point`` attribute on the plotter. Pass a callback
        that takes that point as an argument. The picked
        point can either be a point on the first intersecting mesh, or
        a point in the 3D window.

        The ``picker`` choice will help determine how the point picking
        is performed.

        Parameters
        ----------
        callback : callable, optional
            When input, calls this callable after a pick is made. The
            picked point is input as the first parameter to this
            callable.

        tolerance : float, tolerance: 0.025
            Specify tolerance for performing pick operation. Tolerance
            is specified as fraction of rendering window
            size. Rendering window size is measured across diagonal.
            This is only valid for some choices of ``picker``.

        left_clicking : bool, default: False
            When ``True``, points can be picked by clicking the left mouse
            button. Default is to use the right mouse button.

        picker : str | PickerType, optional
            Choice of VTK picker class type:

                * ``'hardware'``: Uses ``vtkHardwarePicker`` which is more
                  performant for large geometries (default).
                * ``'cell'``: Uses ``vtkCellPicker``.
                * ``'point'``: Uses ``vtkPointPicker`` which will snap to
                  points on the surface of the mesh.
                * ``'volume'``: Uses ``vtkVolumePicker``.

        show_message : bool | str, default: True
            Show the message about how to use the point picking
            tool. If this is a string, that will be the message shown.

        font_size : int, default: 18
            Sets the size of the message.

        color : ColorLike, default: "pink"
            The color of the selected mesh when shown.

        point_size : int, default: 10
            Size of picked points if ``show_point`` is ``True``.

        show_point : bool, default: True
            Show the picked point after clicking.

        use_picker : bool, default: False
            When ``True``, the callback will also be passed the picker.

        pickable_window : bool, default: False
            When ``True`` and the chosen picker supports it, points in the
            3D window are pickable.

        clear_on_no_selection : bool, default: True
            Clear the selections when no point is selected.

        **kwargs : dict, optional
            All remaining keyword arguments are used to control how
            the picked point is interactively displayed.

        Examples
        --------
        Enable point picking with a custom message.

        >>> import pyvista as pv
        >>> pl = pv.Plotter()
        >>> _ = pl.add_mesh(pv.Sphere())
        >>> _ = pl.add_mesh(pv.Cube(), pickable=False)
        >>> pl.enable_point_picking(show_message='Pick a point')

        See :ref:`point_picking_example` for a full example using this method.

        """
        self._validate_picker_not_in_use()
        if 'use_mesh' in kwargs:
            warnings.warn(
                '`use_mesh` is deprecated. See `use_picker` instead.', PyVistaDeprecationWarning
            )
            use_mesh = kwargs.pop('use_mesh')
        else:
            use_mesh = False

        self_ = weakref.ref(self)

        def _end_pick_event(picker, event):
            if (
                not pickable_window
                and hasattr(picker, 'GetDataSet')
                and picker.GetDataSet() is None
            ):
                # Clear the selection
                self._picked_point = None
                if clear_on_no_selection:
                    with self_().iren.poked_subplot():
                        self_()._clear_picking_representations()
                return
            with self_().iren.poked_subplot():
                point = np.array(picker.GetPickPosition())
                point /= self_().scale  # HACK: handle scale
                self_()._picked_point = point
                if show_point:
                    _kwargs = kwargs.copy()
                    self_().add_mesh(
                        self_().picked_point,
                        color=color,
                        point_size=point_size,
                        name=_kwargs.pop('name', PICKED_REPRESENTATION_NAMES['point']),
                        pickable=_kwargs.pop('pickable', False),
                        reset_camera=_kwargs.pop('reset_camera', False),
                        **_kwargs,
                    )
                if callable(callback):
                    if use_picker:
                        _poked_context_callback(self_(), callback, self.picked_point, picker)
                    elif use_mesh:  # Lower priority
                        _poked_context_callback(
                            self_(), callback, picker.GetDataSet(), picker.GetPointId()
                        )
                    else:
                        _poked_context_callback(self_(), callback, self.picked_point)

        if picker is not None:  # If None, that means use already set picker
            self.iren.picker = picker
        if hasattr(self.iren.picker, 'SetTolerance'):
            self.iren.picker.SetTolerance(tolerance)
        self.iren.add_pick_obeserver(_end_pick_event)
        self._init_click_picking_callback(left_clicking=left_clicking)
        self._picker_in_use = True

        # Now add text about cell-selection
        if show_message:
            if show_message is True:
                if left_clicking:
                    show_message = "Left-click"
                else:
                    show_message = "Right-click"
                show_message += ' or press P to pick under the mouse'
            self._picking_text = self.add_text(
                str(show_message), font_size=font_size, name='_point_picking_message'
            )

    def enable_rectangle_picking(
        self,
        callback=None,
        show_message=True,
        font_size=18,
        start=False,
        show_frustum=False,
        style='wireframe',
        color='pink',
        **kwargs,
    ):
        """Enable rectangle based picking at cells.

        Press ``"r"`` to enable retangle based selection. Press
        ``"r"`` again to turn it off.

        Picking with the rectangle selection tool provides two values that
        are passed as the ``RectangleSelection`` object in the callback:

        1. ``RectangleSelection.viewport``: the viewport coordinates of the
           selection rectangle.
        2. ``RectangleSelection.frustum``: the full frustum made from
           the selection rectangle into the scene.

        Parameters
        ----------
        callback : callable, optional
            When input, calls this callable after a selection is made.
            The ``RectangleSelection`` is the only passed argument
            containing the viewport coordinates of the selection and the
            projected frustum.

        show_message : bool | str, default: True
            Show the message about how to use the cell picking tool. If this
            is a string, that will be the message shown.

        font_size : int, default: 18
            Sets the font size of the message.

        start : bool, default: True
            Automatically start the cell selection tool.

        show_frustum : bool, default: False
            Show the frustum in the scene.

        style : str, default: "wireframe"
            Visualization style of the selection frustum. One of the
            following: ``style='surface'``, ``style='wireframe'``, or
            ``style='points'``.

        color : ColorLike, default: "pink"
            The color of the selected frustum when shown.

        **kwargs : dict, optional
            All remaining keyword arguments are used to control how
            the selection frustum is interactively displayed.

        Examples
        --------
        Add a mesh and a cube to a plot and enable cell picking.

        >>> import pyvista as pv
        >>> mesh = pv.Sphere(center=(1, 0, 0))
        >>> cube = pv.Cube()
        >>> pl = pv.Plotter()
        >>> _ = pl.add_mesh(mesh)
        >>> _ = pl.add_mesh(cube)
        >>> _ = pl.enable_rectangle_picking()

        """
        self._validate_picker_not_in_use()

        self_ = weakref.ref(self)

        def _end_pick_helper(picker, *args):
            renderer = picker.GetRenderer()  # TODO: double check this is poked renderer
            x0 = int(renderer.GetPickX1())
            x1 = int(renderer.GetPickX2())
            y0 = int(renderer.GetPickY1())
            y1 = int(renderer.GetPickY2())

            selection = RectangleSelection(frustum=picker.GetFrustum(), viewport=(x0, y0, x1, y1))

            if show_frustum:
                with self_().iren.poked_subplot():
                    _kwargs = kwargs.copy()
                    self_().add_mesh(
                        selection.frustum_mesh,
                        name=_kwargs.pop('name', PICKED_REPRESENTATION_NAMES['frustum']),
                        style=style,
                        color=color,
                        pickable=_kwargs.pop('pickable', False),
                        reset_camera=_kwargs.pop('reset_camera', False),
                        **_kwargs,
                    )

            if callback is not None:
                _poked_context_callback(self_(), callback, selection)

        self.enable_rubber_band_style()  # TODO: better handle?
        self.iren.picker = 'rendered'
        self.iren.add_pick_obeserver(_end_pick_helper)
        self._picker_in_use = True

        # Now add text about cell-selection
        if show_message:
            if show_message is True:
                show_message = "Press R to toggle selection tool"
            self._picking_text = self.add_text(
                str(show_message), font_size=font_size, name='_rectangle_picking_message'
            )

        if start:
            self.iren._style_class.StartSelect()


class PickingMethods(PickingInterface):  # numpydoc ignore=PR01
    """Internal class to contain picking utilities."""

    def __init__(self, *args, **kwargs):
        """Initialize the picking methods."""
        super().__init__(*args, **kwargs)
        self._picked_actor = None
        self._picked_mesh = None
        self._picked_cell = None
        self._picking_text = None
        self._picked_block_index = None

    @property
    def picked_actor(self):  # numpydoc ignore=RT01
        """Return the picked mesh.

        This returns the picked actor after selecting a mesh with
        :func:`enable_surface_point_picking <pyvista.Plotter.enable_surface_point_picking>` or
        :func:`enable_mesh_picking <pyvista.Plotter.enable_mesh_picking>`.

        Returns
        -------
        pyvista.Actor or None
            Picked actor if available.

        """
        return self._picked_actor

    @property
    def picked_mesh(self):  # numpydoc ignore=RT01
        """Return the picked mesh.

        This returns the picked mesh after selecting a mesh with
        :func:`enable_surface_point_picking <pyvista.Plotter.enable_surface_point_picking>` or
        :func:`enable_mesh_picking <pyvista.Plotter.enable_mesh_picking>`.

        Returns
        -------
        pyvista.DataSet or None
            Picked mesh if available.

        """
        return self._picked_mesh

    @property
    def picked_cell(self):  # numpydoc ignore=RT01
        """Return the picked cell.

        This returns the picked cell after selecting a cell.

        Returns
        -------
        pyvista.Cell or None
            Picked cell if available.

        """
        return self._picked_cell

    @property
    def picked_cells(self):  # numpydoc ignore=RT01
        """Return the picked cells.

        This returns the picked cells after selecting cells.

        Returns
        -------
        pyvista.Cell or None
            Picked cell if available.

        """
        return self._picked_cell

    @property
    def picked_block_index(self):  # numpydoc ignore=RT01
        """Return the picked block index.

        This returns the picked block index after selecting a point with
        :func:`enable_point_picking <pyvista.Plotter.enable_point_picking>`.

        Returns
        -------
        int or None
            Picked block if available. If ``-1``, then a non-composite dataset
            was selected.

        """
        return self._picked_block_index

    @wraps(PickingInterface.disable_picking)
    def disable_picking(self):
        """Disable picking."""
        super().disable_picking()
        # remove any picking text
        if hasattr(self, 'renderers'):
            for renderer in self.renderers:
                renderer.remove_actor(self._picking_text, render=False)
        self._picking_text = None

    def enable_surface_point_picking(
        self,
        callback=None,
        show_message=True,
        font_size=18,
        color='pink',
        show_point=True,
        point_size=10,
        tolerance=0.025,
        pickable_window=False,
        left_clicking=False,
        picker=PickerType.CELL,
        use_picker=False,
        clear_on_no_selection=True,
        **kwargs,
    ):
        """Enable picking of a point on the surface of a mesh.

        Parameters
        ----------
        callback : callable, optional
            When input, calls this callable after a selection is made. The
            ``mesh`` is input as the first parameter to this callable.

        show_message : bool | str, default: True
            Show the message about how to use the mesh picking tool. If this
            is a string, that will be the message shown.

        font_size : int, default: 18
            Sets the font size of the message.

        color : ColorLike, default: "pink"
            The color of the selected mesh when shown.

        show_point : bool, default: True
            Show the selection interactively.

        point_size : int, default: 10
            Size of picked points if ``show_point`` is ``True``.

        tolerance : float, default: 0.025
            Specify tolerance for performing pick operation. Tolerance
            is specified as fraction of rendering window
            size. Rendering window size is measured across diagonal.

            .. warning::
                This is ignored with the ``'hardware'`` ``picker``.

        pickable_window : bool, default: False
            When ``True``, points in the 3D window are pickable.

        left_clicking : bool, default: False
            When ``True``, meshes can be picked by clicking the left
            mousebutton.

            .. note::
               If enabled, left-clicking will **not** display the bounding box
               around the picked mesh.

        picker : str | PickerType, optional
            Choice of VTK picker class type:

                * ``'hardware'``: Uses ``vtkHardwarePicker`` which is more
                  performant for large geometries (default).
                * ``'cell'``: Uses ``vtkCellPicker``.
                * ``'point'``: Uses ``vtkPointPicker`` which will snap to
                  points on the surface of the mesh.
                * ``'volume'``: Uses ``vtkVolumePicker``.

        use_picker : bool, default: False
            When ``True``, the callback will also be passed the picker.

        clear_on_no_selection : bool, default: True
            Clear the selections when no point is selected.

        **kwargs : dict, optional
            All remaining keyword arguments are used to control how
            the picked path is interactively displayed.

        Notes
        -----
        Picked point can be accessed from :attr:`picked_point
        <pyvista.Plotter.picked_point>` attribute.

        Examples
        --------
        Add a cube to a plot and enable cell picking.

        >>> import pyvista as pv
        >>> cube = pv.Cube()
        >>> pl = pv.Plotter()
        >>> _ = pl.add_mesh(cube)
        >>> _ = pl.enable_surface_point_picking()

        See :ref:`surface_point_picking_example` for a full example using this method.

        """
        # only allow certain pickers to be used for surface picking
        #  the picker class needs to have `GetDataSet()`
        picker = PickerType.from_any(picker)
        valid_pickers = [PickerType.POINT, PickerType.CELL, PickerType.HARDWARE, PickerType.VOLUME]
        if picker not in valid_pickers:
            raise ValueError(
                f'Invalid picker choice for surface picking. Use one of: {valid_pickers}'
            )

        self_ = weakref.ref(self)

        def _end_pick_event(picked_point, picker):
            if not pickable_window and picker.GetActor() is None:
                self_()._picked_point = None
                self_()._picked_actor = None
                self_()._picked_mesh = None
                if clear_on_no_selection:
                    with self_().iren.poked_subplot():
                        self_()._clear_picking_representations()
                return
            self_()._picked_actor = picker.GetActor()
            self_()._picked_mesh = picker.GetDataSet()

            if show_point:
                with self_().iren.poked_subplot():
                    _kwargs = kwargs.copy()
                    self_().add_mesh(
                        picked_point,
                        color=color,
                        point_size=point_size,
                        name=_kwargs.pop('name', PICKED_REPRESENTATION_NAMES['point']),
                        pickable=_kwargs.pop('pickable', False),
                        reset_camera=_kwargs.pop('reset_camera', False),
                        **_kwargs,
                    )
            if callable(callback):
                if use_picker:
                    _poked_context_callback(self_(), callback, picked_point, picker)
                else:
                    _poked_context_callback(self_(), callback, picked_point)

        self.enable_point_picking(
            callback=_end_pick_event,
            picker=picker,
            show_point=False,
            show_message=show_message,
            left_clicking=left_clicking,
            use_picker=True,
            font_size=font_size,
            tolerance=tolerance,
            pickable_window=True,  # let this callback handle pickable window
            clear_on_no_selection=clear_on_no_selection,
        )

    def enable_surface_picking(self, *args, **kwargs):
        """Surface picking.

        .. deprecated:: 0.40.0
            This method has been renamed to ``enable_surface_point_picking``.

        Parameters
        ----------
        *args : tuple
            Positional arguments.

        **kwargs : dict
            Keyword arguments.

        """
        # Deprecated on v0.40.0, estimated removal on v0.42.0
        warnings.warn(
            "This method has been renamed to `enable_surface_point_picking`.",
            PyVistaDeprecationWarning,
        )
        self.enable_surface_point_picking(*args, **kwargs)

    def enable_mesh_picking(
        self,
        callback=None,
        show=True,
        show_message=True,
        style='wireframe',
        line_width=5,
        color='pink',
        font_size=18,
        left_clicking=False,
        use_actor=False,
        picker=PickerType.CELL,
        **kwargs,
    ):
        """Enable picking of a mesh.

        Parameters
        ----------
        callback : callable, optional
            When input, calls this callable after a selection is made. The
            ``mesh`` is input as the first parameter to this callable.

        show : bool, default: True
            Show the selection interactively. Best when combined with
            ``left_clicking``.

        show_message : bool | str, default: True
            Show the message about how to use the mesh picking tool. If this
            is a string, that will be the message shown.

        style : str, default: "wireframe"
            Visualization style of the selection. One of the following:

            * ``'surface'``
            * ``'wireframe'``
            * ``'points'``

        line_width : float, default: 5.0
            Thickness of selected mesh edges.

        color : ColorLike, default: "pink"
            The color of the selected mesh when shown.

        font_size : int, default: 18
            Sets the font size of the message.

        left_clicking : bool, default: False
            When ``True``, meshes can be picked by clicking the left
            mousebutton.

            .. note::
               If enabled, left-clicking will **not** display the bounding box
               around the picked point.

        use_actor : bool, default: False
            If True, the callback will be passed the picked actor instead of
            the mesh object.

        picker : str | PickerType, optional
            Choice of VTK picker class type:

                * ``'hardware'``: Uses ``vtkHardwarePicker`` which is more
                  performant for large geometries (default).
                * ``'cell'``: Uses ``vtkCellPicker``.
                * ``'point'``: Uses ``vtkPointPicker`` which will snap to
                  points on the surface of the mesh.
                * ``'volume'``: Uses ``vtkVolumePicker``.


        **kwargs : dict, optional
            All remaining keyword arguments are used to control how
            the picked path is interactively displayed.

        Returns
        -------
        vtk.vtkPropPicker
            Property picker.

        Examples
        --------
        Add a sphere and a cube to a plot and enable mesh picking. Enable
        ``left_clicking`` to immediately start picking on the left click and
        disable showing the box. You can still press the ``p`` key to select
        meshes.

        >>> import pyvista as pv
        >>> mesh = pv.Sphere(center=(1, 0, 0))
        >>> cube = pv.Cube()
        >>> pl = pv.Plotter()
        >>> _ = pl.add_mesh(mesh)
        >>> _ = pl.add_mesh(cube)
        >>> _ = pl.enable_mesh_picking()

        See :ref:`mesh_picking_example` for a full example using this method.

        """
        self_ = weakref.ref(self)

        def end_pick_call_back(_, picker):  # numpydoc ignore=GL08
            if callback:
                if use_actor:
                    _poked_context_callback(self_(), callback, self_()._picked_actor)
                else:
                    _poked_context_callback(self_(), callback, self_()._picked_mesh)

            if show:
                # Select the renderer where the mesh is added.
                active_renderer_index = self_().renderers._active_index
                loc = self_().iren.get_event_subplot_loc()
                self_().subplot(*loc)

                # Use try in case selection is empty or invalid
                try:
                    with self_().iren.poked_subplot():
                        _kwargs = kwargs.copy()
                        self_().add_mesh(
                            self_()._picked_mesh,
                            name=_kwargs.pop('name', PICKED_REPRESENTATION_NAMES['mesh']),
                            style=style,
                            color=color,
                            line_width=line_width,
                            pickable=_kwargs.pop('pickable', False),
                            reset_camera=_kwargs.pop('reset_camera', False),
                            **_kwargs,
                        )
                except Exception as e:  # pragma: no cover
                    warnings.warn("Unable to show mesh when picking:\n\n%s", str(e))

                # Reset to the active renderer.
                loc = self_().renderers.index_to_loc(active_renderer_index)
                self_().subplot(*loc)

                # render here prior to running the callback
                self_().render()

        # add on-screen message about point-selection
        if show_message:
            if show_message is True:
                if left_clicking:
                    show_message = "Left-click"
                else:
                    show_message = "Right-click"
                show_message += ' or press P to pick single dataset under the mouse pointer'

        self.enable_surface_point_picking(
            callback=end_pick_call_back,
            picker=picker,
            show_point=False,
            show_message=show_message,
            left_clicking=left_clicking,
            use_picker=True,
            font_size=font_size,
            pickable_window=False,
        )

    def enable_rectangle_through_picking(
        self,
        callback=None,
        show=True,
        style='wireframe',
        line_width=5,
        color='pink',
        show_message=True,
        font_size=18,
        start=False,
        show_frustum=False,
        **kwargs,
    ):
        """Enable rectangle based cell picking through the scene.

        Parameters
        ----------
        callback : callable, optional
            When input, calls this callable after a selection is made.
            The picked cells is the only passed argument.

        show : bool, default: True
            Show the selection interactively.

        style : str, default: "wireframe"
            Visualization style of the selection frustum. One of the
            following: ``style='surface'``, ``style='wireframe'``, or
            ``style='points'``.

        line_width : float, default: 5.0
            Thickness of selected mesh edges.

        color : ColorLike, default: "pink"
            The color of the selected frustum when shown.

        show_message : bool | str, default: True
            Show the message about how to use the cell picking tool. If this
            is a string, that will be the message shown.

        font_size : int, default: 18
            Sets the font size of the message.

        start : bool, default: True
            Automatically start the cell selection tool.

        show_frustum : bool, default: False
            Show the frustum in the scene.

        **kwargs : dict, optional
            All remaining keyword arguments are used to control how
            the selection frustum is interactively displayed.

        """
        self_ = weakref.ref(self)

        def finalize(picked):  # numpydoc ignore=GL08
            if picked is None:
                # Inidcates invalid pick
                with self_().iren.poked_subplot():
                    self_()._clear_picking_representations()
                return

            self._picked_cell = picked

            if show:
                # Use try in case selection is empty
                with self_().iren.poked_subplot():
                    _kwargs = kwargs.copy()
                    self_().add_mesh(
                        picked,
                        name=_kwargs.pop('name', PICKED_REPRESENTATION_NAMES['through']),
                        style=style,
                        color=color,
                        line_width=line_width,
                        pickable=_kwargs.pop('pickable', False),
                        reset_camera=_kwargs.pop('reset_camera', False),
                        **_kwargs,
                    )

            if callback is not None:
                _poked_context_callback(self_(), callback, self_().picked_cells)

        def through_pick_callback(selection):  # numpydoc ignore=GL08
            picked = pyvista.MultiBlock()
            renderer = self_().iren.get_poked_renderer()
            for actor in renderer.actors.values():
                if actor.GetMapper() and actor.GetPickable():
                    input_mesh = pyvista.wrap(actor.GetMapper().GetInputAsDataSet())
                    input_mesh.cell_data['orig_extract_id'] = np.arange(input_mesh.n_cells)
                    extract = _vtk.vtkExtractGeometry()
                    extract.SetInputData(input_mesh)
                    extract.SetImplicitFunction(selection.frustum)
                    extract.Update()
                    picked.append(pyvista.wrap(extract.GetOutput()))

            if picked.n_blocks == 0:
                self_()._picked_cell = None
            elif picked.combine().n_cells < 1:
                self_()._picked_cell = None
            elif picked.n_blocks == 1:
                self_()._picked_cell = picked[0]
            else:
                self_()._picked_cell = picked

            finalize(self_()._picked_cell)

        self.enable_rectangle_picking(
            callback=through_pick_callback,
            show_message=show_message,
            font_size=font_size,
            show_frustum=show_frustum,
            start=start,
            style=style,
            color=color,
        )

    def enable_rectangle_visible_picking(
        self,
        callback=None,
        show=True,
        style='wireframe',
        line_width=5,
        color='pink',
        show_message=True,
        font_size=18,
        start=False,
        show_frustum=False,
        **kwargs,
    ):
        """Enable rectangle based cell picking on visible surfaces.

        Parameters
        ----------
        callback : callable, optional
            When input, calls this callable after a selection is made.
            The picked cells is the only passed argument.

        show : bool, default: True
            Show the selection interactively.

        style : str, default: "wireframe"
            Visualization style of the selection frustum. One of the
            following: ``style='surface'``, ``style='wireframe'``, or
            ``style='points'``.

        line_width : float, default: 5.0
            Thickness of selected mesh edges.

        color : ColorLike, default: "pink"
            The color of the selected frustum when shown.

        show_message : bool | str, default: True
            Show the message about how to use the cell picking tool. If this
            is a string, that will be the message shown.

        font_size : int, default: 18
            Sets the font size of the message.

        start : bool, default: True
            Automatically start the cell selection tool.

        show_frustum : bool, default: False
            Show the frustum in the scene.

        **kwargs : dict, optional
            All remaining keyword arguments are used to control how
            the selection frustum is interactively displayed.

        """
        self_ = weakref.ref(self)

        def finalize(picked):  # numpydoc ignore=GL08
            if picked is None:
                # Inidcates invalid pick
                with self_().iren.poked_subplot():
                    self_()._clear_picking_representations()
                return

            if show:
                # Use try in case selection is empty
                with self_().iren.poked_subplot():
                    _kwargs = kwargs.copy()
                    self_().add_mesh(
                        picked,
                        name=_kwargs.pop('name', PICKED_REPRESENTATION_NAMES['visible']),
                        style=style,
                        color=color,
                        line_width=line_width,
                        pickable=_kwargs.pop('pickable', False),
                        reset_camera=_kwargs.pop('reset_camera', False),
                        **_kwargs,
                    )

            if callback is not None:
                _poked_context_callback(self_(), callback, picked)

        def visible_pick_callback(selection):  # numpydoc ignore=GL08
            picked = pyvista.MultiBlock()
            renderer = self_().iren.get_poked_renderer()
            x0, y0, x1, y1 = renderer.get_pick_position()
            # x0, y0, x1, y1 = selection.viewport
            if x0 >= 0:  # initial pick position is (-1, -1, -1, -1)
                selector = _vtk.vtkOpenGLHardwareSelector()
                selector.SetFieldAssociation(_vtk.vtkDataObject.FIELD_ASSOCIATION_CELLS)
                selector.SetRenderer(renderer)
                selector.SetArea(x0, y0, x1, y1)
                selection = selector.Select()

                for node in range(selection.GetNumberOfNodes()):
                    selection_node = selection.GetNode(node)
                    if selection_node is None:  # pragma: no cover
                        # No selection
                        continue
                    cids = pyvista.convert_array(selection_node.GetSelectionList())
                    actor = selection_node.GetProperties().Get(_vtk.vtkSelectionNode.PROP())

                    # TODO: this is too hacky - find better way to avoid non-dataset actors
                    if not actor.GetMapper() or not hasattr(
                        actor.GetProperty(), 'GetRepresentation'
                    ):
                        continue

                    # if not a surface
                    if actor.GetProperty().GetRepresentation() != 2:  # pragma: no cover
                        warnings.warn(
                            "Display representations other than `surface` will result in incorrect results."
                        )
                    smesh = pyvista.wrap(actor.GetMapper().GetInputAsDataSet())
                    smesh = smesh.copy()
                    smesh["original_cell_ids"] = np.arange(smesh.n_cells)
                    tri_smesh = smesh.extract_surface().triangulate()
                    cids_to_get = tri_smesh.extract_cells(cids)["original_cell_ids"]
                    picked.append(smesh.extract_cells(cids_to_get))

                # memory leak issues on vtk==9.0.20210612.dev0
                # See: https://gitlab.kitware.com/vtk/vtk/-/issues/18239#note_973826
                selection.UnRegister(selection)

            if len(picked) == 0:
                self_()._picked_cell = None
            elif picked.combine().n_cells < 1:
                self_()._picked_cell = None
            elif len(picked) == 1:
                self_()._picked_cell = picked[0]
            else:
                self_()._picked_cell = picked

            finalize(self_()._picked_cell)

        self.enable_rectangle_picking(
            callback=visible_pick_callback,
            show_message=show_message,
            font_size=font_size,
            start=start,
            show_frustum=show_frustum,
            style=style,
            color=color,
        )

    def enable_cell_picking(
        self,
        callback=None,
        through=True,
        show=True,
        show_message=True,
        style='wireframe',
        line_width=5,
        color='pink',
        font_size=18,
        start=False,
        show_frustum=False,
        **kwargs,
    ):
        """Enable picking of cells with a rectangle selection tool.

        Press ``"r"`` to enable retangle based selection.  Press
        ``"r"`` again to turn it off. Selection will be saved to
        ``self.picked_cells``.

        All meshes in the scene are available for picking by default.
        If you would like to only pick a single mesh in the scene,
        use the ``pickable=False`` argument when adding the other
        meshes to the scene.

        When multiple meshes are being picked, the picked cells
        in ``self.picked_cells`` will be a :class:`MultiBlock`
        dataset for each mesh's selection.

        Uses last input mesh for input by default.

        .. warning::
           Visible cell picking (``through=False``) will only work if
           the mesh is displayed with a ``'surface'`` representation
           style (the default).

        Parameters
        ----------
        callback : callable, optional
            When input, calls this callable after a selection is made.
            The picked_cells are input as the first parameter to this
            callable.

        through : bool, default: True
            When ``True`` the picker will select all cells
            through the mesh(es). When ``False``, the picker will select
            only visible cells on the selected surface(s).

        show : bool, default: True
            Show the selection interactively.

        show_message : bool | str, default: True
            Show the message about how to use the cell picking tool. If this
            is a string, that will be the message shown.

        style : str, default: "wireframe"
            Visualization style of the selection.  One of the
            following: ``style='surface'``, ``style='wireframe'``, or
            ``style='points'``.

        line_width : float, default: 5.0
            Thickness of selected mesh edges.

        color : ColorLike, default: "pink"
            The color of the selected mesh when shown.

        font_size : int, default: 18
            Sets the font size of the message.

        start : bool, default: True
            Automatically start the cell selection tool.

        show_frustum : bool, default: False
            Show the frustum in the scene.

        **kwargs : dict, optional
            All remaining keyword arguments are used to control how
            the selection is interactively displayed.

        Examples
        --------
        Add a mesh and a cube to a plot and enable cell picking.

        >>> import pyvista as pv
        >>> mesh = pv.Sphere(center=(1, 0, 0))
        >>> cube = pv.Cube()
        >>> pl = pv.Plotter()
        >>> _ = pl.add_mesh(mesh)
        >>> _ = pl.add_mesh(cube)
        >>> _ = pl.enable_cell_picking()

        """
        if through:
            method = self.enable_rectangle_through_picking
        else:
            method = self.enable_rectangle_visible_picking
        method(
            callback=callback,
            show=show,
            show_message=show_message,
            style=style,
            line_width=line_width,
            color=color,
            font_size=font_size,
            start=start,
            show_frustum=show_frustum,
            **kwargs,
        )

    def enable_element_picking(
        self,
        callback=None,
        mode='cell',
        show=True,
        show_message=True,
        font_size=18,
        color='pink',
        tolerance=0.025,
        pickable_window=False,
        left_clicking=False,
        picker=PickerType.CELL,
        **kwargs,
    ):
        """Select individual elements on a mesh.

        Parameters
        ----------
        callback : callable, optional
            When input, calls this callable after a selection is made. The
            ``mesh`` is input as the first parameter to this callable.

        mode : str | ElementType, default: "cell"
            The picking mode. Either ``"mesh"``, ``"cell"``, ``"face"``,
            ``"edge"``, or ``"point"``.

        show : bool, default: True
            Show the selection interactively.

        show_message : bool | str, default: True
            Show the message about how to use the mesh picking tool. If this
            is a string, that will be the message shown.

        font_size : int, default: 18
            Sets the font size of the message.

        color : ColorLike, default: "pink"
            The color of the selected mesh when shown.

        tolerance : float, default: 0.025
            Specify tolerance for performing pick operation. Tolerance
            is specified as fraction of rendering window
            size. Rendering window size is measured across diagonal.

            .. warning::
                This is ignored with the ``'hardware'`` ``picker``.

        pickable_window : bool, default: False
            When ``True``, points in the 3D window are pickable.

        left_clicking : bool, default: False
            When ``True``, meshes can be picked by clicking the left
            mousebutton.

            .. note::
               If enabled, left-clicking will **not** display the bounding box
               around the picked mesh.

        picker : str | PickerType, optional
            Choice of VTK picker class type:

                * ``'hardware'``: Uses ``vtkHardwarePicker`` which is more
                  performant for large geometries (default).
                * ``'cell'``: Uses ``vtkCellPicker``.
                * ``'point'``: Uses ``vtkPointPicker`` which will snap to
                  points on the surface of the mesh.
                * ``'volume'``: Uses ``vtkVolumePicker``.

        **kwargs : dict, optional
            All remaining keyword arguments are used to control how
            the picked path is interactively displayed.

        """
        mode = ElementType.from_any(mode)
        self_ = weakref.ref(self)

        def _end_handler(picked):
            if callback:
                _poked_context_callback(self_(), callback, picked)

            if mode == ElementType.CELL:
                self._picked_cell = picked

            if show:
                if mode == ElementType.CELL:
                    kwargs.setdefault('color', 'pink')
                elif mode == ElementType.EDGE:
                    kwargs.setdefault('color', 'magenta')
                else:
                    kwargs.setdefault('color', 'pink')

                if mode in [ElementType.CELL, ElementType.FACE]:
                    picked = picked.extract_all_edges()

                with self.iren.poked_subplot():
                    _kwargs = kwargs.copy()
                    self.add_mesh(
                        picked,
                        name=_kwargs.pop('name', PICKED_REPRESENTATION_NAMES['element']),
                        pickable=_kwargs.pop('pickable', False),
                        reset_camera=_kwargs.pop('reset_camera', False),
                        point_size=_kwargs.pop('point_size', 5),
                        line_width=_kwargs.pop('line_width', 5),
                        **_kwargs,
                    )

        handler = PointPickingElementHandler(mode=mode, callback=_end_handler)

        self.enable_surface_point_picking(
            callback=handler,
            show_message=show_message,
            font_size=font_size,
            color=color,
            show_point=False,
            tolerance=tolerance,
            pickable_window=pickable_window,
            left_clicking=left_clicking,
            picker=picker,
            use_picker=True,
            **kwargs,
        )

    def enable_block_picking(self, callback=None, side='left'):
        """Enable composite block picking.

        Use this picker to return the index of a DataSet when using composite
        dataset like :class:`pyvista.MultiBlock` and pass it to a callback.

        Parameters
        ----------
        callback : callable, optional
            When input, this picker calls this callable after a selection is
            made. The composite index is passed to ``callback`` as the first
            argument and the dataset as the second argument.

        side : str, default: "left"
            The mouse button to track (either ``'left'`` or ``'right'``).
            Also accepts ``'r'`` or ``'l'``.

        Notes
        -----
        The picked block index can be accessed from :attr:`picked_block_index
        <pyvista.Plotter.picked_block_index>` attribute.

        Examples
        --------
        Enable block picking with a multiblock dataset. Left clicking will turn
        blocks blue while right picking will turn the block back to the default
        color.

        >>> import pyvista as pv
        >>> multiblock = pv.MultiBlock(
        ...     [pv.Cube(), pv.Sphere(center=(0, 0, 1))]
        ... )
        >>> pl = pv.Plotter()
        >>> actor, mapper = pl.add_composite(multiblock)
        >>> def turn_blue(index, dataset):
        ...     mapper.block_attr[index].color = 'blue'
        ...
        >>> pl.enable_block_picking(callback=turn_blue, side='left')
        >>> def clear_color(index, dataset):
        ...     mapper.block_attr[index].color = None
        ...
        >>> pl.enable_block_picking(callback=clear_color, side='right')
        >>> pl.show()

        """
        # use a weak reference to enable garbage collection
        renderer_ = weakref.ref(self.renderer)
        self_ = weakref.ref(self)

        sel_index = _vtk.vtkSelectionNode.COMPOSITE_INDEX()
        sel_prop = _vtk.vtkSelectionNode.PROP()

        def get_picked_block(*args, **kwargs):  # numpydoc ignore=PR01
            """Get the picked block and pass it to the user callback."""
            x, y = self.mouse_position
            selector = _vtk.vtkOpenGLHardwareSelector()
            selector.SetRenderer(renderer_())
            selector.SetArea(x, y, x, y)  # single pixel
            selection = selector.Select()

            for ii in range(selection.GetNumberOfNodes()):
                node = selection.GetNode(ii)
                if node is None:  # pragma: no cover
                    continue
                node_prop = node.GetProperties()
                self._picked_block_index = node_prop.Get(sel_index)

                # Safely return the dataset as it's possible a non pyvista
                # mapper was added
                mapper = node_prop.Get(sel_prop).GetMapper()
                if isinstance(mapper, CompositePolyDataMapper):
                    dataset = mapper.block_attr.get_block(self._picked_block_index)
                else:  # pragma: no cover
                    dataset = None

                if callable(callback):
                    _poked_context_callback(self_(), callback, self._picked_block_index, dataset)

        self.track_click_position(callback=get_picked_block, viewport=True, side=side)


class PickingHelper(PickingMethods):
    """Internal container class to contain picking helper methods."""

    def __init__(self, *args, **kwargs):
        """Initialize the picking methods."""
        super().__init__(*args, **kwargs)
        self.picked_path = None
        self.picked_geodesic = None
        self.picked_horizon = None

    def fly_to_mouse_position(self, focus=False):
        """Focus on last stored mouse position."""
        if self.mouse_position is None:
            self.store_mouse_position()
        click_point = self.pick_mouse_position()
        if focus:
            self.set_focus(click_point)
        else:
            self.fly_to(click_point)

    def enable_fly_to_right_click(self, callback=None):
        """Set the camera to track right click positions.

        A convenience method to track right click positions and fly to
        the picked point in the scene. The callback will be passed the
        point in 3D space.

        Parameters
        ----------
        callback : callable
            Callback to call immediately after right clicking.

        """
        self_ = weakref.ref(self)

        def _the_callback(*args):
            click_point = self.pick_mouse_position()
            self.fly_to(click_point)
            if callable(callback):
                _poked_context_callback(self_(), callback, click_point)

        self.track_click_position(callback=_the_callback, side="right")

    def enable_path_picking(
        self,
        callback=None,
        show_message=True,
        font_size=18,
        color='pink',
        point_size=10,
        line_width=5,
        show_path=True,
        tolerance=0.025,
        **kwargs,
    ):
        """Enable picking at paths.

        This is a convenience method for :func:`enable_point_picking
        <pyvista.Plotter.enable_point_picking>` to keep track of the
        picked points and create a line using those points.

        The line is saved to the ``.picked_path`` attribute of this
        plotter

        Parameters
        ----------
        callback : callable, optional
            When given, calls this callable after a pick is made.  The
            entire picked path is passed as the only parameter to this
            callable.

        show_message : bool | str, default: True
            Show the message about how to use the point picking
            tool. If this is a string, that will be the message shown.

        font_size : int, default: 18
            Sets the size of the message.

        color : ColorLike, default: "pink"
            The color of the selected mesh when shown.

        point_size : int, default: 10
            Size of picked points if ``show_path`` is ``True``.

        line_width : float, default: 5.0
            Thickness of path representation if ``show_path`` is
            ``True``.

        show_path : bool, default: True
            Show the picked path interactively.

        tolerance : float, default: 0.025
            Specify tolerance for performing pick operation. Tolerance
            is specified as fraction of rendering window
            size.  Rendering window size is measured across diagonal.

        **kwargs : dict, optional
            All remaining keyword arguments are used to control how
            the picked path is interactively displayed.

        """
        self_ = weakref.ref(self)
        kwargs.setdefault('pickable', False)

        def make_line_cells(n_points):  # numpydoc ignore=GL08
            cells = np.arange(0, n_points, dtype=np.int_)
            cells = np.insert(cells, 0, n_points)
            return cells

        the_points = []

        def _the_callback(picked_point, picker):
            if picker.GetDataSet() is None:
                return
            the_points.append(picked_point)
            self.picked_path = pyvista.PolyData(np.array(the_points))
            self.picked_path.lines = make_line_cells(len(the_points))
            if show_path:
                with self.iren.poked_subplot():
                    _kwargs = kwargs.copy()
                    self.add_mesh(
                        self.picked_path,
                        color=color,
                        name=_kwargs.pop('name', PICKED_REPRESENTATION_NAMES['path']),
                        line_width=line_width,
                        point_size=point_size,
                        pickable=_kwargs.pop('pickable', False),
                        reset_camera=_kwargs.pop('reset_camera', False),
                        **_kwargs,
                    )
            if callable(callback):
                _poked_context_callback(self_(), callback, self.picked_path)

        def _clear_path_event_watcher():
            del the_points[:]
            with self.iren.poked_subplot():
                self._clear_picking_representations()

        self.add_key_event('c', _clear_path_event_watcher)
        if show_message is True:
            show_message = "Press P to pick under the mouse\nPress C to clear"

        self.enable_surface_point_picking(
            callback=_the_callback,
            use_picker=True,
            font_size=font_size,
            show_message=show_message,
            show_point=False,
            tolerance=tolerance,
            clear_on_no_selection=False,
        )

    def enable_geodesic_picking(
        self,
        callback=None,
        show_message=True,
        font_size=18,
        color='pink',
        point_size=10,
        line_width=5,
        tolerance=0.025,
        show_path=True,
        keep_order=True,
        **kwargs,
    ):
        """Enable picking at geodesic paths.

        This is a convenience method for ``enable_point_picking`` to
        keep track of the picked points and create a geodesic path
        using those points.

        The geodesic path is saved to the ``.picked_geodesic``
        attribute of this plotter.

        Parameters
        ----------
        callback : callable, optional
            When given, calls this callable after a pick is made.  The
            entire picked, geodesic path is passed as the only
            parameter to this callable.

        show_message : bool | str, default: True
            Show the message about how to use the point picking
            tool. If this is a string, that will be the message shown.

        font_size : int, default: 18
            Sets the size of the message.

        color : ColorLike, default: "pink"
            The color of the selected mesh when shown.

        point_size : int, default: 10
            Size of picked points if ``show_path`` is ``True``.

        line_width : float, default: 5.0
            Thickness of path representation if ``show_path`` is
            ``True``.

        tolerance : float, default: 0.025
            Specify tolerance for performing pick operation. Tolerance
            is specified as fraction of rendering window
            size.  Rendering window size is measured across diagonal.

        show_path : bool, default: True
            Show the picked path interactively.

        keep_order : bool, default: True
            If ``True``, the created geodesic path is a single ordered
            and cleaned line from the first point to the last.

            .. note::

                In older versions there were apparent discontinuities
                in the resulting path due to the behavior of the
                underlying VTK filter which corresponds to
                ``keep_order=False``.

            .. versionadded:: 0.32.0

        **kwargs : dict, optional
            All remaining keyword arguments are used to control how
            the picked path is interactively displayed.

        """
        self_ = weakref.ref(self)

        kwargs.setdefault('pickable', False)

        self.picked_geodesic = pyvista.PolyData()
        self._last_picked_idx = None

        def _the_callback(picked_point, picker):
            if picker.GetDataSet() is None:
                return
            mesh = pyvista.wrap(picker.GetDataSet())
            idx = mesh.find_closest_point(picked_point)
            point = mesh.points[idx]
            if self._last_picked_idx is None:
                self.picked_geodesic = pyvista.PolyData(point)
                self.picked_geodesic['vtkOriginalPointIds'] = [idx]
            else:
                surface = mesh.extract_surface().triangulate()
                locator = _vtk.vtkPointLocator()
                locator.SetDataSet(surface)
                locator.BuildLocator()
                start_idx = locator.FindClosestPoint(mesh.points[self._last_picked_idx])
                end_idx = locator.FindClosestPoint(point)
                self.picked_geodesic += surface.geodesic(start_idx, end_idx, keep_order=keep_order)
                if keep_order:
                    # it makes sense to remove adjacent duplicate points
                    self.picked_geodesic.clean(
                        inplace=True,
                        lines_to_points=False,
                        polys_to_lines=False,
                        strips_to_polys=False,
                    )
            self._last_picked_idx = idx

            if show_path:
                with self.iren.poked_subplot():
                    _kwargs = kwargs.copy()
                    self.add_mesh(
                        self.picked_geodesic,
                        color=color,
                        name=_kwargs.pop('name', PICKED_REPRESENTATION_NAMES['path']),
                        line_width=line_width,
                        point_size=point_size,
                        pickable=_kwargs.pop('pickable', False),
                        reset_camera=_kwargs.pop('reset_camera', False),
                        **_kwargs,
                    )
            if callable(callback):
                _poked_context_callback(self_(), callback, self.picked_geodesic)

        def _clear_g_path_event_watcher():
            self.picked_geodesic = pyvista.PolyData()
            with self.iren.poked_subplot():
                self._clear_picking_representations()
            self._last_picked_idx = None

        self.add_key_event('c', _clear_g_path_event_watcher)
        if show_message is True:
            show_message = "Press P to pick under the mouse\nPress C to clear"

        self.enable_surface_point_picking(
            callback=_the_callback,
            use_picker=True,
            font_size=font_size,
            show_message=show_message,
            tolerance=tolerance,
            show_point=False,
            clear_on_no_selection=False,
        )

    def enable_horizon_picking(
        self,
        callback=None,
        normal=(0.0, 0.0, 1.0),
        width=None,
        show_message=True,
        font_size=18,
        color='pink',
        point_size=10,
        line_width=5,
        show_path=True,
        opacity=0.75,
        show_horizon=True,
        **kwargs,
    ):
        """Enable horizon picking.

        Helper for the ``enable_path_picking`` method to also show a
        ribbon surface along the picked path. Ribbon is saved under
        ``.picked_horizon``.

        Parameters
        ----------
        callback : callable, optional
            When given, calls this callable after a pick is made.  The
            entire picked path is passed as the only parameter to this
            callable.

        normal : sequence[float], default: (0.0, 0.0, 1.0)
            The normal to the horizon surface's projection plane.

        width : float, optional
            The width of the horizon surface. Default behaviour will
            dynamically change the surface width depending on its
            length.

        show_message : bool | str, default: True
            Show the message about how to use the horizon picking
            tool. If this is a string, that will be the message shown.

        font_size : int, default: 18
            Sets the font size of the message.

        color : ColorLike, default: "pink"
            The color of the horizon surface if shown.

        point_size : int, default: 10
            Size of picked points if ``show_horizon`` is ``True``.

        line_width : float, default: 5.0
            Thickness of path representation if ``show_horizon`` is
            ``True``.

        show_path : bool, default: True
            Show the picked path that the horizon is built from
            interactively.

        opacity : float, default: 0.75
            The opacity of the horizon surface if shown.

        show_horizon : bool, default: True
            Show the picked horizon surface interactively.

        **kwargs : dict, optional
            All remaining keyword arguments are used to control how
            the picked path is interactively displayed.

        """
        self_ = weakref.ref(self)

        def _clear_horizon_event_watcher():
            self.picked_horizon = pyvista.PolyData()
            with self.iren.poked_subplot():
                self._clear_picking_representations()

        self.add_key_event('c', _clear_horizon_event_watcher)

        def _the_callback(path):
            if path.n_points < 2:
                _clear_horizon_event_watcher()
                return
            self.picked_horizon = path.ribbon(normal=normal, width=width)

            if show_horizon:
                with self.iren.poked_subplot():
                    _kwargs = kwargs.copy()
                    self.add_mesh(
                        self.picked_horizon,
                        name=_kwargs.get('name', PICKED_REPRESENTATION_NAMES['horizon']),
                        color=color,
                        opacity=opacity,
                        pickable=_kwargs.pop('pickable', False),
                        reset_camera=_kwargs.pop('reset_camera', False),
                        **_kwargs,
                    )

            if callable(callback):
                _poked_context_callback(self_(), callback, path)

        self.enable_path_picking(
            callback=_the_callback,
            show_message=show_message,
            font_size=font_size,
            color=color,
            point_size=point_size,
            line_width=line_width,
            show_path=show_path,
            **kwargs,
        )


# pyvista/plotting/plotter.py

"""PyVista plotting module."""
import collections.abc
from contextlib import contextmanager
from copy import deepcopy
import ctypes
from functools import wraps
import io
import logging
import os
import pathlib
import platform
import sys
import textwrap
from threading import Thread
import time
from typing import Dict, Optional
import warnings
import weakref

import matplotlib
import numpy as np
import scooby

import pyvista
from pyvista.core._typing_core import BoundsLike
from pyvista.core.errors import MissingDataError, PyVistaDeprecationWarning
from pyvista.core.utilities.arrays import (
    FieldAssociation,
    _coerce_pointslike_arg,
    convert_array,
    get_array,
    get_array_association,
    raise_not_matching,
)
from pyvista.core.utilities.helpers import is_pyvista_dataset, wrap
from pyvista.core.utilities.misc import abstract_class, assert_empty_kwargs

from . import _vtk
from ._plotting import (
    USE_SCALAR_BAR_ARGS,
    _common_arg_parser,
    prepare_smooth_shading,
    process_opacity,
)
from ._property import Property
from .actor import Actor
from .colors import Color, get_cmap_safe
from .composite_mapper import CompositePolyDataMapper
from .errors import RenderWindowUnavailable
from .mapper import (
    DataSetMapper,
    FixedPointVolumeRayCastMapper,
    GPUVolumeRayCastMapper,
    OpenGLGPUVolumeRayCastMapper,
    PointGaussianMapper,
    SmartVolumeMapper,
    UnstructuredGridVolumeRayCastMapper,
)
from .picking import PickingHelper
from .render_window_interactor import RenderWindowInteractor
from .renderer import Camera, Renderer
from .renderers import Renderers
from .scalar_bars import ScalarBars
from .texture import numpy_to_texture
from .themes import Theme
from .tools import FONTS, normalize, opacity_transfer_function, parse_font_family  # noqa
from .utilities.algorithms import (
    active_scalars_algorithm,
    algorithm_to_mesh_handler,
    decimation_algorithm,
    extract_surface_algorithm,
    pointset_to_polydata_algorithm,
    set_algorithm_input,
    triangulate_algorithm,
)
from .utilities.gl_checks import uses_egl
from .utilities.regression import image_from_window, run_image_filter
from .volume import Volume
from .volume_property import VolumeProperty
from .widgets import WidgetHelper

SUPPORTED_FORMATS = [".png", ".jpeg", ".jpg", ".bmp", ".tif", ".tiff"]

# EXPERIMENTAL: permit pyvista to kill the render window
KILL_DISPLAY = platform.system() == 'Linux' and os.environ.get('PYVISTA_KILL_DISPLAY')
if KILL_DISPLAY:  # pragma: no cover
    # this won't work under wayland
    try:
        X11 = ctypes.CDLL("libX11.so")
        X11.XCloseDisplay.argtypes = [ctypes.c_void_p]
    except OSError:
        warnings.warn('PYVISTA_KILL_DISPLAY: Unable to load X11.\nProbably using wayland')
        KILL_DISPLAY = False


def close_all():
    """Close all open/active plotters and clean up memory.

    Returns
    -------
    bool
        ``True`` when all plotters have been closed.

    """
    for pl in list(_ALL_PLOTTERS.values()):
        if not pl._closed:
            pl.close()
    _ALL_PLOTTERS.clear()
    return True


log = logging.getLogger(__name__)
log.setLevel('CRITICAL')
log.addHandler(logging.StreamHandler())


def _warn_xserver():  # pragma: no cover
    """Check if plotting is supported and persist this state.

    Check once and cache this value between calls.  Warn the user if
    plotting is not supported.  Configured to check on Linux and Mac
    OS since the Windows check is not quick.

    """
    # disable windows check until we can get a fast way of verifying
    # if windows has a windows manager (which it generally does)
    if os.name == 'nt':
        return

    if not hasattr(_warn_xserver, 'has_support'):
        _warn_xserver.has_support = pyvista.system_supports_plotting()

    if not _warn_xserver.has_support:
        # check if a display has been set
        if 'DISPLAY' in os.environ:
            return

        # finally, check if using a backend that doesn't require an xserver
        if pyvista.global_theme.jupyter_backend in [
            'client',
        ]:
            return

        # Check if VTK has EGL support
        if uses_egl():
            return

        warnings.warn(
            '\n'
            'This system does not appear to be running an xserver.\n'
            'PyVista will likely segfault when rendering.\n\n'
            'Try starting a virtual frame buffer with xvfb, or using\n '
            ' ``pyvista.start_xvfb()``\n'
        )


@abstract_class
class BasePlotter(PickingHelper, WidgetHelper):
    """Base plotting class.

    To be used by the :class:`pyvista.Plotter` and
    :class:`pyvistaqt.QtInteractor` classes.

    Parameters
    ----------
    shape : sequence[int] | str, optional
        Two item sequence of sub-render windows inside of the main window.
        Specify two across with ``shape=(2, 1)`` and a two by two grid
        with ``shape=(2, 2)``.  By default there is only one renderer.
        Can also accept a string descriptor as shape. For example:

        * ``shape="3|1"`` means 3 plots on the left and 1 on the right,
        * ``shape="4/2"`` means 4 plots on top and 2 at the bottom.

    border : bool, default: False
        Draw a border around each render window.

    border_color : ColorLike, default: 'k'
        Either a string, rgb list, or hex color string.  For example:

        * ``color='white'``
        * ``color='w'``
        * ``color=[1.0, 1.0, 1.0]``
        * ``color='#FFFFFF'``

    border_width : float, default: 2.0
        Width of the border in pixels when enabled.

    title : str, optional
        Window title.

    splitting_position : float, optional
        The splitting position of the renderers.

    groups : tuple, optional
        Grouping for renderers.

    row_weights : tuple
        Row weights for renderers.

    col_weights : tuple, optional
        Column weights for renderers.

    lighting : str, default: 'light kit'
        What lighting to set up for the plotter.  Accepted options:

        * ``'light_kit'``: a vtk Light Kit composed of 5 lights.
        * ``'three lights'``: illumination using 3 lights.
        * ``'none'``: no light sources at instantiation.

    theme : pyvista.plotting.themes.Theme, optional
        Plot-specific theme.

    image_scale : int, optional
        Scale factor when saving screenshots. Image sizes will be
        the ``window_size`` multiplied by this scale factor.

    **kwargs : dict, optional
        Additional keyword arguments.

    Examples
    --------
    Simple plotter example showing a blurred cube with a gradient background.

    >>> import pyvista as pv
    >>> pl = pv.Plotter()
    >>> _ = pl.add_mesh(pv.Cube())
    >>> pl.set_background('black', top='white')
    >>> pl.add_blurring()
    >>> pl.show()

    """

    mouse_position = None
    click_position = None

    def __init__(
        self,
        shape=(1, 1),
        border=None,
        border_color='k',
        border_width=2.0,
        title=None,
        splitting_position=None,
        groups=None,
        row_weights=None,
        col_weights=None,
        lighting='light kit',
        theme=None,
        image_scale=None,
        **kwargs,
    ):
        """Initialize base plotter."""
        super().__init__(**kwargs)  # cooperative multiple inheritance
        log.debug('BasePlotter init start')
        self._initialized = False

        self._theme = Theme()
        if theme is None:
            # copy global theme to ensure local plot theme is fixed
            # after creation.
            self._theme.load_theme(pyvista.global_theme)
        else:
            if not isinstance(theme, pyvista.plotting.themes.Theme):
                raise TypeError(
                    'Expected ``pyvista.plotting.themes.Theme`` for '
                    f'``theme``, not {type(theme).__name__}.'
                )
            self._theme.load_theme(theme)

        self.image_transparent_background = self._theme.transparent_background

        # optional function to be called prior to closing
        self.__before_close_callback = None
        self.mesh = None
        if title is None:
            title = self._theme.title
        self.title = str(title)

        # add renderers
        self.renderers = Renderers(
            self,
            shape,
            splitting_position,
            row_weights,
            col_weights,
            groups,
            border,
            border_color,
            border_width,
        )

        # This keeps track of scalars names already plotted and their ranges
        self._scalar_bars = ScalarBars(self)

        # track if the camera has been set up
        self._first_time = True
        # Keep track of the scale

        # track if render window has ever been rendered
        self._rendered = False

        self._on_render_callbacks = set()

        # this helps managing closed plotters
        self._closed = False

        # lighting style; be forgiving with input (accept underscores
        # and ignore case)
        lighting_normalized = str(lighting).replace('_', ' ').lower()
        if lighting_normalized == 'light kit':
            self.enable_lightkit()
        elif lighting_normalized == 'three lights':
            self.enable_3_lights()
        elif lighting_normalized != 'none':
            raise ValueError(f'Invalid lighting option "{lighting}".')

        # Track all active plotters. This has the side effect of ensuring that plotters are not
        # collected until `close()`. See https://github.com//pull/3216
        # This variable should be safe as a variable name
        self._id_name = f"P_{hex(id(self))}_{len(_ALL_PLOTTERS)}"
        _ALL_PLOTTERS[self._id_name] = self

        # Key bindings
        self.reset_key_events()
        log.debug('BasePlotter init stop')

        self._image_depth_null = None
        self.last_image_depth = None
        self.last_image = None
        self.last_vtksz = None
        self._has_background_layer = False
        if image_scale is None:
            image_scale = self._theme.image_scale
        self._image_scale = image_scale

        # set hidden line removal based on theme
        if self.theme.hidden_line_removal:
            self.enable_hidden_line_removal()

        self._initialized = True
        self._suppress_rendering = False

    @property
    def suppress_rendering(self):  # numpydoc ignore=RT01
        """Get or set whether to suppress render calls.

        Returns
        -------
        bool
            ``True`` when rendering is suppressed.

        """
        return self._suppress_rendering

    @suppress_rendering.setter
    def suppress_rendering(self, value):  # numpydoc ignore=GL08
        self._suppress_rendering = bool(value)

    @property
    def render_window(self):  # numpydoc ignore=RT01
        """Access the vtkRenderWindow attached to this plotter.

        If the plotter is closed, this will return ``None``.

        Returns
        -------
        vtk.vtkRenderWindow or None
            Render window if the plotter is not closed.

        Notes
        -----
        Subclass must set ``ren_win`` on initialization.
        """
        if not hasattr(self, 'ren_win'):
            return
        return self.ren_win

    @property
    def theme(self):  # numpydoc ignore=RT01
        """Return or set the theme used for this plotter.

        Returns
        -------
        pyvista.Theme
            Theme of this plotter.

        Examples
        --------
        Use the dark theme for a plotter.

        >>> import pyvista
        >>> from pyvista import themes
        >>> pl = pyvista.Plotter()
        >>> pl.theme = themes.DarkTheme()
        >>> actor = pl.add_mesh(pyvista.Sphere())
        >>> pl.show()

        """
        return self._theme

    @theme.setter
    def theme(self, theme):  # numpydoc ignore=GL08
        if not isinstance(theme, pyvista.plotting.themes.Theme):
            raise TypeError(
                'Expected a pyvista theme like '
                '``pyvista.plotting.themes.Theme``, '
                f'not {type(theme).__name__}.'
            )
        self._theme.load_theme(theme)

    def import_gltf(self, filename, set_camera=True):
        """Import a glTF file into the plotter.

        See https://www.khronos.org/gltf/ for more information.

        Parameters
        ----------
        filename : str
            Path to the glTF file.

        set_camera : bool, default: True
            Set the camera viewing angle to one compatible with the
            default three.js perspective (``'xy'``).

        Examples
        --------
        >>> import pyvista
        >>> from pyvista import examples
        >>> helmet_file = (
        ...     examples.gltf.download_damaged_helmet()
        ... )  # doctest:+SKIP
        >>> texture = (
        ...     examples.hdr.download_dikhololo_night()
        ... )  # doctest:+SKIP
        >>> pl = pyvista.Plotter()  # doctest:+SKIP
        >>> pl.import_gltf(helmet_file)  # doctest:+SKIP
        >>> pl.set_environment_texture(cubemap)  # doctest:+SKIP
        >>> pl.camera.zoom(1.8)  # doctest:+SKIP
        >>> pl.show()  # doctest:+SKIP

        See :ref:`load_gltf` for a full example using this method.

        """
        filename = os.path.abspath(os.path.expanduser(str(filename)))
        if not os.path.isfile(filename):
            raise FileNotFoundError(f'Unable to locate {filename}')

        # lazy import here to avoid importing unused modules
        from vtkmodules.vtkIOImport import vtkGLTFImporter

        importer = vtkGLTFImporter()
        importer.SetFileName(filename)
        importer.SetRenderWindow(self.render_window)
        importer.Update()

        # register last actor in actors
        actor = self.renderer.GetActors().GetLastItem()
        name = actor.GetAddressAsString("")
        self.renderer._actors[name] = actor

        # set camera position to a three.js viewing perspective
        if set_camera:
            self.camera_position = 'xy'

    def import_vrml(self, filename):
        """Import a VRML file into the plotter.

        Parameters
        ----------
        filename : str
            Path to the VRML file.

        Examples
        --------
        >>> import pyvista
        >>> from pyvista import examples
        >>> sextant_file = (
        ...     examples.vrml.download_sextant()
        ... )  # doctest:+SKIP
        >>> pl = pyvista.Plotter()  # doctest:+SKIP
        >>> pl.import_vrml(sextant_file)  # doctest:+SKIP
        >>> pl.show()  # doctest:+SKIP

        See :ref:`load_vrml_example` for a full example using this method.

        """
        from vtkmodules.vtkIOImport import vtkVRMLImporter

        filename = os.path.abspath(os.path.expanduser(str(filename)))
        if not os.path.isfile(filename):
            raise FileNotFoundError(f'Unable to locate {filename}')

        # lazy import here to avoid importing unused modules
        importer = vtkVRMLImporter()
        importer.SetFileName(filename)
        importer.SetRenderWindow(self.render_window)
        importer.Update()

    def export_html(self, filename):
        """Export this plotter as an interactive scene to a HTML file.

        Parameters
        ----------
        filename : str
            Path to export the html file to.

        Returns
        -------
        StringIO
            If filename is None, returns the HTML as a StringIO object.

        Notes
        -----
        You will need ``trame`` installed.

        Examples
        --------
        >>> import pyvista
        >>> from pyvista import examples
        >>> mesh = examples.load_uniform()
        >>> pl = pyvista.Plotter(shape=(1, 2))
        >>> _ = pl.add_mesh(
        ...     mesh, scalars='Spatial Point Data', show_edges=True
        ... )
        >>> pl.subplot(0, 1)
        >>> _ = pl.add_mesh(
        ...     mesh, scalars='Spatial Cell Data', show_edges=True
        ... )
        >>> pl.export_html('pyvista.html')  # doctest:+SKIP

        """
        try:
            from trame_vtk.tools.vtksz2html import write_html
        except ImportError:  # pragma: no cover
            raise ImportError('Please install trame-vtk to export')

        data = self.export_vtksz(filename=None)
        buffer = io.StringIO()
        write_html(data, buffer)
        buffer.seek(0)

        if filename is None:
            return buffer

        if not filename.endswith('.html'):
            filename += '.html'

        # Move to final destination
        with open(filename, 'w', encoding='utf-8') as f:
            f.write(buffer.read())

    def export_vtksz(self, filename='scene-export.vtksz', format='zip'):
        """Export this plotter as a VTK.js OfflineLocalView file.

        The exported file can be viewed with the OfflineLocalView viewer
        available at https://kitware.github.io/vtk-js/examples/OfflineLocalView.html

        Parameters
        ----------
        filename : str, optional
            Path to export the file to. Defaults to ``'scene-export.vtksz'``.

        format : str, optional
            The format of the exported file. Defaults to ``'zip'``. Can be
            either ``'zip'`` or ``'json'``.

        Returns
        -------
        str
            The exported filename.

        """
        try:
            from pyvista.trame import PyVistaLocalView
            from pyvista.trame.jupyter import elegantly_launch
            from pyvista.trame.views import get_server
        except ImportError:  # pragma: no cover
            raise ImportError('Please install trame to export')

        # Ensure trame server is launched
        server = get_server(pyvista.global_theme.trame.jupyter_server_name)
        if not server.running:
            elegantly_launch(pyvista.global_theme.trame.jupyter_server_name)

        view = PyVistaLocalView(self, trame_server=server)

        content = view.export(format=format)

        view.release_resources()
        # Make sure callbacks are unregistered
        self._on_render_callbacks.remove(view._plotter_render_callback)

        if filename is None:
            return content

        with open(filename, 'wb') as f:
            f.write(content)

        return filename

    def export_gltf(self, filename, inline_data=True, rotate_scene=True, save_normals=True):
        """Export the current rendering scene as a glTF file.

        Visit https://gltf-viewer.donmccurdy.com/ for an online viewer.

        See https://vtk.org/doc/nightly/html/classvtkGLTFExporter.html
        for limitations regarding the exporter.

        Parameters
        ----------
        filename : str
            Path to export the gltf file to.

        inline_data : bool, default: True
            Sets if the binary data be included in the json file as a
            base64 string.  When ``True``, only one file is exported.

        rotate_scene : bool, default: True
            Rotate scene to be compatible with the glTF specifications.

        save_normals : bool, default: True
            Saves the point array ``'Normals'`` as ``'NORMAL'`` in
            the outputted scene.

        Notes
        -----
        The VTK exporter only supports :class:`pyvista.PolyData` datasets. If
        the plotter contains any non-PolyData datasets, these will be converted
        in the plotter, leading to a copy of the data internally.

        Examples
        --------
        Output a simple point cloud represented as balls.

        >>> import numpy as np
        >>> import pyvista
        >>> point_cloud = np.random.random((100, 3))
        >>> pdata = pyvista.PolyData(point_cloud)
        >>> pdata['orig_sphere'] = np.arange(100)
        >>> sphere = pyvista.Sphere(radius=0.02)
        >>> pc = pdata.glyph(scale=False, geom=sphere, orient=False)
        >>> pl = pyvista.Plotter()
        >>> _ = pl.add_mesh(
        ...     pc,
        ...     cmap='reds',
        ...     smooth_shading=True,
        ...     show_scalar_bar=False,
        ... )
        >>> pl.export_gltf('balls.gltf')  # doctest:+SKIP
        >>> pl.show()

        Output the orientation plotter.

        >>> from pyvista import demos
        >>> pl = demos.orientation_plotter()
        >>> pl.export_gltf('orientation_plotter.gltf')  # doctest:+SKIP
        >>> pl.show()

        """
        if self.render_window is None:
            raise RuntimeError('This plotter has been closed and is unable to export the scene.')

        from vtkmodules.vtkIOExport import vtkGLTFExporter

        # rotate scene to gltf compatible view
        renamed_arrays = []  # any renamed normal arrays
        if rotate_scene:
            for renderer in self.renderers:
                for actor in renderer.actors.values():
                    if hasattr(actor, 'RotateX'):
                        actor.RotateX(-90)
                        actor.RotateZ(-90)

                    if save_normals:
                        try:
                            mapper = actor.GetMapper()
                            if mapper is None:
                                continue
                            dataset = mapper.dataset
                            if not isinstance(dataset, pyvista.PolyData):
                                warnings.warn(
                                    'Plotter contains non-PolyData datasets. These have been '
                                    'overwritten with PolyData surfaces and are internally '
                                    'copies of the original datasets.'
                                )

                                try:
                                    dataset = dataset.extract_surface()
                                    mapper.SetInputData(dataset)
                                except:  # pragma: no cover
                                    warnings.warn(
                                        'During gLTF export, failed to convert some '
                                        'datasets to PolyData. Exported scene will not have '
                                        'all datasets.'
                                    )

                            if 'Normals' in dataset.point_data:
                                # By default VTK uses the 'Normals' point data for normals
                                # but gLTF uses NORMAL.
                                point_data = dataset.GetPointData()
                                array = point_data.GetArray('Normals')
                                array.SetName('NORMAL')
                                renamed_arrays.append(array)

                        except:  # noqa: E722
                            pass

        exporter = vtkGLTFExporter()
        exporter.SetRenderWindow(self.render_window)
        exporter.SetFileName(filename)
        exporter.SetInlineData(inline_data)
        exporter.SetSaveNormal(save_normals)
        exporter.Update()

        # rotate back if applicable
        if rotate_scene:
            for renderer in self.renderers:
                for actor in renderer.actors.values():
                    if hasattr(actor, 'RotateX'):
                        actor.RotateZ(90)
                        actor.RotateX(90)

        # revert any renamed arrays
        for array in renamed_arrays:
            array.SetName('Normals')

    def export_vrml(self, filename):
        """Export the current rendering scene as a VRML file.

        See `vtk.VRMLExporter <https://vtk.org/doc/nightly/html/classvtkVRMLExporter.html>`_
        for limitations regarding the exporter.

        Parameters
        ----------
        filename : str
            Filename to export the scene to.

        Examples
        --------
        >>> import pyvista
        >>> from pyvista import examples
        >>> pl = pyvista.Plotter()
        >>> _ = pl.add_mesh(examples.load_hexbeam())
        >>> pl.export_vrml("sample")  # doctest:+SKIP

        """
        from vtkmodules.vtkIOExport import vtkVRMLExporter

        if self.render_window is None:
            raise RuntimeError("This plotter has been closed and cannot be shown.")

        exporter = vtkVRMLExporter()
        exporter.SetFileName(filename)
        exporter.SetRenderWindow(self.render_window)
        exporter.Write()

    def enable_hidden_line_removal(self, all_renderers=True):
        """Enable hidden line removal.

        Wireframe geometry will be drawn using hidden line removal if
        the rendering engine supports it.

        Disable this with :func:`disable_hidden_line_removal
        <Plotter.disable_hidden_line_removal>`.

        Parameters
        ----------
        all_renderers : bool, default: True
            If ``True``, applies to all renderers in subplots. If
            ``False``, then only applies to the active renderer.

        Examples
        --------
        Create a side-by-side plotter and render a sphere in wireframe
        with hidden line removal enabled on the left and disabled on
        the right.

        >>> import pyvista
        >>> sphere = pyvista.Sphere(theta_resolution=20, phi_resolution=20)
        >>> pl = pyvista.Plotter(shape=(1, 2))
        >>> _ = pl.add_mesh(sphere, line_width=3, style='wireframe')
        >>> _ = pl.add_text("With hidden line removal")
        >>> pl.enable_hidden_line_removal(all_renderers=False)
        >>> pl.subplot(0, 1)
        >>> pl.disable_hidden_line_removal(all_renderers=False)
        >>> _ = pl.add_mesh(sphere, line_width=3, style='wireframe')
        >>> _ = pl.add_text("Without hidden line removal")
        >>> pl.show()

        """
        if all_renderers:
            for renderer in self.renderers:
                renderer.enable_hidden_line_removal()
        else:
            self.renderer.enable_hidden_line_removal()

    def disable_hidden_line_removal(self, all_renderers=True):
        """Disable hidden line removal.

        Enable again with :func:`enable_hidden_line_removal
        <Plotter.enable_hidden_line_removal>`.

        Parameters
        ----------
        all_renderers : bool, default: True
            If ``True``, applies to all renderers in subplots. If
            ``False``, then only applies to the active renderer.

        Examples
        --------
        Enable and then disable hidden line removal.

        >>> import pyvista
        >>> pl = pyvista.Plotter()
        >>> pl.enable_hidden_line_removal()
        >>> pl.disable_hidden_line_removal()

        """
        if all_renderers:
            for renderer in self.renderers:
                renderer.disable_hidden_line_removal()
        else:
            self.renderer.disable_hidden_line_removal()

    @property
    def scalar_bar(self):  # numpydoc ignore=RT01
        """First scalar bar (kept for backwards compatibility).

        Returns
        -------
        vtk.vtkScalarBarActor
            First scalar bar actor.

        """
        return list(self.scalar_bars.values())[0]

    @property
    def scalar_bars(self):  # numpydoc ignore=RT01
        """Scalar bars.

        Returns
        -------
        pyvista.ScalarBars
            Scalar bar object.

        Examples
        --------
        >>> import pyvista
        >>> sphere = pyvista.Sphere()
        >>> sphere['Data'] = sphere.points[:, 2]
        >>> plotter = pyvista.Plotter()
        >>> _ = plotter.add_mesh(sphere)
        >>> plotter.scalar_bars
        Scalar Bar Title     Interactive
        "Data"               False

        Select a scalar bar actor based on the title of the bar.

        >>> plotter.scalar_bars['Data']
        <vtkmodules.vtkRenderingAnnotation.vtkScalarBarActor(...) at ...>

        """
        return self._scalar_bars

    @property
    def _before_close_callback(self):
        """Return the cached function (expecting a reference)."""
        if self.__before_close_callback is not None:
            return self.__before_close_callback()

    @_before_close_callback.setter
    def _before_close_callback(self, func):
        """Store a weakref.ref of the function being called."""
        if func is not None:
            self.__before_close_callback = weakref.ref(func)
        else:
            self.__before_close_callback = None

    @property
    def shape(self):  # numpydoc ignore=RT01
        """Return the shape of the plotter.

        Returns
        -------
        tuple
            Shape of the plotter.

        Examples
        --------
        Return the plotter shape.

        >>> import pyvista
        >>> plotter = pyvista.Plotter(shape=(2, 2))
        >>> plotter.shape
        (2, 2)
        """
        return self.renderers._shape

    @property
    def renderer(self):  # numpydoc ignore=RT01
        """Return the active renderer.

        Returns
        -------
        pyvista.Renderer
            Active render.

        Examples
        --------
        >>> import pyvista
        >>> pl = pyvista.Plotter()
        >>> pl.renderer
        <Renderer(...) at ...>

        """
        return self.renderers.active_renderer

    @property
    def store_image(self):  # numpydoc ignore=RT01
        """Store last rendered frame on close.

        .. deprecated:: 0.38.0
           ``store_image`` is no longer used. Images are automatically cached
           as needed.

        """
        from pyvista.core.errors import DeprecationError

        raise DeprecationError(
            '`store_image` has been deprecated as of 0.38.0 and is no longer used.'
            ' Images are automatically cached as needed.'
        )

    @store_image.setter
    def store_image(self, value):  # numpydoc ignore=GL08
        from pyvista.core.errors import DeprecationError

        raise DeprecationError(
            '`store_image` has been deprecated as of 0.38.0 and is no longer used.'
            ' Images are automatically cached as needed.'
        )

    def subplot(self, index_row, index_column=None):
        """Set the active subplot.

        Parameters
        ----------
        index_row : int
            Index of the subplot to activate along the rows.

        index_column : int, optional
            Index of the subplot to activate along the columns.

        Examples
        --------
        Create a 2 wide plot and set the background of right-hand plot
        to orange.  Add a cube to the left plot and a sphere to the
        right.

        >>> import pyvista
        >>> pl = pyvista.Plotter(shape=(1, 2))
        >>> actor = pl.add_mesh(pyvista.Cube())
        >>> pl.subplot(0, 1)
        >>> actor = pl.add_mesh(pyvista.Sphere())
        >>> pl.set_background('orange', all_renderers=False)
        >>> pl.show()

        """
        self.renderers.set_active_renderer(index_row, index_column)

    @wraps(Renderer.add_ruler)
    def add_ruler(self, *args, **kwargs):  # numpydoc ignore=PR01,RT01
        """Wrap ``Renderer.add_ruler``."""
        return self.renderer.add_ruler(*args, **kwargs)

    @wraps(Renderer.add_legend_scale)
    def add_legend_scale(self, *args, **kwargs):  # numpydoc ignore=PR01,RT01
        """Wrap ``Renderer.add_legend_scale``."""
        return self.renderer.add_legend_scale(*args, **kwargs)

    @wraps(Renderer.add_legend)
    def add_legend(self, *args, **kwargs):  # numpydoc ignore=PR01,RT01
        """Wrap ``Renderer.add_legend``."""
        return self.renderer.add_legend(*args, **kwargs)

    @wraps(Renderer.remove_legend)
    def remove_legend(self, *args, **kwargs):  # numpydoc ignore=PR01,RT01
        """Wrap ``Renderer.remove_legend``."""
        return self.renderer.remove_legend(*args, **kwargs)

    @property
    def legend(self):  # numpydoc ignore=RT01
        """Legend actor.

        There can only be one legend actor per renderer.  If
        ``legend`` is ``None``, there is no legend actor.

        Returns
        -------
        vtk.vtkLegendBoxActor
            Legend actor.

        """
        return self.renderer.legend

    @wraps(Renderer.add_floor)
    def add_floor(self, *args, **kwargs):  # numpydoc ignore=PR01,RT01
        """Wrap ``Renderer.add_floor``."""
        return self.renderer.add_floor(*args, **kwargs)

    @wraps(Renderer.remove_floors)
    def remove_floors(self, *args, **kwargs):  # numpydoc ignore=PR01,RT01
        """Wrap ``Renderer.remove_floors``."""
        return self.renderer.remove_floors(*args, **kwargs)

    def enable_3_lights(self, only_active=False):
        """Enable 3-lights illumination.

        This will replace all pre-existing lights in the scene.

        Parameters
        ----------
        only_active : bool, default: False
            If ``True``, only change the active renderer. The default
            is that every renderer is affected.

        Examples
        --------
        >>> from pyvista import demos
        >>> pl = demos.orientation_plotter()
        >>> pl.enable_3_lights()
        >>> pl.show()

        Note how this varies from the default plotting.

        >>> pl = demos.orientation_plotter()
        >>> pl.show()

        """

        def _to_pos(elevation, azimuth):
            theta = azimuth * np.pi / 180.0
            phi = (90.0 - elevation) * np.pi / 180.0
            x = np.sin(theta) * np.sin(phi)
            y = np.cos(phi)
            z = np.cos(theta) * np.sin(phi)
            return x, y, z

        renderers = [self.renderer] if only_active else self.renderers
        for renderer in renderers:
            renderer.remove_all_lights()

        # Inspired from Mayavi's version of Raymond Maple 3-lights illumination
        intensities = [1, 0.6, 0.5]
        all_angles = [(45.0, 45.0), (-30.0, -60.0), (-30.0, 60.0)]
        for intensity, angles in zip(intensities, all_angles):
            light = pyvista.Light(light_type='camera light')
            light.intensity = intensity
            light.position = _to_pos(*angles)
            for renderer in renderers:
                renderer.add_light(light)

    def disable_3_lights(self):
        """Please use ``enable_lightkit``, this method has been deprecated."""
        from pyvista.core.errors import DeprecationError

        raise DeprecationError('DEPRECATED: Please use ``enable_lightkit``')

    def enable_lightkit(self, only_active=False):
        """Enable the default light-kit lighting.

        See:
        https://www.researchgate.net/publication/2926068_LightKit_A_lighting_system_for_effective_visualization

        This will replace all pre-existing lights in the renderer.

        Parameters
        ----------
        only_active : bool, default: False
            If ``True``, only change the active renderer. The default is that
            every renderer is affected.

        Examples
        --------
        Create a plotter without any lights and then enable the
        default light kit.

        >>> import pyvista
        >>> pl = pyvista.Plotter(lighting=None)
        >>> pl.enable_lightkit()
        >>> actor = pl.add_mesh(pyvista.Cube(), show_edges=True)
        >>> pl.show()

        """
        renderers = [self.renderer] if only_active else self.renderers

        light_kit = _vtk.vtkLightKit()
        for renderer in renderers:
            renderer.remove_all_lights()
            # Use the renderer as a vtkLightKit parser.
            # Feed it the LightKit, pop off the vtkLights, put back
            # pyvista Lights. This is the price we must pay for using
            # inheritance rather than composition.
            light_kit.AddLightsToRenderer(renderer)
            vtk_lights = renderer.lights
            renderer.remove_all_lights()
            for vtk_light in vtk_lights:
                light = pyvista.Light.from_vtk(vtk_light)
                renderer.add_light(light)
            renderer.LightFollowCameraOn()

    def enable_anti_aliasing(self, aa_type='ssaa', multi_samples=None, all_renderers=True):
        """Enable anti-aliasing.

        This tends to make edges appear softer and less pixelated.

        Parameters
        ----------
        aa_type : str, default: "ssaa"
            Anti-aliasing type. See the notes below. One of the following:

            * ``"ssaa"`` - Super-Sample Anti-Aliasing
            * ``"msaa"`` - Multi-Sample Anti-Aliasing
            * ``"fxaa"`` - Fast Approximate Anti-Aliasing

        multi_samples : int, optional
            The number of multi-samples when ``aa_type`` is ``"msaa"``. Note
            that using this setting automatically enables this for all
            renderers. Defaults to the theme multi_samples.

        all_renderers : bool, default: True
            If ``True``, applies to all renderers in subplots. If ``False``,
            then only applies to the active renderer.

        Notes
        -----
        SSAA, or Super-Sample Anti-Aliasing is a brute force method of
        anti-aliasing. It results in the best image quality but comes at a
        tremendous resource cost. SSAA works by rendering the scene at a higher
        resolution. The final image is produced by downsampling the
        massive source image using an averaging filter. This acts as a low pass
        filter which removes the high frequency components that would cause
        jaggedness.

        MSAA, or Multi-Sample Anti-Aliasing is an optimization of SSAA that
        reduces the amount of pixel shader evaluations that need to be computed
        by focusing on overlapping regions of the scene. The result is
        anti-aliasing along edges that is on par with SSAA and less
        anti-aliasing along surfaces as these make up the bulk of SSAA
        computations. MSAA is substantially less computationally expensive than
        SSAA and results in comparable image quality.

        FXAA, or Fast Approximate Anti-Aliasing is an Anti-Aliasing technique
        that is performed entirely in post processing. FXAA operates on the
        rasterized image rather than the scene geometry. As a consequence,
        forcing FXAA or using FXAA incorrectly can result in the FXAA filter
        smoothing out parts of the visual overlay that are usually kept sharp
        for reasons of clarity as well as smoothing out textures. FXAA is
        inferior to MSAA but is almost free computationally and is thus
        desirable on low end platforms.

        Examples
        --------
        Enable super-sample anti-aliasing (SSAA).

        >>> import pyvista
        >>> pl = pyvista.Plotter()
        >>> pl.enable_anti_aliasing('ssaa')
        >>> _ = pl.add_mesh(pyvista.Sphere(), show_edges=True)
        >>> pl.show()

        See :ref:`anti_aliasing_example` for a full example demonstrating
        VTK's anti-aliasing approaches.

        """
        # apply MSAA to entire render window
        if aa_type == 'msaa':
            if self.render_window is None:
                raise AttributeError('The render window has been closed.')
            if multi_samples is None:
                multi_samples = self._theme.multi_samples
            self.render_window.SetMultiSamples(multi_samples)
            return
        elif aa_type not in ['ssaa', 'fxaa']:
            raise ValueError(
                f'Invalid `aa_type` "{aa_type}". Should be either "fxaa", "ssaa", or "msaa"'
            )
        else:
            # disable MSAA as SSAA or FXAA is being enabled
            self.render_window.SetMultiSamples(0)

        if all_renderers:
            for renderer in self.renderers:
                renderer.enable_anti_aliasing(aa_type)
        else:
            self.renderer.enable_anti_aliasing(aa_type)

    def disable_anti_aliasing(self, all_renderers=True):
        """Disable anti-aliasing.

        Parameters
        ----------
        all_renderers : bool, default: True
            If ``True``, applies to all renderers in subplots. If ``False``,
            then only applies to the active renderer.

        Examples
        --------
        >>> import pyvista
        >>> pl = pyvista.Plotter()
        >>> pl.disable_anti_aliasing()
        >>> _ = pl.add_mesh(pyvista.Sphere(), show_edges=True)
        >>> pl.show()

        See :ref:`anti_aliasing_example` for a full example demonstrating
        VTK's anti-aliasing approaches.

        """
        self.render_window.SetMultiSamples(0)

        if all_renderers:
            for renderer in self.renderers:
                renderer.disable_anti_aliasing()
        else:
            self.renderer.disable_anti_aliasing()

    @wraps(Renderer.set_focus)
    def set_focus(self, *args, render=True, **kwargs):  # numpydoc ignore=PR01,RT01
        """Wrap ``Renderer.set_focus``."""
        log.debug('set_focus: %s, %s', str(args), str(kwargs))
        self.renderer.set_focus(*args, **kwargs)
        if render:
            self.render()

    @wraps(Renderer.set_position)
    def set_position(self, *args, render=True, **kwargs):  # numpydoc ignore=PR01,RT01
        """Wrap ``Renderer.set_position``."""
        self.renderer.set_position(*args, **kwargs)
        if render:
            self.render()

    @wraps(Renderer.set_viewup)
    def set_viewup(self, *args, render=True, **kwargs):  # numpydoc ignore=PR01,RT01
        """Wrap ``Renderer.set_viewup``."""
        self.renderer.set_viewup(*args, **kwargs)
        if render:
            self.render()

    @wraps(Renderer.add_orientation_widget)
    def add_orientation_widget(self, *args, **kwargs):  # numpydoc ignore=PR01,RT01
        """Wrap ``Renderer.add_orientation_widget``."""
        return self.renderer.add_orientation_widget(*args, **kwargs)

    @wraps(Renderer.add_axes)
    def add_axes(self, *args, **kwargs):  # numpydoc ignore=PR01,RT01
        """Wrap ``Renderer.add_axes``."""
        return self.renderer.add_axes(*args, **kwargs)

    @wraps(Renderer.hide_axes)
    def hide_axes(self, *args, **kwargs):  # numpydoc ignore=PR01,RT01
        """Wrap ``Renderer.hide_axes``."""
        return self.renderer.hide_axes(*args, **kwargs)

    @wraps(Renderer.show_axes)
    def show_axes(self, *args, **kwargs):  # numpydoc ignore=PR01,RT01
        """Wrap ``Renderer.show_axes``."""
        return self.renderer.show_axes(*args, **kwargs)

    @wraps(Renderer.update_bounds_axes)
    def update_bounds_axes(self, *args, **kwargs):  # numpydoc ignore=PR01,RT01
        """Wrap ``Renderer.update_bounds_axes``."""
        return self.renderer.update_bounds_axes(*args, **kwargs)

    @wraps(Renderer.add_chart)
    def add_chart(self, *args, **kwargs):  # numpydoc ignore=PR01,RT01
        """Wrap ``Renderer.add_chart``."""
        return self.renderer.add_chart(*args, **kwargs)

    @wraps(Renderer.remove_chart)
    def remove_chart(self, *args, **kwargs):  # numpydoc ignore=PR01,RT01
        """Wrap ``Renderer.remove_chart``."""
        return self.renderer.remove_chart(*args, **kwargs)

    @wraps(Renderers.set_chart_interaction)
    def set_chart_interaction(self, *args, **kwargs):  # numpydoc ignore=PR01,RT01
        """Wrap ``Renderers.set_chart_interaction``."""
        return self.renderers.set_chart_interaction(*args, **kwargs)

    @wraps(Renderer.add_actor)
    def add_actor(self, *args, **kwargs):  # numpydoc ignore=PR01,RT01
        """Wrap ``Renderer.add_actor``."""
        return self.renderer.add_actor(*args, **kwargs)

    @wraps(Renderer.enable_parallel_projection)
    def enable_parallel_projection(self, *args, **kwargs):  # numpydoc ignore=PR01,RT01
        """Wrap ``Renderer.enable_parallel_projection``."""
        return self.renderer.enable_parallel_projection(*args, **kwargs)

    @wraps(Renderer.disable_parallel_projection)
    def disable_parallel_projection(self, *args, **kwargs):  # numpydoc ignore=PR01,RT01
        """Wrap ``Renderer.disable_parallel_projection``."""
        return self.renderer.disable_parallel_projection(*args, **kwargs)

    @wraps(Renderer.enable_ssao)
    def enable_ssao(self, *args, **kwargs):  # numpydoc ignore=PR01,RT01
        """Wrap ``Renderer.enable_ssao``."""
        return self.renderer.enable_ssao(*args, **kwargs)

    @wraps(Renderer.disable_ssao)
    def disable_ssao(self, *args, **kwargs):  # numpydoc ignore=PR01,RT01
        """Wrap ``Renderer.disable_ssao``."""
        return self.renderer.disable_ssao(*args, **kwargs)

    @wraps(Renderer.enable_shadows)
    def enable_shadows(self, *args, **kwargs):  # numpydoc ignore=PR01,RT01
        """Wrap ``Renderer.enable_shadows``."""
        return self.renderer.enable_shadows(*args, **kwargs)

    @wraps(Renderer.disable_shadows)
    def disable_shadows(self, *args, **kwargs):  # numpydoc ignore=PR01,RT01
        """Wrap ``Renderer.disable_shadows``."""
        return self.renderer.disable_shadows(*args, **kwargs)

    @property
    def parallel_projection(self):  # numpydoc ignore=RT01
        """Return or set parallel projection state of active render window."""
        return self.renderer.parallel_projection

    @parallel_projection.setter
    def parallel_projection(self, state):  # numpydoc ignore=GL08
        self.renderer.parallel_projection = state

    @property
    def parallel_scale(self):  # numpydoc ignore=RT01
        """Return or set parallel scale of active render window."""
        return self.renderer.parallel_scale

    @parallel_scale.setter
    def parallel_scale(self, value):  # numpydoc ignore=GL08
        self.renderer.parallel_scale = value

    @wraps(Renderer.add_axes_at_origin)
    def add_axes_at_origin(self, *args, **kwargs):  # numpydoc ignore=PR01,RT01
        """Wrap ``Renderer.add_axes_at_origin``."""
        return self.renderer.add_axes_at_origin(*args, **kwargs)

    @wraps(Renderer.show_bounds)
    def show_bounds(self, *args, **kwargs):  # numpydoc ignore=PR01,RT01
        """Wrap ``Renderer.show_bounds``."""
        return self.renderer.show_bounds(*args, **kwargs)

    @wraps(Renderer.add_bounding_box)
    def add_bounding_box(self, *args, **kwargs):  # numpydoc ignore=PR01,RT01
        """Wrap ``Renderer.add_bounding_box``."""
        return self.renderer.add_bounding_box(*args, **kwargs)

    @wraps(Renderer.remove_bounding_box)
    def remove_bounding_box(self, *args, **kwargs):  # numpydoc ignore=PR01,RT01
        """Wrap ``Renderer.remove_bounding_box``."""
        return self.renderer.remove_bounding_box(*args, **kwargs)

    @wraps(Renderer.remove_bounds_axes)
    def remove_bounds_axes(self, *args, **kwargs):  # numpydoc ignore=PR01,RT01
        """Wrap ``Renderer.remove_bounds_axes``."""
        return self.renderer.remove_bounds_axes(*args, **kwargs)

    @wraps(Renderer.show_grid)
    def show_grid(self, *args, **kwargs):  # numpydoc ignore=PR01,RT01
        """Wrap ``Renderer.show_grid``."""
        return self.renderer.show_grid(*args, **kwargs)

    @wraps(Renderer.set_scale)
    def set_scale(self, *args, **kwargs):  # numpydoc ignore=PR01,RT01
        """Wrap ``Renderer.set_scale``."""
        return self.renderer.set_scale(*args, **kwargs)

    @wraps(Renderer.enable_depth_of_field)
    def enable_depth_of_field(self, *args, **kwargs):  # numpydoc ignore=PR01,RT01
        """Wrap ``Renderer.enable_depth_of_field``."""
        return self.renderer.enable_depth_of_field(*args, **kwargs)

    @wraps(Renderer.disable_depth_of_field)
    def disable_depth_of_field(self, *args, **kwargs):  # numpydoc ignore=PR01,RT01
        """Wrap ``Renderer.disable_depth_of_field``."""
        return self.renderer.disable_depth_of_field(*args, **kwargs)

    @wraps(Renderer.add_blurring)
    def add_blurring(self, *args, **kwargs):  # numpydoc ignore=PR01,RT01
        """Wrap ``Renderer.add_blurring``."""
        return self.renderer.add_blurring(*args, **kwargs)

    @wraps(Renderer.remove_blurring)
    def remove_blurring(self, *args, **kwargs):  # numpydoc ignore=PR01,RT01
        """Wrap ``Renderer.remove_blurring``."""
        return self.renderer.remove_blurring(*args, **kwargs)

    @wraps(Renderer.enable_eye_dome_lighting)
    def enable_eye_dome_lighting(self, *args, **kwargs):  # numpydoc ignore=PR01,RT01
        """Wrap ``Renderer.enable_eye_dome_lighting``."""
        return self.renderer.enable_eye_dome_lighting(*args, **kwargs)

    @wraps(Renderer.disable_eye_dome_lighting)
    def disable_eye_dome_lighting(self, *args, **kwargs):  # numpydoc ignore=PR01,RT01
        """Wrap ``Renderer.disable_eye_dome_lighting``."""
        self.renderer.disable_eye_dome_lighting(*args, **kwargs)

    @wraps(Renderer.reset_camera)
    def reset_camera(self, *args, **kwargs):  # numpydoc ignore=PR01,RT01
        """Wrap ``Renderer.reset_camera``."""
        self.renderer.reset_camera(*args, **kwargs)
        self.render()

    @wraps(Renderer.isometric_view)
    def isometric_view(self, *args, **kwargs):  # numpydoc ignore=PR01,RT01
        """Wrap ``Renderer.isometric_view``."""
        self.renderer.isometric_view(*args, **kwargs)

    @wraps(Renderer.view_isometric)
    def view_isometric(self, *args, **kwarg):  # numpydoc ignore=PR01,RT01
        """Wrap ``Renderer.view_isometric``."""
        self.renderer.view_isometric(*args, **kwarg)

    @wraps(Renderer.view_vector)
    def view_vector(self, *args, **kwarg):  # numpydoc ignore=PR01,RT01
        """Wrap ``Renderer.view_vector``."""
        self.renderer.view_vector(*args, **kwarg)

    @wraps(Renderer.view_xy)
    def view_xy(self, *args, **kwarg):  # numpydoc ignore=PR01,RT01
        """Wrap ``Renderer.view_xy``."""
        self.renderer.view_xy(*args, **kwarg)

    @wraps(Renderer.view_yx)
    def view_yx(self, *args, **kwarg):  # numpydoc ignore=PR01,RT01
        """Wrap ``Renderer.view_yx``."""
        self.renderer.view_yx(*args, **kwarg)

    @wraps(Renderer.view_xz)
    def view_xz(self, *args, **kwarg):  # numpydoc ignore=PR01,RT01
        """Wrap ``Renderer.view_xz``."""
        self.renderer.view_xz(*args, **kwarg)

    @wraps(Renderer.view_zx)
    def view_zx(self, *args, **kwarg):  # numpydoc ignore=PR01,RT01
        """Wrap ``Renderer.view_zx``."""
        self.renderer.view_zx(*args, **kwarg)

    @wraps(Renderer.view_yz)
    def view_yz(self, *args, **kwarg):  # numpydoc ignore=PR01,RT01
        """Wrap ``Renderer.view_yz``."""
        self.renderer.view_yz(*args, **kwarg)

    @wraps(Renderer.view_zy)
    def view_zy(self, *args, **kwarg):  # numpydoc ignore=PR01,RT01
        """Wrap ``Renderer.view_zy``."""
        self.renderer.view_zy(*args, **kwarg)

    @wraps(Renderer.disable)
    def disable(self, *args, **kwarg):  # numpydoc ignore=PR01,RT01
        """Wrap ``Renderer.disable``."""
        self.renderer.disable(*args, **kwarg)

    @wraps(Renderer.enable)
    def enable(self, *args, **kwarg):  # numpydoc ignore=PR01,RT01
        """Wrap ``Renderer.enable``."""
        self.renderer.enable(*args, **kwarg)

    @wraps(Renderer.enable_depth_peeling)
    def enable_depth_peeling(self, *args, **kwargs):  # numpydoc ignore=PR01,RT01
        """Wrap ``Renderer.enable_depth_peeling``."""
        if self.render_window is not None:
            result = self.renderer.enable_depth_peeling(*args, **kwargs)
            if result:
                self.render_window.AlphaBitPlanesOn()
            return result

    @wraps(Renderer.disable_depth_peeling)
    def disable_depth_peeling(self):  # numpydoc ignore=PR01,RT01
        """Wrap ``Renderer.disable_depth_peeling``."""
        if self.render_window is not None:
            self.render_window.AlphaBitPlanesOff()
            return self.renderer.disable_depth_peeling()

    @wraps(Renderer.get_default_cam_pos)
    def get_default_cam_pos(self, *args, **kwargs):  # numpydoc ignore=PR01,RT01
        """Wrap ``Renderer.get_default_cam_pos``."""
        return self.renderer.get_default_cam_pos(*args, **kwargs)

    @wraps(Renderer.remove_actor)
    def remove_actor(self, *args, **kwargs):  # numpydoc ignore=PR01,RT01
        """Wrap ``Renderer.remove_actor``."""
        for renderer in self.renderers:
            renderer.remove_actor(*args, **kwargs)
        return True

    @wraps(Renderer.set_environment_texture)
    def set_environment_texture(self, *args, **kwargs):  # numpydoc ignore=PR01,RT01
        """Wrap ``Renderer.set_environment_texture``."""
        return self.renderer.set_environment_texture(*args, **kwargs)

    @wraps(Renderer.remove_environment_texture)
    def remove_environment_texture(self, *args, **kwargs):  # numpydoc ignore=PR01,RT01
        """Wrap ``Renderer.remove_environment_texture``."""
        return self.renderer.remove_environment_texture(*args, **kwargs)

    #### Properties from Renderer ####

    @property
    def actors(self):  # numpydoc ignore=RT01
        """Return the actors of the active renderer.

        Returns
        -------
        dict
            Dictionary of active actors.

        """
        return self.renderer.actors

    @property
    def camera(self):  # numpydoc ignore=RT01
        """Return the active camera of the active renderer.

        Returns
        -------
        pyvista.Camera
            Camera from the active renderer.

        """
        if not self.renderer.camera.is_set:
            self.camera_position = self.get_default_cam_pos()
            self.reset_camera()
            self.renderer.camera.is_set = True
        return self.renderer.camera

    @camera.setter
    def camera(self, camera):  # numpydoc ignore=GL08
        self.renderer.camera = camera

    @property
    def camera_set(self):  # numpydoc ignore=RT01
        """Return or set if the camera of the active renderer has been set."""
        return self.renderer.camera.is_set

    @camera_set.setter
    def camera_set(self, is_set):  # numpydoc ignore=GL08
        self.renderer.camera.is_set = is_set

    @property
    def bounds(self) -> BoundsLike:  # numpydoc ignore=RT01
        """Return the bounds of the active renderer.

        Returns
        -------
        tuple[float, float, float, float, float, float]
            Bounds of the active renderer.

        Examples
        --------
        >>> import pyvista
        >>> pl = pyvista.Plotter()
        >>> _ = pl.add_mesh(pyvista.Cube())
        >>> pl.bounds
        (-0.5, 0.5, -0.5, 0.5, -0.5, 0.5)

        """
        return self.renderer.bounds

    @property
    def length(self):  # numpydoc ignore=RT01
        """Return the length of the diagonal of the bounding box of the scene."""
        return self.renderer.length

    @property
    def center(self):  # numpydoc ignore=RT01
        """Return the center of the active renderer."""
        return self.renderer.center

    @property
    def _scalar_bar_slots(self):
        """Return the scalar bar slots of the active renderer."""
        return self.renderer._scalar_bar_slots

    @_scalar_bar_slots.setter
    def _scalar_bar_slots(self, value):
        """Set the scalar bar slots of the active renderer."""
        self.renderer._scalar_bar_slots = value

    @property
    def _scalar_bar_slot_lookup(self):
        """Return the scalar bar slot lookup of the active renderer."""
        return self.renderer._scalar_bar_slot_lookup

    @_scalar_bar_slot_lookup.setter
    def _scalar_bar_slot_lookup(self, value):
        self.renderer._scalar_bar_slot_lookup = value

    @property
    def scale(self):  # numpydoc ignore=RT01
        """Return the scaling of the active renderer."""
        return self.renderer.scale

    @scale.setter
    def scale(self, scale):  # numpydoc ignore=GL08
        self.renderer.set_scale(*scale)

    @property
    def camera_position(self):  # numpydoc ignore=RT01
        """Return camera position of the active render window.

        Examples
        --------
        Return camera's position and then reposition it via a list of tuples.

        >>> import pyvista as pv
        >>> from pyvista import examples
        >>> mesh = examples.download_bunny_coarse()
        >>> pl = pv.Plotter()
        >>> _ = pl.add_mesh(mesh, show_edges=True, reset_camera=True)
        >>> pl.camera_position
        [(0.02430, 0.0336, 0.9446),
         (0.02430, 0.0336, -0.02225),
         (0.0, 1.0, 0.0)]
        >>> pl.camera_position = [
        ...     (0.3914, 0.4542, 0.7670),
        ...     (0.0243, 0.0336, -0.0222),
        ...     (-0.2148, 0.8998, -0.3796),
        ... ]
        >>> pl.show()

        Set the camera position using a string and look at the ``'xy'`` plane.

        >>> pl = pv.Plotter()
        >>> _ = pl.add_mesh(mesh, show_edges=True)
        >>> pl.camera_position = 'xy'
        >>> pl.show()

        Set the camera position using a string and look at the ``'zy'`` plane.

        >>> pl = pv.Plotter()
        >>> _ = pl.add_mesh(mesh, show_edges=True)
        >>> pl.camera_position = 'zy'
        >>> pl.show()

        For more examples, see :ref:`cameras_api`.

        """
        return self.renderer.camera_position

    @camera_position.setter
    def camera_position(self, camera_location):  # numpydoc ignore=GL08
        self.renderer.camera_position = camera_location

    @property
    def background_color(self):  # numpydoc ignore=RT01
        """Return the background color of the active render window.

        Examples
        --------
        Set the background color to ``"pink"`` and plot it.

        >>> import pyvista as pv
        >>> pl = pv.Plotter()
        >>> _ = pl.add_mesh(pv.Cube(), show_edges=True)
        >>> pl.background_color = "pink"
        >>> pl.background_color
        Color(name='pink', hex='#ffc0cbff', opacity=255)
        >>> pl.show()

        """
        return self.renderers.active_renderer.background_color

    @background_color.setter
    def background_color(self, color):  # numpydoc ignore=GL08
        self.set_background(color)

    @property
    def window_size(self):  # numpydoc ignore=RT01
        """Return the render window size in ``(width, height)``.

        Examples
        --------
        Change the window size from ``200 x 200`` to ``400 x 400``.

        >>> import pyvista
        >>> pl = pyvista.Plotter(window_size=[200, 200])
        >>> pl.window_size
        [200, 200]
        >>> pl.window_size = [400, 400]
        >>> pl.window_size
        [400, 400]

        """
        return list(self.render_window.GetSize())

    @window_size.setter
    def window_size(self, window_size):  # numpydoc ignore=GL08
        self.render_window.SetSize(window_size[0], window_size[1])
        self._window_size_unset = False
        self.render()

    @contextmanager
    def window_size_context(self, window_size=None):
        """Set the render window size in an isolated context.

        Parameters
        ----------
        window_size : sequence[int], optional
            Window size in pixels.  Defaults to :attr:`pyvista.Plotter.window_size`.

        Examples
        --------
        Take two different screenshots with two different window sizes.

        >>> import pyvista as pv
        >>> pl = pv.Plotter(off_screen=True)
        >>> _ = pl.add_mesh(pv.Cube())
        >>> with pl.window_size_context((400, 400)):
        ...     pl.screenshot('/tmp/small_screenshot.png')  # doctest:+SKIP
        ...
        >>> with pl.window_size_context((1000, 1000)):
        ...     pl.screenshot('/tmp/big_screenshot.png')  # doctest:+SKIP
        ...

        """
        # No op if not set
        if window_size is None:
            yield self
            return
        # If render window is not current
        if self.render_window is None:
            warnings.warn('Attempting to set window_size on an unavailable render widow.')
            yield self
            return
        size_before = self.window_size
        if window_size is not None:
            self.window_size = window_size
        try:
            yield self
        finally:
            # Sometimes the render window is destroyed within the context
            # and re-setting will fail
            if self.render_window is not None:
                self.window_size = size_before

    @property
    def image_depth(self):  # numpydoc ignore=RT01
        """Return a depth image representing current render window.

        Helper attribute for ``get_image_depth``.

        """
        return self.get_image_depth()

    def _check_rendered(self):
        """Check if the render window has been shown and raise an exception if not."""
        if not self._rendered:
            raise AttributeError(
                '\nThis plotter has not yet been set up and rendered '
                'with ``show()``.\n'
                'Consider setting ``off_screen=True`` '
                'for off screen rendering.\n'
            )

    def _check_has_ren_win(self):
        """Check if render window attribute exists and raise an exception if not."""
        if self.render_window is None:
            raise RenderWindowUnavailable('Render window is not available.')
        if not self.render_window.IsCurrent():
            raise RenderWindowUnavailable('Render window is not current.')

    def _make_render_window_current(self):
        if self.render_window is None:
            raise RenderWindowUnavailable('Render window is not available.')
        self.render_window.MakeCurrent()  # pragma: no cover

    @property
    def image(self):  # numpydoc ignore=RT01
        """Return an image array of current render window."""
        if self.render_window is None and self.last_image is not None:
            return self.last_image

        self._check_rendered()
        self._check_has_ren_win()

        data = image_from_window(self.render_window, scale=self.image_scale)
        if self.image_transparent_background:
            return data

        # ignore alpha channel
        return data[:, :, :-1]

    @property
    def image_scale(self) -> int:  # numpydoc ignore=RT01
        """Get or set the scale factor when saving a screenshot.

        This will scale up the screenshots taken of the render window to save a
        higher resolution image than what is rendered on screen.

        Image sizes will be the :py:attr:`window_size
        <pyvista.Plotter.window_size>` multiplied by this scale factor.

        Returns
        -------
        int
            Image scale factor.

        Examples
        --------
        Double the resolution of a screenshot.

        >>> import pyvista as pv
        >>> pl = pv.Plotter()
        >>> _ = pl.add_mesh(pv.Sphere())
        >>> pl.image_scale = 2
        >>> pl.screenshot('screenshot.png')  # doctest:+SKIP

        Set the image scale from ``Plotter``.

        >>> import pyvista as pv
        >>> pl = pv.Plotter(image_scale=2)
        >>> _ = pl.add_mesh(pv.Sphere())
        >>> pl.screenshot('screenshot.png')  # doctest:+SKIP

        """
        return self._image_scale

    @image_scale.setter
    def image_scale(self, value: int):  # numpydoc ignore=GL08
        value = int(value)
        if value < 1:
            raise ValueError('Scale factor must be a positive integer.')
        self._image_scale = value

    @contextmanager
    def image_scale_context(self, scale: Optional[int] = None):
        """Set the image scale in an isolated context.

        Parameters
        ----------
        scale : int, optional
            Integer scale factor.  Defaults to :attr:`pyvista.Plotter.image_scale`.

        """
        scale_before = self.image_scale
        if scale is not None:
            self.image_scale = scale
        try:
            yield self
        finally:
            self.image_scale = scale_before

    def render(self):
        """Render the main window.

        Will not render until ``show`` has been called.

        Any render callbacks added with
        :func:`add_on_render_callback() <pyvista.Plotter.add_on_render_callback>`
        and the ``render_event=False`` option set will still execute on any call.
        """
        if self.render_window is not None and not self._first_time and not self._suppress_rendering:
            log.debug('Rendering')
            self.renderers.on_plotter_render()
            self.render_window.Render()
            self._rendered = True
        for callback in self._on_render_callbacks:
            callback(self)

    def add_on_render_callback(self, callback, render_event=False):
        """Add a method to be called post-render.

        Parameters
        ----------
        callback : callable
            The callback method to run post-render. This takes a single
            argument which is the plotter object.

        render_event : bool, default: False
            If ``True``, associate with all VTK RenderEvents. Otherwise, the
            callback is only handled on a successful ``render()`` from the
            PyVista plotter directly.

        """
        if render_event:
            for renderer in self.renderers:
                renderer.AddObserver(_vtk.vtkCommand.RenderEvent, lambda *args: callback(self))
        else:
            self._on_render_callbacks.add(callback)

    def clear_on_render_callbacks(self):
        """Clear all callback methods previously registered with ``render()``."""
        for renderer in self.renderers:
            renderer.RemoveObservers(_vtk.vtkCommand.RenderEvent)
        self._on_render_callbacks = set()

    @wraps(RenderWindowInteractor.add_key_event)
    def add_key_event(self, *args, **kwargs):  # numpydoc ignore=PR01,RT01
        """Wrap RenderWindowInteractor.add_key_event."""
        if hasattr(self, 'iren'):
            self.iren.add_key_event(*args, **kwargs)

    @wraps(RenderWindowInteractor.clear_events_for_key)
    def clear_events_for_key(self, *args, **kwargs):  # numpydoc ignore=PR01,RT01
        """Wrap RenderWindowInteractor.clear_events_for_key."""
        if hasattr(self, 'iren'):
            self.iren.clear_events_for_key(*args, **kwargs)

    def store_mouse_position(self, *args):
        """Store mouse position."""
        if not hasattr(self, "iren"):
            raise AttributeError("This plotting window is not interactive.")
        self.mouse_position = self.iren.get_event_position()

    def store_click_position(self, *args):
        """Store click position in viewport coordinates."""
        if not hasattr(self, "iren"):
            raise AttributeError("This plotting window is not interactive.")
        self.click_position = self.iren.get_event_position()
        self.mouse_position = self.click_position

    def track_mouse_position(self):
        """Keep track of the mouse position.

        This will potentially slow down the interactor. No callbacks
        supported here - use
        :func:`pyvista.Plotter.track_click_position` instead.

        """
        self.iren.track_mouse_position(self.store_mouse_position)

    def untrack_mouse_position(self):
        """Stop tracking the mouse position."""
        self.iren.untrack_mouse_position()

    @wraps(RenderWindowInteractor.track_click_position)
    def track_click_position(self, *args, **kwargs):  # numpydoc ignore=PR01,RT01
        """Wrap RenderWindowInteractor.track_click_position."""
        self.iren.track_click_position(*args, **kwargs)

    @wraps(RenderWindowInteractor.untrack_click_position)
    def untrack_click_position(self, *args, **kwargs):  # numpydoc ignore=PR01,RT01
        """Stop tracking the click position."""
        self.iren.untrack_click_position(*args, **kwargs)

    @property
    def pickable_actors(self):  # numpydoc ignore=RT01
        """Return or set the pickable actors.

        When setting, this will be the list of actors to make
        pickable. All actors not in the list will be made unpickable.
        If ``actors`` is ``None``, all actors will be made unpickable.

        Returns
        -------
        list[pyvista.Actor]
            List of actors.

        Examples
        --------
        Add two actors to a :class:`pyvista.Plotter`, make one
        pickable, and then list the pickable actors.

        >>> import pyvista as pv
        >>> pl = pv.Plotter()
        >>> sphere_actor = pl.add_mesh(pv.Sphere())
        >>> cube_actor = pl.add_mesh(
        ...     pv.Cube(), pickable=False, style='wireframe'
        ... )
        >>> len(pl.pickable_actors)
        1

        Set the pickable actors to both actors.

        >>> pl.pickable_actors = [sphere_actor, cube_actor]
        >>> len(pl.pickable_actors)
        2

        Set the pickable actors to ``None``.

        >>> pl.pickable_actors = None
        >>> len(pl.pickable_actors)
        0

        """
        pickable = []
        for renderer in self.renderers:
            for actor in renderer.actors.values():
                if actor.GetPickable():
                    pickable.append(actor)
        return pickable

    @pickable_actors.setter
    def pickable_actors(self, actors=None):  # numpydoc ignore=GL08
        actors = [] if actors is None else actors
        if isinstance(actors, _vtk.vtkActor):
            actors = [actors]

        if not all([isinstance(actor, _vtk.vtkActor) for actor in actors]):
            raise TypeError(
                f'Expected a vtkActor instance or a list of vtkActors, got '
                f'{[type(actor) for actor in actors]} instead.'
            )

        for renderer in self.renderers:
            for actor in renderer.actors.values():
                actor.SetPickable(actor in actors)

    def _prep_for_close(self):
        """Make sure a screenshot is acquired before closing.

        This doesn't actually close anything. It just preps the plotter for
        closing.
        """
        # Grab screenshot right before renderer closes
        self.last_image = self.screenshot(True, return_img=True)
        self.last_image_depth = self.get_image_depth()

    def increment_point_size_and_line_width(self, increment):
        """Increment point size and line width of all actors.

        For every actor in the scene, increment both its point size
        and line width by the given value.

        Parameters
        ----------
        increment : float
            Amount to increment point size and line width.

        """
        for renderer in self.renderers:
            for actor in renderer._actors.values():
                if hasattr(actor, "GetProperty"):
                    prop = actor.GetProperty()
                    if hasattr(prop, "SetPointSize"):
                        prop.SetPointSize(prop.GetPointSize() + increment)
                    if hasattr(prop, "SetLineWidth"):
                        prop.SetLineWidth(prop.GetLineWidth() + increment)
        self.render()
        return

    def reset_key_events(self):
        """Reset all of the key press events to their defaults."""
        if not hasattr(self, 'iren'):
            return

        self.iren.clear_key_event_callbacks()

        self.add_key_event('q', self._prep_for_close)  # Add no matter what
        b_left_down_callback = lambda: self.iren.add_observer(
            'LeftButtonPressEvent', self.left_button_down
        )
        self.add_key_event('b', b_left_down_callback)
        self.add_key_event('v', lambda: self.isometric_view_interactive())
        self.add_key_event('C', lambda: self.enable_cell_picking())
        self.add_key_event('Up', lambda: self.camera.Zoom(1.05))
        self.add_key_event('Down', lambda: self.camera.Zoom(0.95))
        self.add_key_event('plus', lambda: self.increment_point_size_and_line_width(1))
        self.add_key_event('minus', lambda: self.increment_point_size_and_line_width(-1))

    @wraps(RenderWindowInteractor.key_press_event)
    def key_press_event(self, *args, **kwargs):  # numpydoc ignore=PR01,RT01
        """Wrap RenderWindowInteractor.key_press_event."""
        self.iren.key_press_event(*args, **kwargs)

    def left_button_down(self, obj, event_type):
        """Register the event for a left button down click."""
        if hasattr(self.render_window, 'GetOffScreenFramebuffer'):
            if not self.render_window.GetOffScreenFramebuffer().GetFBOIndex():
                # must raise a runtime error as this causes a segfault on VTK9
                raise ValueError('Invoking helper with no framebuffer')
        # Get 2D click location on window
        click_pos = self.iren.get_event_position()

        # Get corresponding click location in the 3D plot
        picker = _vtk.vtkWorldPointPicker()
        picker.Pick(click_pos[0], click_pos[1], 0, self.renderer)
        self.pickpoint = np.asarray(picker.GetPickPosition()).reshape((-1, 3))
        if np.any(np.isnan(self.pickpoint)):
            self.pickpoint[:] = 0

    @wraps(RenderWindowInteractor.enable_trackball_style)
    def enable_trackball_style(self):  # numpydoc ignore=PR01,RT01
        """Wrap RenderWindowInteractor.enable_trackball_style."""
        self.iren.enable_trackball_style()

    @wraps(RenderWindowInteractor.enable_trackball_actor_style)
    def enable_trackball_actor_style(self):  # numpydoc ignore=PR01,RT01
        """Wrap RenderWindowInteractor.enable_trackball_actor_style."""
        self.iren.enable_trackball_actor_style()

    @wraps(RenderWindowInteractor.enable_image_style)
    def enable_image_style(self):  # numpydoc ignore=PR01,RT01
        """Wrap RenderWindowInteractor.enable_image_style."""
        self.iren.enable_image_style()

    @wraps(RenderWindowInteractor.enable_joystick_style)
    def enable_joystick_style(self):  # numpydoc ignore=PR01,RT01
        """Wrap RenderWindowInteractor.enable_joystick_style."""
        self.iren.enable_joystick_style()

    @wraps(RenderWindowInteractor.enable_joystick_actor_style)
    def enable_joystick_actor_style(self):  # numpydoc ignore=PR01,RT01
        """Wrap RenderWindowInteractor.enable_joystick_actor_style."""
        self.iren.enable_joystick_actor_style()

    @wraps(RenderWindowInteractor.enable_zoom_style)
    def enable_zoom_style(self):  # numpydoc ignore=PR01,RT01
        """Wrap RenderWindowInteractor.enable_zoom_style."""
        self.iren.enable_zoom_style()

    @wraps(RenderWindowInteractor.enable_terrain_style)
    def enable_terrain_style(self, *args, **kwargs):  # numpydoc ignore=PR01,RT01
        """Wrap RenderWindowInteractor.enable_terrain_style."""
        self.iren.enable_terrain_style(*args, **kwargs)

    @wraps(RenderWindowInteractor.enable_rubber_band_style)
    def enable_rubber_band_style(self):  # numpydoc ignore=PR01,RT01
        """Wrap RenderWindowInteractor.enable_rubber_band_style."""
        self.iren.enable_rubber_band_style()

    @wraps(RenderWindowInteractor.enable_rubber_band_2d_style)
    def enable_rubber_band_2d_style(self):  # numpydoc ignore=PR01,RT01
        """Wrap RenderWindowInteractor.enable_rubber_band_2d_style."""
        self.iren.enable_rubber_band_2d_style()

    def enable_stereo_render(self):
        """Enable anaglyph stereo rendering.

        Disable this with :func:`disable_stereo_render
        <Plotter.disable_stereo_render>`

        Examples
        --------
        Enable stereo rendering to show a cube as an anaglyph image.

        >>> import pyvista as pv
        >>> pl = pv.Plotter()
        >>> _ = pl.add_mesh(pv.Cube())
        >>> pl.enable_stereo_render()
        >>> pl.show()

        """
        if self.render_window is not None:
            self.render_window.SetStereoTypeToAnaglyph()
            self.render_window.StereoRenderOn()

    def disable_stereo_render(self):
        """Disable anaglyph stereo rendering.

        Enable again with :func:`enable_stereo_render
        <Plotter.enable_stereo_render>`

        Examples
        --------
        Enable and then disable stereo rendering. It should show a simple cube.

        >>> import pyvista as pv
        >>> pl = pv.Plotter()
        >>> _ = pl.add_mesh(pv.Cube())
        >>> pl.enable_stereo_render()
        >>> pl.disable_stereo_render()
        >>> pl.show()

        """
        if self.render_window is not None:
            self.render_window.StereoRenderOff()

    def hide_axes_all(self):
        """Hide the axes orientation widget in all renderers."""
        for renderer in self.renderers:
            renderer.hide_axes()

    def show_axes_all(self):
        """Show the axes orientation widget in all renderers.

        Examples
        --------
        >>> import pyvista
        >>> from pyvista import examples
        >>>
        >>> mesh = examples.load_globe()
        >>> texture = examples.load_globe_texture()
        >>>
        >>> # create multi-window plot (1 row, 2 columns)
        >>> pl = pyvista.Plotter(shape=(1, 2))
        >>>
        >>> # activate subplot 1 and add a mesh
        >>> pl.subplot(0, 0)
        >>> _ = pl.add_mesh(mesh, texture=texture)
        >>>
        >>> # activate subplot 2 and add a mesh
        >>> pl.subplot(0, 1)
        >>> _ = pl.add_mesh(examples.load_airplane())
        >>>
        >>> # show the axes orientation widget in all subplots
        >>> pl.show_axes_all()
        >>>
        >>> # display the window
        >>> pl.show()

        """
        for renderer in self.renderers:
            renderer.show_axes()

    def isometric_view_interactive(self):
        """Set the current interactive render window to isometric view."""
        interactor = self.iren.get_interactor_style()
        renderer = interactor.GetCurrentRenderer()
        if renderer is None:
            renderer = self.renderer
        renderer.view_isometric()

    def update(self, stime=1, force_redraw=True):
        """Update window, redraw, process messages query.

        Parameters
        ----------
        stime : int, default: 1
            Duration of timer that interrupt vtkRenderWindowInteractor
            in milliseconds.

        force_redraw : bool, default: True
            Call ``render`` immediately.

        """
        if stime <= 0:
            stime = 1

        curr_time = time.time()
        if Plotter.last_update_time > curr_time:
            Plotter.last_update_time = curr_time

        if self.iren is not None:
            update_rate = self.iren.get_desired_update_rate()
            if (curr_time - Plotter.last_update_time) > (1.0 / update_rate):
                # Allow interaction for a brief moment during interactive updating
                # Use the non-blocking ProcessEvents method.
                self.iren.process_events()
                # Rerender
                self.render()
                Plotter.last_update_time = curr_time
                return

        if force_redraw:
            self.render()

    def add_composite(
        self,
        dataset,
        color=None,
        style=None,
        scalars=None,
        clim=None,
        show_edges=None,
        edge_color=None,
        point_size=None,
        line_width=None,
        opacity=1.0,
        flip_scalars=False,
        lighting=None,
        n_colors=256,
        interpolate_before_map=True,
        cmap=None,
        label=None,
        reset_camera=None,
        scalar_bar_args=None,
        show_scalar_bar=None,
        multi_colors=False,
        name=None,
        render_points_as_spheres=None,
        render_lines_as_tubes=None,
        smooth_shading=None,
        split_sharp_edges=None,
        ambient=None,
        diffuse=None,
        specular=None,
        specular_power=None,
        nan_color=None,
        nan_opacity=1.0,
        culling=None,
        rgb=None,
        categories=None,
        below_color=None,
        above_color=None,
        annotations=None,
        pickable=True,
        preference="point",
        log_scale=False,
        pbr=None,
        metallic=None,
        roughness=None,
        render=True,
        component=None,
        color_missing_with_nan=False,
        copy_mesh=False,
        show_vertices=None,
        **kwargs,
    ):
        """Add a composite dataset to the plotter.

        Parameters
        ----------
        dataset : pyvista.MultiBlock
            A :class:`pyvista.MultiBlock` dataset.

        color : ColorLike, default: :attr:`pyvista.plotting.themes.Theme.color`
            Use to make the entire mesh have a single solid color.
            Either a string, RGB list, or hex color string.  For example:
            ``color='white'``, ``color='w'``, ``color=[1.0, 1.0, 1.0]``, or
            ``color='#FFFFFF'``. Color will be overridden if scalars are
            specified. To color each element of the composite dataset
            individually, you will need to iteratively call ``add_mesh`` for
            each sub-dataset.

        style : str, default: 'wireframe'
            Visualization style of the mesh.  One of the following:
            ``style='surface'``, ``style='wireframe'``, ``style='points'``.
            Defaults to ``'surface'``. Note that ``'wireframe'`` only shows a
            wireframe of the outer geometry.

        scalars : str, optional
            Scalars used to "color" the points or cells of the dataset.
            Accepts only a string name of an array that is present on the
            composite dataset.

        clim : sequence[float], optional
            Two item color bar range for scalars.  Defaults to minimum and
            maximum of scalars array.  Example: ``[-1, 2]``. ``rng`` is
            also an accepted alias for this.

        show_edges : bool, default: :attr:`pyvista.global_theme.show_edges <pyvista.plotting.themes.Theme.show_edges>`
            Shows the edges of a mesh.  Does not apply to a wireframe
            representation.

        edge_color : ColorLike, default: :attr:`pyvista.global_theme.edge_color <pyvista.plotting.themes.Theme.edge_color>`
            The solid color to give the edges when ``show_edges=True``.
            Either a string, RGB list, or hex color string.

            Defaults to :attr:`pyvista.global_theme.edge_color
            <pyvista.plotting.themes.Theme.edge_color>`.

        point_size : float, default: 5.0
            Point size of any points in the dataset plotted. Also
            applicable when style='points'. Default ``5.0``.

        line_width : float, optional
            Thickness of lines.  Only valid for wireframe and surface
            representations.

        opacity : float, default: 1.0
            Opacity of the mesh. A single float value that will be applied
            globally opacity of the mesh and uniformly
            applied everywhere - should be between 0 and 1.

        flip_scalars : bool, default: False
            Flip direction of cmap. Most colormaps allow ``*_r``
            suffix to do this as well.

        lighting : bool, default: True
            Enable or disable view direction lighting.

        n_colors : int, default: 256
            Number of colors to use when displaying scalars.  The scalar bar
            will also have this many colors.

        interpolate_before_map : bool, default: True
            Enabling makes for a smoother scalars display.  When ``False``,
            OpenGL will interpolate the mapped colors which can result in
            showing colors that are not present in the color map.

        cmap : str | list, | pyvista.LookupTable, default: :attr:`pyvista.plotting.themes.Theme.cmap`
            If a string, this is the name of the ``matplotlib`` colormap to use
            when mapping the ``scalars``.  See available Matplotlib colormaps.
            Only applicable for when displaying ``scalars``.
            ``colormap`` is also an accepted alias
            for this. If ``colorcet`` or ``cmocean`` are installed, their
            colormaps can be specified by name.

            You can also specify a list of colors to override an existing
            colormap with a custom one.  For example, to create a three color
            colormap you might specify ``['green', 'red', 'blue']``.

            This parameter also accepts a :class:`pyvista.LookupTable`. If this
            is set, all parameters controlling the color map like ``n_colors``
            will be ignored.

        label : str, optional
            String label to use when adding a legend to the scene with
            :func:`pyvista.Plotter.add_legend`.

        reset_camera : bool, optional
            Reset the camera after adding this mesh to the scene. The default
            setting is ``None``, where the camera is only reset if this plotter
            has already been shown. If ``False``, the camera is not reset
            regardless of the state of the ``Plotter``. When ``True``, the
            camera is always reset.

        scalar_bar_args : dict, optional
            Dictionary of keyword arguments to pass when adding the
            scalar bar to the scene. For options, see
            :func:`pyvista.Plotter.add_scalar_bar`.

        show_scalar_bar : bool
            If ``False``, a scalar bar will not be added to the
            scene. Defaults to ``True`` unless ``rgba=True``.

        multi_colors : bool, default: False
            Color each block by a solid color using matplotlib's color cycler.

        name : str, optional
            The name for the added mesh/actor so that it can be easily
            updated.  If an actor of this name already exists in the
            rendering window, it will be replaced by the new actor.

        render_points_as_spheres : bool, default: False
            Render points as spheres rather than dots.

        render_lines_as_tubes : bool, default: False
            Show lines as thick tubes rather than flat lines.  Control
            the width with ``line_width``.

        smooth_shading : bool, default: :attr`pyvista.plotting.themes.Theme.smooth_shading`
            Enable smooth shading when ``True`` using the Phong shading
            algorithm.  When ``False``, uses flat shading.  Automatically
            enabled when ``pbr=True``.  See :ref:`shading_example`.

        split_sharp_edges : bool, default: False
            Split sharp edges exceeding 30 degrees when plotting with smooth
            shading.  Control the angle with the optional keyword argument
            ``feature_angle``.  By default this is ``False`` unless overridden
            by the global or plotter theme.  Note that enabling this will
            create a copy of the input mesh within the plotter.  See
            :ref:`shading_example`.

        ambient : float, default: 0.0
            When lighting is enabled, this is the amount of light in
            the range of 0 to 1 (default 0.0) that reaches the actor
            when not directed at the light source emitted from the
            viewer.

        diffuse : float, default: 1.0
            The diffuse lighting coefficient.

        specular : float, default: 0.0
            The specular lighting coefficient.

        specular_power : float, default: 1.0
            The specular power. Between 0.0 and 128.0.

        nan_color : ColorLike, default: :attr:`pyvista.plotting.themes.Theme.nan_color`
            The color to use for all ``NaN`` values in the plotted
            scalar array.

        nan_opacity : float, default: 1.0
            Opacity of ``NaN`` values.  Should be between 0 and 1.

        culling : str, bool, default: False
            Does not render faces that are culled. This can be helpful for
            dense surface meshes, especially when edges are visible, but can
            cause flat meshes to be partially displayed. One of the following:

            * ``True`` - Enable backface culling
            * ``"b"`` - Enable backface culling
            * ``"back"`` - Enable backface culling
            * ``"backface"`` - Enable backface culling
            * ``"f"`` - Enable frontface culling
            * ``"front"`` - Enable frontface culling
            * ``"frontface"`` - Enable frontface culling
            * ``False`` - Disable both backface and frontface culling

        rgb : bool, default: False
            If an 2 dimensional array is passed as the scalars, plot
            those values as RGB(A) colors. ``rgba`` is also an
            accepted alias for this.  Opacity (the A) is optional.  If
            a scalars array ending with ``"_rgba"`` is passed, the default
            becomes ``True``.  This can be overridden by setting this
            parameter to ``False``.

        categories : bool, optional
            If set to ``True``, then the number of unique values in
            the scalar array will be used as the ``n_colors``
            argument.

            .. deprecated:: 0.39.0
               This keyword argument is no longer used. Instead, use
               ``n_colors``.

        below_color : ColorLike, optional
            Solid color for values below the scalars range
            (``clim``). This will automatically set the scalar bar
            ``below_label`` to ``'below'``.

        above_color : ColorLike, optional
            Solid color for values below the scalars range
            (``clim``). This will automatically set the scalar bar
            ``above_label`` to ``'above'``.

        annotations : dict, optional
            Pass a dictionary of annotations. Keys are the float
            values in the scalars range to annotate on the scalar bar
            and the values are the string annotations.

        pickable : bool, default: True
            Set whether this actor is pickable.

        preference : str, default: 'point'
            For each block, when ``block.n_points == block.n_cells`` and
            setting scalars, this parameter sets how the scalars will be mapped
            to the mesh.  For example, when ``'point'`` the scalars will be
            associated with the mesh points if available.  Can be either
            ``'point'`` or ``'cell'``.

        log_scale : bool, default: False
            Use log scale when mapping data to colors. Scalars less
            than zero are mapped to the smallest representable
            positive float.

        pbr : bool, default: False
            Enable physics based rendering (PBR) if the mesh is
            ``PolyData``.  Use the ``color`` argument to set the base
            color.

        metallic : float, default: 0.0
            Usually this value is either 0 or 1 for a real material
            but any value in between is valid. This parameter is only
            used by PBR interpolation.

        roughness : float, default: 0.5
            This value has to be between 0 (glossy) and 1 (rough). A
            glossy material has reflections and a high specular
            part. This parameter is only used by PBR
            interpolation.

        render : bool, default: True
            Force a render when ``True``.

        component : int, optional
            Set component of vector valued scalars to plot.  Must be
            nonnegative, if supplied. If ``None``, the magnitude of
            the vector is plotted.

        color_missing_with_nan : bool, default: False
            Color any missing values with the ``nan_color``. This is useful
            when not all blocks of the composite dataset have the specified
            ``scalars``.

        copy_mesh : bool, default: False
            If ``True``, a copy of the mesh will be made before adding it to
            the plotter.  This is useful if e.g. you would like to add the same
            mesh to a plotter multiple times and display different
            scalars. Setting ``copy_mesh`` to ``False`` is necessary if you
            would like to update the mesh after adding it to the plotter and
            have these updates rendered, e.g. by changing the active scalars or
            through an interactive widget.

        show_vertices : bool, optional
            When ``style`` is not ``'points'``, render the external surface
            vertices. The following optional keyword arguments may be used to
            control the style of the vertices:

            * ``vertex_color`` - The color of the vertices
            * ``vertex_style`` - Change style to ``'points_gaussian'``
            * ``vertex_opacity`` - Control the opacity of the vertices

        **kwargs : dict, optional
            Optional keyword arguments.

        Returns
        -------
        pyvista.Actor
            Actor of the composite dataset.

        pyvista.CompositePolyDataMapper
            Composite PolyData mapper.

        Examples
        --------
        Add a sphere and a cube as a multiblock dataset to a plotter and then
        change the visibility and color of the blocks.

        Note index ``1`` and ``2`` are used to access the individual blocks of
        the composite dataset. This is because the :class:`pyvista.MultiBlock`
        is the root node of the "tree" and is index ``0``. This allows you to
        access individual blocks or the entire composite dataset itself in the
        case of multiple nested composite datasets.

        >>> import pyvista as pv
        >>> dataset = pv.MultiBlock(
        ...     [pv.Cube(), pv.Sphere(center=(0, 0, 1))]
        ... )
        >>> pl = pv.Plotter()
        >>> actor, mapper = pl.add_composite(dataset)
        >>> mapper.block_attr[1].color = 'b'
        >>> mapper.block_attr[1].opacity = 0.5
        >>> mapper.block_attr[2].color = 'r'
        >>> pl.show()

        """
        if not isinstance(dataset, _vtk.vtkCompositeDataSet):
            raise TypeError(f'Invalid type ({type(dataset)}). Must be a composite dataset.')
        # always convert
        dataset = dataset.as_polydata_blocks(copy_mesh)
        self.mesh = dataset  # for legacy behavior

        # Parse arguments
        (
            scalar_bar_args,
            split_sharp_edges,
            show_scalar_bar,
            feature_angle,
            render_points_as_spheres,
            smooth_shading,
            clim,
            cmap,
            culling,
            name,
            nan_color,
            color,
            texture,
            rgb,
            interpolation,
            remove_existing_actor,
            vertex_color,
            vertex_style,
            vertex_opacity,
        ) = _common_arg_parser(
            dataset,
            self._theme,
            n_colors,
            scalar_bar_args,
            split_sharp_edges,
            show_scalar_bar,
            render_points_as_spheres,
            smooth_shading,
            pbr,
            clim,
            cmap,
            culling,
            name,
            nan_color,
            nan_opacity,
            color,
            None,
            rgb,
            style,
            **kwargs,
        )
        if show_vertices is None:
            show_vertices = self._theme.show_vertices

        # Compute surface normals if using smooth shading
        if smooth_shading:
            dataset = dataset._compute_normals(
                cell_normals=False,
                split_vertices=True,
                feature_angle=feature_angle,
            )

        self.mapper = CompositePolyDataMapper(
            dataset,
            theme=self._theme,
            color_missing_with_nan=color_missing_with_nan,
            interpolate_before_map=interpolate_before_map,
        )

        actor, _ = self.add_actor(self.mapper)

        prop = Property(
            self._theme,
            interpolation=interpolation,
            metallic=metallic,
            roughness=roughness,
            point_size=point_size,
            ambient=ambient,
            diffuse=diffuse,
            specular=specular,
            specular_power=specular_power,
            show_edges=show_edges,
            color=self.renderer.next_color if color is None else color,
            style=style,
            edge_color=edge_color,
            render_points_as_spheres=render_points_as_spheres,
            render_lines_as_tubes=render_lines_as_tubes,
            lighting=lighting,
            line_width=line_width,
            opacity=opacity,
            culling=culling,
        )
        actor.SetProperty(prop)

        if label is not None:
            self._add_legend_label(actor, label, None, prop.color)

        # check if there are any consistent active scalars
        if color is not None:
            self.mapper.scalar_visibility = False
        elif multi_colors:
            self.mapper.set_unique_colors()
        else:
            if scalars is None:
                point_name, cell_name = dataset._get_consistent_active_scalars()
                if point_name and cell_name:
                    if preference == 'point':
                        scalars = point_name
                    else:
                        scalars = cell_name
                else:
                    scalars = point_name if point_name is not None else cell_name

            elif not isinstance(scalars, str):
                raise TypeError(
                    f'`scalars` must be a string for `add_composite`, not ({type(scalars)})'
                )

            if categories:
                # Deprecated on 0.39.0, estimated removal on v0.42.0
                warnings.warn(
                    '`categories` is deprecated for composite datasets. Use `n_colors` instead.',
                    PyVistaDeprecationWarning,
                )
                if not isinstance(categories, int):
                    raise TypeError('Categories must be an integer for a composite dataset.')
                n_colors = categories

            if scalars is not None:
                scalar_bar_args = self.mapper.set_scalars(
                    scalars,
                    preference,
                    component,
                    annotations,
                    rgb,
                    scalar_bar_args,
                    n_colors,
                    nan_color,
                    above_color,
                    below_color,
                    clim,
                    cmap,
                    flip_scalars,
                    log_scale,
                )
            else:
                self.mapper.scalar_visibility = False

        # Only show scalar bar if there are scalars
        if show_scalar_bar and scalars is not None:
            self.add_scalar_bar(**scalar_bar_args)

        # by default reset the camera if the plotting window has been rendered
        if reset_camera is None:
            reset_camera = not self._first_time and not self.camera_set

        # add this immediately prior to adding the actor to ensure vertices
        # are rendered
        if show_vertices and style not in ['points', 'points_gaussian']:
            self.add_composite(
                dataset,
                style=vertex_style,
                point_size=point_size,
                color=vertex_color,
                render_points_as_spheres=render_points_as_spheres,
                name=f'{name}-vertices',
                opacity=vertex_opacity,
                lighting=lighting,
                render=False,
                show_vertices=False,
            )

        self.add_actor(
            actor,
            reset_camera=reset_camera,
            name=name,
            pickable=pickable,
            render=render,
            remove_existing_actor=remove_existing_actor,
        )

        return actor, self.mapper

    def add_mesh(
        self,
        mesh,
        color=None,
        style=None,
        scalars=None,
        clim=None,
        show_edges=None,
        edge_color=None,
        point_size=None,
        line_width=None,
        opacity=None,
        flip_scalars=False,
        lighting=None,
        n_colors=256,
        interpolate_before_map=None,
        cmap=None,
        label=None,
        reset_camera=None,
        scalar_bar_args=None,
        show_scalar_bar=None,
        multi_colors=False,
        name=None,
        texture=None,
        render_points_as_spheres=None,
        render_lines_as_tubes=None,
        smooth_shading=None,
        split_sharp_edges=None,
        ambient=None,
        diffuse=None,
        specular=None,
        specular_power=None,
        nan_color=None,
        nan_opacity=1.0,
        culling=None,
        rgb=None,
        categories=False,
        silhouette=None,
        use_transparency=False,
        below_color=None,
        above_color=None,
        annotations=None,
        pickable=True,
        preference="point",
        log_scale=False,
        pbr=None,
        metallic=None,
        roughness=None,
        render=True,
        component=None,
        emissive=None,
        copy_mesh=False,
        backface_params=None,
        show_vertices=None,
        **kwargs,
    ):
        """Add any PyVista/VTK mesh or dataset that PyVista can wrap to the scene.

        This method is using a mesh representation to view the surfaces
        and/or geometry of datasets. For volume rendering, see
        :func:`pyvista.Plotter.add_volume`.

        To see the what most of the following parameters look like in action,
        please refer to :class:`pyvista.Property`.

        Parameters
        ----------
        mesh : pyvista.DataSet or pyvista.MultiBlock or vtk.vtkAlgorithm
            Any PyVista or VTK mesh is supported. Also, any dataset
            that :func:`pyvista.wrap` can handle including NumPy
            arrays of XYZ points. Plotting also supports VTK algorithm
            objects (``vtk.vtkAlgorithm`` and ``vtk.vtkAlgorithmOutput``).
            When passing an algorithm, the rendering pipeline will be
            connected to the passed algorithm to dynamically update
            the scene.

        color : ColorLike, optional
            Use to make the entire mesh have a single solid color.
            Either a string, RGB list, or hex color string.  For example:
            ``color='white'``, ``color='w'``, ``color=[1.0, 1.0, 1.0]``, or
            ``color='#FFFFFF'``. Color will be overridden if scalars are
            specified.

            Defaults to :attr:`pyvista.global_theme.color
            <pyvista.plotting.themes.Theme.color>`.

        style : str, optional
            Visualization style of the mesh.  One of the following:
            ``style='surface'``, ``style='wireframe'``, ``style='points'``,
            ``style='points_gaussian'``. Defaults to ``'surface'``. Note that
            ``'wireframe'`` only shows a wireframe of the outer geometry.
            ``'points_gaussian'`` can be modified with the ``emissive``,
            ``render_points_as_spheres`` options.

        scalars : str | numpy.ndarray, optional
            Scalars used to "color" the mesh.  Accepts a string name
            of an array that is present on the mesh or an array equal
            to the number of cells or the number of points in the
            mesh.  Array should be sized as a single vector. If both
            ``color`` and ``scalars`` are ``None``, then the active
            scalars are used.

        clim : sequence[float], optional
            Two item color bar range for scalars.  Defaults to minimum and
            maximum of scalars array.  Example: ``[-1, 2]``. ``rng`` is
            also an accepted alias for this.

        show_edges : bool, optional
            Shows the edges of a mesh.  Does not apply to a wireframe
            representation.

        edge_color : ColorLike, optional
            The solid color to give the edges when ``show_edges=True``.
            Either a string, RGB list, or hex color string.

            Defaults to :attr:`pyvista.global_theme.edge_color
            <pyvista.plotting.themes.Theme.edge_color>`.

        point_size : float, optional
            Point size of any nodes in the dataset plotted. Also
            applicable when style='points'. Default ``5.0``.

        line_width : float, optional
            Thickness of lines.  Only valid for wireframe and surface
            representations.  Default ``None``.

        opacity : float | str| array_like
            Opacity of the mesh. If a single float value is given, it
            will be the global opacity of the mesh and uniformly
            applied everywhere - should be between 0 and 1. A string
            can also be specified to map the scalars range to a
            predefined opacity transfer function (options include:
            ``'linear'``, ``'linear_r'``, ``'geom'``, ``'geom_r'``).
            A string could also be used to map a scalars array from
            the mesh to the opacity (must have same number of elements
            as the ``scalars`` argument). Or you can pass a custom
            made transfer function that is an array either
            ``n_colors`` in length or shorter.

        flip_scalars : bool, default: False
            Flip direction of cmap. Most colormaps allow ``*_r``
            suffix to do this as well.

        lighting : bool, optional
            Enable or disable view direction lighting. Default ``False``.

        n_colors : int, optional
            Number of colors to use when displaying scalars. Defaults to 256.
            The scalar bar will also have this many colors.

        interpolate_before_map : bool, optional
            Enabling makes for a smoother scalars display.  Default is
            ``True``.  When ``False``, OpenGL will interpolate the
            mapped colors which can result is showing colors that are
            not present in the color map.

        cmap : str | list | pyvista.LookupTable, default: :attr:`pyvista.plotting.themes.Theme.cmap`
            If a string, this is the name of the ``matplotlib`` colormap to use
            when mapping the ``scalars``.  See available Matplotlib colormaps.
            Only applicable for when displaying ``scalars``.
            ``colormap`` is also an accepted alias
            for this. If ``colorcet`` or ``cmocean`` are installed, their
            colormaps can be specified by name.

            You can also specify a list of colors to override an existing
            colormap with a custom one.  For example, to create a three color
            colormap you might specify ``['green', 'red', 'blue']``.

            This parameter also accepts a :class:`pyvista.LookupTable`. If this
            is set, all parameters controlling the color map like ``n_colors``
            will be ignored.

        label : str, optional
            String label to use when adding a legend to the scene with
            :func:`pyvista.Plotter.add_legend`.

        reset_camera : bool, optional
            Reset the camera after adding this mesh to the scene. The default
            setting is ``None``, where the camera is only reset if this plotter
            has already been shown. If ``False``, the camera is not reset
            regardless of the state of the ``Plotter``. When ``True``, the
            camera is always reset.

        scalar_bar_args : dict, optional
            Dictionary of keyword arguments to pass when adding the
            scalar bar to the scene. For options, see
            :func:`pyvista.Plotter.add_scalar_bar`.

        show_scalar_bar : bool, optional
            If ``False``, a scalar bar will not be added to the
            scene.

        multi_colors : bool, default: False
            If a :class:`pyvista.MultiBlock` dataset is given this will color
            each block by a solid color using matplotlib's color cycler.

        name : str, optional
            The name for the added mesh/actor so that it can be easily
            updated.  If an actor of this name already exists in the
            rendering window, it will be replaced by the new actor.

        texture : pyvista.Texture or np.ndarray, optional
            A texture to apply if the input mesh has texture
            coordinates.  This will not work with MultiBlock
            datasets.

        render_points_as_spheres : bool, optional
            Render points as spheres rather than dots.

        render_lines_as_tubes : bool, optional
            Show lines as thick tubes rather than flat lines.  Control
            the width with ``line_width``.

        smooth_shading : bool, optional
            Enable smooth shading when ``True`` using the Phong
            shading algorithm.  When ``False``, use flat shading.
            Automatically enabled when ``pbr=True``.  See
            :ref:`shading_example`.

        split_sharp_edges : bool, optional
            Split sharp edges exceeding 30 degrees when plotting with smooth
            shading.  Control the angle with the optional keyword argument
            ``feature_angle``.  By default this is ``False`` unless overridden
            by the global or plotter theme.  Note that enabling this will
            create a copy of the input mesh within the plotter.  See
            :ref:`shading_example`.

        ambient : float, optional
            When lighting is enabled, this is the amount of light in
            the range of 0 to 1 (default 0.0) that reaches the actor
            when not directed at the light source emitted from the
            viewer.

        diffuse : float, optional
            The diffuse lighting coefficient. Default 1.0.

        specular : float, optional
            The specular lighting coefficient. Default 0.0.

        specular_power : float, optional
            The specular power. Between 0.0 and 128.0.

        nan_color : ColorLike, optional
            The color to use for all ``NaN`` values in the plotted
            scalar array.

        nan_opacity : float, optional
            Opacity of ``NaN`` values.  Should be between 0 and 1.
            Default 1.0.

        culling : str, optional
            Does not render faces that are culled. Options are
            ``'front'`` or ``'back'``. This can be helpful for dense
            surface meshes, especially when edges are visible, but can
            cause flat meshes to be partially displayed.  Defaults to
            ``False``.

        rgb : bool, optional
            If an 2 dimensional array is passed as the scalars, plot
            those values as RGB(A) colors. ``rgba`` is also an
            accepted alias for this.  Opacity (the A) is optional.  If
            a scalars array ending with ``"_rgba"`` is passed, the default
            becomes ``True``.  This can be overridden by setting this
            parameter to ``False``.

        categories : bool, optional
            If set to ``True``, then the number of unique values in
            the scalar array will be used as the ``n_colors``
            argument.

        silhouette : dict, bool, optional
            If set to ``True``, plot a silhouette highlight for the
            mesh. This feature is only available for a triangulated
            ``PolyData``.  As a ``dict``, it contains the properties
            of the silhouette to display:

                * ``color``: ``ColorLike``, color of the silhouette
                * ``line_width``: ``float``, edge width
                * ``opacity``: ``float`` between 0 and 1, edge transparency
                * ``feature_angle``: If a ``float``, display sharp edges
                  exceeding that angle in degrees.
                * ``decimate``: ``float`` between 0 and 1, level of decimation

        use_transparency : bool, optional
            Invert the opacity mappings and make the values correspond
            to transparency.

        below_color : ColorLike, optional
            Solid color for values below the scalars range
            (``clim``). This will automatically set the scalar bar
            ``below_label`` to ``'below'``.

        above_color : ColorLike, optional
            Solid color for values below the scalars range
            (``clim``). This will automatically set the scalar bar
            ``above_label`` to ``'above'``.

        annotations : dict, optional
            Pass a dictionary of annotations. Keys are the float
            values in the scalars range to annotate on the scalar bar
            and the values are the string annotations.

        pickable : bool, optional
            Set whether this actor is pickable.

        preference : str, default: "point"
            When ``mesh.n_points == mesh.n_cells`` and setting
            scalars, this parameter sets how the scalars will be
            mapped to the mesh.  Default ``'point'``, causes the
            scalars will be associated with the mesh points.  Can be
            either ``'point'`` or ``'cell'``.

        log_scale : bool, default: False
            Use log scale when mapping data to colors. Scalars less
            than zero are mapped to the smallest representable
            positive float.

        pbr : bool, optional
            Enable physics based rendering (PBR) if the mesh is
            ``PolyData``.  Use the ``color`` argument to set the base
            color.

        metallic : float, optional
            Usually this value is either 0 or 1 for a real material
            but any value in between is valid. This parameter is only
            used by PBR interpolation.

        roughness : float, optional
            This value has to be between 0 (glossy) and 1 (rough). A
            glossy material has reflections and a high specular
            part. This parameter is only used by PBR
            interpolation.

        render : bool, default: True
            Force a render when ``True``.

        component : int, optional
            Set component of vector valued scalars to plot.  Must be
            nonnegative, if supplied. If ``None``, the magnitude of
            the vector is plotted.

        emissive : bool, optional
            Treat the points/splats as emissive light sources. Only valid for
            ``style='points_gaussian'`` representation.

        copy_mesh : bool, default: False
            If ``True``, a copy of the mesh will be made before adding it to
            the plotter.  This is useful if you would like to add the same
            mesh to a plotter multiple times and display different
            scalars. Setting ``copy_mesh`` to ``False`` is necessary if you
            would like to update the mesh after adding it to the plotter and
            have these updates rendered, e.g. by changing the active scalars or
            through an interactive widget. This should only be set to ``True``
            with caution. Defaults to ``False``. This is ignored if the input
            is a ``vtkAlgorithm`` subclass.

        backface_params : dict | pyvista.Property, optional
            A :class:`pyvista.Property` or a dict of parameters to use for
            backface rendering. This is useful for instance when the inside of
            oriented surfaces has a different color than the outside. When a
            :class:`pyvista.Property`, this is directly used for backface
            rendering. When a dict, valid keys are :class:`pyvista.Property`
            attributes, and values are corresponding values to use for the
            given property. Omitted keys (or the default of
            ``backface_params=None``) default to the corresponding frontface
            properties.

        show_vertices : bool, optional
            When ``style`` is not ``'points'``, render the external surface
            vertices. The following optional keyword arguments may be used to
            control the style of the vertices:

            * ``vertex_color`` - The color of the vertices
            * ``vertex_style`` - Change style to ``'points_gaussian'``
            * ``vertex_opacity`` - Control the opacity of the vertices

        **kwargs : dict, optional
            Optional keyword arguments.

        Returns
        -------
        pyvista.plotting.actor.Actor
            Actor of the mesh.

        Examples
        --------
        Add a sphere to the plotter and show it with a custom scalar
        bar title.

        >>> import pyvista as pv
        >>> sphere = pv.Sphere()
        >>> sphere['Data'] = sphere.points[:, 2]
        >>> plotter = pv.Plotter()
        >>> _ = plotter.add_mesh(
        ...     sphere, scalar_bar_args={'title': 'Z Position'}
        ... )
        >>> plotter.show()

        Plot using RGB on a single cell.  Note that since the number of
        points and the number of cells are identical, we have to pass
        ``preference='cell'``.

        >>> import pyvista as pv
        >>> import numpy as np
        >>> vertices = np.array(
        ...     [
        ...         [0, 0, 0],
        ...         [1, 0, 0],
        ...         [0.5, 0.667, 0],
        ...         [0.5, 0.33, 0.667],
        ...     ]
        ... )
        >>> faces = np.hstack(
        ...     [[3, 0, 1, 2], [3, 0, 3, 2], [3, 0, 1, 3], [3, 1, 2, 3]]
        ... )
        >>> mesh = pv.PolyData(vertices, faces)
        >>> mesh.cell_data['colors'] = [
        ...     [255, 255, 255],
        ...     [0, 255, 0],
        ...     [0, 0, 255],
        ...     [255, 0, 0],
        ... ]
        >>> plotter = pv.Plotter()
        >>> _ = plotter.add_mesh(
        ...     mesh,
        ...     scalars='colors',
        ...     lighting=False,
        ...     rgb=True,
        ...     preference='cell',
        ... )
        >>> plotter.camera_position = 'xy'
        >>> plotter.show()

        Note how this varies from ``preference=='point'``.  This is
        because each point is now being individually colored, versus
        in ``preference=='point'``, each cell face is individually
        colored.

        >>> plotter = pv.Plotter()
        >>> _ = plotter.add_mesh(
        ...     mesh,
        ...     scalars='colors',
        ...     lighting=False,
        ...     rgb=True,
        ...     preference='point',
        ... )
        >>> plotter.camera_position = 'xy'
        >>> plotter.show()

        Plot a plane with a constant color and vary its opacity by point.

        >>> plane = pv.Plane()
        >>> plane.plot(
        ...     color='b',
        ...     opacity=np.linspace(0, 1, plane.n_points),
        ...     show_edges=True,
        ... )

        Plot the points of a sphere with Gaussian smoothing while coloring by z
        position.

        >>> mesh = pv.Sphere()
        >>> mesh.plot(
        ...     scalars=mesh.points[:, 2],
        ...     style='points_gaussian',
        ...     opacity=0.5,
        ...     point_size=10,
        ...     render_points_as_spheres=False,
        ...     show_scalar_bar=False,
        ... )

        """
        if style == 'points_gaussian':
            self.mapper = PointGaussianMapper(theme=self.theme, emissive=emissive)
        else:
            self.mapper = DataSetMapper(theme=self.theme)

        if render_lines_as_tubes and show_edges:
            warnings.warn(
                '`show_edges=True` not supported when `render_lines_as_tubes=True`. Ignoring `show_edges`.',
                UserWarning,
            )
            show_edges = False

        mesh, algo = algorithm_to_mesh_handler(mesh)

        # Convert the VTK data object to a pyvista wrapped object if necessary
        if not is_pyvista_dataset(mesh):
            mesh = wrap(mesh)
            if not is_pyvista_dataset(mesh):
                raise TypeError(
                    f'Object type ({type(mesh)}) not supported for plotting in PyVista.'
                )
        if isinstance(mesh, pyvista.PointSet):
            # cast to PointSet to PolyData
            if algo is not None:
                algo = pointset_to_polydata_algorithm(algo)
                mesh, algo = algorithm_to_mesh_handler(algo)
            else:
                mesh = mesh.cast_to_polydata(deep=False)
        elif isinstance(mesh, pyvista.MultiBlock):
            if algo is not None:
                raise TypeError(
                    'Algorithms with `MultiBlock` output type are not supported by `add_mesh` at this time.'
                )
            actor, _ = self.add_composite(
                mesh,
                color=color,
                style=style,
                scalars=scalars,
                clim=clim,
                show_edges=show_edges,
                edge_color=edge_color,
                point_size=point_size,
                line_width=line_width,
                opacity=opacity,
                flip_scalars=flip_scalars,
                lighting=lighting,
                n_colors=n_colors,
                interpolate_before_map=interpolate_before_map,
                cmap=cmap,
                label=label,
                reset_camera=reset_camera,
                scalar_bar_args=scalar_bar_args,
                show_scalar_bar=show_scalar_bar,
                multi_colors=multi_colors,
                name=name,
                render_points_as_spheres=render_points_as_spheres,
                render_lines_as_tubes=render_lines_as_tubes,
                smooth_shading=smooth_shading,
                split_sharp_edges=split_sharp_edges,
                ambient=ambient,
                diffuse=diffuse,
                specular=specular,
                specular_power=specular_power,
                nan_color=nan_color,
                nan_opacity=nan_opacity,
                culling=culling,
                rgb=rgb,
                categories=categories,
                below_color=below_color,
                above_color=above_color,
                pickable=pickable,
                preference=preference,
                log_scale=log_scale,
                pbr=pbr,
                metallic=metallic,
                roughness=roughness,
                render=render,
                show_vertices=show_vertices,
                **kwargs,
            )
            return actor
        elif copy_mesh and algo is None:
            # A shallow copy of `mesh` is made here so when we set (or add) scalars
            # active, it doesn't modify the original input mesh.
            # We ignore `copy_mesh` if the input is an algorithm
            mesh = mesh.copy(deep=False)

        # Parse arguments
        (
            scalar_bar_args,
            split_sharp_edges,
            show_scalar_bar,
            feature_angle,
            render_points_as_spheres,
            smooth_shading,
            clim,
            cmap,
            culling,
            name,
            nan_color,
            color,
            texture,
            rgb,
            interpolation,
            remove_existing_actor,
            vertex_color,
            vertex_style,
            vertex_opacity,
        ) = _common_arg_parser(
            mesh,
            self._theme,
            n_colors,
            scalar_bar_args,
            split_sharp_edges,
            show_scalar_bar,
            render_points_as_spheres,
            smooth_shading,
            pbr,
            clim,
            cmap,
            culling,
            name,
            nan_color,
            nan_opacity,
            color,
            texture,
            rgb,
            style,
            **kwargs,
        )

        if show_vertices is None:
            show_vertices = self._theme.show_vertices

        if silhouette is None:
            silhouette = self._theme.silhouette.enabled
        if silhouette:
            if isinstance(silhouette, dict):
                self.add_silhouette(algo or mesh, **silhouette)
            else:
                self.add_silhouette(algo or mesh)

        # Try to plot something if no preference given
        if scalars is None and color is None and texture is None:
            # Make sure scalars components are not vectors/tuples
            scalars = mesh.active_scalars_name
            # Don't allow plotting of string arrays by default
            if scalars is not None:  # and np.issubdtype(mesh.active_scalars.dtype, np.number):
                scalar_bar_args.setdefault('title', scalars)
            else:
                scalars = None

        # Make sure scalars is a numpy array after this point
        original_scalar_name = None
        scalars_name = pyvista.DEFAULT_SCALARS_NAME
        if isinstance(scalars, str):
            self.mapper.array_name = scalars

            # enable rgb if the scalars name ends with rgb or rgba
            if rgb is None:
                if scalars.endswith('_rgb') or scalars.endswith('_rgba'):
                    rgb = True

            original_scalar_name = scalars
            scalars = get_array(mesh, scalars, preference=preference, err=True)
            scalar_bar_args.setdefault('title', original_scalar_name)
            scalars_name = original_scalar_name

            # Set the active scalars name here. If the name already exists in
            # the input mesh, it may not be set as the active scalars within
            # the mapper. This should be refactored by 0.36.0
            field = get_array_association(mesh, original_scalar_name, preference=preference)
            self.mapper.scalar_map_mode = field.name

            if algo is not None:
                # Ensures that the right scalars are set as active on
                # each pipeline request
                algo = active_scalars_algorithm(algo, original_scalar_name, preference=preference)
                mesh, algo = algorithm_to_mesh_handler(algo)
            else:
                # Otherwise, make sure the mesh object's scalars are set
                if field == FieldAssociation.POINT:
                    mesh.point_data.active_scalars_name = original_scalar_name
                elif field == FieldAssociation.CELL:
                    mesh.cell_data.active_scalars_name = original_scalar_name

        # Compute surface normals if using smooth shading
        if smooth_shading:
            if algo is not None:
                raise TypeError(
                    'Smooth shading is not currently supported when a vtkAlgorithm is passed.'
                )
            mesh, scalars = prepare_smooth_shading(
                mesh, scalars, texture, split_sharp_edges, feature_angle, preference
            )

        if rgb:
            show_scalar_bar = False
            if scalars.ndim != 2 or scalars.shape[1] < 3 or scalars.shape[1] > 4:
                raise ValueError('RGB array must be n_points/n_cells by 3/4 in shape.')

        if algo is None and not mesh.n_points:
            # Algorithms may initialize with an empty mesh
            raise ValueError('Empty meshes cannot be plotted. Input mesh has zero points.')

        # set main values
        self.mesh = mesh
        self.mapper.dataset = self.mesh
        if interpolate_before_map is not None:
            self.mapper.interpolate_before_map = interpolate_before_map
        set_algorithm_input(self.mapper, algo or mesh)

        actor = Actor(mapper=self.mapper)

        if texture is not None:
            if isinstance(texture, np.ndarray):
                texture = numpy_to_texture(texture)
            if not isinstance(texture, (_vtk.vtkTexture, _vtk.vtkOpenGLTexture)):
                raise TypeError(f'Invalid texture type ({type(texture)})')
            if mesh.GetPointData().GetTCoords() is None:
                raise ValueError(
                    'Input mesh does not have texture coordinates to support the texture.'
                )
            actor.texture = texture
            # Set color to white by default when using a texture
            if color is None:
                color = 'white'
            if scalars is None:
                show_scalar_bar = False
            self.mapper.scalar_visibility = False

            # see https://github.com/pyvista/pyvista/issues/950
            mesh.set_active_scalars(None)

        # Handle making opacity array
        custom_opac, opacity = process_opacity(
            mesh, opacity, preference, n_colors, scalars, use_transparency
        )

        # Scalars formatting ==================================================
        if scalars is not None:
            self.mapper.set_scalars(
                scalars,
                scalars_name,
                n_colors,
                scalar_bar_args,
                rgb,
                component,
                preference,
                custom_opac,
                annotations,
                log_scale,
                nan_color,
                above_color,
                below_color,
                cmap,
                flip_scalars,
                opacity,
                categories,
                clim,
            )
            self.mapper.scalar_visibility = True
        elif custom_opac:  # no scalars but custom opacity
            self.mapper.set_custom_opacity(
                opacity,
                color,
                n_colors,
                preference,
            )
            self.mapper.scalar_visibility = True
        else:
            self.mapper.scalar_visibility = False

        # Set actor properties ================================================
        prop_kwargs = dict(
            theme=self._theme,
            interpolation=interpolation,
            metallic=metallic,
            roughness=roughness,
            point_size=point_size,
            ambient=ambient,
            diffuse=diffuse,
            specular=specular,
            specular_power=specular_power,
            show_edges=show_edges,
            color=self.renderer.next_color if color is None else color,
            style=style if style != 'points_gaussian' else 'points',
            edge_color=edge_color,
            render_lines_as_tubes=render_lines_as_tubes,
            lighting=lighting,
            line_width=line_width,
            culling=culling,
        )

        if isinstance(opacity, (float, int)):
            prop_kwargs['opacity'] = opacity
        prop = Property(**prop_kwargs)
        actor.SetProperty(prop)

        if style == 'points_gaussian':
            self.mapper.scale_factor = prop.point_size * self.mapper.dataset.length / 1300
            if not render_points_as_spheres and not self.mapper.emissive:
                if prop.opacity >= 1.0:
                    prop.opacity = 0.9999  # otherwise, weird triangles

        if render_points_as_spheres:
            if style == 'points_gaussian':
                self.mapper.use_circular_splat(prop.opacity)
                prop.opacity = 1.0
            else:
                prop.render_points_as_spheres = render_points_as_spheres

        if backface_params is not None:
            if isinstance(backface_params, Property):
                backface_prop = backface_params
            elif isinstance(backface_params, dict):
                # preserve omitted kwargs from frontface
                backface_kwargs = deepcopy(prop_kwargs)
                backface_kwargs.update(backface_params)
                backface_prop = Property(**backface_kwargs)
            else:
                raise TypeError(
                    'Backface params must be a pyvista.Property or a dict, '
                    f'not {type(backface_params).__name__}.'
                )
            actor.backface_prop = backface_prop

        # legend label
        if label is not None:
            self._add_legend_label(actor, label, scalars, actor.prop.color)

        # by default reset the camera if the plotting window has been rendered
        if reset_camera is None:
            reset_camera = not self._first_time and not self.camera_set

        # add this immediately prior to adding the actor to ensure vertices
        # are rendered
        if show_vertices and style not in ['points', 'points_gaussian']:
            self.add_mesh(
                extract_surface_algorithm(algo or mesh),
                style=vertex_style,
                point_size=point_size,
                color=vertex_color,
                render_points_as_spheres=render_points_as_spheres,
                name=f'{name}-vertices',
                opacity=vertex_opacity,
                lighting=lighting,
                render=False,
                show_vertices=False,
            )

        self.add_actor(
            actor,
            reset_camera=reset_camera,
            name=name,
            pickable=pickable,
            render=render,
            remove_existing_actor=remove_existing_actor,
        )

        # hide scalar bar if using special scalars
        if scalar_bar_args.get('title') == '__custom_rgba':
            show_scalar_bar = False

        # Only show scalar bar if there are scalars
        if show_scalar_bar and scalars is not None:
            self.add_scalar_bar(**scalar_bar_args)

        self.renderer.Modified()

        return actor

    def _add_legend_label(self, actor, label, scalars, color):
        """Add a legend label based on an actor and its scalars."""
        if not isinstance(label, str):
            raise TypeError('Label must be a string')
        geom = pyvista.Triangle()
        if scalars is not None:
            geom = pyvista.Box()
            color = Color('black')
        geom.points -= geom.center
        addr = actor.GetAddressAsString("")
        self.renderer._labels[addr] = [geom, label, color]

    def add_volume(
        self,
        volume,
        scalars=None,
        clim=None,
        resolution=None,
        opacity='linear',
        n_colors=256,
        cmap=None,
        flip_scalars=False,
        reset_camera=None,
        name=None,
        ambient=None,
        categories=False,
        culling=False,
        multi_colors=False,
        blending='composite',
        mapper=None,
        scalar_bar_args=None,
        show_scalar_bar=None,
        annotations=None,
        pickable=True,
        preference="point",
        opacity_unit_distance=None,
        shade=False,
        diffuse=0.7,  # TODO: different default for volumes
        specular=0.2,  # TODO: different default for volumes
        specular_power=10.0,  # TODO: different default for volumes
        render=True,
        log_scale=False,
        **kwargs,
    ):
        """Add a volume, rendered using a smart mapper by default.

        Requires a 3D data type like :class:`numpy.ndarray`,
        :class:`pyvista.ImageData`, :class:`pyvista.RectilinearGrid`,
        or :class:`pyvista.UnstructuredGrid`.

        Parameters
        ----------
        volume : 3D numpy.ndarray | pyvista.DataSet
            The input volume to visualize. 3D numpy arrays are accepted.

            .. warning::
                If the input is not :class:`numpy.ndarray`,
                :class:`pyvista.ImageData`, or :class:`pyvista.RectilinearGrid`,
                volume rendering will often have poor performance.

        scalars : str | numpy.ndarray, optional
            Scalars used to "color" the mesh.  Accepts a string name of an
            array that is present on the mesh or an array with length equal
            to the number of cells or the number of points in the
            mesh. If ``scalars`` is ``None``, then the active scalars are used.

            Scalars may be 1 dimensional or 2 dimensional. If 1 dimensional,
            the scalars will be mapped to the lookup table. If 2 dimensional
            the scalars will be directly mapped to RGBA values, array should be
            shaped ``(N, 4)`` where ``N`` is the number of points, and of
            datatype ``np.uint8``.

            Scalars may be 1 dimensional or 2 dimensional. If 1 dimensional,
            the scalars will be mapped to the lookup table. If 2 dimensional
            the scalars will be directly mapped to RGBA values, array should be
            shaped ``(N, 4)`` where ``N`` is the number of points, and of
            datatype ``np.uint8``.

        clim : sequence[float] | float, optional
            Color bar range for scalars.  For example: ``[-1, 2]``. Defaults to
            minimum and maximum of scalars array if the scalars dtype is not
            ``np.uint8``. ``rng`` is also an accepted alias for this parameter.

            If the scalars datatype is ``np.uint8``, this parameter defaults to
            ``[0, 256]``.

            If a single value is given, the range ``[-clim, clim]`` is used.

        resolution : list, optional
            Block resolution. For example ``[1, 1, 1]``. Resolution must be
            non-negative. While VTK accepts negative spacing, this results in
            unexpected behavior. See:
            `pyvista #1967 <https://github.com/pyvista/pyvista/issues/1967>`_.

        opacity : str | numpy.ndarray, optional
            Opacity mapping for the scalars array.

            A string can also be specified to map the scalars range to a
            predefined opacity transfer function. Or you can pass a custom made
            transfer function that is an array either ``n_colors`` in length or
            array, or you can pass a string to select a built in transfer
            function. If a string, should be one of the following:

            * ``'linear'`` - Linear
            * ``'linear_r'`` - Linear except reversed
            * ``'geom'`` - Evenly spaced on the log scale
            * ``'geom_r'`` - Evenly spaced on the log scale except reversed
            * ``'sigmoid'`` - Linear map between -10.0 and 10.0
            * ``'sigmoid_1'`` - Linear map between -1.0 and 1.0
            * ``'sigmoid_2'`` - Linear map between -2.0 and 2.0
            * ``'sigmoid_3'`` - Linear map between -3.0 and 3.0
            * ``'sigmoid_4'`` - Linear map between -4.0 and 4.0
            * ``'sigmoid_5'`` - Linear map between -5.0 and 5.0
            * ``'sigmoid_6'`` - Linear map between -6.0 and 6.0
            * ``'sigmoid_7'`` - Linear map between -7.0 and 7.0
            * ``'sigmoid_8'`` - Linear map between -8.0 and 8.0
            * ``'sigmoid_9'`` - Linear map between -9.0 and 9.0
            * ``'sigmoid_10'`` - Linear map between -10.0 and 10.0
            * ``'foreground'`` - Transparent background and opaque foreground.
                Intended for use with segmentation labels. Assumes the smallest
                scalar value of the array is the background value (e.g. 0).

            If RGBA scalars are provided, this parameter is set to ``'linear'``
            to ensure the opacity transfer function has no effect on the input
            opacity values.

        n_colors : int, optional
            Number of colors to use when displaying scalars. Defaults to 256.
            The scalar bar will also have this many colors.

        cmap : str | list | pyvista.LookupTable, default: :attr:`pyvista.plotting.themes.Theme.cmap`
            If a string, this is the name of the ``matplotlib`` colormap to use
            when mapping the ``scalars``.  See available Matplotlib colormaps.
            Only applicable for when displaying ``scalars``.
            ``colormap`` is also an accepted alias
            for this. If ``colorcet`` or ``cmocean`` are installed, their
            colormaps can be specified by name.

            You can also specify a list of colors to override an existing
            colormap with a custom one.  For example, to create a three color
            colormap you might specify ``['green', 'red', 'blue']``.

            This parameter also accepts a :class:`pyvista.LookupTable`. If this
            is set, all parameters controlling the color map like ``n_colors``
            will be ignored.

        flip_scalars : bool, optional
            Flip direction of cmap. Most colormaps allow ``*_r`` suffix to do
            this as well.

        reset_camera : bool, optional
            Reset the camera after adding this mesh to the scene.

        name : str, optional
            The name for the added actor so that it can be easily
            updated.  If an actor of this name already exists in the
            rendering window, it will be replaced by the new actor.

        ambient : float, optional
            When lighting is enabled, this is the amount of light from
            0 to 1 that reaches the actor when not directed at the
            light source emitted from the viewer.  Default 0.0.

        categories : bool, optional
            If set to ``True``, then the number of unique values in the scalar
            array will be used as the ``n_colors`` argument.

        culling : str, optional
            Does not render faces that are culled. Options are ``'front'`` or
            ``'back'``. This can be helpful for dense surface meshes,
            especially when edges are visible, but can cause flat
            meshes to be partially displayed.  Defaults ``False``.

        multi_colors : bool, optional
            Whether or not to use multiple colors when plotting MultiBlock
            object. Blocks will be colored sequentially as 'Reds', 'Greens',
            'Blues', and 'Grays'.

        blending : str, optional
            Blending mode for visualisation of the input object(s). Can be
            one of 'additive', 'maximum', 'minimum', 'composite', or
            'average'. Defaults to 'composite'.

        mapper : str, optional
            Volume mapper to use given by name. Options include:
            ``'fixed_point'``, ``'gpu'``, ``'open_gl'``, and
            ``'smart'``.  If ``None`` the ``"volume_mapper"`` in the
            ``self._theme`` is used. If using ``'fixed_point'``,
            only ``ImageData`` types can be used.

            .. note::
                If a :class:`pyvista.UnstructuredGrid` is input, the 'ugrid'
                mapper (``vtkUnstructuredGridVolumeRayCastMapper``) will be
                used regardless.

            .. note::
                The ``'smart'`` mapper chooses one of the other listed
                mappers based on rendering parameters and available
                hardware. Most of the time the ``'smart'`` simply checks
                if a GPU is available and if so, uses the ``'gpu'``
                mapper, otherwise using the ``'fixed_point'`` mapper.

            .. warning::
                The ``'fixed_point'`` mapper is CPU-based and will have
                lower performance than the ``'gpu'`` or ``'open_gl'``
                mappers.

        scalar_bar_args : dict, optional
            Dictionary of keyword arguments to pass when adding the
            scalar bar to the scene. For options, see
            :func:`pyvista.Plotter.add_scalar_bar`.

        show_scalar_bar : bool
            If ``False``, a scalar bar will not be added to the
            scene. Defaults to ``True``.

        annotations : dict, optional
            Pass a dictionary of annotations. Keys are the float
            values in the scalars range to annotate on the scalar bar
            and the values are the string annotations.

        pickable : bool, optional
            Set whether this mesh is pickable.

        preference : str, optional
            When ``mesh.n_points == mesh.n_cells`` and setting
            scalars, this parameter sets how the scalars will be
            mapped to the mesh.  Default ``'point'``, causes the
            scalars will be associated with the mesh points.  Can be
            either ``'point'`` or ``'cell'``.

        opacity_unit_distance : float, optional
            Set/Get the unit distance on which the scalar opacity
            transfer function is defined. Meaning that over that
            distance, a given opacity (from the transfer function) is
            accumulated. This is adjusted for the actual sampling
            distance during rendering. By default, this is the length
            of the diagonal of the bounding box of the volume divided
            by the dimensions.

        shade : bool, default: False
            Default off. If shading is turned on, the mapper may
            perform shading calculations - in some cases shading does
            not apply (for example, in a maximum intensity projection)
            and therefore shading will not be performed even if this
            flag is on.

        diffuse : float, default: 0.7
            The diffuse lighting coefficient.

        specular : float, default: 0.2
            The specular lighting coefficient.

        specular_power : float, default: 10.0
            The specular power. Between ``0.0`` and ``128.0``.

        render : bool, default: True
            Force a render when True.

        log_scale : bool, default: False
            Use log scale when mapping data to colors. Scalars less
            than zero are mapped to the smallest representable
            positive float.

        **kwargs : dict, optional
            Optional keyword arguments.

        Returns
        -------
        pyvista.Actor
            Actor of the volume.

        Examples
        --------
        Show a built-in volume example with the coolwarm colormap.

        >>> from pyvista import examples
        >>> import pyvista as pv
        >>> bolt_nut = examples.download_bolt_nut()
        >>> pl = pv.Plotter()
        >>> _ = pl.add_volume(bolt_nut, cmap="coolwarm")
        >>> pl.show()

        Create a volume from scratch and plot it using single vector of
        scalars.

        >>> import pyvista as pv
        >>> grid = pv.ImageData(dimensions=(9, 9, 9))
        >>> grid['scalars'] = -grid.x
        >>> pl = pv.Plotter()
        >>> _ = pl.add_volume(grid, opacity='linear')
        >>> pl.show()

        Plot a volume from scratch using RGBA scalars

        >>> import pyvista as pv
        >>> import numpy as np
        >>> grid = pv.ImageData(dimensions=(5, 20, 20))
        >>> scalars = grid.points - (grid.origin)
        >>> scalars /= scalars.max()
        >>> opacity = np.linalg.norm(
        ...     grid.points - grid.center, axis=1
        ... ).reshape(-1, 1)
        >>> opacity /= opacity.max()
        >>> scalars = np.hstack((scalars, opacity**3))
        >>> scalars *= 255
        >>> pl = pv.Plotter()
        >>> vol = pl.add_volume(grid, scalars=scalars.astype(np.uint8))
        >>> vol.prop.interpolation_type = 'linear'
        >>> pl.show()

        Plot an UnstructuredGrid.

        >>> from pyvista import examples
        >>> import pyvista as pv
        >>> mesh = examples.download_letter_a()
        >>> mesh['scalars'] = mesh.points[:, 1]
        >>> pl = pv.Plotter()
        >>> _ = pl.add_volume(mesh, opacity_unit_distance=0.1)
        >>> pl.show()

        """
        # Handle default arguments

        # Supported aliases
        clim = kwargs.pop('rng', clim)
        cmap = kwargs.pop('colormap', cmap)
        culling = kwargs.pop('backface_culling', culling)

        if "scalar" in kwargs:
            raise TypeError(
                "`scalar` is an invalid keyword argument for `add_mesh`. Perhaps you mean `scalars` with an s?"
            )
        assert_empty_kwargs(**kwargs)

        if show_scalar_bar is None:
            show_scalar_bar = self._theme.show_scalar_bar or scalar_bar_args

        # Avoid mutating input
        if scalar_bar_args is None:
            scalar_bar_args = {}
        else:
            scalar_bar_args = scalar_bar_args.copy()
        # account for legacy behavior
        if 'stitle' in kwargs:  # pragma: no cover
            # Deprecated on ..., estimated removal on v0.40.0
            warnings.warn(USE_SCALAR_BAR_ARGS, PyVistaDeprecationWarning)
            scalar_bar_args.setdefault('title', kwargs.pop('stitle'))

        if culling is True:
            culling = 'backface'

        if mapper is None:
            # Default mapper choice. Overridden later if UnstructuredGrid
            mapper = self._theme.volume_mapper

        # only render when the plotter has already been shown
        if render is None:
            render = not self._first_time

        # Convert the VTK data object to a pyvista wrapped object if necessary
        if not is_pyvista_dataset(volume):
            if isinstance(volume, np.ndarray):
                volume = wrap(volume)
                if resolution is None:
                    resolution = [1, 1, 1]
                elif len(resolution) != 3:
                    raise ValueError('Invalid resolution dimensions.')
                volume.spacing = resolution
            else:
                volume = wrap(volume)
                if not is_pyvista_dataset(volume):
                    raise TypeError(
                        f'Object type ({type(volume)}) not supported for plotting in PyVista.'
                    )
        else:
            # HACK: Make a copy so the original object is not altered.
            #       Also, place all data on the nodes as issues arise when
            #       volume rendering on the cells.
            volume = volume.cell_data_to_point_data()

        if name is None:
            name = f'{type(volume).__name__}({volume.memory_address})'

        if isinstance(volume, pyvista.MultiBlock):
            from itertools import cycle

            cycler = cycle(['Reds', 'Greens', 'Blues', 'Greys', 'Oranges', 'Purples'])
            # Now iteratively plot each element of the multiblock dataset
            actors = []
            for idx in range(volume.GetNumberOfBlocks()):
                if volume[idx] is None:
                    continue
                # Get a good name to use
                next_name = f'{name}-{idx}'
                # Get the data object
                block = wrap(volume.GetBlock(idx))
                if resolution is None:
                    try:
                        block_resolution = block.GetSpacing()
                    except AttributeError:
                        block_resolution = resolution
                else:
                    block_resolution = resolution
                if multi_colors:
                    color = next(cycler)
                else:
                    color = cmap

                a = self.add_volume(
                    block,
                    resolution=block_resolution,
                    opacity=opacity,
                    n_colors=n_colors,
                    cmap=color,
                    flip_scalars=flip_scalars,
                    reset_camera=reset_camera,
                    name=next_name,
                    ambient=ambient,
                    categories=categories,
                    culling=culling,
                    clim=clim,
                    mapper=mapper,
                    pickable=pickable,
                    opacity_unit_distance=opacity_unit_distance,
                    shade=shade,
                    diffuse=diffuse,
                    specular=specular,
                    specular_power=specular_power,
                    render=render,
                    show_scalar_bar=show_scalar_bar,
                )

                actors.append(a)
            return actors

        # Make sure structured grids are not less than 3D
        # ImageData and RectilinearGrid should be olay as <3D
        if isinstance(volume, pyvista.StructuredGrid):
            if any(d < 2 for d in volume.dimensions):
                raise ValueError('StructuredGrids must be 3D dimensional.')

        if isinstance(volume, pyvista.PolyData):
            raise TypeError(
                f'Type {type(volume)} not supported for volume rendering as it is not 3D.'
            )
        elif not isinstance(
            volume, (pyvista.ImageData, pyvista.RectilinearGrid, pyvista.UnstructuredGrid)
        ):
            volume = volume.cast_to_unstructured_grid()

        # Override mapper choice for UnstructuredGrid
        if isinstance(volume, pyvista.UnstructuredGrid):
            # Unstructured grid must be all tetrahedrals
            if not (volume.celltypes == pyvista.CellType.TETRA).all():
                volume = volume.triangulate()
            mapper = 'ugrid'

        if mapper == 'fixed_point' and not isinstance(volume, pyvista.ImageData):
            raise TypeError(
                f'Type {type(volume)} not supported for volume rendering with the `"fixed_point"` mapper. Use `pyvista.ImageData`.'
            )
        elif isinstance(volume, pyvista.UnstructuredGrid) and mapper != 'ugrid':
            raise TypeError(
                f'Type {type(volume)} not supported for volume rendering with the `{mapper}` mapper. Use the "ugrid" mapper or simply leave as None.'
            )

        if opacity_unit_distance is None and not isinstance(volume, pyvista.UnstructuredGrid):
            opacity_unit_distance = volume.length / (np.mean(volume.dimensions) - 1)

        if scalars is None:
            # Make sure scalars components are not vectors/tuples
            scalars = volume.active_scalars
            # Don't allow plotting of string arrays by default
            if scalars is not None and np.issubdtype(scalars.dtype, np.number):
                scalar_bar_args.setdefault('title', volume.active_scalars_info[1])
            else:
                raise MissingDataError('No scalars to use for volume rendering.')

        title = 'Data'
        if isinstance(scalars, str):
            title = scalars
            scalars = get_array(volume, scalars, preference=preference, err=True)
            scalar_bar_args.setdefault('title', title)
        elif not isinstance(scalars, np.ndarray):
            scalars = np.asarray(scalars)

        if scalars.ndim != 1:
            if scalars.ndim != 2:
                raise ValueError('`add_volume` only supports scalars with 1 or 2 dimensions')
            if scalars.shape[1] != 4 or scalars.dtype != np.uint8:
                raise ValueError(
                    '`add_volume` only supports scalars with 2 dimensions that have 4 components of datatype np.uint8.\n\n'
                    f'Scalars have shape {scalars.shape} and dtype {scalars.dtype.name!r}.'
                )

        if not np.issubdtype(scalars.dtype, np.number):
            raise TypeError('Non-numeric scalars are currently not supported for volume rendering.')
        if scalars.ndim != 1:
            if scalars.ndim != 2:
                raise ValueError('`add_volume` only supports scalars with 1 or 2 dimensions')
            if scalars.shape[1] != 4 or scalars.dtype != np.uint8:
                raise ValueError(
                    f'`add_volume` only supports scalars with 2 dimension that have 4 components of datatype np.uint8, scalars have shape {scalars.shape} and datatype {scalars.dtype}'
                )
            if opacity != 'linear':
                opacity = 'linear'
                warnings.warn('Ignoring custom opacity due to RGBA scalars.')

        # Define mapper, volume, and add the correct properties
        mappers_lookup = {
            'fixed_point': FixedPointVolumeRayCastMapper,
            'gpu': GPUVolumeRayCastMapper,
            'open_gl': OpenGLGPUVolumeRayCastMapper,
            'smart': SmartVolumeMapper,
            'ugrid': UnstructuredGridVolumeRayCastMapper,
        }
        if not isinstance(mapper, str) or mapper not in mappers_lookup.keys():
            raise TypeError(
                f"Mapper ({mapper}) unknown. Available volume mappers include: {', '.join(mappers_lookup.keys())}"
            )
        self.mapper = mappers_lookup[mapper](theme=self._theme)

        # Set scalars range
        min_, max_ = None, None
        if clim is None:
            if scalars.dtype == np.uint8:
                clim = [0, 255]
            else:
                min_, max_ = np.nanmin(scalars), np.nanmax(scalars)
                clim = [min_, max_]
        elif isinstance(clim, float) or isinstance(clim, int):
            clim = [-clim, clim]

        if log_scale:
            if clim[0] <= 0:
                clim = [sys.float_info.min, clim[1]]

        # data must be between [0, 255], but not necessarily UINT8
        # Preserve backwards compatibility and have same behavior as VTK.
        if scalars.dtype != np.uint8 and clim != [0, 255]:
            # must copy to avoid modifying inplace and remove any VTK weakref
            scalars = np.array(scalars)
            clim = np.asarray(clim, dtype=scalars.dtype)
            scalars.clip(clim[0], clim[1], out=scalars)
            if log_scale:
                out = matplotlib.colors.LogNorm(clim[0], clim[1])(scalars)
                scalars = out.data * 255
            else:
                if min_ is None:
                    min_, max_ = np.nanmin(scalars), np.nanmax(scalars)
                np.true_divide((scalars - min_), (max_ - min_) / 255, out=scalars, casting='unsafe')

        volume[title] = scalars
        volume.active_scalars_name = title

        # Scalars interpolation approach
        if scalars.shape[0] == volume.n_points:
            self.mapper.scalar_mode = 'point'
        elif scalars.shape[0] == volume.n_cells:
            self.mapper.scalar_mode = 'cell'
        else:
            raise_not_matching(scalars, volume)

        self.mapper.scalar_range = clim

        if isinstance(cmap, pyvista.LookupTable):
            self.mapper.lookup_table = cmap
        else:
            if cmap is None:
                cmap = self._theme.cmap

            cmap = get_cmap_safe(cmap)
            if categories:
                if categories is True:
                    n_colors = len(np.unique(scalars))
                elif isinstance(categories, int):
                    n_colors = categories

            if flip_scalars:
                cmap = cmap.reversed()

            # Set colormap and build lookup table
            self.mapper.lookup_table.apply_cmap(cmap, n_colors)
            self.mapper.lookup_table.apply_opacity(opacity)
            self.mapper.lookup_table.scalar_range = clim
            self.mapper.lookup_table.log_scale = log_scale
            if isinstance(annotations, dict):
                self.mapper.lookup_table.annotations = annotations

        self.mapper.dataset = volume
        self.mapper.blend_mode = blending
        self.mapper.update()

        self.volume = Volume()
        self.volume.mapper = self.mapper

        self.volume.prop = VolumeProperty(
            lookup_table=self.mapper.lookup_table,
            ambient=ambient,
            shade=shade,
            specular=specular,
            specular_power=specular_power,
            diffuse=diffuse,
            opacity_unit_distance=opacity_unit_distance,
        )

        if scalars.ndim == 2:
            self.volume.prop.independent_components = False
            show_scalar_bar = False

        actor, prop = self.add_actor(
            self.volume,
            reset_camera=reset_camera,
            name=name,
            culling=culling,
            pickable=pickable,
            render=render,
        )

        # Add scalar bar if scalars are available
        if show_scalar_bar and scalars is not None:
            self.add_scalar_bar(**scalar_bar_args)

        self.renderer.Modified()
        return actor

    def add_silhouette(
        self,
        mesh,
        color=None,
        line_width=None,
        opacity=None,
        feature_angle=None,
        decimate=None,
        params=None,
    ):
        """Add a silhouette of a PyVista or VTK dataset to the scene.

        A silhouette can also be generated directly in
        :func:`add_mesh <pyvista.Plotter.add_mesh>`. See also
        :ref:`silhouette_example`.

        Parameters
        ----------
        mesh : pyvista.DataSet | vtk.vtkAlgorithm
            Mesh or mesh-producing algorithm for generating silhouette
            to plot.

        color : ColorLike, optional
            Color of the silhouette lines.

        line_width : float, optional
            Silhouette line width.

        opacity : float, optional
            Line transparency between ``0`` and ``1``.

        feature_angle : float, optional
            If set, display sharp edges exceeding that angle in degrees.

        decimate : float, optional
            Level of decimation between ``0`` and ``1``. Decimating will
            improve rendering performance. A good rule of thumb is to
            try ``0.9``  first and decrease until the desired rendering
            performance is achieved.

        params : dict, optional
            Optional silhouette parameters.

            .. deprecated:: 0.38.0
               This keyword argument is no longer used. Instead, input the
               parameters to this function directly.

        Returns
        -------
        pyvista.Actor
            Actor of the silhouette.

        Examples
        --------
        >>> import pyvista as pv
        >>> from pyvista import examples
        >>> bunny = examples.download_bunny()
        >>> plotter = pv.Plotter()
        >>> _ = plotter.add_mesh(bunny, color='lightblue')
        >>> _ = plotter.add_silhouette(bunny, color='red', line_width=8.0)
        >>> plotter.view_xy()
        >>> plotter.show()

        """
        mesh, algo = algorithm_to_mesh_handler(mesh)
        if not isinstance(mesh, pyvista.PolyData):
            algo = extract_surface_algorithm(algo or mesh)
            mesh, algo = algorithm_to_mesh_handler(algo)

        silhouette_params = self._theme.silhouette.to_dict()

        if params is not None:
            # Deprecated on 0.38.0, estimated removal on v0.40.0
            warnings.warn(
                '`params` is deprecated. Set the arguments directly.',
                PyVistaDeprecationWarning,
                stacklevel=3,
            )
            silhouette_params.update(params)

        if color is None:
            color = silhouette_params["color"]
        if line_width is None:
            line_width = silhouette_params["line_width"]
        if opacity is None:
            opacity = silhouette_params["opacity"]
        if feature_angle is None:
            feature_angle = silhouette_params["feature_angle"]
        if decimate is None:
            decimate = silhouette_params["decimate"]

        # At this point we are dealing with a pipeline, so no `algo or mesh`
        if decimate:
            # Always triangulate as decimation filters needs it
            # and source mesh could have been any type
            algo = triangulate_algorithm(algo or mesh)
            algo = decimation_algorithm(algo, decimate)
            mesh, algo = algorithm_to_mesh_handler(algo)

        alg = _vtk.vtkPolyDataSilhouette()
        set_algorithm_input(alg, algo or mesh)
        alg.SetCamera(self.renderer.camera)
        if feature_angle is not None:
            alg.SetEnableFeatureAngle(True)
            alg.SetFeatureAngle(feature_angle)
        else:
            alg.SetEnableFeatureAngle(False)
        mapper = DataSetMapper(theme=self._theme)
        mapper.SetInputConnection(alg.GetOutputPort())
        actor, prop = self.add_actor(mapper)
        prop.SetColor(Color(color).float_rgb)
        prop.SetOpacity(opacity)
        prop.SetLineWidth(line_width)

        return actor

    def update_scalar_bar_range(self, clim, name=None):
        """Update the value range of the active or named scalar bar.

        Parameters
        ----------
        clim : sequence[float]
            The new range of scalar bar. For example ``[-1, 2]``.

        name : str, optional
            The title of the scalar bar to update.

        """
        if isinstance(clim, (float, int)):
            clim = [-clim, clim]
        if len(clim) != 2:
            raise TypeError('clim argument must be a length 2 iterable of values: (min, max).')
        if name is None:
            if not hasattr(self, 'mapper'):
                raise AttributeError('This plotter does not have an active mapper.')
            self.mapper.scalar_range = clim
            return

        try:
            # use the name to find the desired actor
            for mh in self.scalar_bars._scalar_bar_mappers[name]:
                mh.scalar_range = clim
        except KeyError:
            raise ValueError(f'Name ({name!r}) not valid/not found in this plotter.') from None

    def clear_actors(self):
        """Clear actors from all renderers."""
        self.renderers.clear_actors()

    def clear(self):
        """Clear plot by removing all actors and properties.

        Examples
        --------
        >>> import pyvista
        >>> plotter = pyvista.Plotter()
        >>> actor = plotter.add_mesh(pyvista.Sphere())
        >>> plotter.clear()
        >>> plotter.renderer.actors
        {}

        """
        self.renderers.clear()
        self.scalar_bars.clear()
        self.mesh = None
        self.mapper = None

    def link_views(self, views=0):
        """Link the views' cameras.

        Parameters
        ----------
        views : int | tuple | list, default: 0
            If ``views`` is int, link the views to the given view
            index or if ``views`` is a tuple or a list, link the given
            views cameras.

        Examples
        --------
        Not linked view case.

        >>> import pyvista
        >>> from pyvista import demos
        >>> ocube = demos.orientation_cube()
        >>> pl = pyvista.Plotter(shape=(1, 2))
        >>> pl.subplot(0, 0)
        >>> _ = pl.add_mesh(ocube['cube'], show_edges=True)
        >>> _ = pl.add_mesh(ocube['x_p'], color='blue')
        >>> _ = pl.add_mesh(ocube['x_n'], color='blue')
        >>> _ = pl.add_mesh(ocube['y_p'], color='green')
        >>> _ = pl.add_mesh(ocube['y_n'], color='green')
        >>> _ = pl.add_mesh(ocube['z_p'], color='red')
        >>> _ = pl.add_mesh(ocube['z_n'], color='red')
        >>> pl.camera_position = 'yz'
        >>> pl.subplot(0, 1)
        >>> _ = pl.add_mesh(ocube['cube'], show_edges=True)
        >>> _ = pl.add_mesh(ocube['x_p'], color='blue')
        >>> _ = pl.add_mesh(ocube['x_n'], color='blue')
        >>> _ = pl.add_mesh(ocube['y_p'], color='green')
        >>> _ = pl.add_mesh(ocube['y_n'], color='green')
        >>> _ = pl.add_mesh(ocube['z_p'], color='red')
        >>> _ = pl.add_mesh(ocube['z_n'], color='red')
        >>> pl.show_axes()
        >>> pl.show()

        Linked view case.

        >>> pl = pyvista.Plotter(shape=(1, 2))
        >>> pl.subplot(0, 0)
        >>> _ = pl.add_mesh(ocube['cube'], show_edges=True)
        >>> _ = pl.add_mesh(ocube['x_p'], color='blue')
        >>> _ = pl.add_mesh(ocube['x_n'], color='blue')
        >>> _ = pl.add_mesh(ocube['y_p'], color='green')
        >>> _ = pl.add_mesh(ocube['y_n'], color='green')
        >>> _ = pl.add_mesh(ocube['z_p'], color='red')
        >>> _ = pl.add_mesh(ocube['z_n'], color='red')
        >>> pl.camera_position = 'yz'
        >>> pl.subplot(0, 1)
        >>> _ = pl.add_mesh(ocube['cube'], show_edges=True)
        >>> _ = pl.add_mesh(ocube['x_p'], color='blue')
        >>> _ = pl.add_mesh(ocube['x_n'], color='blue')
        >>> _ = pl.add_mesh(ocube['y_p'], color='green')
        >>> _ = pl.add_mesh(ocube['y_n'], color='green')
        >>> _ = pl.add_mesh(ocube['z_p'], color='red')
        >>> _ = pl.add_mesh(ocube['z_n'], color='red')
        >>> pl.show_axes()
        >>> pl.link_views()
        >>> pl.show()

        """
        if isinstance(views, (int, np.integer)):
            camera = self.renderers[views].camera
            camera_status = self.renderers[views].camera.is_set
            for renderer in self.renderers:
                renderer.camera = camera
                renderer.camera.is_set = camera_status
            return
        views = np.asarray(views)
        if np.issubdtype(views.dtype, np.integer):
            camera = self.renderers[views[0]].camera
            camera_status = self.renderers[views[0]].camera.is_set
            for view_index in views:
                self.renderers[view_index].camera = camera
                self.renderers[view_index].camera.is_set = camera_status
        else:
            raise TypeError(f'Expected type is int, list or tuple: {type(views)} is given')

    def unlink_views(self, views=None):
        """Unlink the views' cameras.

        Parameters
        ----------
        views : int | tuple | list, optional
            If ``views`` is None unlink all the views, if ``views``
            is int unlink the selected view's camera or if ``views``
            is a tuple or a list, unlink the given views cameras.

        """
        if views is None:
            for renderer in self.renderers:
                renderer.camera = Camera()
                renderer.reset_camera()
                renderer.camera.is_set = False
        elif isinstance(views, int):
            self.renderers[views].camera = Camera()
            self.renderers[views].reset_camera()
            self.renderers[views].camera.is_set = False
        elif isinstance(views, collections.abc.Iterable):
            for view_index in views:
                self.renderers[view_index].camera = Camera()
                self.renderers[view_index].reset_camera()
                self.renderers[view_index].cemera_set = False
        else:
            raise TypeError(f'Expected type is None, int, list or tuple: {type(views)} is given')

    @wraps(ScalarBars.add_scalar_bar)
    def add_scalar_bar(self, *args, **kwargs):  # numpydoc ignore=PR01,RT01
        """Wrap for ``ScalarBars.add_scalar_bar``."""
        # only render when the plotter has already been shown
        render = kwargs.get('render', None)
        if render is None:
            kwargs['render'] = not self._first_time

        # check if maper exists
        mapper = kwargs.get('mapper', None)
        if mapper is None:
            if not hasattr(self, 'mapper') or self.mapper is None:
                raise AttributeError('Mapper does not exist.  Add a mesh with scalars first.')
            kwargs['mapper'] = self.mapper

        # title can be the first and only arg
        if len(args):
            title = args[0]
        else:
            title = kwargs.get('title', '')
        if title is None:
            title = ''
        kwargs['title'] = title

        interactive = kwargs.get('interactive', None)
        if interactive is None:
            interactive = self._theme.interactive
            if self.shape != (1, 1):
                interactive = False
        elif interactive and self.shape != (1, 1):
            raise ValueError('Interactive scalar bars disabled for multi-renderer plots')
        # by default, use the plotter local theme
        kwargs.setdefault('theme', self._theme)
        return self.scalar_bars.add_scalar_bar(**kwargs)

    def update_scalars(self, scalars, mesh=None, render=True):
        """Update scalars of an object in the plotter.

        Parameters
        ----------
        scalars : sequence
            Scalars to replace existing scalars.

        mesh : vtk.PolyData | vtk.UnstructuredGrid, optional
            Object that has already been added to the Plotter.  If
            None, uses last added mesh.

        render : bool, default: True
            Force a render when True.
        """
        if mesh is None:
            mesh = self.mesh

        if isinstance(mesh, (collections.abc.Iterable, pyvista.MultiBlock)):
            # Recursive if need to update scalars on many meshes
            for m in mesh:
                self.update_scalars(scalars, mesh=m, render=False)
            if render:
                self.render()
            return

        if isinstance(scalars, str):
            # Grab scalars array if name given
            scalars = get_array(mesh, scalars)

        if scalars is None:
            if render:
                self.render()
            return

        if scalars.shape[0] == mesh.GetNumberOfPoints():
            data = mesh.GetPointData()
        elif scalars.shape[0] == mesh.GetNumberOfCells():
            data = mesh.GetCellData()
        else:
            raise_not_matching(scalars, mesh)

        vtk_scalars = data.GetScalars()
        if vtk_scalars is None:
            raise ValueError('No active scalars')
        s = convert_array(vtk_scalars)
        s[:] = scalars
        vtk_scalars.Modified()
        data.Modified()
        try:
            # Why are the points updated here? Not all datasets have points
            # and only the scalars array is modified by this function...
            mesh.GetPoints().Modified()
        except:
            pass

        if render:
            self.render()

    def update_coordinates(self, points, mesh=None, render=True):
        """Update the points of an object in the plotter.

        Parameters
        ----------
        points : np.ndarray
            Points to replace existing points.

        mesh : vtk.PolyData | vtk.UnstructuredGrid, optional
            Object that has already been added to the Plotter.  If ``None``, uses
            last added mesh.

        render : bool, default: True
            Force a render when True.
        """
        if mesh is None:
            mesh = self.mesh

        mesh.points = points

        # only render when the plotter has already been shown
        if render is None:
            render = not self._first_time

        if render:
            self.render()

    def _clear_ren_win(self):
        """Clear the render window."""
        # Not using `render_window` property here to enforce clean up
        if hasattr(self, 'ren_win'):
            self.ren_win.Finalize()
            del self.ren_win

    def close(self, render=False):
        """Close the render window.

        Parameters
        ----------
        render : bool
            Unused argument.

        """
        # optionally run just prior to exiting the plotter
        if self._before_close_callback is not None:
            self._before_close_callback(self)
            self._before_close_callback = None

        # must close out widgets first
        super().close()
        # Renderer has an axes widget, so close it
        self.renderers.close()
        self.renderers.remove_all_lights()

        # Grab screenshots of last render
        # self.last_image = self.screenshot(None, return_img=True)
        # self.last_image_depth = self.get_image_depth()

        # reset scalar bars
        self.scalar_bars.clear()
        self.mesh = None
        self.mapper = None

        # grab the display id before clearing the window
        # this is an experimental feature
        if KILL_DISPLAY:  # pragma: no cover
            disp_id = None
            if self.render_window is not None:
                disp_id = self.render_window.GetGenericDisplayId()
        self._clear_ren_win()

        if self.iren is not None:
            self.iren.close()
            if KILL_DISPLAY:  # pragma: no cover
                _kill_display(disp_id)
            self.iren = None

        if hasattr(self, 'textActor'):
            del self.textActor

        # end movie
        if hasattr(self, 'mwriter'):
            try:
                self.mwriter.close()
            except BaseException:
                pass

        # Remove the global reference to this plotter unless building the
        # gallery to allow it to collect.
        if not pyvista.BUILDING_GALLERY:
            if _ALL_PLOTTERS is not None:
                _ALL_PLOTTERS.pop(self._id_name, None)

        # this helps managing closed plotters
        self._closed = True

    def deep_clean(self):
        """Clean the plotter of the memory."""
        self.disable_picking()
        if hasattr(self, 'renderers'):
            self.renderers.deep_clean()
        self.mesh = None
        self.mapper = None
        self.volume = None
        self.textActor = None

    def add_text(
        self,
        text,
        position='upper_left',
        font_size=18,
        color=None,
        font=None,
        shadow=False,
        name=None,
        viewport=False,
        orientation=0.0,
        *,
        render=True,
    ):
        """Add text to plot object in the top left corner by default.

        Parameters
        ----------
        text : str
            The text to add the rendering.

        position : str | sequence[float], default: "upper_left"
            Position to place the bottom left corner of the text box.
            If tuple is used, the position of the text uses the pixel
            coordinate system (default). In this case,
            it returns a more general `vtkOpenGLTextActor`.
            If string name is used, it returns a `vtkCornerAnnotation`
            object normally used for fixed labels (like title or xlabel).
            Default is to find the top left corner of the rendering window
            and place text box up there. Available position: ``'lower_left'``,
            ``'lower_right'``, ``'upper_left'``, ``'upper_right'``,
            ``'lower_edge'``, ``'upper_edge'``, ``'right_edge'``, and
            ``'left_edge'``.

        font_size : float, default: 18
            Sets the size of the title font.

        color : ColorLike, optional
            Either a string, RGB list, or hex color string.  For example:

            * ``color='white'``
            * ``color='w'``
            * ``color=[1.0, 1.0, 1.0]``
            * ``color='#FFFFFF'``

            Defaults to :attr:`pyvista.global_theme.font.color <pyvista.plotting.themes._Font.color>`.

        font : str, optional
            Font name may be ``'courier'``, ``'times'``, or ``'arial'``.

        shadow : bool, default: False
            Adds a black shadow to the text.

        name : str, optional
            The name for the added actor so that it can be easily updated.
            If an actor of this name already exists in the rendering window, it
            will be replaced by the new actor.

        viewport : bool, default: False
            If ``True`` and position is a tuple of float, uses the
            normalized viewport coordinate system (values between 0.0
            and 1.0 and support for HiDPI).

        orientation : float, default: 0.0
            Angle orientation of text counterclockwise in degrees.  The text
            is rotated around an anchor point that may be on the edge or
            corner of the text.  The default is horizontal (0.0 degrees).

        render : bool, optional
            Force a render when ``True`` (default).

        Returns
        -------
        vtk.vtkTextActor
            Text actor added to plot.

        Examples
        --------
        >>> import pyvista
        >>> pl = pyvista.Plotter()
        >>> actor = pl.add_text(
        ...     'Sample Text',
        ...     position='upper_right',
        ...     color='blue',
        ...     shadow=True,
        ...     font_size=26,
        ... )
        >>> pl.show()

        """
        if font is None:
            font = self._theme.font.family
        if font_size is None:
            font_size = self._theme.font.size
        if position is None:
            # Set the position of the text to the top left corner
            window_size = self.window_size
            x = (window_size[0] * 0.02) / self.shape[0]
            y = (window_size[1] * 0.85) / self.shape[0]
            position = [x, y]

        corner_mappings = {
            'lower_left': _vtk.vtkCornerAnnotation.LowerLeft,
            'lower_right': _vtk.vtkCornerAnnotation.LowerRight,
            'upper_left': _vtk.vtkCornerAnnotation.UpperLeft,
            'upper_right': _vtk.vtkCornerAnnotation.UpperRight,
            'lower_edge': _vtk.vtkCornerAnnotation.LowerEdge,
            'upper_edge': _vtk.vtkCornerAnnotation.UpperEdge,
            'left_edge': _vtk.vtkCornerAnnotation.LeftEdge,
            'right_edge': _vtk.vtkCornerAnnotation.RightEdge,
        }
        corner_mappings['ll'] = corner_mappings['lower_left']
        corner_mappings['lr'] = corner_mappings['lower_right']
        corner_mappings['ul'] = corner_mappings['upper_left']
        corner_mappings['ur'] = corner_mappings['upper_right']
        corner_mappings['top'] = corner_mappings['upper_edge']
        corner_mappings['bottom'] = corner_mappings['lower_edge']
        corner_mappings['right'] = corner_mappings['right_edge']
        corner_mappings['r'] = corner_mappings['right_edge']
        corner_mappings['left'] = corner_mappings['left_edge']
        corner_mappings['l'] = corner_mappings['left_edge']

        if isinstance(position, (int, str, bool)):
            if isinstance(position, str):
                position = corner_mappings[position]
            elif position is True:
                position = corner_mappings['upper_left']
            self.textActor = _vtk.vtkCornerAnnotation()
            # This is how you set the font size with this actor
            self.textActor.SetLinearFontScaleFactor(font_size // 2)
            self.textActor.SetText(position, text)
        else:
            self.textActor = _vtk.vtkTextActor()
            self.textActor.SetInput(text)
            self.textActor.SetPosition(position)
            if viewport:
                self.textActor.GetActualPositionCoordinate().SetCoordinateSystemToNormalizedViewport()
                self.textActor.GetActualPosition2Coordinate().SetCoordinateSystemToNormalizedViewport()
            self.textActor.GetTextProperty().SetFontSize(int(font_size * 2))

        text_prop = self.textActor.GetTextProperty()
        text_prop.SetColor(Color(color, default_color=self._theme.font.color).float_rgb)
        text_prop.SetFontFamily(FONTS[font].value)
        text_prop.SetShadow(shadow)
        text_prop.SetOrientation(orientation)

        self.add_actor(self.textActor, reset_camera=False, name=name, pickable=False, render=render)
        return self.textActor

    def open_movie(self, filename, framerate=24, quality=5, **kwargs):
        """Establish a connection to the ffmpeg writer.

        Requires ``imageio`` to be installed.

        Parameters
        ----------
        filename : str
            Filename of the movie to open.  Filename should end in mp4,
            but other filetypes may be supported.  See :func:`imageio.get_writer()
            <imageio.v2.get_writer>`.

        framerate : int, default: 24
            Frames per second.

        quality : int, default: 5
            Quality 10 is the top possible quality for any codec. The
            range is ``0 - 10``.  Higher quality leads to a larger file.

        **kwargs : dict, optional
            See the documentation for :func:`imageio.get_writer()
            <imageio.v2.get_writer>` for additional kwargs.

        Notes
        -----
        See the documentation for :func:`imageio.get_writer() <imageio.v2.get_writer>`.

        Examples
        --------
        Open a MP4 movie and set the quality to maximum.

        >>> import pyvista
        >>> pl = pyvista.Plotter
        >>> pl.open_movie('movie.mp4', quality=10)  # doctest:+SKIP

        """
        try:
            from imageio import get_writer
        except ModuleNotFoundError:  # pragma: no cover
            raise ModuleNotFoundError(
                'Install imageio to use `open_movie` with:\n\n   pip install imageio'
            ) from None

        if isinstance(pyvista.FIGURE_PATH, str) and not os.path.isabs(filename):
            filename = os.path.join(pyvista.FIGURE_PATH, filename)
        self.mwriter = get_writer(filename, fps=framerate, quality=quality, **kwargs)

    def open_gif(
        self,
        filename,
        loop=0,
        fps=10,
        palettesize=256,
        subrectangles=False,
        **kwargs,
    ):
        """Open a gif file.

        Requires ``imageio`` to be installed.

        Parameters
        ----------
        filename : str
            Filename of the gif to open.  Filename must end in ``"gif"``.

        loop : int, default: 0
            The number of iterations. Default value of 0 loops indefinitely.

        fps : float, default: 10
            The number of frames per second. If duration is not given, the
            duration for each frame is set to 1/fps.

        palettesize : int, default: 256
            The number of colors to quantize the image to. Is rounded to the
            nearest power of two. Must be between 2 and 256.

        subrectangles : bool, default: False
            If ``True``, will try and optimize the GIF by storing only the rectangular
            parts of each frame that change with respect to the previous.

            .. note::
               Setting this to ``True`` may help reduce jitter in colorbars.

        **kwargs : dict, optional
            See the documentation for :func:`imageio.get_writer() <imageio.v2.get_writer>`
            for additional kwargs.

        Notes
        -----
        Consider using `pygifsicle
        <https://github.com/LucaCappelletti94/pygifsicle>`_ to reduce the final
        size of the gif. See `Optimizing a GIF using pygifsicle
        <https://imageio.readthedocs.io/en/stable/examples.html#optimizing-a-gif-using-pygifsicle>`_.

        Examples
        --------
        Open a gif file, setting the framerate to 8 frames per second and
        reducing the colorspace to 64.

        >>> import pyvista
        >>> pl = pyvista.Plotter()
        >>> pl.open_gif(
        ...     'movie.gif', fps=8, palettesize=64
        ... )  # doctest:+SKIP

        See :ref:`gif_movie_example` for a full example using this method.

        """
        try:
            from imageio import __version__, get_writer
        except ModuleNotFoundError:  # pragma: no cover
            raise ModuleNotFoundError(
                'Install imageio to use `open_gif` with:\n\n   pip install imageio'
            ) from None

        if filename[-3:] != 'gif':
            raise ValueError('Unsupported filetype.  Must end in .gif')
        if isinstance(pyvista.FIGURE_PATH, str) and not os.path.isabs(filename):
            filename = os.path.join(pyvista.FIGURE_PATH, filename)
        self._gif_filename = os.path.abspath(filename)

        kwargs['mode'] = 'I'
        kwargs['loop'] = loop
        kwargs['palettesize'] = palettesize
        kwargs['subrectangles'] = subrectangles
        if scooby.meets_version(__version__, '2.28.1'):
            kwargs['duration'] = 1000 * 1 / fps
        else:  # pragma: no cover
            kwargs['fps'] = fps

        self.mwriter = get_writer(filename, **kwargs)

    def write_frame(self):
        """Write a single frame to the movie file.

        Examples
        --------
        >>> import pyvista
        >>> plotter = pyvista.Plotter()
        >>> plotter.open_movie(filename)  # doctest:+SKIP
        >>> plotter.add_mesh(pyvista.Sphere())  # doctest:+SKIP
        >>> plotter.write_frame()  # doctest:+SKIP

        See :ref:`movie_example` for a full example using this method.

        """
        # if off screen, show has not been called and we must render
        # before extracting an image
        if self._first_time:
            self._on_first_render_request()
            self.render()

        if not hasattr(self, 'mwriter'):
            raise RuntimeError('This plotter has not opened a movie or GIF file.')
        self.update()
        self.mwriter.append_data(self.image)

    def get_image_depth(self, fill_value=np.nan, reset_camera_clipping_range=True):
        """Return a depth image representing current render window.

        Parameters
        ----------
        fill_value : float, default: numpy.nan
            Fill value for points in image that do not include objects
            in scene.  To not use a fill value, pass ``None``.

        reset_camera_clipping_range : bool, default: True
            Reset the camera clipping range to include data in view.

        Returns
        -------
        numpy.ndarray
            Image of depth values from camera orthogonal to image
            plane.

        Notes
        -----
        Values in image_depth are negative to adhere to a
        right-handed coordinate system.

        Examples
        --------
        >>> import pyvista
        >>> plotter = pyvista.Plotter()
        >>> actor = plotter.add_mesh(pyvista.Sphere())
        >>> plotter.show()
        >>> zval = plotter.get_image_depth()

        """
        # allow no render window
        if self.render_window is None and self.last_image_depth is not None:
            zval = self.last_image_depth.copy()
            if fill_value is not None:
                zval[self._image_depth_null] = fill_value
            return zval

        self._check_rendered()
        self._check_has_ren_win()

        # Ensure points in view are within clipping range of renderer?
        if reset_camera_clipping_range:
            self.renderer.ResetCameraClippingRange()

        # Get the z-buffer image
        ifilter = _vtk.vtkWindowToImageFilter()
        ifilter.SetInput(self.render_window)
        ifilter.SetScale(self.image_scale)
        ifilter.ReadFrontBufferOff()
        ifilter.SetInputBufferTypeToZBuffer()
        zbuff = run_image_filter(ifilter)[:, :, 0]

        # Convert z-buffer values to depth from camera
        with warnings.catch_warnings():
            warnings.filterwarnings('ignore')
            near, far = self.camera.clipping_range
            if self.camera.parallel_projection:
                zval = (zbuff - near) / (far - near)
            else:
                zval = 2 * near * far / ((zbuff - 0.5) * 2 * (far - near) - near - far)

            # Consider image values outside clipping range as nans
            self._image_depth_null = np.logical_or(zval < -far, np.isclose(zval, -far))

        if fill_value is not None:
            zval[self._image_depth_null] = fill_value

        return zval

    def add_lines(self, lines, color='w', width=5, label=None, name=None, connected=False):
        """Add lines to the plotting object.

        Parameters
        ----------
        lines : np.ndarray
            Points representing line segments.  For example, two line
            segments would be represented as ``np.array([[0, 1, 0],
            [1, 0, 0], [1, 1, 0], [2, 0, 0]])``.

        color : ColorLike, default: 'w'
            Either a string, rgb list, or hex color string.  For example:

            * ``color='white'``
            * ``color='w'``
            * ``color=[1.0, 1.0, 1.0]``
            * ``color='#FFFFFF'``

        width : float, default: 5
            Thickness of lines.

        label : str, default: None
            String label to use when adding a legend to the scene with
            :func:`pyvista.Plotter.add_legend`.

        name : str, default: None
            The name for the added actor so that it can be easily updated.
            If an actor of this name already exists in the rendering window, it
            will be replaced by the new actor.

        connected : bool, default: False
            Treat ``lines`` as points representing a series of *connected* lines.
            For example, two connected line segments would be represented as
            ``np.array([[0, 0, 0], [1, 0, 0], [1, 1, 0]])``. If ``False``, an *even*
            number of points must be passed to ``lines``, and the lines need not be
            connected.


        Returns
        -------
        vtk.vtkActor
            Lines actor.

        Examples
        --------
        Plot two lines.

        >>> import numpy as np
        >>> import pyvista
        >>> pl = pyvista.Plotter()
        >>> points = np.array([[0, 1, 0], [1, 0, 0], [1, 1, 0], [2, 0, 0]])
        >>> actor = pl.add_lines(points, color='purple', width=3)
        >>> pl.camera_position = 'xy'
        >>> pl.show()

        Adding lines with ``connected=True`` will add a series of connected
        line segments.

        >>> pl = pyvista.Plotter()
        >>> points = np.array([[0, 1, 0], [1, 0, 0], [1, 1, 0], [2, 0, 0]])
        >>> actor = pl.add_lines(
        ...     points, color='purple', width=3, connected=True
        ... )
        >>> pl.camera_position = 'xy'
        >>> pl.show()

        """
        if not isinstance(lines, np.ndarray):
            raise TypeError('Input should be an array of point segments')

        lines = (
            pyvista.lines_from_points(lines)
            if connected
            else pyvista.line_segments_from_points(lines)
        )

        actor = Actor(mapper=DataSetMapper(lines))
        actor.prop.line_width = width
        actor.prop.show_edges = True
        actor.prop.edge_color = color
        actor.prop.color = color
        actor.prop.lighting = False

        # legend label
        if label:
            if not isinstance(label, str):
                raise TypeError('Label must be a string')
            addr = actor.GetAddressAsString("")
            self.renderer._labels[addr] = [lines, label, Color(color)]

        # Add to renderer
        self.add_actor(actor, reset_camera=False, name=name, pickable=False)
        return actor

    @wraps(ScalarBars.remove_scalar_bar)
    def remove_scalar_bar(self, *args, **kwargs):  # numpydoc ignore=PR01,RT01
        """Remove the active scalar bar."""
        self.scalar_bars.remove_scalar_bar(*args, **kwargs)

    def add_point_labels(
        self,
        points,
        labels,
        italic=False,
        bold=True,
        font_size=None,
        text_color=None,
        font_family=None,
        shadow=False,
        show_points=True,
        point_color=None,
        point_size=None,
        name=None,
        shape_color='grey',
        shape='rounded_rect',
        fill_shape=True,
        margin=3,
        shape_opacity=1.0,
        pickable=False,
        render_points_as_spheres=False,
        tolerance=0.001,
        reset_camera=None,
        always_visible=False,
        render=True,
    ):
        """Create a point actor with one label from list labels assigned to each point.

        Parameters
        ----------
        points : sequence | pyvista.DataSet | vtk.vtkAlgorithm
            An ``n x 3`` sequence points or :class:`pyvista.DataSet` with
            points or mesh-producing algorithm.

        labels : list | str
            List of labels.  Must be the same length as points. If a
            string name is given with a :class:`pyvista.DataSet` input for
            points, then these are fetched.

        italic : bool, default: False
            Italicises title and bar labels.

        bold : bool, default: True
            Bolds title and bar labels.

        font_size : float, optional
            Sets the size of the title font.

        text_color : ColorLike, optional
            Color of text. Either a string, RGB sequence, or hex color string.

            * ``text_color='white'``
            * ``text_color='w'``
            * ``text_color=[1.0, 1.0, 1.0]``
            * ``text_color='#FFFFFF'``

        font_family : str, optional
            Font family.  Must be either ``'courier'``, ``'times'``,
            or ``'arial``.

        shadow : bool, default: False
            Adds a black shadow to the text.

        show_points : bool, default: True
            Controls if points are visible.

        point_color : ColorLike, optional
            Either a string, rgb list, or hex color string.  One of
            the following.

            * ``point_color='white'``
            * ``point_color='w'``
            * ``point_color=[1.0, 1.0, 1.0]``
            * ``point_color='#FFFFFF'``

        point_size : float, optional
            Size of points if visible.

        name : str, optional
            The name for the added actor so that it can be easily
            updated.  If an actor of this name already exists in the
            rendering window, it will be replaced by the new actor.

        shape_color : ColorLike, default: "grey"
            Color of shape (if visible).  Either a string, rgb
            sequence, or hex color string.

        shape : str, default: "rounded_rect"
            The string name of the shape to use. Options are ``'rect'`` or
            ``'rounded_rect'``. If you want no shape, pass ``None``.

        fill_shape : bool, default: True
            Fill the shape with the ``shape_color``. Outlines if ``False``.

        margin : int, default: 3
            The size of the margin on the label background shape.

        shape_opacity : float, default: 1.0
            The opacity of the shape in the range of ``[0, 1]``.

        pickable : bool, default: False
            Set whether this actor is pickable.

        render_points_as_spheres : bool, default: False
            Render points as spheres rather than dots.

        tolerance : float, default: 0.001
            A tolerance to use to determine whether a point label is
            visible.  A tolerance is usually required because the
            conversion from world space to display space during
            rendering introduces numerical round-off.

        reset_camera : bool, optional
            Reset the camera after adding the points to the scene.

        always_visible : bool, default: False
            Skip adding the visibility filter.

        render : bool, default: True
            Force a render when ``True``.

        Returns
        -------
        vtk.vtkActor2D
            VTK label actor.  Can be used to change properties of the labels.

        Examples
        --------
        >>> import numpy as np
        >>> import pyvista
        >>> pl = pyvista.Plotter()
        >>> points = np.array(
        ...     [[0.0, 0.0, 0.0], [1.0, 1.0, 0.0], [2.0, 0.0, 0.0]]
        ... )
        >>> labels = ['Point A', 'Point B', 'Point C']
        >>> actor = pl.add_point_labels(
        ...     points,
        ...     labels,
        ...     italic=True,
        ...     font_size=20,
        ...     point_color='red',
        ...     point_size=20,
        ...     render_points_as_spheres=True,
        ...     always_visible=True,
        ...     shadow=True,
        ... )
        >>> pl.camera_position = 'xy'
        >>> pl.show()

        """
        if font_family is None:
            font_family = self._theme.font.family
        if font_size is None:
            font_size = self._theme.font.size
        point_color = Color(point_color, default_color=self._theme.color)

        if isinstance(points, (list, tuple)):
            points = np.array(points)

        if isinstance(points, np.ndarray):
            points = pyvista.PolyData(points)  # Cast to poly data
        elif not is_pyvista_dataset(points) and not isinstance(points, _vtk.vtkAlgorithm):
            raise TypeError(f'Points type not usable: {type(points)}')
        points, algo = algorithm_to_mesh_handler(points)
        if algo is not None:
            if pyvista.vtk_version_info < (9, 1):  # pragma: no cover
                from pyvista.core.errors import VTKVersionError

                raise VTKVersionError(
                    'To use vtkAlgorithms with `add_point_labels` requires VTK 9.1 or later.'
                )
            # Extract points filter
            pc_algo = _vtk.vtkConvertToPointCloud()
            set_algorithm_input(pc_algo, algo)
            algo = pc_algo

        if name is None:
            name = f'{type(points).__name__}({points.memory_address})'

        hier = _vtk.vtkPointSetToLabelHierarchy()
        if not isinstance(labels, str):
            if algo is not None:
                raise TypeError(
                    'If using a vtkAlgorithm input, the labels must be a named array on the dataset.'
                )
            points = pyvista.PolyData(points.points)
            if len(points.points) != len(labels):
                raise ValueError('There must be one label for each point')
            vtklabels = _vtk.vtkStringArray()
            vtklabels.SetName('labels')
            for item in labels:
                vtklabels.InsertNextValue(str(item))
            points.GetPointData().AddArray(vtklabels)
            hier.SetLabelArrayName('labels')
        else:
            # Make sure PointData
            if labels not in points.point_data:
                raise ValueError(f'Array {labels!r} not found in point data.')
            hier.SetLabelArrayName(labels)

        if always_visible:
            set_algorithm_input(hier, algo or points)
        else:
            # Only show visible points
            vis_points = _vtk.vtkSelectVisiblePoints()
            set_algorithm_input(vis_points, algo or points)
            vis_points.SetRenderer(self.renderer)
            vis_points.SetTolerance(tolerance)

            hier.SetInputConnection(vis_points.GetOutputPort())

        # create label mapper
        labelMapper = _vtk.vtkLabelPlacementMapper()
        labelMapper.SetInputConnection(hier.GetOutputPort())
        if not isinstance(shape, str):
            labelMapper.SetShapeToNone()
        elif shape.lower() in 'rect':
            labelMapper.SetShapeToRect()
        elif shape.lower() in 'rounded_rect':
            labelMapper.SetShapeToRoundedRect()
        else:
            raise ValueError(f'Shape ({shape}) not understood')
        if fill_shape:
            labelMapper.SetStyleToFilled()
        else:
            labelMapper.SetStyleToOutline()
        labelMapper.SetBackgroundColor(Color(shape_color).float_rgb)
        labelMapper.SetBackgroundOpacity(shape_opacity)
        labelMapper.SetMargin(margin)

        textprop = hier.GetTextProperty()
        textprop.SetItalic(italic)
        textprop.SetBold(bold)
        textprop.SetFontSize(font_size)
        textprop.SetFontFamily(parse_font_family(font_family))
        textprop.SetColor(Color(text_color, default_color=self._theme.font.color).float_rgb)
        textprop.SetShadow(shadow)

        self.remove_actor(f'{name}-points', reset_camera=False)
        self.remove_actor(f'{name}-labels', reset_camera=False)

        # add points
        if show_points:
            self.add_mesh(
                algo or points,
                color=point_color,
                point_size=point_size,
                name=f'{name}-points',
                pickable=pickable,
                render_points_as_spheres=render_points_as_spheres,
                reset_camera=reset_camera,
                render=render,
            )

        label_actor = _vtk.vtkActor2D()
        label_actor.SetMapper(labelMapper)
        self.add_actor(label_actor, reset_camera=False, name=f'{name}-labels', pickable=False)
        return label_actor

    def add_point_scalar_labels(self, points, labels, fmt=None, preamble='', **kwargs):
        """Label the points from a dataset with the values of their scalars.

        Wrapper for :func:`pyvista.Plotter.add_point_labels`.

        Parameters
        ----------
        points : sequence[float] | np.ndarray | pyvista.DataSet
            An ``n x 3`` numpy.ndarray or pyvista dataset with points.

        labels : list | str
            List of scalars of labels.  Must be the same length as points. If a
            string name is given with a :class:`pyvista.DataSet` input for
            points, then these are fetched.

        fmt : str, optional
            String formatter used to format numerical data.

        preamble : str, default: ""
            Text before the start of each label.

        **kwargs : dict, optional
            Keyword arguments passed to
            :func:`pyvista.Plotter.add_point_labels`.

        Returns
        -------
        vtk.vtkActor2D
            VTK label actor.  Can be used to change properties of the labels.

        """
        if not is_pyvista_dataset(points):
            points, _ = _coerce_pointslike_arg(points, copy=False)
        if not isinstance(labels, (str, list)):
            raise TypeError(
                'labels must be a string name of the scalars array to use or list of scalars'
            )
        if fmt is None:
            fmt = self._theme.font.fmt
        if fmt is None:
            fmt = '%.6e'
        if isinstance(points, np.ndarray):
            scalars = labels
        elif is_pyvista_dataset(points):
            scalars = points.point_data[labels]
        phrase = f'{preamble} {fmt}'
        labels = [phrase % val for val in scalars]
        return self.add_point_labels(points, labels, **kwargs)

    def add_points(self, points, style='points', **kwargs):
        """Add points to a mesh.

        Parameters
        ----------
        points : numpy.ndarray or pyvista.DataSet
            Array of points or the points from a pyvista object.

        style : str, default: 'points'
            Visualization style of the mesh.  One of the following:
            ``style='points'``, ``style='points_gaussian'``.
            ``'points_gaussian'`` can be controlled with the ``emissive`` and
            ``render_points_as_spheres`` options.

        **kwargs : dict, optional
            See :func:`pyvista.Plotter.add_mesh` for optional
            keyword arguments.

        Returns
        -------
        pyvista.Actor
            Actor of the mesh.

        Examples
        --------
        Add a numpy array of points to a mesh.

        >>> import numpy as np
        >>> import pyvista
        >>> points = np.random.random((10, 3))
        >>> pl = pyvista.Plotter()
        >>> actor = pl.add_points(
        ...     points, render_points_as_spheres=True, point_size=100.0
        ... )
        >>> pl.show()

        Plot using the ``'points_gaussian'`` style

        >>> points = np.random.random((10, 3))
        >>> pl = pyvista.Plotter()
        >>> actor = pl.add_points(points, style='points_gaussian')
        >>> pl.show()

        """
        if style not in ['points', 'points_gaussian']:
            raise ValueError(
                f'Invalid style {style} for add_points. Should be either "points" or '
                '"points_gaussian".'
            )
        return self.add_mesh(points, style=style, **kwargs)

    def add_arrows(self, cent, direction, mag=1, **kwargs):
        """Add arrows to the plotter.

        Parameters
        ----------
        cent : np.ndarray
            Array of centers.

        direction : np.ndarray
            Array of direction vectors.

        mag : float, optional
            Amount to scale the direction vectors.

        **kwargs : dict, optional
            See :func:`pyvista.Plotter.add_mesh` for optional
            keyword arguments.

        Returns
        -------
        pyvista.Actor
            Actor of the arrows.

        Examples
        --------
        Plot a random field of vectors and save a screenshot of it.

        >>> import numpy as np
        >>> import pyvista
        >>> cent = np.random.random((10, 3))
        >>> direction = np.random.random((10, 3))
        >>> plotter = pyvista.Plotter()
        >>> _ = plotter.add_arrows(cent, direction, mag=2)
        >>> plotter.show()

        """
        if cent.shape != direction.shape:  # pragma: no cover
            raise ValueError('center and direction arrays must have the same shape')

        direction = direction.copy()
        if cent.ndim != 2:
            cent = cent.reshape((-1, 3))

        if direction.ndim != 2:
            direction = direction.reshape((-1, 3))

        if mag != 1:
            direction = direction * mag

        pdata = pyvista.vector_poly_data(cent, direction)
        # Create arrow object
        arrow = _vtk.vtkArrowSource()
        arrow.Update()
        glyph3D = _vtk.vtkGlyph3D()
        glyph3D.SetSourceData(arrow.GetOutput())
        glyph3D.SetInputData(pdata)
        glyph3D.SetVectorModeToUseVector()
        glyph3D.Update()

        arrows = wrap(glyph3D.GetOutput())
        return self.add_mesh(arrows, **kwargs)

    @staticmethod
    def _save_image(image, filename, return_img):
        """Save to file and/or return a NumPy image array.

        This is an internal helper.

        """
        if not image.size:
            raise ValueError('Empty image. Have you run plot() first?')
        # write screenshot to file if requested
        if isinstance(filename, (str, pathlib.Path, io.BytesIO)):
            from PIL import Image

            if isinstance(filename, (str, pathlib.Path)):
                filename = pathlib.Path(filename)
                if isinstance(pyvista.FIGURE_PATH, str) and not filename.is_absolute():
                    filename = pathlib.Path(os.path.join(pyvista.FIGURE_PATH, filename))
                if not filename.suffix:
                    filename = filename.with_suffix('.png')
                elif filename.suffix not in SUPPORTED_FORMATS:
                    raise ValueError(
                        f'Unsupported extension {filename.suffix}\n'
                        f'Must be one of the following: {SUPPORTED_FORMATS}'
                    )
                filename = os.path.abspath(os.path.expanduser(str(filename)))
                Image.fromarray(image).save(filename)
            else:
                Image.fromarray(image).save(filename, format="PNG")
        # return image array if requested
        if return_img:
            return image

    def save_graphic(self, filename, title='PyVista Export', raster=True, painter=True):
        """Save a screenshot of the rendering window as a graphic file.

        This can be helpful for publication documents.

        The supported formats are:

        * ``'.svg'``
        * ``'.eps'``
        * ``'.ps'``
        * ``'.pdf'``
        * ``'.tex'``

        Parameters
        ----------
        filename : str
            Path to fsave the graphic file to.

        title : str, default: "PyVista Export"
            Title to use within the file properties.

        raster : bool, default: True
            Attempt to write 3D properties as a raster image.

        painter : bool, default: True
            Configure the exporter to expect a painter-ordered 2D
            rendering, that is, a rendering at a fixed depth where
            primitives are drawn from the bottom up.

        Examples
        --------
        >>> import pyvista
        >>> from pyvista import examples
        >>> pl = pyvista.Plotter()
        >>> _ = pl.add_mesh(examples.load_airplane(), smooth_shading=True)
        >>> _ = pl.add_background_image(examples.mapfile)
        >>> pl.save_graphic("img.svg")  # doctest:+SKIP

        """
        from vtkmodules.vtkIOExportGL2PS import vtkGL2PSExporter

        if self.render_window is None:
            raise AttributeError('This plotter is closed and unable to save a screenshot.')
        if self._first_time:
            self._on_first_render_request()
            self.render()
        if isinstance(pyvista.FIGURE_PATH, str) and not os.path.isabs(filename):
            filename = os.path.join(pyvista.FIGURE_PATH, filename)
        filename = os.path.abspath(os.path.expanduser(filename))
        extension = pyvista.core.utilities.fileio.get_ext(filename)

        writer = vtkGL2PSExporter()
        modes = {
            '.svg': writer.SetFileFormatToSVG,
            '.eps': writer.SetFileFormatToEPS,
            '.ps': writer.SetFileFormatToPS,
            '.pdf': writer.SetFileFormatToPDF,
            '.tex': writer.SetFileFormatToTeX,
        }
        if extension not in modes:
            raise ValueError(
                f"Extension ({extension}) is an invalid choice.\n\n"
                f"Valid options include: {', '.join(modes.keys())}"
            )
        writer.CompressOff()
        writer.SetFilePrefix(filename.replace(extension, ''))
        writer.SetInput(self.render_window)
        modes[extension]()
        writer.SetTitle(title)
        writer.SetWrite3DPropsAsRasterImage(raster)
        if painter:
            writer.UsePainterSettings()
        writer.Update()

    def screenshot(
        self,
        filename=None,
        transparent_background=None,
        return_img=True,
        window_size=None,
        scale=None,
    ):
        """Take screenshot at current camera position.

        Parameters
        ----------
        filename : str | pathlib.Path | io.BytesIO, optional
            Location to write image to.  If ``None``, no image is written.

        transparent_background : bool, optional
            Whether to make the background transparent.  The default is
            looked up on the plotter's theme.

        return_img : bool, default: True
            If ``True``, a :class:`numpy.ndarray` of the image will be
            returned.

        window_size : sequence[int], optional
            Set the plotter's size to this ``(width, height)`` before
            taking the screenshot.

        scale : int, optional
            Set the factor to scale the window size to make a higher
            resolution image. If ``None`` this will use the ``image_scale``
            property on this plotter which defaults to one.

        Returns
        -------
        numpy.ndarray
            Array containing pixel RGB and alpha.  Sized:

            * [Window height x Window width x 3] if
              ``transparent_background`` is set to ``False``.
            * [Window height x Window width x 4] if
              ``transparent_background`` is set to ``True``.

        Examples
        --------
        >>> import pyvista
        >>> sphere = pyvista.Sphere()
        >>> plotter = pyvista.Plotter(off_screen=True)
        >>> actor = plotter.add_mesh(sphere)
        >>> plotter.screenshot('screenshot.png')  # doctest:+SKIP

        """
        with self.window_size_context(window_size):
            # configure image filter
            if transparent_background is None:
                transparent_background = self._theme.transparent_background
            self.image_transparent_background = transparent_background

            # This if statement allows you to save screenshots of closed plotters
            # This is needed for the sphinx-gallery to work
            if self.render_window is None:
                # If plotter has been closed...
                # check if last_image exists
                if self.last_image is not None:
                    # Save last image
                    if scale is not None:
                        warnings.warn(
                            'This plotter is closed and cannot be scaled. Using the last saved image. Try using the `image_scale` property directly.'
                        )
                    return self._save_image(self.last_image, filename, return_img)
                # Plotter hasn't been rendered or was improperly closed
                raise RuntimeError('This plotter is closed and unable to save a screenshot.')

            if self._first_time and not self.off_screen:
                raise RuntimeError(
                    "Nothing to screenshot - call .show first or use the off_screen argument"
                )

            # if off screen, show has not been called and we must render
            # before extracting an image
            if self._first_time:
                self._on_first_render_request()
                self.render()

            with self.image_scale_context(scale):
                self._make_render_window_current()
                return self._save_image(self.image, filename, return_img)

    @wraps(Renderers.set_background)
    def set_background(self, *args, **kwargs):  # numpydoc ignore=PR01,RT01
        """Wrap ``Renderers.set_background``."""
        self.renderers.set_background(*args, **kwargs)

    @wraps(Renderers.set_color_cycler)
    def set_color_cycler(self, *args, **kwargs):  # numpydoc ignore=PR01,RT01
        """Wrap ``Renderers.set_color_cycler``."""
        self.renderers.set_color_cycler(*args, **kwargs)

    def generate_orbital_path(self, factor=3.0, n_points=20, viewup=None, shift=0.0):
        """Generate an orbital path around the data scene.

        Parameters
        ----------
        factor : float, default: 3.0
            A scaling factor when building the orbital extent.

        n_points : int, default: 20
            Number of points on the orbital path.

        viewup : sequence[float], optional
            The normal to the orbital plane.

        shift : float, default: 0.0
            Shift the plane up/down from the center of the scene by
            this amount.

        Returns
        -------
        pyvista.PolyData
            PolyData containing the orbital path.

        Examples
        --------
        Generate an orbital path around a sphere.

        >>> import pyvista
        >>> plotter = pyvista.Plotter()
        >>> _ = plotter.add_mesh(pyvista.Sphere())
        >>> viewup = [0, 0, 1]
        >>> orbit = plotter.generate_orbital_path(
        ...     factor=2.0, n_points=50, shift=0.0, viewup=viewup
        ... )

        See :ref:`orbiting_example` for a full example using this method.

        """
        if viewup is None:
            viewup = self._theme.camera['viewup']
        center = np.array(self.center)
        bnds = np.array(self.bounds)
        radius = (bnds[1] - bnds[0]) * factor
        y = (bnds[3] - bnds[2]) * factor
        if y > radius:
            radius = y
        center += np.array(viewup) * shift
        return pyvista.Polygon(center=center, radius=radius, normal=viewup, n_sides=n_points)

    def fly_to(self, point):
        """Move the current camera's focal point to a position point.

        The movement is animated over the number of frames specified in
        NumberOfFlyFrames. The LOD desired frame rate is used.

        Parameters
        ----------
        point : sequence[float]
            Point to fly to in the form of ``(x, y, z)``.

        """
        self.iren.fly_to(self.renderer, point)

    def orbit_on_path(
        self,
        path=None,
        focus=None,
        step=0.5,
        viewup=None,
        write_frames=False,
        threaded=False,
        progress_bar=False,
    ):
        """Orbit on the given path focusing on the focus point.

        Parameters
        ----------
        path : pyvista.PolyData
            Path of orbital points. The order in the points is the order of
            travel.

        focus : sequence[float], optional
            The point of focus the camera. For example ``(0.0, 0.0, 0.0)``.

        step : float, default: 0.5
            The timestep between flying to each camera position. Ignored when
            ``plotter.off_screen = True``.

        viewup : sequence[float], optional
            The normal to the orbital plane.

        write_frames : bool, default: False
            Assume a file is open and write a frame on each camera
            view during the orbit.

        threaded : bool, default: False
            Run this as a background thread.  Generally used within a
            GUI (i.e. PyQt).

        progress_bar : bool, default: False
            Show the progress bar when proceeding through the path.
            This can be helpful to show progress when generating
            movies with ``off_screen=True``.

        Examples
        --------
        Plot an orbit around the earth.  Save the gif as a temporary file.

        >>> import os
        >>> from tempfile import mkdtemp
        >>> import pyvista
        >>> from pyvista import examples
        >>> mesh = examples.load_globe()
        >>> texture = examples.load_globe_texture()
        >>> filename = os.path.join(mkdtemp(), 'orbit.gif')
        >>> plotter = pyvista.Plotter(window_size=[300, 300])
        >>> _ = plotter.add_mesh(
        ...     mesh, texture=texture, smooth_shading=True
        ... )
        >>> plotter.open_gif(filename)
        >>> viewup = [0, 0, 1]
        >>> orbit = plotter.generate_orbital_path(
        ...     factor=2.0, n_points=24, shift=0.0, viewup=viewup
        ... )
        >>> plotter.orbit_on_path(
        ...     orbit, write_frames=True, viewup=viewup, step=0.02
        ... )

        See :ref:`orbiting_example` for a full example using this method.

        """
        if focus is None:
            focus = self.center
        if viewup is None:
            viewup = self._theme.camera['viewup']
        if path is None:
            path = self.generate_orbital_path(viewup=viewup)
        if not is_pyvista_dataset(path):
            path = pyvista.PolyData(path)
        points = path.points

        # Make sure the whole scene is visible
        self.camera.thickness = path.length

        if progress_bar:
            try:
                from tqdm import tqdm
            except ImportError:  # pragma: no cover
                raise ImportError("Please install `tqdm` to use ``progress_bar=True``")

        def orbit():
            """Define the internal thread for running the orbit."""
            if progress_bar:
                points_seq = tqdm(points)
            else:
                points_seq = points

            for point in points_seq:
                tstart = time.time()  # include the render time in the step time
                self.set_position(point, render=False)
                self.set_focus(focus, render=False)
                self.set_viewup(viewup, render=False)
                self.renderer.ResetCameraClippingRange()
                if write_frames:
                    self.write_frame()
                else:
                    self.render()
                sleep_time = step - (time.time() - tstart)
                if sleep_time > 0 and not self.off_screen:
                    time.sleep(sleep_time)
            if write_frames:
                self.mwriter.close()

        if threaded:
            thread = Thread(target=orbit)
            thread.start()
        else:
            orbit()

    def export_vtkjs(self, *args, **kwargs):
        """Export the current rendering scene as a VTKjs scene.

        .. deprecated:: 0.40.0
            This export routine has been broken for some time and has
            been completely removed in version 0.40.0.  Use :func:`pyvista.Plotter.export_vtksz` instead.

        Parameters
        ----------
        *args : tuple
            Positional arguments.

        **kwargs : dict, optional
            Keyword arguments.

        """
        from pyvista.core.errors import DeprecationError

        raise DeprecationError('export_vtkjs is deprecated. Use export_vtksz instead.')

    def export_obj(self, filename):
        """Export scene to OBJ format.

        Parameters
        ----------
        filename : str
            Filename to export the scene to.  Must end in ``'.obj'``.

        Examples
        --------
        Export the scene to "scene.obj"

        >>> import pyvista as pv
        >>> pl = pv.Plotter()
        >>> _ = pl.add_mesh(pv.Sphere())
        >>> pl.export_obj('scene.obj')  # doctest:+SKIP

        """
        from vtkmodules.vtkIOExport import vtkOBJExporter

        if self.render_window is None:
            raise RuntimeError("This plotter must still have a render window open.")
        if isinstance(pyvista.FIGURE_PATH, str) and not os.path.isabs(filename):
            filename = os.path.join(pyvista.FIGURE_PATH, filename)
        else:
            filename = os.path.abspath(os.path.expanduser(filename))

        if not filename.endswith('.obj'):
            raise ValueError('`filename` must end with ".obj"')

        exporter = vtkOBJExporter()
        # remove the extension as VTK always adds it in
        exporter.SetFilePrefix(filename[:-4])
        exporter.SetRenderWindow(self.render_window)
        exporter.Write()

    @property
    def _datasets(self):
        """Return a list of all datasets associated with this plotter."""
        datasets = []
        for renderer in self.renderers:
            for actor in renderer.actors.values():
                mapper = actor.GetMapper()

                # ignore any mappers whose inputs are not datasets
                if hasattr(mapper, 'GetInputAsDataSet'):
                    datasets.append(wrap(mapper.GetInputAsDataSet()))

        return datasets

    def __del__(self):
        """Delete the plotter."""
        # We have to check here if the plotter was only partially initialized
        if self._initialized:
            if not self._closed:
                self.close()
        self.deep_clean()
        if self._initialized:
            del self.renderers

    def add_background_image(self, image_path, scale=1.0, auto_resize=True, as_global=True):
        """Add a background image to a plot.

        Parameters
        ----------
        image_path : str
            Path to an image file.

        scale : float, default: 1.0
            Scale the image larger or smaller relative to the size of
            the window.  For example, a scale size of 2 will make the
            largest dimension of the image twice as large as the
            largest dimension of the render window.

        auto_resize : bool, default: True
            Resize the background when the render window changes size.

        as_global : bool, default: True
            When multiple render windows are present, setting
            ``as_global=False`` will cause the background to only
            appear in one window.

        Examples
        --------
        >>> import pyvista
        >>> from pyvista import examples
        >>> plotter = pyvista.Plotter()
        >>> actor = plotter.add_mesh(pyvista.Sphere())
        >>> plotter.add_background_image(examples.mapfile)
        >>> plotter.show()

        """
        if self.renderers.has_active_background_renderer:
            raise RuntimeError(
                'A background image already exists.  '
                'Remove it with ``remove_background_image`` '
                'before adding one'
            )

        # Need to change the number of layers to support an additional
        # background layer
        if not self._has_background_layer:
            self.render_window.SetNumberOfLayers(3)
        renderer = self.renderers.add_background_renderer(image_path, scale, as_global)
        self.render_window.AddRenderer(renderer)

        # set up autoscaling of the image
        if auto_resize:  # pragma: no cover
            self.iren.add_observer('ModifiedEvent', renderer.resize)

    @wraps(Renderers.remove_background_image)
    def remove_background_image(self):  # numpydoc ignore=PR01,RT01
        """Wrap ``Renderers.remove_background_image``."""
        self.renderers.remove_background_image()

        # return the active renderer to the top, otherwise flat background
        # will not be rendered
        self.renderer.layer = 0

    def _on_first_render_request(self):
        """Once an image or render is officially requested, run this routine.

        For example on the show call or any screenshot producing code.
        """
        # reset unless camera for the first render unless camera is set
        if self._first_time:
            for renderer in self.renderers:
                if not renderer.camera.is_set:
                    renderer.camera_position = renderer.get_default_cam_pos()
                    renderer.ResetCamera()
            self._first_time = False

    def reset_camera_clipping_range(self):
        """Reset camera clipping planes."""
        self.renderer.ResetCameraClippingRange()

    def add_light(self, light, only_active=False):
        """Add a Light to the scene.

        Parameters
        ----------
        light : Light or vtkLight
            The light to be added.

        only_active : bool, default: False
            If ``True``, only add the light to the active
            renderer. The default is that every renderer adds the
            light. To add the light to an arbitrary renderer, see
            :func:`pyvista.Renderer.add_light`.

        Examples
        --------
        Create a plotter that we initialize with no lights, and add a
        cube and a single headlight to it.

        >>> import pyvista as pv
        >>> plotter = pv.Plotter(lighting='none')
        >>> _ = plotter.add_mesh(pv.Cube())
        >>> light = pv.Light(color='cyan', light_type='headlight')
        >>> plotter.add_light(light)
        >>> plotter.show()

        """
        renderers = [self.renderer] if only_active else self.renderers
        for renderer in renderers:
            renderer.add_light(light)

    def remove_all_lights(self, only_active=False):
        """Remove all lights from the scene.

        Parameters
        ----------
        only_active : bool, default: False
            If ``True``, only remove lights from the active
            renderer. The default is that lights are stripped from
            every renderer.

        Examples
        --------
        Create a plotter and remove all lights after initialization.
        Note how the mesh rendered is completely flat

        >>> import pyvista as pv
        >>> plotter = pv.Plotter()
        >>> plotter.remove_all_lights()
        >>> plotter.renderer.lights
        []
        >>> _ = plotter.add_mesh(pv.Sphere(), show_edges=True)
        >>> plotter.show()

        Note how this differs from a plot with default lighting

        >>> pv.Sphere().plot(show_edges=True, lighting=True)

        """
        renderers = [self.renderer] if only_active else self.renderers
        for renderer in renderers:
            renderer.remove_all_lights()

    def where_is(self, name):
        """Return the subplot coordinates of a given actor.

        Parameters
        ----------
        name : str
            Actor's name.

        Returns
        -------
        list(tuple(int))
            A list with the subplot coordinates of the actor.

        Examples
        --------
        >>> import pyvista as pv
        >>> plotter = pv.Plotter(shape=(2, 2))
        >>> plotter.subplot(0, 0)
        >>> _ = plotter.add_mesh(pv.Box(), name='box')
        >>> plotter.subplot(0, 1)
        >>> _ = plotter.add_mesh(pv.Sphere(), name='sphere')
        >>> plotter.subplot(1, 0)
        >>> _ = plotter.add_mesh(pv.Box(), name='box')
        >>> plotter.subplot(1, 1)
        >>> _ = plotter.add_mesh(pv.Cone(), name='cone')
        >>> plotter.where_is('box')
        [(0, 0), (1, 0)]

        >>> plotter.show()
        """
        places = []
        for index in range(len(self.renderers)):
            if name in self.renderers[index]._actors:
                places.append(tuple(self.renderers.index_to_loc(index)))
        return places


class Plotter(BasePlotter):
    """Plotting object to display vtk meshes or numpy arrays.

    Parameters
    ----------
    off_screen : bool, optional
        Renders off screen when ``True``.  Useful for automated
        screenshots.

    notebook : bool, optional
        When ``True``, the resulting plot is placed inline a jupyter
        notebook.  Assumes a jupyter console is active.  Automatically
        enables ``off_screen``.

    shape : sequence[int], optional
        Number of sub-render windows inside of the main window.
        Specify two across with ``shape=(2, 1)`` and a two by two grid
        with ``shape=(2, 2)``.  By default there is only one render
        window.  Can also accept a string descriptor as shape. E.g.:

        * ``shape="3|1"`` means 3 plots on the left and 1 on the right,
        * ``shape="4/2"`` means 4 plots on top and 2 at the bottom.

    border : bool, optional
        Draw a border around each render window.

    border_color : ColorLike, default: "k"
        Either a string, rgb list, or hex color string.  For example:

            * ``color='white'``
            * ``color='w'``
            * ``color=[1.0, 1.0, 1.0]``
            * ``color='#FFFFFF'``

    window_size : sequence[int], optional
        Window size in pixels.  Defaults to ``[1024, 768]``, unless
        set differently in the relevant theme's ``window_size``
        property.

    multi_samples : int, optional
        The number of multi-samples used to mitigate aliasing. 4 is a
        good default but 8 will have better results with a potential
        impact on performance.

    line_smoothing : bool, default: False
        If ``True``, enable line smoothing.

    polygon_smoothing : bool, default: False
        If ``True``, enable polygon smoothing.

    lighting : str, default: 'light kit"
        Lighting to set up for the plotter. Accepted options:

        * ``'light kit'``: a vtk Light Kit composed of 5 lights.
        * ``'three lights'``: illumination using 3 lights.
        * ``'none'``: no light sources at instantiation.

        The default is a ``'light kit'`` (to be precise, 5 separate
        lights that act like a Light Kit).

    theme : pyvista.plotting.themes.Theme, optional
        Plot-specific theme.

    image_scale : int, optional
        Scale factor when saving screenshots. Image sizes will be
        the ``window_size`` multiplied by this scale factor.

    Examples
    --------
    >>> import pyvista as pv
    >>> mesh = pv.Cube()
    >>> another_mesh = pv.Sphere()
    >>> pl = pv.Plotter()
    >>> actor = pl.add_mesh(
    ...     mesh, color='red', style='wireframe', line_width=4
    ... )
    >>> actor = pl.add_mesh(another_mesh, color='blue')
    >>> pl.show()

    """

    last_update_time = 0.0

    def __init__(
        self,
        off_screen=None,
        notebook=None,
        shape=(1, 1),
        groups=None,
        row_weights=None,
        col_weights=None,
        border=None,
        border_color='k',
        border_width=2.0,
        window_size=None,
        multi_samples=None,
        line_smoothing=False,
        point_smoothing=False,
        polygon_smoothing=False,
        splitting_position=None,
        title=None,
        lighting='light kit',
        theme=None,
        image_scale=None,
    ):
        """Initialize a vtk plotting object."""
        super().__init__(
            shape=shape,
            border=border,
            border_color=border_color,
            border_width=border_width,
            groups=groups,
            row_weights=row_weights,
            col_weights=col_weights,
            splitting_position=splitting_position,
            title=title,
            lighting=lighting,
            theme=theme,
            image_scale=image_scale,
        )
        # reset partial initialization flag
        self._initialized = False

        log.debug('Plotter init start')

        # check if a plotting backend is enabled
        _warn_xserver()

        if off_screen is None:
            off_screen = pyvista.OFF_SCREEN

        if notebook is None:
            if self._theme.notebook is not None:
                notebook = self._theme.notebook
            else:
                notebook = scooby.in_ipykernel()

        self.notebook = notebook
        if self.notebook:
            off_screen = True
        self.off_screen = off_screen

        # initialize render window
        self.ren_win = _vtk.vtkRenderWindow()
        self.render_window.SetMultiSamples(0)
        self.render_window.SetBorders(True)
        if line_smoothing:
            self.render_window.LineSmoothingOn()
        if point_smoothing:
            self.render_window.PointSmoothingOn()
        if polygon_smoothing:
            self.render_window.PolygonSmoothingOn()

        for renderer in self.renderers:
            self.render_window.AddRenderer(renderer)

        # Add the shadow renderer to allow us to capture interactions within
        # a given viewport
        # https://vtk.org/pipermail/vtkusers/2018-June/102030.html
        number_or_layers = self.render_window.GetNumberOfLayers()
        current_layer = self.renderer.GetLayer()
        self.render_window.SetNumberOfLayers(number_or_layers + 1)
        self.render_window.AddRenderer(self.renderers.shadow_renderer)
        self.renderers.shadow_renderer.SetLayer(current_layer + 1)
        self.renderers.shadow_renderer.SetInteractive(False)  # never needs to capture

        if self.off_screen:
            self.render_window.SetOffScreenRendering(1)
            # vtkGenericRenderWindowInteractor has no event loop and
            # allows the display client to close on Linux when
            # off_screen.  We still want an interactor for off screen
            # plotting since there are some widgets (like the axes
            # widget) that need an interactor
            interactor = _vtk.vtkGenericRenderWindowInteractor()
        else:
            interactor = None

        # Add ren win and interactor
        self.iren = RenderWindowInteractor(self, light_follow_camera=False, interactor=interactor)
        self.iren.set_render_window(self.render_window)
        self.reset_key_events()
        self.enable_trackball_style()  # internally calls update_style()
        self.iren.add_observer("KeyPressEvent", self.key_press_event)

        # Set camera widget based on theme. This requires that an
        # interactor be present.
        if self.theme._enable_camera_orientation_widget:
            self.add_camera_orientation_widget()

        # Set background
        self.set_background(self._theme.background)

        # Set window size
        self._window_size_unset = False
        if window_size is None:
            self.window_size = self._theme.window_size
            if self.window_size == pyvista.plotting.themes.Theme().window_size:
                self._window_size_unset = True
        else:
            self.window_size = window_size

        if self._theme.depth_peeling.enabled:
            if self.enable_depth_peeling():
                for renderer in self.renderers:
                    renderer.enable_depth_peeling()

        # set anti_aliasing based on theme
        if self.theme.anti_aliasing:
            self.enable_anti_aliasing(self.theme.anti_aliasing)

        # some cleanup only necessary for fully initialized plotters
        self._initialized = True
        log.debug('Plotter init stop')

    def show(
        self,
        title=None,
        window_size=None,
        interactive=True,
        auto_close=None,
        interactive_update=False,
        full_screen=None,
        screenshot=False,
        return_img=False,
        cpos=None,
        jupyter_backend=None,
        return_viewer=False,
        return_cpos=None,
        before_close_callback=None,
        **kwargs,
    ):
        """Display the plotting window.

        Parameters
        ----------
        title : str, optional
            Title of plotting window.  Defaults to
            :attr:`pyvista.global_theme.title <pyvista.plotting.themes.Theme.title>`.

        window_size : list, optional
            Window size in pixels.  Defaults to
            :attr:`pyvista.global_theme.window_size <pyvista.plotting.themes.Theme.window_size>`.

        interactive : bool, optional
            Enabled by default.  Allows user to pan and move figure.
            Defaults to
            :attr:`pyvista.global_theme.interactive <pyvista.plotting.themes.Theme.interactive>`.

        auto_close : bool, optional
            Exits plotting session when user closes the window when
            interactive is ``True``.  Defaults to
            :attr:`pyvista.global_theme.auto_close <pyvista.plotting.themes.Theme.auto_close>`.

        interactive_update : bool, default: False
            Allows user to non-blocking draw, user should call
            :func:`Plotter.update` in each iteration.

        full_screen : bool, optional
            Opens window in full screen.  When enabled, ignores
            ``window_size``.  Defaults to
            :attr:`pyvista.global_theme.full_screen <pyvista.plotting.themes.Theme.full_screen>`.

        screenshot : str | pathlib.Path | io.BytesIO | bool, default: False
            Take a screenshot of the initial state of the plot.  If a string,
            it specifies the path to which the screenshot is saved. If
            ``True``, the screenshot is returned as an array. For interactive
            screenshots it's recommended to first call ``show()`` with
            ``auto_close=False`` to set the scene, then save the screenshot in
            a separate call to ``show()`` or :func:`Plotter.screenshot`.
            See also the ``before_close_callback`` parameter for an
            alternative.

        return_img : bool, default: False
            Returns a numpy array representing the last image along
            with the camera position.

        cpos : sequence[sequence[float]], optional
            The camera position.  You can also set this with
            :attr:`Plotter.camera_position`.

        jupyter_backend : str, optional
            Jupyter notebook plotting backend to use.  One of the
            following:

            * ``'none'`` : Do not display in the notebook.
            * ``'static'`` : Display a static figure.
            * ``'trame'`` : Display a dynamic figure with Trame.

            This can also be set globally with
            :func:`pyvista.set_jupyter_backend`.

            A dictionary ``jupyter_kwargs`` can also be passed to further
            configure how the backend displays.

        return_viewer : bool, default: False
            Return the jupyterlab viewer, scene, or display object when
            plotting with Jupyter notebook. When ``False`` and within a Jupyter
            environment, the scene will be immediately shown within the
            notebook. Set this to ``True`` to return the scene instead.

        return_cpos : bool, optional
            Return the last camera position from the render window
            when enabled.  Default based on theme setting.  See
            :attr:`pyvista.plotting.themes.Theme.return_cpos`.

        before_close_callback : Callable, optional
            Callback that is called before the plotter is closed.
            The function takes a single parameter, which is the plotter object
            before it closes. An example of use is to capture a screenshot after
            interaction::

                def fun(plotter):
                    plotter.screenshot('file.png')

        **kwargs : dict, optional
            Developer keyword arguments.

        Returns
        -------
        cpos : list
            List of camera position, focal point, and view up.
            Returned only when ``return_cpos=True`` or set in the
            default global or plot theme.

        image : np.ndarray
            Numpy array of the last image when either ``return_img=True``
            or ``screenshot=True`` is set. Optionally contains alpha
            values. Sized:

            * [Window height x Window width x 3] if the theme sets
              ``transparent_background=False``.
            * [Window height x Window width x 4] if the theme sets
              ``transparent_background=True``.

        widget : ipywidgets.Widget
            IPython widget when ``return_viewer=True``.

        Notes
        -----
        Please use the ``q``-key to close the plotter as some
        operating systems (namely Windows) will experience issues
        saving a screenshot if the exit button in the GUI is pressed.

        Examples
        --------
        Simply show the plot of a mesh.

        >>> import pyvista as pv
        >>> pl = pv.Plotter()
        >>> _ = pl.add_mesh(pv.Cube())
        >>> pl.show()

        Take a screenshot interactively.  Screenshot will be of the
        first image shown, so use the first call with
        ``auto_close=False`` to set the scene before taking the
        screenshot.

        >>> pl = pv.Plotter()
        >>> _ = pl.add_mesh(pv.Cube())
        >>> pl.show(auto_close=False)  # doctest:+SKIP
        >>> pl.show(screenshot='my_image.png')  # doctest:+SKIP

        Obtain the camera position when using ``show``.

        >>> pl = pv.Plotter()
        >>> _ = pl.add_mesh(pv.Sphere())
        >>> pl.show(return_cpos=True)  # doctest:+SKIP
        [(2.223005211686484, -0.3126909484828709, 2.4686209867735065),
        (0.0, 0.0, 0.0),
        (-0.6839951597283509, -0.47207319712073137, 0.5561452310578585)]

        """
        jupyter_kwargs = kwargs.pop('jupyter_kwargs', {})
        assert_empty_kwargs(**kwargs)

        if before_close_callback is None:
            before_close_callback = pyvista.global_theme._before_close_callback
        self._before_close_callback = before_close_callback

        if interactive_update and auto_close is None:
            auto_close = False
        elif interactive_update and auto_close:
            warnings.warn(
                textwrap.dedent(
                    """
                    The plotter will close immediately automatically since ``auto_close=True``.
                    Either, do not specify ``auto_close``, or set it to ``False`` if you want to
                    interact with the plotter interactively.
                    """
                ).strip()
            )
        elif auto_close is None:
            auto_close = self._theme.auto_close

        if self.render_window is None:
            raise RuntimeError("This plotter has been closed and cannot be shown.")

        if full_screen is None:
            full_screen = self._theme.full_screen

        if full_screen:
            self.render_window.SetFullScreen(True)
            self.render_window.BordersOn()  # super buggy when disabled
        else:
            if window_size is None:
                window_size = self.window_size
            else:
                self._window_size_unset = False
            self.render_window.SetSize(window_size[0], window_size[1])

        # reset unless camera for the first render unless camera is set
        self.camera_position = cpos
        self._on_first_render_request()

        # handle plotter notebook
        if jupyter_backend and not self.notebook:
            warnings.warn(
                'Not within a jupyter notebook environment.\nIgnoring ``jupyter_backend``.'
            )

        jupyter_disp = None
        if self.notebook:
            from pyvista.jupyter.notebook import handle_plotter

            if jupyter_backend is None:
                jupyter_backend = self._theme.jupyter_backend

            if jupyter_backend.lower() != 'none':
                jupyter_disp = handle_plotter(self, backend=jupyter_backend, **jupyter_kwargs)

        self.render()

        # initial double render needed for certain passes when offscreen
        if self.off_screen and 'vtkDepthOfFieldPass' in self.renderer._render_passes._passes:
            self.render()

        # This has to be after the first render for some reason
        if title is None:
            title = self.title
        if title:
            self.render_window.SetWindowName(title)
            self.title = title

        # Keep track of image for sphinx-gallery
        if pyvista.BUILDING_GALLERY:
            # always save screenshots for sphinx_gallery
            self.last_image = self.screenshot(screenshot, return_img=True)
            self.last_image_depth = self.get_image_depth()
            try:
                self.last_vtksz = self.export_vtksz(filename=None)
            except ImportError:
                pass

        # See: https://github.com/pyvista/pyvista/issues/186#issuecomment-550993270
        if interactive and not self.off_screen:
            try:  # interrupts will be caught here
                log.debug('Starting iren')
                self.iren.update_style()
                if not interactive_update:
                    # Resolves #1260
                    if os.name == 'nt':  # pragma: no cover
                        self.iren.process_events()
                    self.iren.start()

                if pyvista.vtk_version_info < (9, 2, 3):  # pragma: no cover
                    self.iren.initialize()

            except KeyboardInterrupt:
                log.debug('KeyboardInterrupt')
                self.close()
                raise KeyboardInterrupt
        # In the event that the user hits the exit-button on the GUI  (on
        # Windows OS) then it must be finalized and deleted as accessing it
        # will kill the kernel.
        # Here we check for that and clean it up before moving on to any of
        # the closing routines that might try to still access that
        # render window.
        # Ignore if using a Jupyter display
        _is_current = self.render_window.IsCurrent()
        if jupyter_disp is None and not _is_current:
            self._clear_ren_win()  # The ren_win is deleted
            # proper screenshots cannot be saved if this happens
            if not auto_close:
                warnings.warn(
                    "`auto_close` ignored: by clicking the exit button, "
                    "you have destroyed the render window and we have to "
                    "close it out."
                )
            self.close()
            if screenshot:
                warnings.warn(
                    "A screenshot is unable to be taken as the render window is not current or rendering is suppressed."
                )
        if _is_current:
            self.last_image = self.screenshot(screenshot, return_img=True)
            self.last_image_depth = self.get_image_depth()
        # NOTE: after this point, nothing from the render window can be accessed
        #       as if a user pressed the close button, then it destroys the
        #       the render view and a stream of errors will kill the Python
        #       kernel if code here tries to access that renderer.
        #       See issues #135 and #186 for insight before editing the
        #       remainder of this function.

        # Close the render window if requested
        if jupyter_disp is None and auto_close:
            # Plotters are never auto-closed in Jupyter
            self.close()

        if jupyter_disp is not None and not return_viewer:
            # Default behaviour is to display the Jupyter viewer
            try:
                from IPython import display
            except ImportError:  # pragma: no cover
                raise ImportError('Install IPython to display an image in a notebook')
            display.display(jupyter_disp)

        # Three possible return values: (cpos, image, widget)
        return_values = tuple(
            val
            for val in (
                self.camera_position if return_cpos else None,
                self.last_image if return_img or screenshot is True else None,
                jupyter_disp if return_viewer else None,
            )
            if val is not None
        )
        if len(return_values) == 1:
            return return_values[0]
        return return_values or None

    def add_title(self, title, font_size=18, color=None, font=None, shadow=False):
        """Add text to the top center of the plot.

        This is merely a convenience method that calls ``add_text``
        with ``position='upper_edge'``.

        Parameters
        ----------
        title : str
            The text to add the rendering.

        font_size : float, default: 18
            Sets the size of the title font.

        color : ColorLike, optional
            Either a string, rgb list, or hex color string.  Defaults
            to white or the value of the global theme if set.  For
            example:

            * ``color='white'``
            * ``color='w'``
            * ``color=[1.0, 1.0, 1.0]``
            * ``color='#FFFFFF'``

        font : str, optional
            Font name may be ``'courier'``, ``'times'``, or ``'arial'``.

        shadow : bool, default: False
            Adds a black shadow to the text.

        Returns
        -------
        vtk.vtkTextActor
            Text actor added to plot.

        Examples
        --------
        >>> import pyvista
        >>> pl = pyvista.Plotter()
        >>> pl.background_color = 'grey'
        >>> actor = pl.add_title(
        ...     'Plot Title', font='courier', color='k', font_size=40
        ... )
        >>> pl.show()

        """
        # add additional spacing from the top of the figure by default
        title = '\n' + title
        return self.add_text(
            title,
            position='upper_edge',
            font_size=font_size,
            color=color,
            font=font,
            shadow=shadow,
            name='title',
            viewport=False,
        )

    def add_cursor(
        self,
        bounds=(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0),
        focal_point=(0.0, 0.0, 0.0),
        color=None,
    ):
        """Add a cursor of a PyVista or VTK dataset to the scene.

        Parameters
        ----------
        bounds : sequence[float], default: (-1.0, 1.0, -1.0, 1.0, -1.0, 1.0)
            Specify the bounds in the format of:

            - ``(xmin, xmax, ymin, ymax, zmin, zmax)``

        focal_point : sequence[float], default: (0.0, 0.0, 0.0)
            The focal point of the cursor.

        color : ColorLike, optional
            Either a string, RGB sequence, or hex color string.  For one
            of the following.

            * ``color='white'``
            * ``color='w'``
            * ``color=[1.0, 1.0, 1.0]``
            * ``color='#FFFFFF'``

        Returns
        -------
        vtk.vtkActor
            VTK actor of the 2D cursor.

        Examples
        --------
        >>> import pyvista
        >>> sphere = pyvista.Sphere()
        >>> plotter = pyvista.Plotter()
        >>> _ = plotter.add_mesh(sphere)
        >>> _ = plotter.add_cursor()
        >>> plotter.show()

        """
        alg = _vtk.vtkCursor3D()
        alg.SetModelBounds(bounds)
        alg.SetFocalPoint(focal_point)
        alg.AllOn()
        mapper = DataSetMapper(theme=self._theme)
        mapper.SetInputConnection(alg.GetOutputPort())
        actor, prop = self.add_actor(mapper)
        prop.SetColor(Color(color).float_rgb)

        return actor

    @property
    def meshes(self):  # numpydoc ignore=RT01
        """Return plotter meshes.

        Returns
        -------
        List[Union[pyvista.DataSet, PyVista.MultiBlock]]
            List of mesh objects such as pv.PolyData, pv.UnstructuredGrid, etc.
        """
        meshes = []
        for actor in self.actors.values():
            if hasattr(actor, 'mapper'):
                meshes.append(actor.mapper.dataset)

        return meshes


# Tracks created plotters.  This is the end of the module as we need to
# define ``BasePlotter`` before including it in the type definition.
#
# When pyvista.BUILDING_GALLERY = False, the objects will be ProxyType, and
# when True, BasePlotter.
_ALL_PLOTTERS: Dict[str, BasePlotter] = {}


def _kill_display(disp_id):  # pragma: no cover
    """Forcibly close the display on Linux.

    See: https://gitlab.kitware.com/vtk/vtk/-/issues/17917#note_783584

    And more details into why...
    https://stackoverflow.com/questions/64811503

    Notes
    -----
    This is to be used experimentally and is known to cause issues
    on `pyvistaqt`

    """
    if platform.system() != 'Linux':
        raise OSError('This method only works on Linux')

    if disp_id:
        cdisp_id = int(disp_id[1:].split('_')[0], 16)

        # this is unsafe as events might be queued, but sometimes the
        # window fails to close if we don't just close it
        Thread(target=X11.XCloseDisplay, args=(cdisp_id,)).start()


# pyvista/plotting/prop3d.py

"""Prop3D module."""
from typing import Tuple

from pyvista.core._typing_core import BoundsLike, Vector

from . import _vtk


class Prop3D(_vtk.vtkProp3D):
    """Prop3D wrapper for vtkProp3D.

    Used to represent an entity in a rendering scene. It handles functions
    related to the position, orientation and scaling. Used as parent class
    in Actor and Volume class.
    """

    def __init__(self):
        """Initialize Prop3D."""
        super().__init__()

    @property
    def scale(self) -> Tuple[float, float, float]:  # numpydoc ignore=RT01
        """Return or set entity scale.

        Examples
        --------
        Create an actor using the :class:`pyvista.Plotter` and then change the
        scale of the actor.

        >>> import pyvista as pv
        >>> pl = pv.Plotter()
        >>> actor = pl.add_mesh(pv.Sphere())
        >>> actor.scale = (2.0, 2.0, 2.0)
        >>> actor.scale
        (2.0, 2.0, 2.0)

        """
        return self.GetScale()

    @scale.setter
    def scale(self, value: Vector):  # numpydoc ignore=GL08
        return self.SetScale(value)

    @property
    def position(self) -> Tuple[float, float, float]:  # numpydoc ignore=RT01
        """Return or set the entity position.

        Examples
        --------
        Change the position of an actor. Note how this does not change the
        position of the underlying dataset, just the relative location of the
        actor in the :class:`pyvista.Plotter`.

        >>> import pyvista as pv
        >>> mesh = pv.Sphere()
        >>> pl = pv.Plotter()
        >>> _ = pl.add_mesh(mesh, color='b')
        >>> actor = pl.add_mesh(mesh, color='r')
        >>> actor.position = (0, 0, 1)  # shifts the red sphere up
        >>> pl.show()

        """
        return self.GetPosition()

    @position.setter
    def position(self, value: Vector):  # numpydoc ignore=GL08
        self.SetPosition(value)

    def rotate_x(self, angle: float):
        """Rotate the entity about the x axis.

        Parameters
        ----------
        angle : float
            Angle to rotate the entity about the x axis in degrees.

        Examples
        --------
        Rotate the actor about the x axis 45 degrees. Note how this does not
        change the location of the underlying dataset.

        >>> import pyvista as pv
        >>> mesh = pv.Cube()
        >>> pl = pv.Plotter()
        >>> _ = pl.add_mesh(mesh, color='b')
        >>> actor = pl.add_mesh(
        ...     mesh,
        ...     color='r',
        ...     style='wireframe',
        ...     line_width=5,
        ...     lighting=False,
        ... )
        >>> actor.rotate_x(45)
        >>> pl.show_axes()
        >>> pl.show()

        """
        self.RotateX(angle)

    def rotate_y(self, angle: float):
        """Rotate the entity about the y axis.

        Parameters
        ----------
        angle : float
            Angle to rotate the entity about the y axis in degrees.

        Examples
        --------
        Rotate the actor about the y axis 45 degrees. Note how this does not
        change the location of the underlying dataset.

        >>> import pyvista as pv
        >>> mesh = pv.Cube()
        >>> pl = pv.Plotter()
        >>> _ = pl.add_mesh(mesh, color='b')
        >>> actor = pl.add_mesh(
        ...     mesh,
        ...     color='r',
        ...     style='wireframe',
        ...     line_width=5,
        ...     lighting=False,
        ... )
        >>> actor.rotate_y(45)
        >>> pl.show_axes()
        >>> pl.show()

        """
        self.RotateY(angle)

    def rotate_z(self, angle: float):
        """Rotate the entity about the z axis.

        Parameters
        ----------
        angle : float
            Angle to rotate the entity about the z axis in degrees.

        Examples
        --------
        Rotate the actor about the Z axis 45 degrees. Note how this does not
        change the location of the underlying dataset.

        >>> import pyvista as pv
        >>> mesh = pv.Cube()
        >>> pl = pv.Plotter()
        >>> _ = pl.add_mesh(mesh, color='b')
        >>> actor = pl.add_mesh(
        ...     mesh,
        ...     color='r',
        ...     style='wireframe',
        ...     line_width=5,
        ...     lighting=False,
        ... )
        >>> actor.rotate_z(45)
        >>> pl.show_axes()
        >>> pl.show()

        """
        self.RotateZ(angle)

    @property
    def orientation(self) -> tuple:  # numpydoc ignore=RT01
        """Return or set the entity orientation.

        Orientation is defined as the rotation from the global axes in degrees
        about the actor's x, y, and z axes.

        Examples
        --------
        Reorient just the actor and plot it. Note how the actor is rotated
        about its own axes as defined by its position.

        >>> import pyvista as pv
        >>> mesh = pv.Cube()
        >>> pl = pv.Plotter()
        >>> _ = pl.add_mesh(mesh, color='b')
        >>> actor = pl.add_mesh(
        ...     mesh,
        ...     color='r',
        ...     style='wireframe',
        ...     line_width=5,
        ...     lighting=False,
        ... )
        >>> actor.position = (0, 0, 1)
        >>> actor.orientation = (45, 0, 0)
        >>> pl.show_axes()
        >>> pl.show()

        Show that the orientation changes with rotation.

        >>> import pyvista as pv
        >>> mesh = pv.Cube()
        >>> pl = pv.Plotter()
        >>> actor = pl.add_mesh(mesh)
        >>> actor.rotate_x(90)
        >>> actor.orientation  # doctest:+SKIP
        (90, 0, 0)

        Set the orientation directly.

        >>> actor.orientation = (0, 45, 45)
        >>> actor.orientation  # doctest:+SKIP
        (0, 45, 45)

        """
        return self.GetOrientation()

    @orientation.setter
    def orientation(self, value: tuple):  # numpydoc ignore=GL08
        self.SetOrientation(value)

    @property
    def bounds(self) -> BoundsLike:  # numpydoc ignore=RT01
        """Return the bounds of the entity.

        Bounds are ``(-X, +X, -Y, +Y, -Z, +Z)``

        Examples
        --------
        >>> import pyvista as pv
        >>> pl = pv.Plotter()
        >>> mesh = pv.Cube(x_length=0.1, y_length=0.2, z_length=0.3)
        >>> actor = pl.add_mesh(mesh)
        >>> actor.bounds
        (-0.05, 0.05, -0.1, 0.1, -0.15, 0.15)

        """
        return self.GetBounds()

    @property
    def center(self) -> tuple:  # numpydoc ignore=RT01
        """Return the center of the entity.

        Examples
        --------
        >>> import pyvista as pv
        >>> pl = pv.Plotter()
        >>> actor = pl.add_mesh(pv.Sphere(center=(0.5, 0.5, 1)))
        >>> actor.center  # doctest:+SKIP
        (0.5, 0.5, 1)
        """
        return self.GetCenter()


# pyvista/plotting/render_passes.py

"""Render passes module for PyVista."""
import weakref

from . import _vtk

# The order of both the pre and post-passes matters.
PRE_PASS = [
    'vtkEDLShading',
]

POST_PASS = [
    'vtkDepthOfFieldPass',
    'vtkGaussianBlurPass',
    'vtkOpenGLFXAAPass',
    'vtkSSAOPass',
    'vtkSSAAPass',  # should be last
]


class RenderPasses:
    """Class to support multiple render passes for a renderer.

    Notes
    -----
    Passes are organized here as "primary" (vtkOpenGLRenderPass) that act
    within the renderer and "post-processing" (vtkImageProcessingPass) passes,
    which act on the image generated from the renderer.

    The primary passes are added as part of a vtk.vtkRenderPassCollection or
    are "stacked", while the post-processing passes are added as a final pass
    to the rendered image.

    Parameters
    ----------
    renderer : vtk.vtkRenderer
        Renderer to initialize render passes for.

    """

    def __init__(self, renderer):
        """Initialize render passes."""
        self._renderer_ref = weakref.ref(renderer)

        self._passes = {}
        self._fxaa_pass = None
        self._shadow_map_pass = None
        self._edl_pass = None
        self._dof_pass = None
        self._ssaa_pass = None
        self._ssao_pass = None
        self._blur_passes = []
        self.__pass_collection = None
        self.__seq_pass = None
        self.__camera_pass = None

    @property
    def _pass_collection(self):
        """Initialize (when necessary) the pass collection and return it.

        This lets us lazily generate the pass collection only when we need it
        rather than at initialization of the class.

        """
        if self.__pass_collection is None:
            self._init_passes()
        return self.__pass_collection

    @property
    def _seq_pass(self):
        """Initialize (when necessary) the sequence collection and return it.

        This lets us lazily generate the sequence collection only when we need it
        rather than at initialization of the class.

        """
        if self.__seq_pass is None:
            self._init_passes()
        return self.__seq_pass

    @property
    def _camera_pass(self):
        """Initialize (when necessary) the camera pass and return it.

        This lets us lazily generate the camera pass only when we need it
        rather than at initialization of the class.

        """
        if self.__camera_pass is None:
            self._init_passes()
        return self.__camera_pass

    def _init_passes(self):
        """Initialize the renderer's standard passes."""
        # simulate the standard VTK rendering passes and put them in a sequence
        self.__pass_collection = _vtk.vtkRenderPassCollection()
        self.__pass_collection.AddItem(_vtk.vtkRenderStepsPass())

        self.__seq_pass = _vtk.vtkSequencePass()
        self.__seq_pass.SetPasses(self._pass_collection)

        # Make the sequence the delegate of a camera pass.
        self.__camera_pass = _vtk.vtkCameraPass()
        self.__camera_pass.SetDelegatePass(self._seq_pass)

    @property
    def _renderer(self):
        """Return the renderer."""
        if self._renderer_ref is not None:
            return self._renderer_ref()

    def deep_clean(self):
        """Delete all render passes."""
        if self._renderer is not None:
            self._renderer.SetPass(None)
        self._renderer_ref = None
        if self.__seq_pass is not None:
            self.__seq_pass.SetPasses(None)
        self.__seq_pass = None
        self.__pass_collection = None
        self.__camera_pass = None
        self._passes = {}
        self._shadow_map_pass = None
        self._edl_pass = None
        self._dof_pass = None
        self._ssaa_pass = None
        self._ssao_pass = None
        self._blur_passes = []

    def enable_edl_pass(self):
        """Enable the EDL pass.

        Returns
        -------
        vtk.vtkEDLShading
            The enabled EDL pass.

        """
        if self._edl_pass is not None:
            return
        self._edl_pass = _vtk.vtkEDLShading()
        self._add_pass(self._edl_pass)
        return self._edl_pass

    def disable_edl_pass(self):
        """Disable the EDL pass."""
        if self._edl_pass is None:
            return
        self._remove_pass(self._edl_pass)
        self._edl_pass = None

    def add_blur_pass(self):
        """Add a vtkGaussianBlurPass pass.

        This is a vtkImageProcessingPass and delegates to the last pass.

        Returns
        -------
        vtk.vtkGaussianBlurPass
            The added Gaussian blur pass.

        """
        blur_pass = _vtk.vtkGaussianBlurPass()
        self._add_pass(blur_pass)
        self._blur_passes.append(blur_pass)
        return blur_pass

    def remove_blur_pass(self):
        """Remove a single vtkGaussianBlurPass pass."""
        if self._blur_passes:
            # order of the blur passes does not matter
            self._remove_pass(self._blur_passes.pop())

    def enable_shadow_pass(self):
        """Enable shadow pass.

        Returns
        -------
        vtk.vtkShadowMapPass
            The enabled shadow pass.

        """
        # shadow pass can be directly added to the base pass collection
        if self._shadow_map_pass is not None:
            return
        self._shadow_map_pass = _vtk.vtkShadowMapPass()
        self._pass_collection.AddItem(self._shadow_map_pass.GetShadowMapBakerPass())
        self._pass_collection.AddItem(self._shadow_map_pass)
        self._update_passes()
        return self._shadow_map_pass

    def disable_shadow_pass(self):
        """Disable shadow pass."""
        if self._shadow_map_pass is None:
            return
        self._pass_collection.RemoveItem(self._shadow_map_pass.GetShadowMapBakerPass())
        self._pass_collection.RemoveItem(self._shadow_map_pass)
        self._update_passes()

    def enable_depth_of_field_pass(self, automatic_focal_distance=True):
        """Enable the depth of field pass.

        Parameters
        ----------
        automatic_focal_distance : bool, default: True
            If ``True``, the depth of field effect will automatically compute
            the focal distance. If ``False``, the user must specify the distance.

        Returns
        -------
        vtk.vtkDepthOfFieldPass
            The enabled depth of field pass.

        """
        if self._dof_pass is not None:
            return

        if self._ssao_pass is not None:
            raise RuntimeError('Depth of field pass is incompatible with the SSAO pass.')

        self._dof_pass = _vtk.vtkDepthOfFieldPass()
        self._dof_pass.SetAutomaticFocalDistance(automatic_focal_distance)
        self._add_pass(self._dof_pass)
        return self._dof_pass

    def disable_depth_of_field_pass(self):
        """Disable the depth of field pass."""
        if self._dof_pass is None:
            return
        self._remove_pass(self._dof_pass)
        self._dof_pass = None

    def enable_ssao_pass(self, radius, bias, kernel_size, blur):
        """Enable the screen space ambient occlusion pass.

        Parameters
        ----------
        radius : float
            Radius of occlusion generation.
        bias : float
            Bias to adjust the occlusion generation.
        kernel_size : int
            Size of the kernel for occlusion generation.
        blur : bool
            If ``True``, the pass uses a blur stage.

        Returns
        -------
        vtk.vtkSSAOPass
            The enabled screen space ambient occlusion pass.

        """
        if self._dof_pass is not None:
            raise RuntimeError('SSAO pass is incompatible with the depth of field pass.')

        if self._ssao_pass is not None:
            return
        self._ssao_pass = _vtk.vtkSSAOPass()
        self._ssao_pass.SetRadius(radius)
        self._ssao_pass.SetBias(bias)
        self._ssao_pass.SetKernelSize(kernel_size)
        self._ssao_pass.SetBlur(blur)
        self._add_pass(self._ssao_pass)
        return self._ssao_pass

    def disable_ssao_pass(self):
        """Disable the screen space ambient occlusion pass."""
        if self._ssao_pass is None:
            return
        self._remove_pass(self._ssao_pass)
        self._ssao_pass = None

    def enable_ssaa_pass(self):
        """Enable super-sample anti-aliasing pass.

        Returns
        -------
        vtk.vtkSSAAPass
            The enabled super-sample anti-aliasing pass.

        """
        if self._ssaa_pass is not None:
            return
        self._ssaa_pass = _vtk.vtkSSAAPass()
        self._add_pass(self._ssaa_pass)
        return self._ssaa_pass

    def disable_ssaa_pass(self):
        """Disable super-sample anti-aliasing pass."""
        if self._ssaa_pass is None:
            return
        self._remove_pass(self._ssaa_pass)
        self._ssaa_pass = None

    def _update_passes(self):
        """Reassemble pass delegation."""
        if self._renderer is None:  # pragma: no cover
            raise RuntimeError('The renderer has been closed.')

        current_pass = self._camera_pass
        for class_name in PRE_PASS + POST_PASS:
            if class_name in self._passes:
                for render_pass in self._passes[class_name]:
                    render_pass.SetDelegatePass(current_pass)
                    current_pass = render_pass

        # reset to the default rendering if no special passes have been added
        if current_pass is self._camera_pass and self._shadow_map_pass is None:
            self._renderer.SetPass(None)
        else:
            self._renderer.SetPass(current_pass)

    def _add_pass(self, render_pass):
        """Add a render pass."""
        class_name = render_pass.GetClassName()

        if class_name in PRE_PASS and render_pass in self._passes:
            return

        if class_name not in self._passes:
            self._passes[class_name] = [render_pass]
        else:
            self._passes[class_name].append(render_pass)

        self._update_passes()

    def _remove_pass(self, render_pass):
        """Remove a pass.

        Remove a pass and reassemble the pass ordering.

        """
        class_name = render_pass.GetClassName()

        if class_name not in self._passes:  # pragma: no cover
            return
        else:
            self._passes[class_name].remove(render_pass)
            if not self._passes[class_name]:
                self._passes.pop(class_name)

        self._update_passes()


# pyvista/plotting/render_window_interactor.py

"""Wrap vtk.vtkRenderWindowInteractor."""
import collections.abc
from contextlib import contextmanager
from functools import partial
import logging
import time
import warnings
import weakref

from pyvista.core.errors import PyVistaDeprecationWarning
from pyvista.core.utilities.misc import try_callback
from pyvista.report import vtk_version_info

from . import _vtk
from .opts import PickerType

log = logging.getLogger(__name__)
log.setLevel('CRITICAL')
log.addHandler(logging.StreamHandler())

_CLASSES = {}


class RenderWindowInteractor:
    """Wrap vtk.vtkRenderWindowInteractor.

    This class has been added for the purpose of making some methods
    we add to the RenderWindowInteractor more python, like certain
    testing methods.

    Parameters
    ----------
    plotter : pyvista.Plotter
        Plotter object upon which the initialization of
        RenderWindowInteractor is based.

    desired_update_rate : float, default: 30
        The desired update rate of the interactor.

    light_follow_camera : bool, default: True
        If set to ``True``, the light follows the camera.

    interactor : vtk.vtkRenderWindowInteractor, default: None
        The render window interactor. If set to ``None``, a new
        vtkRenderWindowInteractor instance will be created.
    """

    def __init__(self, plotter, desired_update_rate=30, light_follow_camera=True, interactor=None):
        """Initialize."""
        if interactor is None:
            interactor = _vtk.vtkRenderWindowInteractor()
        self.interactor = interactor
        self.interactor.SetDesiredUpdateRate(desired_update_rate)
        if not light_follow_camera:
            self.interactor.LightFollowCameraOff()

        # Map of observers to events
        self._observers = {}
        self._key_press_event_callbacks = collections.defaultdict(list)
        self._click_event_callbacks = {
            event: {(double, v): [] for double in (False, True) for v in (False, True)}
            for event in ("LeftButtonPressEvent", "RightButtonPressEvent")
        }
        self._click_time = 0
        self._MAX_CLICK_DELAY = 0.8  # seconds
        self._MAX_CLICK_DELTA = 40  # squared => ~6 pixels

        # Set default style
        self._style = 'RubberBandPick'
        self._style_class = None
        self.__plotter = weakref.ref(plotter)

        # Toggle interaction style when clicked on a visible chart (to
        # enable interaction with visible charts)
        self._context_style = _vtk.vtkContextInteractorStyle()
        self.track_click_position(
            self._toggle_chart_interaction, side="left", double=True, viewport=True
        )

        self.reset_picker()
        self.picker = PickerType.POINT

    @property
    def _plotter(self):
        """Return the plotter."""
        return self.__plotter()

    def add_key_event(self, key, callback):
        """Add a function to callback when the given key is pressed.

        These are non-unique - thus a key could map to many callback
        functions. The callback function must not have any arguments.

        Parameters
        ----------
        key : str
            The key to trigger the event.

        callback : callable
            A callable that takes no arguments.

        """
        if not callable(callback):
            raise TypeError('callback must be callable.')
        self._key_press_event_callbacks[key].append(callback)

    @staticmethod
    def _get_event_str(event):
        if isinstance(event, str):
            # Make sure we pass it at least once through these functions, such that
            # invalid event names are mapped to "NoEvent".
            event = _vtk.vtkCommand.GetEventIdFromString(event)
        return _vtk.vtkCommand.GetStringFromEventId(event)

    def add_observer(self, event, call):
        """Add an observer for the given event.

        Parameters
        ----------
        event : str | int
            The event to observe. Either the name of this event (string) or
            a VTK event identifier (int).

        call : callable
            Callback to be called when the event is invoked.

        Returns
        -------
        int
            The identifier of the added observer.

        Examples
        --------
        Add a custom observer.

        >>> import pyvista
        >>> pl = pyvista.Plotter()
        >>> obs_enter = pl.iren.add_observer(
        ...     "EnterEvent", lambda *_: print('Enter!')
        ... )

        """
        call = partial(try_callback, call)
        event = self._get_event_str(event)
        observer = self.interactor.AddObserver(event, call)
        self._observers[observer] = event
        return observer

    def remove_observer(self, observer):
        """Remove an observer.

        Parameters
        ----------
        observer : int
            The identifier of the observer to remove.

        Examples
        --------
        Add an observer and immediately remove it.

        >>> import pyvista
        >>> pl = pyvista.Plotter()
        >>> obs_enter = pl.iren.add_observer(
        ...     "EnterEvent", lambda *_: print('Enter!')
        ... )
        >>> pl.iren.remove_observer(obs_enter)

        """
        if observer in self._observers:
            self.interactor.RemoveObserver(observer)
            del self._observers[observer]

    def remove_observers(self, event=None):
        """Remove all observers.

        Parameters
        ----------
        event : str | int, optional
            If provided, only removes observers of the given event. Otherwise,
            if it is ``None``, removes all observers.

        Examples
        --------
        Add two observers and immediately remove them.

        >>> import pyvista
        >>> pl = pyvista.Plotter()
        >>> obs_enter = pl.iren.add_observer(
        ...     "EnterEvent", lambda *_: print('Enter!')
        ... )
        >>> obs_leave = pl.iren.add_observer(
        ...     "LeaveEvent", lambda *_: print('Leave!')
        ... )
        >>> pl.iren.remove_observers()

        """
        if event is None:
            observers = list(self._observers.keys())
        else:
            event = self._get_event_str(event)
            observers = [obs for obs, ev in self._observers.items() if event == ev]
        for observer in observers:
            self.remove_observer(observer)

    def clear_events_for_key(self, key, raise_on_missing=False):
        """Remove the callbacks associated to the key.

        Parameters
        ----------
        key : str
            Key to clear events for.

        raise_on_missing : bool, default: False
            Whether to raise a :class:`ValueError` if there are no events
            registered for the given key.
        """
        try:
            self._key_press_event_callbacks.pop(key)
        except KeyError:
            if raise_on_missing:
                raise ValueError(f'No events found for key {key!r}.') from None

    def track_mouse_position(self, callback):
        """Keep track of the mouse position.

        This will potentially slow down the interactor. No callbacks supported
        here - use :func:`pyvista.Plotter.track_click_position` instead.

        Parameters
        ----------
        callback : callable
            A function to call back when the mouse moves. This function will be
            passed the current mouse position.

        """
        self.add_observer(_vtk.vtkCommand.MouseMoveEvent, callback)

    def untrack_mouse_position(self):
        """Stop tracking the mouse position."""
        self.remove_observers(_vtk.vtkCommand.MouseMoveEvent)

    @staticmethod
    def _get_click_event(side):
        side = str(side).lower()
        if side in ["right", "r"]:
            return "RightButtonPressEvent"
        elif side in ["left", "l"]:
            return "LeftButtonPressEvent"
        else:
            raise TypeError(f"Side ({side}) not supported. Try `left` or `right`.")

    def _click_event(self, obj, event):
        t = time.time()
        dt = t - self._click_time
        last_pos = self._plotter.click_position or (0, 0)

        self._plotter.store_click_position()
        dp = (self._plotter.click_position[0] - last_pos[0]) ** 2
        dp += (self._plotter.click_position[1] - last_pos[1]) ** 2
        double = dp < self._MAX_CLICK_DELTA and dt < self._MAX_CLICK_DELAY
        # Reset click time in case of a double click, otherwise a subsequent third click
        # is considered to be a double click as well.
        self._click_time = 0 if double else t

        for callback in self._click_event_callbacks[event][double, False]:
            callback(self._plotter.pick_click_position())
        for callback in self._click_event_callbacks[event][double, True]:
            callback(self._plotter.click_position)

    def track_click_position(self, callback=None, side="right", double=False, viewport=False):
        """Keep track of the click position.

        By default, it only tracks right clicks.

        Parameters
        ----------
        callback : callable, optional
            A callable method that will use the click position. Passes
            the click position as a length two tuple.

        side : str, default: "right"
            The mouse button to track (either ``'left'`` or ``'right'``).
            Also accepts ``'r'`` or ``'l'``.

        double : bool, default: False
            Track single clicks if ``False``, double clicks if ``True``.
            Defaults to single clicks.

        viewport : bool, default: False
            If ``True``, uses the normalized viewport coordinate
            system (values between 0.0 and 1.0 and support for HiDPI)
            when passing the click position to the callback.

        """
        event = self._get_click_event(side)
        add_observer = all(len(cbs) == 0 for cbs in self._click_event_callbacks[event].values())
        if callback is None and add_observer:
            # No observers for this event yet and custom callback not given => insert dummy callback
            callback = lambda obs, event: None
        if callable(callback):
            self._click_event_callbacks[event][double, viewport].append(callback)
        else:
            raise ValueError(
                "Invalid callback provided, it should be either ``None`` or a callable."
            )

        if add_observer:
            self.add_observer(event, self._click_event)

    def untrack_click_position(self, side="right"):
        """Stop tracking the click position.

        Parameters
        ----------
        side : str, optional
            The mouse button to stop tracking (either ``'left'`` or
            ``'right'``). Default is ``'right'``. Also accepts ``'r'``
            or ``'l'``.

        """
        event = self._get_click_event(side)
        self.remove_observers(event)
        for cbs in self._click_event_callbacks[event].values():
            cbs.clear()

    def clear_key_event_callbacks(self):
        """Clear key event callbacks."""
        self._key_press_event_callbacks.clear()

    def key_press_event(self, obj, event):
        """Listen for key press event."""
        key = self.interactor.GetKeySym()
        log.debug(f'Key {key} pressed')
        self._last_key = key
        if key in self._key_press_event_callbacks.keys():
            # Note that defaultdict's will never throw a key error
            callbacks = self._key_press_event_callbacks[key]
            for func in callbacks:
                func()

    def update_style(self):
        """Update the camera interactor style."""
        if self._style_class is None:
            # We need an actually custom style to handle button up events
            self._style_class = _style_factory(self._style)(self)
        self.interactor.SetInteractorStyle(self._style_class)

    def _toggle_chart_interaction(self, mouse_pos):
        """Toggle interaction with indicated charts.

        Parameters
        ----------
        mouse_pos : tuple of float
            Tuple containing the mouse position.

        """
        # Loop over all renderers to see whether any charts need to be made interactive
        interactive_scene = None
        for renderer in self._plotter.renderers:
            if interactive_scene is None and renderer.IsInViewport(*mouse_pos):
                # No interactive charts yet and mouse is within this renderer's viewport,
                # so collect all charts indicated by the mouse (typically only one, except
                # when there are overlapping charts).
                origin = renderer.GetOrigin()  # Correct for viewport origin (see #3278)
                charts = renderer._get_charts_by_pos(
                    (mouse_pos[0] - origin[0], mouse_pos[1] - origin[1])
                )
                if charts:
                    # Toggle interaction for indicated charts and determine whether
                    # there are any remaining interactive charts.
                    interactive_charts = renderer.set_chart_interaction(charts, toggle=True)
                    if interactive_charts:
                        # Save a reference to this renderer's scene if there are
                        # remaining interactive charts.
                        interactive_scene = renderer._charts._scene
                else:
                    # No indicated charts, so disable interaction with all charts
                    # for this renderer.
                    renderer.set_chart_interaction(False)
            else:
                # Not in viewport or interactive charts were already found in another
                # renderer, so disable interaction with all charts for this renderer.
                renderer.set_chart_interaction(False)
        # Manually set context_style based on found interactive scene (or stop interaction
        # with any scene if there are no interactive charts).
        self._set_context_style(interactive_scene)

    def _set_context_style(self, scene):
        """
        Set the context style interactor or switch back to previous interactor style.

        Parameters
        ----------
        scene : vtkContextScene, optional
            The scene to interact with or ``None`` to stop interaction with any scene.

        """
        # Set scene to interact with or reset it to stop interaction (otherwise crash)
        if vtk_version_info < (9, 3, 0):  # pragma: no cover
            if scene is not None and len(self._plotter.renderers) > 1:
                warnings.warn(
                    "Interaction with charts is not possible when using multiple subplots."
                    "Upgrade to VTK 9.3 or newer to enable this feature."
                )
                scene = None
        self._context_style.SetScene(scene)
        if scene is None and self._style == "Context":
            # Switch back to previous interactor style
            self._style = self._prev_style
            self._style_class = self._prev_style_class
            self._prev_style = None
            self._prev_style_class = None
        elif scene is not None and self._style != "Context":
            # Enable context interactor style
            self._prev_style = self._style
            self._prev_style_class = self._style_class
            self._style = "Context"
            self._style_class = self._context_style
        self.update_style()

    def enable_trackball_style(self):
        """Set the interactive style to Trackball Camera.

        The trackball camera is the default interactor style. Moving
        the mouse moves the camera around, leaving the scene intact.

        For a 3-button mouse, the left button is for rotation, the
        right button for zooming, the middle button for panning, and
        ctrl + left button for spinning the view around the vewing
        axis of the camera.  Alternatively, ctrl + shift + left button
        or mouse wheel zooms, and shift + left button pans.

        Examples
        --------
        Create a simple scene with a plotter that has the Trackball
        Camera interactive style (which is also the default):

        >>> import pyvista as pv
        >>> plotter = pv.Plotter()
        >>> _ = plotter.add_mesh(pv.Cube(center=(1, 0, 0)))
        >>> _ = plotter.add_mesh(pv.Cube(center=(0, 1, 0)))
        >>> plotter.show_axes()
        >>> plotter.enable_trackball_style()
        >>> plotter.show()  # doctest:+SKIP

        """
        self._style = 'TrackballCamera'
        self._style_class = None
        self.update_style()

    def enable_trackball_actor_style(self):
        """Set the interactive style to Trackball Actor.

        This allows to rotate actors around the scene. The controls
        are similar to the default Trackball Camera style, but
        movements transform specific objects under the mouse cursor.

        For a 3-button mouse, the left button is for rotation, the
        right button for zooming, the middle button for panning, and
        ctrl + left button for spinning objects around the axis
        connecting the camera with the their center.  Alternatively,
        shift + left button pans.

        Examples
        --------
        Create a simple scene with a plotter that has the Trackball
        Actor interactive style:

        >>> import pyvista as pv
        >>> plotter = pv.Plotter()
        >>> _ = plotter.add_mesh(pv.Cube(center=(1, 0, 0)))
        >>> _ = plotter.add_mesh(pv.Cube(center=(0, 1, 0)))
        >>> plotter.show_axes()
        >>> plotter.enable_trackball_actor_style()
        >>> plotter.show()  # doctest:+SKIP

        """
        self._style = 'TrackballActor'
        self._style_class = None
        self.update_style()

    def enable_image_style(self):
        """Set the interactive style to Image.

        Controls:
         - Left Mouse button triggers window level events
         - CTRL Left Mouse spins the camera around its view plane normal
         - SHIFT Left Mouse pans the camera
         - CTRL SHIFT Left Mouse dollies (a positional zoom) the camera
         - Middle mouse button pans the camera
         - Right mouse button dollies the camera
         - SHIFT Right Mouse triggers pick events

        Examples
        --------
        Create a simple scene with a plotter that has the Image
        interactive style:

        >>> import pyvista as pv
        >>> plotter = pv.Plotter()
        >>> _ = plotter.add_mesh(pv.Cube(center=(1, 0, 0)))
        >>> _ = plotter.add_mesh(pv.Cube(center=(0, 1, 0)))
        >>> plotter.show_axes()
        >>> plotter.enable_image_style()
        >>> plotter.show()  # doctest:+SKIP

        """
        self._style = 'Image'
        self._style_class = None
        self.update_style()

    def enable_joystick_style(self):
        """Set the interactive style to Joystick Camera.

        It allows the user to move (rotate, pan, etc.) the camera, the
        point of view for the scene.  The position of the mouse
        relative to the center of the scene determines the speed at
        which the camera moves, so the camera continues to move even
        if the mouse if not moving.

        For a 3-button mouse, the left button is for rotation, the
        right button for zooming, the middle button for panning, and
        ctrl + left button for spinning.  (With fewer mouse buttons,
        ctrl + shift + left button is for zooming, and shift + left
        button is for panning.)

        Examples
        --------
        Create a simple scene with a plotter that has the Joystick
        Camera interactive style:

        >>> import pyvista as pv
        >>> plotter = pv.Plotter()
        >>> _ = plotter.add_mesh(pv.Cube(center=(1, 0, 0)))
        >>> _ = plotter.add_mesh(pv.Cube(center=(0, 1, 0)))
        >>> plotter.show_axes()
        >>> plotter.enable_joystick_style()
        >>> plotter.show()  # doctest:+SKIP

        """
        self._style = 'JoystickCamera'
        self._style_class = None
        self.update_style()

    def enable_joystick_actor_style(self):
        """Set the interactive style to Joystick Actor.

        Similar to the Joystick Camera interaction style, however
        in case of the Joystick Actor style the objects in the scene
        rather than the camera can be moved (rotated, panned, etc.).
        The position of the mouse relative to the center of the object
        determines the speed at which the object moves, so the object
        continues to move even if the mouse is not moving.

        For a 3-button mouse, the left button is for rotation, the
        right button for zooming, the middle button for panning, and
        ctrl + left button for spinning.  (With fewer mouse buttons,
        ctrl + shift + left button is for zooming, and shift + left
        button is for panning.)

        Examples
        --------
        Create a simple scene with a plotter that has the Joystick
        Actor interactive style:

        >>> import pyvista as pv
        >>> plotter = pv.Plotter()
        >>> _ = plotter.add_mesh(pv.Cube(center=(1, 0, 0)))
        >>> _ = plotter.add_mesh(pv.Cube(center=(0, 1, 0)))
        >>> plotter.show_axes()
        >>> plotter.enable_joystick_actor_style()
        >>> plotter.show()  # doctest:+SKIP

        """
        self._style = 'JoystickActor'
        self._style_class = None
        self.update_style()

    def enable_zoom_style(self):
        """Set the interactive style to Rubber Band Zoom.

        This interactor style allows the user to draw a rectangle in
        the render window using the left mouse button.  When the mouse
        button is released, the current camera zooms by an amount
        determined from the shorter side of the drawn rectangle.

        Examples
        --------
        Create a simple scene with a plotter that has the Rubber Band
        Zoom interactive style:

        >>> import pyvista as pv
        >>> plotter = pv.Plotter()
        >>> _ = plotter.add_mesh(pv.Cube(center=(1, 0, 0)))
        >>> _ = plotter.add_mesh(pv.Cube(center=(0, 1, 0)))
        >>> plotter.show_axes()
        >>> plotter.enable_zoom_style()
        >>> plotter.show()  # doctest:+SKIP

        """
        self._style = 'RubberBandZoom'
        self._style_class = None
        self.update_style()

    def enable_terrain_style(self, mouse_wheel_zooms=False, shift_pans=False):
        """Set the interactive style to Terrain.

        Used to manipulate a camera which is viewing a scene with a
        natural view up, e.g., terrain. The camera in such a scene is
        manipulated by specifying azimuth (angle around the view up
        vector) and elevation (the angle from the horizon). Similar to
        the default Trackball Camera style and in contrast to the
        Joystick Camera style, movements of the mouse translate to
        movements of the camera.

        Left mouse click rotates the camera around the focal point
        using both elevation and azimuth invocations on the camera.
        Left mouse motion in the horizontal direction results in
        azimuth motion; left mouse motion in the vertical direction
        results in elevation motion. Therefore, diagonal motion results
        in a combination of azimuth and elevation. (If the shift key is
        held during motion, then only one of elevation or azimuth is
        invoked, depending on the whether the mouse motion is primarily
        horizontal or vertical.) Middle mouse button pans the camera
        across the scene (again the shift key has a similar effect on
        limiting the motion to the vertical or horizontal direction.
        The right mouse is used to dolly towards or away from the focal
        point (zoom in or out). Panning and zooming behavior can be
        overridden to match the Trackball Camera style.

        The class also supports some keypress events. The ``r`` key
        resets the camera. The ``e`` key invokes the exit callback
        and closes the plotter. The ``f`` key sets a new
        camera focal point and flies towards that point. The ``u``
        key invokes the user event. The ``3`` key toggles between
        stereo and non-stero mode. The ``l`` key toggles on/off
        latitude/longitude markers that can be used to estimate/control
        position.

        Parameters
        ----------
        mouse_wheel_zooms : bool, default: False
            Whether to use the mouse wheel for zooming. By default
            zooming can be performed with right click and drag.

        shift_pans : bool, default: False
            Whether shift + left mouse button pans the scene. By default
            shift + left mouse button rotates the view restricted to
            only horizontal or vertical movements, and panning is done
            holding down the middle mouse button.

        Examples
        --------
        Create a simple scene with a plotter that has the Terrain
        interactive style:

        >>> import pyvista as pv
        >>> plotter = pv.Plotter()
        >>> _ = plotter.add_mesh(pv.Cube(center=(1, 0, 0)))
        >>> _ = plotter.add_mesh(pv.Cube(center=(0, 1, 0)))
        >>> plotter.show_axes()
        >>> plotter.enable_terrain_style()
        >>> plotter.show()  # doctest:+SKIP

        Use controls that are closer to the default style:

        >>> plotter = pv.Plotter()
        >>> _ = plotter.add_mesh(pv.Cube(center=(1, 0, 0)))
        >>> _ = plotter.add_mesh(pv.Cube(center=(0, 1, 0)))
        >>> plotter.show_axes()
        >>> plotter.enable_terrain_style(
        ...     mouse_wheel_zooms=True, shift_pans=True
        ... )
        >>> plotter.show()  # doctest:+SKIP

        """
        self._style = 'Terrain'
        self._style_class = None
        self.update_style()

        if mouse_wheel_zooms:

            def wheel_zoom_callback(obj, event):  # pragma: no cover
                """Zoom in or out on mouse wheel roll."""
                if event == 'MouseWheelForwardEvent':
                    # zoom in
                    zoom_factor = 1.1
                elif event == 'MouseWheelBackwardEvent':
                    # zoom out
                    zoom_factor = 1 / 1.1
                self._plotter.camera.zoom(zoom_factor)
                self._plotter.render()

            callback = partial(try_callback, wheel_zoom_callback)

            for event in 'MouseWheelForwardEvent', 'MouseWheelBackwardEvent':
                self._style_class.add_observer(event, callback)

        if shift_pans:

            def pan_on_shift_callback(obj, event):  # pragma: no cover
                """Trigger left mouse panning if shift is pressed."""
                if event == 'LeftButtonPressEvent':
                    if self.interactor.GetShiftKey():
                        self._style_class.StartPan()
                    self._style_class.OnLeftButtonDown()
                elif event == 'LeftButtonReleaseEvent':
                    # always stop panning on release
                    self._style_class.EndPan()
                    self._style_class.OnLeftButtonUp()

            callback = partial(try_callback, pan_on_shift_callback)

            for event in 'LeftButtonPressEvent', 'LeftButtonReleaseEvent':
                self._style_class.add_observer(event, callback)

    def enable_rubber_band_style(self):
        """Set the interactive style to Rubber Band Picking.

        This interactor style allows the user to draw a rectangle in
        the render window by hitting ``r`` and then using the left
        mouse button. When the mouse button is released, the attached
        picker operates on the pixel in the center of the selection
        rectangle. If the picker happens to be a ``vtkAreaPicker``
        it will operate on the entire selection rectangle. When the
        ``p`` key is hit the above pick operation occurs on a 1x1
        rectangle. In other respects it behaves the same as the
        Trackball Camera style.

        Examples
        --------
        Create a simple scene with a plotter that has the Rubber Band
        Pick interactive style:

        >>> import pyvista as pv
        >>> plotter = pv.Plotter()
        >>> _ = plotter.add_mesh(pv.Cube(center=(1, 0, 0)))
        >>> _ = plotter.add_mesh(pv.Cube(center=(0, 1, 0)))
        >>> plotter.show_axes()
        >>> plotter.enable_rubber_band_style()
        >>> plotter.show()  # doctest:+SKIP

        """
        self._style = 'RubberBandPick'
        self._style_class = None
        self.update_style()

    def enable_rubber_band_2d_style(self):
        """Set the interactive style to Rubber Band 2D.

        Camera rotation is not enabled with this interactor
        style. Zooming affects the camera's parallel scale only, and
        assumes that the camera is in parallel projection mode. The
        style also allows to draw a rubber band using the left mouse
        button. All camera changes invoke ``StartInteractionEvent`` when
        the button is pressed, ``InteractionEvent`` when the mouse (or
        wheel) is moved, and ``EndInteractionEvent`` when the button is
        released. The bindings are as follows:

          * Left mouse: Select (invokes a ``SelectionChangedEvent``).
          * Right mouse: Zoom.
          * Middle mouse: Pan.
          * Scroll wheel: Zoom.

        Examples
        --------
        Create a simple scene with a plotter that has the Rubber Band
        2D interactive style:

        >>> import pyvista as pv
        >>> plotter = pv.Plotter()
        >>> _ = plotter.add_mesh(pv.Cube(center=(1, 0, 0)))
        >>> _ = plotter.add_mesh(pv.Cube(center=(0, 1, 0)))
        >>> plotter.show_axes()
        >>> plotter.enable_rubber_band_2d_style()
        >>> plotter.show()  # doctest:+SKIP

        """
        self._style = 'RubberBand2D'
        self._style_class = None
        self.update_style()

    def _simulate_keypress(self, key):  # pragma:
        """Simulate a keypress."""
        if len(key) > 1:
            raise ValueError('Only accepts a single key')
        self.interactor.SetKeyCode(key)
        self.interactor.CharEvent()

    def _mouse_left_button_press(
        self, x=None, y=None
    ):  # pragma:  # numpydoc ignore=PR01,RT01 no cover
        """Simulate a left mouse button press.

        If ``x`` and ``y`` are entered then simulates a movement to
        that position.

        """
        if x is not None and y is not None:
            self._mouse_move(x, y)
        self.interactor.LeftButtonPressEvent()

    def _mouse_left_button_release(
        self, x=None, y=None
    ):  # pragma:  # numpydoc ignore=PR01,RT01 no cover
        """Simulate a left mouse button release."""
        if x is not None and y is not None:
            self._mouse_move(x, y)
        self.interactor.LeftButtonReleaseEvent()

    def _mouse_left_button_click(self, x=None, y=None, count=1):
        for _ in range(count):
            self._mouse_left_button_press(x, y)
            self._mouse_left_button_release()

    def _mouse_right_button_press(
        self, x=None, y=None
    ):  # pragma:  # numpydoc ignore=PR01,RT01 no cover
        """Simulate a right mouse button press.

        If ``x`` and ``y`` are entered then simulates a movement to
        that position.

        """
        if x is not None and y is not None:
            self._mouse_move(x, y)
        self.interactor.RightButtonPressEvent()

    def _mouse_right_button_release(
        self, x=None, y=None
    ):  # pragma:  # numpydoc ignore=PR01,RT01 no cover
        """Simulate a right mouse button release."""
        if x is not None and y is not None:
            self._mouse_move(x, y)
        self.interactor.RightButtonReleaseEvent()

    def _mouse_right_button_click(self, x=None, y=None, count=1):
        for _ in range(count):
            self._mouse_right_button_press(x, y)
            self._mouse_right_button_release()

    def _mouse_move(self, x, y):  # pragma:
        """Simulate moving the mouse to ``(x, y)`` screen coordinates."""
        self.interactor.SetEventInformation(x, y)
        self.interactor.MouseMoveEvent()

    def get_event_position(self):
        """Get the event position.

        Returns
        -------
        tuple
            The ``(x, y)`` coordinate position.

        """
        return self.interactor.GetEventPosition()

    def get_poked_renderer(self, x=None, y=None):
        """Get poked renderer for last or specific event position.

        Parameters
        ----------
        x : float, default: None
            The x-coordinate for a user-defined event position.

        y : float, default: None
            The y-coordinate for a user-defined event position.

        Returns
        -------
        vtk.vtkRenderer
            The poked renderer for given or last event position.
        """
        if x is None or y is None:
            x, y = self.get_event_position()
        return self.interactor.FindPokedRenderer(x, y)

    def get_event_subplot_loc(self):
        """Get the subplot location of the last event.

        Returns
        -------
        tuple
            A tuple containing the location of the subplot.

        Raises
        ------
        RuntimeError
            If the poked renderer is not found in the Plotter.

        """
        poked_renderer = self.get_poked_renderer()
        for index in range(len(self._plotter.renderers)):
            renderer = self._plotter.renderers[index]
            if renderer is poked_renderer:
                return self._plotter.renderers.index_to_loc(index)
        raise RuntimeError('Poked renderer not found in Plotter.')

    @contextmanager
    def poked_subplot(self):
        """Activate the sublot that was last interacted."""
        active_renderer_index = self._plotter.renderers._active_index
        loc = self.get_event_subplot_loc()
        self._plotter.subplot(*loc)
        try:
            yield
        finally:
            # Reset to the active renderer.
            loc = self._plotter.renderers.index_to_loc(active_renderer_index)
            self._plotter.subplot(*loc)

    def get_interactor_style(self):
        """Get the interactor style.

        Returns
        -------
        vtk.vtkInteractorStyle
            VTK interactor style.
        """
        return self.interactor.GetInteractorStyle()

    def get_desired_update_rate(self):
        """Get the desired update rate.

        Returns
        -------
        float
            Desired update rate.
        """
        return self.interactor.GetDesiredUpdateRate()

    def create_timer(self, duration, repeating=True):
        """Create a timer.

        Parameters
        ----------
        duration : int
            Time (in milliseconds) before the timer emits a TimerEvent.

        repeating : bool, default: True
            When ``False`` a one-shot timer is created, which only fires
            once. When ``True`` a repeating timer is created, which
            continuously fires (every ``duration`` milliseconds) until
            destruction.

        Returns
        -------
        int
            Timer ID.
        """
        if repeating:
            timer_id = self.interactor.CreateRepeatingTimer(duration)
        else:
            timer_id = self.interactor.CreateOneShotTimer(duration)
        return timer_id

    def destroy_timer(self, timer_id):
        """Destroy the given timer.

        Parameters
        ----------
        timer_id : int
            The ID of the timer to destroy.
        """
        self.interactor.DestroyTimer(timer_id)

    def start(self):
        """Start interactions."""
        self.interactor.Start()

    def initialize(self):
        """Initialize the interactor."""
        self.interactor.Initialize()

    def set_render_window(self, render_window):
        """Set the render window for the interactor.

        Parameters
        ----------
        render_window : vtk.vtkRenderWindow
            Render window to set for the interactor.
        """
        self.interactor.SetRenderWindow(render_window)

    def process_events(self):
        """Process events."""
        if not self.initialized:
            raise RuntimeError(
                'Render window interactor must be initialized before processing events.'
            )
        self.interactor.ProcessEvents()

    @property
    def initialized(self):  # numpydoc ignore=RT01
        """Return if the interactor has been initialized."""
        return self.interactor.GetInitialized()

    def get_picker(self):
        """Get the picker.

        Returns
        -------
        vtk.vtkAbstractPicker
            VTK picker.
        """
        # Deprecated on v0.39.0, estimated removal on v0.41.0
        warnings.warn(
            "Use of `get_picker` is deprecated. Use `picker` property instead.",
            PyVistaDeprecationWarning,
        )
        return self.picker

    def set_picker(self, picker):
        """Set the picker for the interactor.

        Parameters
        ----------
        picker : vtk.vtkAbstractPicker
            The picker to set for the interactor.
        """
        # Deprecated on v0.39.0, estimated removal on v0.41.0
        warnings.warn(
            "Use of `get_picker` is deprecated. Use `picker` property instead.",
            PyVistaDeprecationWarning,
        )
        self.picker = picker

    @property
    def picker(self):  # numpydoc ignore=RT01
        """Get/set the picker.

        Returns
        -------
        vtk.vtkAbstractPicker
            VTK picker.
        """
        return self.interactor.GetPicker()

    @picker.setter
    def picker(self, picker):  # numpydoc ignore=GL08
        pickers = {
            PickerType.AREA: _vtk.vtkAreaPicker,
            PickerType.CELL: _vtk.vtkCellPicker,
            PickerType.POINT: _vtk.vtkPointPicker,
            PickerType.PROP: _vtk.vtkPropPicker,
            PickerType.RENDERED: _vtk.vtkRenderedAreaPicker,
            PickerType.RESLICE: _vtk.vtkResliceCursorPicker,
            PickerType.SCENE: _vtk.vtkScenePicker,
            PickerType.VOLUME: _vtk.vtkVolumePicker,
            PickerType.WORLD: _vtk.vtkWorldPointPicker,
        }
        if _vtk.vtkHardwarePicker is not None:
            # Unavailable on VTK < 9.2
            pickers[PickerType.HARDWARE] = _vtk.vtkHardwarePicker
        if isinstance(picker, (str, int, PickerType)):
            picker = PickerType.from_any(picker)
            try:
                picker = pickers[picker]()
            except KeyError:
                raise KeyError(f'Picker class `{picker}` is unknown.')
            # Set default tolerance for internal configurations
            if hasattr(picker, 'SetTolerance'):
                picker.SetTolerance(0.025)
        self.interactor.SetPicker(picker)

    def add_pick_obeserver(self, observer):
        """Add an observer to call back when pick events end.

        Parameters
        ----------
        observer : callable
            The observer function to call when a pick event ends.
        """
        self.picker.AddObserver(_vtk.vtkCommand.EndPickEvent, observer)

    def reset_picker(self):
        """Reset the picker."""
        # Remove observers
        self.picker.RemoveObservers(_vtk.vtkCommand.EndPickEvent)
        # Set default picker to vtkWorldPointPicker
        self.picker = 'world'

    def fly_to(self, renderer, point):
        """Fly the interactor to the given point in a renderer.

        Parameters
        ----------
        renderer : vtk.vtkRenderer
            The renderer in which the action will take place.

        point : list or tuple
            The point to fly to.
        """
        self.interactor.FlyTo(renderer, *point)

    def terminate_app(self):
        """Terminate the app."""
        if self.initialized:
            # #################################################################
            # 9.0.2+ compatibility:
            # See: https://gitlab.kitware.com/vtk/vtk/-/issues/18242
            if hasattr(self.interactor, 'GetDone'):
                self.interactor.SetDone(True)
            # #################################################################

            self.interactor.TerminateApp()

    def close(self):
        """Close out the render window interactor.

        This will terminate the render window if it is not already closed.
        """
        self.remove_observers()
        if self._style_class == self._context_style:  # pragma: no cover
            self._set_context_style(None)  # Disable context interactor style first
        if self._style_class is not None:
            self._style_class.remove_observers()
            self._style_class = None

        self.terminate_app()
        self.interactor = None
        self._click_event_callbacks = None


def _style_factory(klass):
    """Create a subclass with capturing ability, return it."""
    # We have to use a custom subclass for this because the default ones
    # swallow the release events
    # http://vtk.1045678.n5.nabble.com/Mouse-button-release-event-is-still-broken-in-VTK-6-0-0-td5724762.html  # noqa

    def _make_class(klass):
        """Make the class."""
        try:
            from vtkmodules import vtkInteractionStyle
        except ImportError:  # pragma: no cover
            import vtk as vtkInteractionStyle

        class CustomStyle(getattr(vtkInteractionStyle, 'vtkInteractorStyle' + klass)):
            def __init__(self, parent):
                super().__init__()
                self._parent = weakref.ref(parent)

                self._observers = []
                self._observers.append(
                    self.AddObserver("LeftButtonPressEvent", partial(try_callback, self._press))
                )
                self._observers.append(
                    self.AddObserver("LeftButtonReleaseEvent", partial(try_callback, self._release))
                )

            def _press(self, obj, event):
                # Figure out which renderer has the event and disable the
                # others
                super().OnLeftButtonDown()
                parent = self._parent()
                if len(parent._plotter.renderers) > 1:
                    click_pos = parent.get_event_position()
                    for renderer in parent._plotter.renderers:
                        interact = renderer.IsInViewport(*click_pos)
                        renderer.SetInteractive(interact)

            def _release(self, obj, event):
                super().OnLeftButtonUp()
                parent = self._parent()
                if len(parent._plotter.renderers) > 1:
                    for renderer in parent._plotter.renderers:
                        renderer.SetInteractive(True)

            def add_observer(self, event, callback):
                self._observers.append(self.AddObserver(event, callback))

            def remove_observers(self):
                for obs in self._observers:
                    self.RemoveObserver(obs)

        return CustomStyle

    # cache classes
    if klass not in _CLASSES:
        _CLASSES[klass] = _make_class(klass)
    return _CLASSES[klass]


# pyvista/plotting/renderer.py

"""Module containing pyvista implementation of vtkRenderer."""

import collections.abc
from functools import partial, wraps
from typing import Sequence, cast
import warnings

import numpy as np

import pyvista
from pyvista import MAX_N_COLOR_BARS
from pyvista.core._typing_core import BoundsLike
from pyvista.core.errors import PyVistaDeprecationWarning
from pyvista.core.utilities.helpers import wrap
from pyvista.core.utilities.misc import assert_empty_kwargs, try_callback

from . import _vtk
from .actor import Actor
from .camera import Camera
from .charts import Charts
from .colors import Color, get_cycler
from .errors import InvalidCameraError
from .helpers import view_vectors
from .render_passes import RenderPasses
from .tools import create_axes_marker, create_axes_orientation_box, parse_font_family
from .utilities.gl_checks import check_depth_peeling, uses_egl

ACTOR_LOC_MAP = [
    'upper right',
    'upper left',
    'lower left',
    'lower right',
    'center left',
    'center right',
    'lower center',
    'upper center',
    'center',
]


def map_loc_to_pos(loc, size, border=0.05):
    """Map location and size to a VTK position and position2.

    Parameters
    ----------
    loc : str
        Location of the actor. Can be a string with values such as 'right',
        'left', 'upper', or 'lower'.
    size : Sequence of length 2
        Size of the actor. It must be a list of length 2.
    border : float, default: 0.05
        Size of the border around the actor.

    Returns
    -------
    tuple
        The VTK position and position2 coordinates. Tuple of the form (x, y, size).

    Raises
    ------
    ValueError
        If the ``size`` parameter is not a list of length 2.

    """
    if not isinstance(size, Sequence) or len(size) != 2:
        raise ValueError(f'`size` must be a list of length 2. Passed value is {size}')

    if 'right' in loc:
        x = 1 - size[1] - border
    elif 'left' in loc:
        x = border
    else:
        x = 0.5 - size[1] / 2

    if 'upper' in loc:
        y = 1 - size[1] - border
    elif 'lower' in loc:
        y = border
    else:
        y = 0.5 - size[1] / 2

    return x, y, size


def make_legend_face(face):
    """
    Create the legend face based on the given face.

    Parameters
    ----------
    face : str | None | pyvista.PolyData
        The shape of the legend face. Valid strings are:
        '-', 'line', '^', 'triangle', 'o', 'circle', 'r', 'rectangle'.
        Also accepts ``None`` and instances of ``pyvista.PolyData``.

    Returns
    -------
    pyvista.PolyData
        The legend face as a PolyData object.

    Raises
    ------
    ValueError
        If the provided face value is invalid.
    """
    if face is None:
        legendface = pyvista.PolyData([0.0, 0.0, 0.0])
    elif face in ["-", "line"]:
        legendface = _line_for_legend()
    elif face in ["^", "triangle"]:
        legendface = pyvista.Triangle()
    elif face in ["o", "circle"]:
        legendface = pyvista.Circle()
    elif face in ["r", "rectangle"]:
        legendface = pyvista.Rectangle()
    elif isinstance(face, pyvista.PolyData):
        legendface = face
    else:
        raise ValueError(
            f'Invalid face "{face}".  Must be one of the following:\n'
            '\t"triangle"\n'
            '\t"circle"\n'
            '\t"rectangle"\n'
            '\tNone'
            '\tpyvista.PolyData'
        )
    return legendface


def scale_point(camera, point, invert=False):
    """Scale a point using the camera's transform matrix.

    Parameters
    ----------
    camera : Camera
        The camera who's matrix to use.

    point : sequence[float]
        Scale point coordinates.

    invert : bool, default: False
        If ``True``, invert the matrix to transform the point out of
        the camera's transformed space. Default is ``False`` to
        transform a point from world coordinates to the camera's
        transformed space.

    Returns
    -------
    tuple
        Scaling of the camera in ``(x, y, z)``.

    """
    if invert:
        mtx = _vtk.vtkMatrix4x4()
        mtx.DeepCopy(camera.GetModelTransformMatrix())
        mtx.Invert()
    else:
        mtx = camera.GetModelTransformMatrix()
    scaled = mtx.MultiplyDoublePoint((point[0], point[1], point[2], 0.0))
    return (scaled[0], scaled[1], scaled[2])


class CameraPosition:
    """Container to hold camera location attributes.

    Parameters
    ----------
    position : sequence[float]
        Position of the camera.

    focal_point : sequence[float]
        The focal point of the camera.

    viewup : sequence[float]
        View up of the camera.

    """

    def __init__(self, position, focal_point, viewup):
        """Initialize a new camera position descriptor."""
        self._position = position
        self._focal_point = focal_point
        self._viewup = viewup

    def to_list(self):
        """Convert to a list of the position, focal point, and viewup.

        Returns
        -------
        list
            List of the position, focal point, and view up of the camera.

        Examples
        --------
        >>> import pyvista
        >>> pl = pyvista.Plotter()
        >>> pl.camera_position.to_list()
        [(0.0, 0.0, 1.0), (0.0, 0.0, 0.0), (0.0, 1.0, 0.0)]

        """
        return [self._position, self._focal_point, self._viewup]

    def __repr__(self):
        """List representation method."""
        return "[{},\n {},\n {}]".format(*self.to_list())

    def __getitem__(self, index):
        """Fetch a component by index location like a list."""
        return self.to_list()[index]

    def __eq__(self, other):
        """Comparison operator to act on list version of CameraPosition object."""
        if isinstance(other, CameraPosition):
            return self.to_list() == other.to_list()
        return self.to_list() == other

    @property
    def position(self):  # numpydoc ignore=RT01
        """Location of the camera in world coordinates."""
        return self._position

    @position.setter
    def position(self, value):  # numpydoc ignore=GL08
        self._position = value

    @property
    def focal_point(self):  # numpydoc ignore=RT01
        """Location of the camera's focus in world coordinates."""
        return self._focal_point

    @focal_point.setter
    def focal_point(self, value):  # numpydoc ignore=GL08
        self._focal_point = value

    @property
    def viewup(self):  # numpydoc ignore=RT01
        """Viewup vector of the camera."""
        return self._viewup

    @viewup.setter
    def viewup(self, value):  # numpydoc ignore=GL08
        self._viewup = value


class Renderer(_vtk.vtkOpenGLRenderer):
    """Renderer class."""

    # map camera_position string to an attribute
    CAMERA_STR_ATTR_MAP = {
        'xy': 'view_xy',
        'xz': 'view_xz',
        'yz': 'view_yz',
        'yx': 'view_yx',
        'zx': 'view_zx',
        'zy': 'view_zy',
        'iso': 'view_isometric',
    }

    def __init__(
        self, parent, border=True, border_color='w', border_width=2.0
    ):  # numpydoc ignore=PR01,RT01
        """Initialize the renderer."""
        super().__init__()
        self._actors = {}
        self.parent = parent  # weakref.proxy to the plotter from Renderers
        self._theme = parent.theme
        self.bounding_box_actor = None
        self.scale = [1.0, 1.0, 1.0]
        self.AutomaticLightCreationOff()
        self._labels = {}  # tracks labeled actors
        self._legend = None
        self._floor = None
        self._floors = []
        self._floor_kwargs = []
        # this keeps track of lights added manually to prevent garbage collection
        self._lights = []
        self._camera = Camera(self)
        self.SetActiveCamera(self._camera)
        self._empty_str = None  # used to track reference to a vtkStringArray
        self._shadow_pass = None
        self._render_passes = RenderPasses(self)
        self.cube_axes_actor = None

        # This is a private variable to keep track of how many colorbars exist
        # This allows us to keep adding colorbars without overlapping
        self._scalar_bar_slots = set(range(MAX_N_COLOR_BARS))
        self._scalar_bar_slot_lookup = {}
        self.__charts = None

        self._border_actor = None
        if border:
            self.add_border(border_color, border_width)

        self.set_color_cycler(self._theme.color_cycler)

    @property
    def camera_set(self) -> bool:  # numpydoc ignore=RT01
        """Get or set whether this camera has been configured."""
        if self.camera is None:  # pragma: no cover
            return False
        return self.camera.is_set

    @camera_set.setter
    def camera_set(self, is_set: bool):  # numpydoc ignore=GL08
        self.camera.is_set = is_set

    def set_color_cycler(self, color_cycler):
        """Set or reset this renderer's color cycler.

        This color cycler is iterated over by each sequential :class:`add_mesh() <pyvista.Plotter.add_mesh>`
        call to set the default color of the dataset being plotted.

        When setting, the value must be either a list of color-like objects,
        or a cycler of color-like objects. If the value passed is a single
        string, it must be one of:

            * ``'default'`` - Use the default color cycler (matches matplotlib's default)
            * ``'matplotlib`` - Dynamically get matplotlib's current theme's color cycler.
            * ``'all'`` - Cycle through all of the available colors in ``pyvista.plotting.colors.hexcolors``

        Setting to ``None`` will disable the use of the color cycler on this
        renderer.

        Parameters
        ----------
        color_cycler : str | cycler.Cycler | sequence[ColorLike]
            The colors to cycle through.

        Examples
        --------
        Set the default color cycler to iterate through red, green, and blue.

        >>> import pyvista as pv
        >>> pl = pv.Plotter()
        >>> pl.renderer.set_color_cycler(['red', 'green', 'blue'])
        >>> _ = pl.add_mesh(pv.Cone(center=(0, 0, 0)))  # red
        >>> _ = pl.add_mesh(pv.Cube(center=(1, 0, 0)))  # green
        >>> _ = pl.add_mesh(pv.Sphere(center=(1, 1, 0)))  # blue
        >>> _ = pl.add_mesh(pv.Cylinder(center=(0, 1, 0)))  # red again
        >>> pl.show()

        """
        cycler = get_cycler(color_cycler)
        if cycler is not None:
            # Color cycler - call object to generate `cycle` instance
            self._color_cycle = cycler()
        else:
            self._color_cycle = None

    @property
    def next_color(self):  # numpydoc ignore=RT01
        """Return next color from this renderer's color cycler."""
        if self._color_cycle is None:
            return self._theme.color
        return next(self._color_cycle)['color']

    @property
    def _charts(self):
        """Return the charts collection."""
        # lazy instantiation here to avoid creating the charts object unless needed.
        if self.__charts is None:
            self.__charts = Charts(self)
            self.AddObserver("StartEvent", partial(try_callback, self._before_render_event))
        return self.__charts

    @property
    def camera_position(self):  # numpydoc ignore=RT01
        """Return or set the camera position of active render window.

        Returns
        -------
        pyvista.CameraPosition
            Camera position.

        """
        return CameraPosition(
            scale_point(self.camera, self.camera.position, invert=True),
            scale_point(self.camera, self.camera.focal_point, invert=True),
            self.camera.up,
        )

    @camera_position.setter
    def camera_position(self, camera_location):  # numpydoc ignore=GL08
        if camera_location is None:
            return
        elif isinstance(camera_location, str):
            camera_location = camera_location.lower()
            if camera_location not in self.CAMERA_STR_ATTR_MAP:
                raise InvalidCameraError(
                    'Invalid view direction.  '
                    'Use one of the following:\n   '
                    f'{", ".join(self.CAMERA_STR_ATTR_MAP)}'
                )

            getattr(self, self.CAMERA_STR_ATTR_MAP[camera_location])()

        elif isinstance(camera_location[0], (int, float)):
            if len(camera_location) != 3:
                raise InvalidCameraError
            self.view_vector(camera_location)
        else:
            # check if a valid camera position
            if not isinstance(camera_location, CameraPosition):
                if not len(camera_location) == 3:
                    raise InvalidCameraError
                elif any([len(item) != 3 for item in camera_location]):
                    raise InvalidCameraError

            # everything is set explicitly
            self.camera.position = scale_point(self.camera, camera_location[0], invert=False)
            self.camera.focal_point = scale_point(self.camera, camera_location[1], invert=False)
            self.camera.up = camera_location[2]

        # reset clipping range
        self.reset_camera_clipping_range()
        self.camera_set = True
        self.Modified()

    def reset_camera_clipping_range(self):
        """Reset the camera clipping range based on the bounds of the visible actors.

        This ensures that no props are cut off
        """
        self.ResetCameraClippingRange()

    @property
    def camera(self):  # numpydoc ignore=RT01
        """Return the active camera for the rendering scene."""
        return self._camera

    @camera.setter
    def camera(self, source):  # numpydoc ignore=GL08
        self._camera = source
        self.SetActiveCamera(self._camera)
        self.camera_position = CameraPosition(
            scale_point(source, source.position, invert=True),
            scale_point(source, source.focal_point, invert=True),
            source.up,
        )
        self.Modified()
        self.camera_set = True

    @property
    def bounds(self) -> BoundsLike:  # numpydoc ignore=RT01
        """Return the bounds of all actors present in the rendering window."""
        the_bounds = np.array([np.inf, -np.inf, np.inf, -np.inf, np.inf, -np.inf])

        def _update_bounds(bounds):
            def update_axis(ax):
                if bounds[ax * 2] < the_bounds[ax * 2]:
                    the_bounds[ax * 2] = bounds[ax * 2]
                if bounds[ax * 2 + 1] > the_bounds[ax * 2 + 1]:
                    the_bounds[ax * 2 + 1] = bounds[ax * 2 + 1]

            for ax in range(3):
                update_axis(ax)
            return

        for actor in self._actors.values():
            if isinstance(actor, (_vtk.vtkCubeAxesActor, _vtk.vtkLightActor)):
                continue
            if (
                hasattr(actor, 'GetBounds')
                and actor.GetBounds() is not None
                and id(actor) != id(self.bounding_box_actor)
            ):
                _update_bounds(actor.GetBounds())

        if np.any(np.abs(the_bounds)):
            the_bounds[the_bounds == np.inf] = -1.0
            the_bounds[the_bounds == -np.inf] = 1.0

        return cast(BoundsLike, tuple(the_bounds))

    @property
    def length(self):  # numpydoc ignore=RT01
        """Return the length of the diagonal of the bounding box of the scene.

        Returns
        -------
        float
            Length of the diagional of the bounding box.
        """
        return pyvista.Box(self.bounds).length

    @property
    def center(self):  # numpydoc ignore=RT01
        """Return the center of the bounding box around all data present in the scene.

        Returns
        -------
        list
            Cartesian coordinates of the center.

        """
        bounds = self.bounds
        x = (bounds[1] + bounds[0]) / 2
        y = (bounds[3] + bounds[2]) / 2
        z = (bounds[5] + bounds[4]) / 2
        return [x, y, z]

    @property
    def background_color(self):  # numpydoc ignore=RT01
        """Return the background color of this renderer."""
        return Color(self.GetBackground())

    @background_color.setter
    def background_color(self, color):  # numpydoc ignore=GL08
        self.set_background(color)
        self.Modified()

    def _before_render_event(self, *args, **kwargs):
        """Notify all charts about render event."""
        for chart in self._charts:
            chart._render_event(*args, **kwargs)

    def enable_depth_peeling(self, number_of_peels=None, occlusion_ratio=None):
        """Enable depth peeling to improve rendering of translucent geometry.

        Parameters
        ----------
        number_of_peels : int, optional
            The maximum number of peeling layers. Initial value is 4
            and is set in the ``pyvista.global_theme``. A special value of
            0 means no maximum limit.  It has to be a positive value.

        occlusion_ratio : float, optional
            The threshold under which the depth peeling algorithm
            stops to iterate over peel layers. This is the ratio of
            the number of pixels that have been touched by the last
            layer over the total number of pixels of the viewport
            area. Initial value is 0.0, meaning rendering has to be
            exact. Greater values may speed up the rendering with
            small impact on the quality.

        Returns
        -------
        bool
            If depth peeling is supported.

        """
        if number_of_peels is None:
            number_of_peels = self._theme.depth_peeling.number_of_peels
        if occlusion_ratio is None:
            occlusion_ratio = self._theme.depth_peeling.occlusion_ratio
        depth_peeling_supported = check_depth_peeling(number_of_peels, occlusion_ratio)
        if depth_peeling_supported:
            self.SetUseDepthPeeling(True)
            self.SetMaximumNumberOfPeels(number_of_peels)
            self.SetOcclusionRatio(occlusion_ratio)
        self.Modified()
        return depth_peeling_supported

    def disable_depth_peeling(self):
        """Disable depth peeling."""
        self.SetUseDepthPeeling(False)
        self.Modified()

    def enable_anti_aliasing(self, aa_type='ssaa'):
        """Enable anti-aliasing.

        Parameters
        ----------
        aa_type : str, default: 'ssaa'
            Anti-aliasing type. Either ``"fxaa"`` or ``"ssaa"``.

        """
        if not isinstance(aa_type, str):
            raise TypeError(f'`aa_type` must be a string, not {type(aa_type)}')
        aa_type = aa_type.lower()

        if aa_type == 'fxaa':
            if uses_egl():  # pragma: no cover
                # only display the warning when not building documentation
                if not pyvista.BUILDING_GALLERY:
                    warnings.warn(
                        "VTK compiled with OSMesa/EGL does not properly support "
                        "FXAA anti-aliasing and SSAA will be used instead."
                    )
                self._render_passes.enable_ssaa_pass()
                return
            self._enable_fxaa()

        elif aa_type == 'ssaa':
            self._render_passes.enable_ssaa_pass()

        else:
            raise ValueError(f'Invalid `aa_type` "{aa_type}". Should be either "fxaa" or "ssaa"')

    def disable_anti_aliasing(self):
        """Disable all anti-aliasing."""
        self._render_passes.disable_ssaa_pass()
        self.SetUseFXAA(False)
        self.Modified()

    def _enable_fxaa(self):
        """Enable FXAA anti-aliasing."""
        self.SetUseFXAA(True)
        self.Modified()

    def _disable_fxaa(self):
        """Disable FXAA anti-aliasing."""
        self.SetUseFXAA(False)
        self.Modified()

    def add_border(self, color='white', width=2.0):
        """Add borders around the frame.

        Parameters
        ----------
        color : ColorLike, default: "white"
            Color of the border.

        width : float, default: 2.0
            Width of the border.

        Returns
        -------
        vtk.vtkActor2D
            Border actor.

        """
        points = np.array([[1.0, 1.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 0.0], [1.0, 0.0, 0.0]])

        lines = np.array([[2, 0, 1], [2, 1, 2], [2, 2, 3], [2, 3, 0]]).ravel()

        poly = pyvista.PolyData()
        poly.points = points
        poly.lines = lines

        coordinate = _vtk.vtkCoordinate()
        coordinate.SetCoordinateSystemToNormalizedViewport()

        mapper = _vtk.vtkPolyDataMapper2D()
        mapper.SetInputData(poly)
        mapper.SetTransformCoordinate(coordinate)

        actor = _vtk.vtkActor2D()
        actor.SetMapper(mapper)
        actor.GetProperty().SetColor(Color(color).float_rgb)
        actor.GetProperty().SetLineWidth(width)

        self.AddViewProp(actor)
        self.Modified()

        self._border_actor = actor
        return actor

    @property
    def has_border(self):  # numpydoc ignore=RT01
        """Return if the renderer has a border."""
        return self._border_actor is not None

    @property
    def border_width(self):  # numpydoc ignore=RT01
        """Return the border width."""
        if self.has_border:
            return self._border_actor.GetProperty().GetLineWidth()
        return 0

    @property
    def border_color(self):  # numpydoc ignore=RT01
        """Return the border color."""
        if self.has_border:
            return Color(self._border_actor.GetProperty().GetColor())
        return None

    def add_chart(self, chart, *charts):
        """Add a chart to this renderer.

        Parameters
        ----------
        chart : Chart
            Chart to add to renderer.

        *charts : Chart
            Charts to add to renderer.

        Examples
        --------
        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> _ = chart.plot(range(10), range(10))
        >>> pl = pyvista.Plotter()
        >>> pl.add_chart(chart)
        >>> pl.show()

        """
        if _vtk.vtkRenderingContextOpenGL2 is None:  # pragma: no cover
            from pyvista.core.errors import VTKVersionError

            raise VTKVersionError(
                "VTK is missing vtkRenderingContextOpenGL2. Try installing VTK v9.1.0 or newer."
            )
        self._charts.add_chart(chart, *charts)

    @property
    def has_charts(self):  # numpydoc ignore=RT01
        """Return whether this renderer has charts."""
        return self.__charts is not None

    @wraps(Charts.set_interaction)
    def set_chart_interaction(self, interactive, toggle=False):  # numpydoc ignore=PR01,RT01
        """Wrap ``Charts.set_interaction``."""
        # Make sure we don't create the __charts object if this renderer has no charts yet.
        return self._charts.set_interaction(interactive, toggle) if self.has_charts else []

    @wraps(Charts.get_charts_by_pos)
    def _get_charts_by_pos(self, pos):
        """Wrap ``Charts.get_charts_by_pos``."""
        # Make sure we don't create the __charts object if this renderer has no charts yet.
        return self._charts.get_charts_by_pos(pos) if self.has_charts else []

    def remove_chart(self, chart_or_index):
        """Remove a chart from this renderer.

        Parameters
        ----------
        chart_or_index : Chart or int
            Either the chart to remove from this renderer or its index in the collection of charts.

        Examples
        --------
        First define a function to add two charts to a renderer.

        >>> import pyvista
        >>> def plotter_with_charts():
        ...     pl = pyvista.Plotter()
        ...     pl.background_color = 'w'
        ...     chart_left = pyvista.Chart2D(size=(0.5, 1))
        ...     _ = chart_left.line([0, 1, 2], [2, 1, 3])
        ...     pl.add_chart(chart_left)
        ...     chart_right = pyvista.Chart2D(size=(0.5, 1), loc=(0.5, 0))
        ...     _ = chart_right.line([0, 1, 2], [3, 1, 2])
        ...     pl.add_chart(chart_right)
        ...     return pl, chart_left, chart_right
        ...
        >>> pl, *_ = plotter_with_charts()
        >>> pl.show()

        Now reconstruct the same plotter but remove the right chart by index.

        >>> pl, *_ = plotter_with_charts()
        >>> pl.remove_chart(1)
        >>> pl.show()

        Finally, remove the left chart by reference.

        >>> pl, chart_left, chart_right = plotter_with_charts()
        >>> pl.remove_chart(chart_left)
        >>> pl.show()

        """
        # Make sure we don't create the __charts object if this renderer has no charts yet.
        if self.has_charts:
            self._charts.remove_chart(chart_or_index)

    @property
    def actors(self):  # numpydoc ignore=RT01
        """Return a dictionary of actors assigned to this renderer."""
        return self._actors

    def add_actor(
        self,
        actor,
        reset_camera=False,
        name=None,
        culling=False,
        pickable=True,
        render=True,
        remove_existing_actor=True,
    ):
        """Add an actor to render window.

        Creates an actor if input is a mapper.

        Parameters
        ----------
        actor : vtk.vtkActor | vtk.vtkMapper | pyvista.Actor
            The actor to be added. Can be either ``vtkActor`` or ``vtkMapper``.

        reset_camera : bool, default: False
            Resets the camera when ``True``.

        name : str, optional
            Name to assign to the actor.  Defaults to the memory address.

        culling : str, default: False
            Does not render faces that are culled. Options are
            ``'front'`` or ``'back'``. This can be helpful for dense
            surface meshes, especially when edges are visible, but can
            cause flat meshes to be partially displayed.

        pickable : bool, default: True
            Whether to allow this actor to be pickable within the
            render window.

        render : bool, default: True
            If the render window is being shown, trigger a render
            after adding the actor.

        remove_existing_actor : bool, default: True
            Removes any existing actor if the named actor ``name`` is already
            present.

        Returns
        -------
        actor : vtk.vtkActor or pyvista.Actor
            The actor.

        actor_properties : vtk.Properties
            Actor properties.
        """
        # Remove actor by that name if present
        rv = None
        if name and remove_existing_actor:
            rv = self.remove_actor(name, reset_camera=False, render=False)

        if isinstance(actor, _vtk.vtkMapper):
            actor = Actor(mapper=actor, name=name)

        if isinstance(actor, Actor) and name:
            # WARNING: this will override the name if already set on Actor
            actor.name = name

        if name is None:
            if isinstance(actor, Actor):
                name = actor.name
            else:
                # Fallback for non-wrapped actors
                # e.g., vtkScalarBarActor
                name = actor.GetAddressAsString("")

        actor.SetPickable(pickable)
        # Apply this renderer's scale to the actor (which can be further scaled)
        if hasattr(actor, 'SetScale'):
            actor.SetScale(np.array(actor.GetScale()) * np.array(self.scale))
        self.AddActor(actor)  # must add actor before resetting camera
        self._actors[name] = actor

        if reset_camera:
            self.reset_camera(render)
        elif not self.camera_set and reset_camera is None and not rv:
            self.reset_camera(render)
        elif render:
            self.parent.render()

        self.update_bounds_axes()

        if isinstance(culling, str):
            culling = culling.lower()

        if culling:
            if culling in [True, 'back', 'backface', 'b']:
                try:
                    actor.GetProperty().BackfaceCullingOn()
                except AttributeError:  # pragma: no cover
                    pass
            elif culling in ['front', 'frontface', 'f']:
                try:
                    actor.GetProperty().FrontfaceCullingOn()
                except AttributeError:  # pragma: no cover
                    pass
            else:
                raise ValueError(f'Culling option ({culling}) not understood.')

        self.Modified()

        prop = None
        if hasattr(actor, 'GetProperty'):
            prop = actor.GetProperty()

        return actor, prop

    def add_axes_at_origin(
        self,
        x_color=None,
        y_color=None,
        z_color=None,
        xlabel='X',
        ylabel='Y',
        zlabel='Z',
        line_width=2,
        labels_off=False,
    ):
        """Add axes actor at origin.

        Parameters
        ----------
        x_color : ColorLike, optional
            The color of the x axes arrow.

        y_color : ColorLike, optional
            The color of the y axes arrow.

        z_color : ColorLike, optional
            The color of the z axes arrow.

        xlabel : str, default: "X"
            The label of the x axes arrow.

        ylabel : str, default: "Y"
            The label of the y axes arrow.

        zlabel : str, default: "Z"
            The label of the z axes arrow.

        line_width : int, default: 2
            Width of the arrows.

        labels_off : bool, default: False
            Disables the label text when ``True``.

        Returns
        -------
        vtk.vtkAxesActor
            Actor of the axes.

        Examples
        --------
        >>> import pyvista
        >>> pl = pyvista.Plotter()
        >>> _ = pl.add_mesh(pyvista.Sphere(center=(2, 0, 0)), color='r')
        >>> _ = pl.add_mesh(pyvista.Sphere(center=(0, 2, 0)), color='g')
        >>> _ = pl.add_mesh(pyvista.Sphere(center=(0, 0, 2)), color='b')
        >>> _ = pl.add_axes_at_origin()
        >>> pl.show()

        """
        self._marker_actor = create_axes_marker(
            line_width=line_width,
            x_color=x_color,
            y_color=y_color,
            z_color=z_color,
            xlabel=xlabel,
            ylabel=ylabel,
            zlabel=zlabel,
            labels_off=labels_off,
        )
        self.AddActor(self._marker_actor)
        memory_address = self._marker_actor.GetAddressAsString("")
        self._actors[memory_address] = self._marker_actor
        self.Modified()
        return self._marker_actor

    def add_orientation_widget(
        self, actor, interactive=None, color=None, opacity=1.0, viewport=None
    ):
        """Use the given actor in an orientation marker widget.

        Color and opacity are only valid arguments if a mesh is passed.

        Parameters
        ----------
        actor : vtk.vtkActor | pyvista.DataSet
            The mesh or actor to use as the marker.

        interactive : bool, optional
            Control if the orientation widget is interactive.  By
            default uses the value from
            :attr:`pyvista.global_theme.interactive
            <pyvista.plotting.themes.Theme.interactive>`.

        color : ColorLike, optional
            The color of the actor.  This only applies if ``actor`` is
            a :class:`pyvista.DataSet`.

        opacity : int | float, default: 1.0
            Opacity of the marker.

        viewport : sequence[float], optional
            Viewport ``(xstart, ystart, xend, yend)`` of the widget.

        Returns
        -------
        vtk.vtkOrientationMarkerWidget
            Orientation marker widget.

        Examples
        --------
        Use an Arrow as the orientation widget.

        >>> import pyvista
        >>> pl = pyvista.Plotter()
        >>> actor = pl.add_mesh(pyvista.Cube(), show_edges=True)
        >>> actor = pl.add_orientation_widget(pyvista.Arrow(), color='r')
        >>> pl.show()

        """
        if isinstance(actor, pyvista.DataSet):
            mapper = _vtk.vtkDataSetMapper()
            mesh = actor.copy()
            mesh.clear_data()
            mapper.SetInputData(mesh)
            actor = pyvista.Actor(mapper=mapper)
            if color is not None:
                actor.prop.color = color
            actor.prop.opacity = opacity
        if hasattr(self, 'axes_widget'):
            # Delete the old one
            self.axes_widget.EnabledOff()
            self.Modified()
            del self.axes_widget
        if interactive is None:
            interactive = self._theme.interactive
        self.axes_widget = _vtk.vtkOrientationMarkerWidget()
        self.axes_widget.SetOrientationMarker(actor)
        if hasattr(self.parent, 'iren'):
            self.axes_widget.SetInteractor(self.parent.iren.interactor)
            self.axes_widget.SetEnabled(1)
            self.axes_widget.SetInteractive(interactive)
        self.axes_widget.SetCurrentRenderer(self)
        if viewport is not None:
            self.axes_widget.SetViewport(viewport)
        self.Modified()
        return self.axes_widget

    def add_axes(
        self,
        interactive=None,
        line_width=2,
        color=None,
        x_color=None,
        y_color=None,
        z_color=None,
        xlabel='X',
        ylabel='Y',
        zlabel='Z',
        labels_off=False,
        box=None,
        box_args=None,
        viewport=(0, 0, 0.2, 0.2),
        marker_args=None,
        **kwargs,
    ):
        """Add an interactive axes widget in the bottom left corner.

        Parameters
        ----------
        interactive : bool, optional
            Enable this orientation widget to be moved by the user.

        line_width : int, default: 2
            The width of the marker lines.

        color : ColorLike, optional
            Color of the labels.

        x_color : ColorLike, optional
            Color used for the x axis arrow.  Defaults to theme axes parameters.

        y_color : ColorLike, optional
            Color used for the y axis arrow.  Defaults to theme axes parameters.

        z_color : ColorLike, optional
            Color used for the z axis arrow.  Defaults to theme axes parameters.

        xlabel : str, default: "X"
            Text used for the x axis.

        ylabel : str, default: "Y"
            Text used for the y axis.

        zlabel : str, default: "Z"
            Text used for the z axis.

        labels_off : bool, default: false
            Enable or disable the text labels for the axes.

        box : bool, optional
            Show a box orientation marker. Use ``box_args`` to adjust.
            See :func:`pyvista.create_axes_orientation_box` for details.

        box_args : dict, optional
            Parameters for the orientation box widget when
            ``box=True``. See the parameters of
            :func:`pyvista.create_axes_orientation_box`.

        viewport : sequence[float], default: (0, 0, 0.2, 0.2)
            Viewport ``(xstart, ystart, xend, yend)`` of the widget.

        marker_args : dict, optional
            Marker arguments.

            .. deprecated:: 0.37.0
               Use ``**kwargs`` for passing parameters for the orientation
               marker widget. See the parameters of
               :func:`pyvista.create_axes_marker`.

        **kwargs : dict, optional
            Used for passing parameters for the orientation marker
            widget. See the parameters of :func:`pyvista.create_axes_marker`.

        Returns
        -------
        vtk.vtkAxesActor
            Axes actor.

        Examples
        --------
        Show axes without labels and with thick lines.

        >>> import pyvista
        >>> pl = pyvista.Plotter()
        >>> actor = pl.add_mesh(pyvista.Box(), show_edges=True)
        >>> _ = pl.add_axes(line_width=5, labels_off=True)
        >>> pl.show()

        Use the axes orientation widget instead of the default arrows.

        >>> pl = pyvista.Plotter()
        >>> actor = pl.add_mesh(pyvista.Sphere())
        >>> _ = pl.add_axes(box=True)
        >>> pl.show()

        Specify more parameters for the axes marker.

        >>> import pyvista
        >>> pl = pyvista.Plotter()
        >>> actor = pl.add_mesh(pyvista.Box(), show_edges=True)
        >>> _ = pl.add_axes(
        ...     line_width=5,
        ...     cone_radius=0.6,
        ...     shaft_length=0.7,
        ...     tip_length=0.3,
        ...     ambient=0.5,
        ...     label_size=(0.4, 0.16),
        ... )
        >>> pl.show()

        """
        # Deprecated on v0.37.0, estimated removal on v0.40.0
        if marker_args is not None:  # pragma: no cover
            warnings.warn(
                "Use of `marker_args` is deprecated. Use `**kwargs` instead.",
                PyVistaDeprecationWarning,
            )
            kwargs.update(marker_args)

        if interactive is None:
            interactive = self._theme.interactive
        if hasattr(self, 'axes_widget'):
            self.axes_widget.EnabledOff()
            self.Modified()
            del self.axes_widget
        if box is None:
            box = self._theme.axes.box
        if box:
            if box_args is None:
                box_args = {}
            self.axes_actor = create_axes_orientation_box(
                label_color=color,
                line_width=line_width,
                x_color=x_color,
                y_color=y_color,
                z_color=z_color,
                xlabel=xlabel,
                ylabel=ylabel,
                zlabel=zlabel,
                labels_off=labels_off,
                **box_args,
            )
        else:
            self.axes_actor = create_axes_marker(
                label_color=color,
                line_width=line_width,
                x_color=x_color,
                y_color=y_color,
                z_color=z_color,
                xlabel=xlabel,
                ylabel=ylabel,
                zlabel=zlabel,
                labels_off=labels_off,
                **kwargs,
            )
        axes_widget = self.add_orientation_widget(
            self.axes_actor, interactive=interactive, color=None
        )
        axes_widget.SetViewport(viewport)
        return self.axes_actor

    def hide_axes(self):
        """Hide the axes orientation widget.

        Examples
        --------
        >>> import pyvista as pv
        >>> pl = pv.Plotter()
        >>> pl.hide_axes()

        """
        if hasattr(self, 'axes_widget') and self.axes_widget.GetEnabled():
            self.axes_widget.EnabledOff()
            self.Modified()

    def show_axes(self):
        """Show the axes orientation widget.

        Examples
        --------
        >>> import pyvista
        >>> pl = pyvista.Plotter()
        >>> pl.show_axes()

        """
        if hasattr(self, 'axes_widget'):
            self.axes_widget.EnabledOn()
            self.axes_widget.SetCurrentRenderer(self)
        else:
            self.add_axes()
        self.Modified()

    @property
    def axes_enabled(self):  # numpydoc ignore=RT01
        """Return ``True`` when axes are enabled.

        Examples
        --------
        >>> import pyvista
        >>> pl = pyvista.Plotter()
        >>> pl.hide_axes()
        >>> pl.renderer.axes_enabled
        False

        """
        if hasattr(self, 'axes_widget'):
            return bool(self.axes_widget.GetEnabled())
        return False

    def show_bounds(
        self,
        mesh=None,
        bounds=None,
        axes_ranges=None,
        show_xaxis=True,
        show_yaxis=True,
        show_zaxis=True,
        show_xlabels=True,
        show_ylabels=True,
        show_zlabels=True,
        bold=True,
        font_size=None,
        font_family=None,
        color=None,
        xtitle='X Axis',
        ytitle='Y Axis',
        ztitle='Z Axis',
        n_xlabels=5,
        n_ylabels=5,
        n_zlabels=5,
        use_2d=False,
        grid=None,
        location='closest',
        ticks=None,
        all_edges=False,
        corner_factor=0.5,
        fmt=None,
        minor_ticks=False,
        padding=0.0,
        use_3d_text=True,
        render=None,
        **kwargs,
    ):
        """Add bounds axes.

        Shows the bounds of the most recent input mesh unless mesh is
        specified.

        Parameters
        ----------
        mesh : pyvista.DataSet | pyvista.MultiBlock, optional
            Input mesh to draw bounds axes around.

        bounds : sequence[float], optional
            Bounds to override mesh bounds in the form ``[xmin, xmax,
            ymin, ymax, zmin, zmax]``.

        axes_ranges : sequence[float], optional
            When set, these values override the values that are shown on the
            axes. This can be useful when plotting scaled datasets or if you wish
            to manually display different values. These values must be in the
            form:

            ``[xmin, xmax, ymin, ymax, zmin, zmax]``.

        show_xaxis : bool, default: True
            Makes X axis visible.

        show_yaxis : bool, default: True
            Makes Y axis visible.

        show_zaxis : bool, default: True
            Makes Z axis visible.

        show_xlabels : bool, default: True
            Shows X labels.

        show_ylabels : bool, default: True
            Shows Y labels.

        show_zlabels : bool, default: True
            Shows Z labels.

        bold : bool, default: True
            Bolds axis labels and numbers.

        font_size : float, optional
            Sets the size of the label font. Defaults to
            :attr:`pyvista.global_theme.font.size
            <pyvista.plotting.themes._Font.size>`.

        font_family : str, optional
            Font family.  Must be either ``'courier'``, ``'times'``,
            or ``'arial'``. Defaults to :attr:`pyvista.global_theme.font.family
            <pyvista.plotting.themes._Font.family>`.

        color : ColorLike, optional
            Color of all labels and axis titles.  Defaults to
            :attr:`pyvista.global_theme.font.color
            <pyvista.plotting.themes._Font.color>`.

            Either a string, RGB list, or hex color string.  For
            example:

            * ``color='white'``
            * ``color='w'``
            * ``color=[1.0, 1.0, 1.0]``
            * ``color='#FFFFFF'``

        xtitle : str, default: "X Axis"
            Title of the X axis.  Default ``"X Axis"``.

        ytitle : str, default: "Y Axis"
            Title of the Y axis.  Default ``"Y Axis"``.

        ztitle : str, default: "Z Axis"
            Title of the Z axis.  Default ``"Z Axis"``.

        n_xlabels : int, default: 5
            Number of labels for the X axis.

        n_ylabels : int, default: 5
            Number of labels for the Y axis.

        n_zlabels : int, default: 5
            Number of labels for the Z axis.

        use_2d : bool, default: False
            This can be enabled for smoother plotting.

        grid : bool or str, optional
            Add grid lines to the backface (``True``, ``'back'``, or
            ``'backface'``) or to the frontface (``'front'``,
            ``'frontface'``) of the axes actor.

        location : str, default: "closest"
            Set how the axes are drawn: either static (``'all'``), closest
            triad (``'front'``, ``'closest'``, ``'default'``), furthest triad
            (``'back'``, ``'furthest'``), static closest to the origin
            (``'origin'``), or outer edges (``'outer'``) in relation to the
            camera position.

        ticks : str, optional
            Set how the ticks are drawn on the axes grid. Options include:
            ``'inside', 'outside', 'both'``.

        all_edges : bool, default: False
            Adds an unlabeled and unticked box at the boundaries of
            plot. Useful for when wanting to plot outer grids while
            still retaining all edges of the boundary.

        corner_factor : float, default: 0.5
            If ``all_edges``, this is the factor along each axis to
            draw the default box. Default shows the full box.

        fmt : str, optional
            A format string defining how tick labels are generated from
            tick positions. A default is looked up on the active theme.

        minor_ticks : bool, default: False
            If ``True``, also plot minor ticks on all axes.

        padding : float, default: 0.0
            An optional percent padding along each axial direction to
            cushion the datasets in the scene from the axes
            annotations. Defaults no padding.

        use_3d_text : bool, default: True
            Use ``vtkTextActor3D`` for titles and labels.

        render : bool, optional
            If the render window is being shown, trigger a render
            after showing bounds.

        **kwargs : dict, optional
            Deprecated keyword arguments.

        Returns
        -------
        vtk.vtkCubeAxesActor
            Bounds actor.

        Examples
        --------
        >>> import pyvista as pv
        >>> from pyvista import examples

        >>> mesh = pv.Sphere()
        >>> plotter = pv.Plotter()
        >>> actor = plotter.add_mesh(mesh)
        >>> actor = plotter.show_bounds(
        ...     grid='front',
        ...     location='outer',
        ...     all_edges=True,
        ... )
        >>> plotter.show()

        Control how many labels are displayed.

        >>> mesh = examples.load_random_hills()

        >>> plotter = pv.Plotter()
        >>> actor = plotter.add_mesh(
        ...     mesh, cmap='terrain', show_scalar_bar=False
        ... )
        >>> actor = plotter.show_bounds(
        ...     grid='back',
        ...     location='outer',
        ...     ticks='both',
        ...     n_xlabels=2,
        ...     n_ylabels=2,
        ...     n_zlabels=2,
        ...     xtitle='Easting',
        ...     ytitle='Northing',
        ...     ztitle='Elevation',
        ... )
        >>> plotter.show()

        Hide labels, but still show axis titles.

        >>> plotter = pv.Plotter()
        >>> actor = plotter.add_mesh(
        ...     mesh, cmap='terrain', show_scalar_bar=False
        ... )
        >>> actor = plotter.show_bounds(
        ...     grid='back',
        ...     location='outer',
        ...     ticks='both',
        ...     show_xlabels=False,
        ...     show_ylabels=False,
        ...     show_zlabels=False,
        ...     xtitle='Easting',
        ...     ytitle='Northing',
        ...     ztitle='Elevation',
        ... )
        >>> plotter.show()

        """
        self.remove_bounds_axes()

        if font_family is None:
            font_family = self._theme.font.family
        if font_size is None:
            font_size = self._theme.font.size
        if fmt is None:
            fmt = self._theme.font.fmt
        if fmt is None:
            fmt = '%.1f'  # fallback

        if 'xlabel' in kwargs:  # pragma: no cover
            xtitle = kwargs.pop('xlabel')
            warnings.warn(
                "`xlabel` is deprecated. Use `xtitle` instead.",
                PyVistaDeprecationWarning,
            )
        if 'ylabel' in kwargs:  # pragma: no cover
            ytitle = kwargs.pop('ylabel')
            warnings.warn(
                "`ylabel` is deprecated. Use `ytitle` instead.",
                PyVistaDeprecationWarning,
            )
        if 'zlabel' in kwargs:  # pragma: no cover
            ztitle = kwargs.pop('zlabel')
            warnings.warn(
                "`zlabel` is deprecated. Use `ztitle` instead.",
                PyVistaDeprecationWarning,
            )
        assert_empty_kwargs(**kwargs)

        color = Color(color, default_color=self._theme.font.color)

        if mesh is None and bounds is None:
            # Use the bounds of all data in the rendering window
            bounds = np.array(self.bounds)
        elif bounds is None:
            # otherwise, use the bounds of the mesh (if available)
            bounds = np.array(mesh.bounds)
        else:
            bounds = np.asanyarray(bounds, dtype=float)

        # create actor
        cube_axes_actor = pyvista.CubeAxesActor(
            self.camera,
            minor_ticks=minor_ticks,
            tick_location=ticks,
            x_title=xtitle,
            y_title=ytitle,
            z_title=ztitle,
            x_axis_visibility=show_xaxis,
            y_axis_visibility=show_yaxis,
            z_axis_visibility=show_zaxis,
            x_label_format=fmt,
            y_label_format=fmt,
            z_label_format=fmt,
            x_label_visibility=show_xlabels,
            y_label_visibility=show_ylabels,
            z_label_visibility=show_zlabels,
            n_xlabels=n_xlabels,
            n_ylabels=n_ylabels,
            n_zlabels=n_zlabels,
        )

        cube_axes_actor.use_2d_mode = use_2d or not np.allclose(self.scale, [1.0, 1.0, 1.0])

        if grid:
            grid = 'back' if grid is True else grid
            if not isinstance(grid, str):
                raise TypeError(f'`grid` must be a str, not {type(grid)}')
            grid = grid.lower()
            if grid in ('front', 'frontface'):
                cube_axes_actor.SetGridLineLocation(cube_axes_actor.VTK_GRID_LINES_CLOSEST)
            elif grid in ('both', 'all'):
                cube_axes_actor.SetGridLineLocation(cube_axes_actor.VTK_GRID_LINES_ALL)
            elif grid in ('back', True):
                cube_axes_actor.SetGridLineLocation(cube_axes_actor.VTK_GRID_LINES_FURTHEST)
            else:
                raise ValueError(f'`grid` must be either "front", "back, or, "all", not {grid}')
            # Only show user desired grid lines
            cube_axes_actor.SetDrawXGridlines(show_xaxis)
            cube_axes_actor.SetDrawYGridlines(show_yaxis)
            cube_axes_actor.SetDrawZGridlines(show_zaxis)
            # Set the colors
            cube_axes_actor.GetXAxesGridlinesProperty().SetColor(color.float_rgb)
            cube_axes_actor.GetYAxesGridlinesProperty().SetColor(color.float_rgb)
            cube_axes_actor.GetZAxesGridlinesProperty().SetColor(color.float_rgb)

        if isinstance(location, str):
            location = location.lower()
            if location in ('all'):
                cube_axes_actor.SetFlyModeToStaticEdges()
            elif location in ('origin'):
                cube_axes_actor.SetFlyModeToStaticTriad()
            elif location in ('outer'):
                cube_axes_actor.SetFlyModeToOuterEdges()
            elif location in ('default', 'closest', 'front'):
                cube_axes_actor.SetFlyModeToClosestTriad()
            elif location in ('furthest', 'back'):
                cube_axes_actor.SetFlyModeToFurthestTriad()
            else:
                raise ValueError(
                    f'Value of location ("{location}") should be either "all", "origin",'
                    ' "outer", "default", "closest", "front", "furthest", or "back".'
                )
        elif location is not None:
            raise TypeError('location must be a string')

        if isinstance(padding, (int, float)) and 0.0 <= padding < 1.0:
            if not np.any(np.abs(bounds) == np.inf):
                cushion = (
                    np.array(
                        [
                            np.abs(bounds[1] - bounds[0]),
                            np.abs(bounds[3] - bounds[2]),
                            np.abs(bounds[5] - bounds[4]),
                        ]
                    )
                    * padding
                )
                bounds[::2] -= cushion
                bounds[1::2] += cushion
        else:
            raise ValueError(f'padding ({padding}) not understood. Must be float between 0 and 1')
        cube_axes_actor.bounds = bounds

        # set axes ranges if input
        if axes_ranges is not None:
            if isinstance(axes_ranges, (collections.abc.Sequence, np.ndarray)):
                axes_ranges = np.asanyarray(axes_ranges)
            else:
                raise TypeError('Input axes_ranges must be a numeric sequence.')

            if not np.issubdtype(axes_ranges.dtype, np.number):
                raise TypeError('All of the elements of axes_ranges must be numbers.')

            # set the axes ranges
            if axes_ranges.shape != (6,):
                raise ValueError(
                    '`axes_ranges` must be passed as a [xmin, xmax, ymin, ymax, zmin, zmax] sequence.'
                )

            cube_axes_actor.x_axis_range = axes_ranges[0], axes_ranges[1]
            cube_axes_actor.y_axis_range = axes_ranges[2], axes_ranges[3]
            cube_axes_actor.z_axis_range = axes_ranges[4], axes_ranges[5]

        # set color
        cube_axes_actor.GetXAxesLinesProperty().SetColor(color.float_rgb)
        cube_axes_actor.GetYAxesLinesProperty().SetColor(color.float_rgb)
        cube_axes_actor.GetZAxesLinesProperty().SetColor(color.float_rgb)

        # set font
        font_family = parse_font_family(font_family)

        if not use_3d_text or not np.allclose(self.scale, [1.0, 1.0, 1.0]):
            use_3d_text = False
            cube_axes_actor.SetUseTextActor3D(False)
        else:
            cube_axes_actor.SetUseTextActor3D(True)

        props = [
            cube_axes_actor.GetTitleTextProperty(0),
            cube_axes_actor.GetTitleTextProperty(1),
            cube_axes_actor.GetTitleTextProperty(2),
            cube_axes_actor.GetLabelTextProperty(0),
            cube_axes_actor.GetLabelTextProperty(1),
            cube_axes_actor.GetLabelTextProperty(2),
        ]

        for prop in props:
            prop.SetColor(color.float_rgb)
            prop.SetFontFamily(font_family)
            prop.SetBold(bold)

            # this merely makes the font sharper
            if use_3d_text:
                prop.SetFontSize(50)

        # Note: font_size does nothing as a property, use SetScreenSize instead
        # Here, we normalize relative to 12 to give the user an illusion of
        # just changing the font size relative to a font size of 12. 10 is used
        # here since it's the default "screen size".
        cube_axes_actor.SetScreenSize(font_size / 12 * 10.0)

        self.add_actor(cube_axes_actor, reset_camera=False, pickable=False, render=render)
        self.cube_axes_actor = cube_axes_actor

        if all_edges:
            self.add_bounding_box(color=color, corner_factor=corner_factor)

        self.Modified()
        return cube_axes_actor

    def show_grid(self, **kwargs):
        """Show grid lines and bounds axes labels.

        A wrapped implementation of :func:`show_bounds()
        <pyvista.Renderer.show_bounds>` to change default behavior to use
        grid lines and showing the axes labels on the outer edges.

        This is intended to be similar to :func:`matplotlib.pyplot.grid`.

        Parameters
        ----------
        **kwargs : dict, optional
            See :func:`Renderer.show_bounds` for additional keyword
            arguments.

        Returns
        -------
        vtk.vtkAxesActor
            Bounds actor.

        Examples
        --------
        >>> import pyvista as pv
        >>> mesh = pv.Cone()
        >>> pl = pv.Plotter()
        >>> _ = pl.add_mesh(mesh)
        >>> _ = pl.show_grid()
        >>> pl.show()

        """
        kwargs.setdefault('grid', 'back')
        kwargs.setdefault('location', 'outer')
        kwargs.setdefault('ticks', 'both')
        return self.show_bounds(**kwargs)

    def remove_bounding_box(self, render=True):
        """Remove bounding box.

        Parameters
        ----------
        render : bool, default: True
            Trigger a render once the bounding box is removed.

        Examples
        --------
        >>> import pyvista
        >>> pl = pyvista.Plotter()
        >>> _ = pl.add_bounding_box()
        >>> pl.remove_bounding_box()

        """
        if hasattr(self, '_box_object'):
            actor = self.bounding_box_actor
            self.bounding_box_actor = None
            del self._box_object
            self.remove_actor(actor, reset_camera=False, render=render)
            self.Modified()

    def add_bounding_box(
        self,
        color="grey",
        corner_factor=0.5,
        line_width=None,
        opacity=1.0,
        render_lines_as_tubes=False,
        lighting=None,
        reset_camera=None,
        outline=True,
        culling='front',
    ):
        """Add an unlabeled and unticked box at the boundaries of plot.

        Useful for when wanting to plot outer grids while still
        retaining all edges of the boundary.

        Parameters
        ----------
        color : ColorLike, default: "grey"
            Color of all labels and axis titles.  Default white.
            Either a string, rgb sequence, or hex color string.  For
            example:

            * ``color='white'``
            * ``color='w'``
            * ``color=[1.0, 1.0, 1.0]``
            * ``color='#FFFFFF'``

        corner_factor : float, default: 0.5
            This is the factor along each axis to draw the default
            box. Default is 0.5 to show the full box.

        line_width : float, optional
            Thickness of lines.

        opacity : float, default: 1.0
            Opacity of mesh. Should be between 0 and 1.

        render_lines_as_tubes : bool, default: False
            Show lines as thick tubes rather than flat lines.  Control
            the width with ``line_width``.

        lighting : bool, optional
            Enable or disable directional lighting for this actor.

        reset_camera : bool, optional
            Reset camera position when ``True`` to include all actors.

        outline : bool, default: True
            Default is ``True``. when ``False``, a box with faces is
            shown with the specified culling.

        culling : str, default: "front"
            Does not render faces on the bounding box that are culled. Options
            are ``'front'`` or ``'back'``.

        Returns
        -------
        vtk.vtkActor
            VTK actor of the bounding box.

        Examples
        --------
        >>> import pyvista
        >>> pl = pyvista.Plotter()
        >>> _ = pl.add_mesh(pyvista.Sphere())
        >>> _ = pl.add_bounding_box(line_width=5, color='black')
        >>> pl.show()

        """
        if lighting is None:
            lighting = self._theme.lighting

        self.remove_bounding_box()
        if outline:
            self._bounding_box = _vtk.vtkOutlineCornerSource()
            self._bounding_box.SetCornerFactor(corner_factor)
        else:
            self._bounding_box = _vtk.vtkCubeSource()
        self._bounding_box.SetBounds(self.bounds)
        self._bounding_box.Update()
        self._box_object = wrap(self._bounding_box.GetOutput())
        name = f'BoundingBox({hex(id(self._box_object))})'

        mapper = _vtk.vtkDataSetMapper()
        mapper.SetInputData(self._box_object)
        self.bounding_box_actor, prop = self.add_actor(
            mapper, reset_camera=reset_camera, name=name, culling=culling, pickable=False
        )

        prop.SetColor(Color(color, default_color=self._theme.outline_color).float_rgb)
        prop.SetOpacity(opacity)
        if render_lines_as_tubes:
            prop.SetRenderLinesAsTubes(render_lines_as_tubes)

        # lighting display style
        if lighting is False:
            prop.LightingOff()

        # set line thickness
        if line_width:
            prop.SetLineWidth(line_width)

        prop.SetRepresentationToSurface()
        self.Modified()
        return self.bounding_box_actor

    def add_floor(
        self,
        face='-z',
        i_resolution=10,
        j_resolution=10,
        color=None,
        line_width=None,
        opacity=1.0,
        show_edges=False,
        lighting=False,
        edge_color=None,
        reset_camera=None,
        pad=0.0,
        offset=0.0,
        pickable=False,
        store_floor_kwargs=True,
    ):
        """Show a floor mesh.

        This generates planes at the boundaries of the scene to behave
        like floors or walls.

        Parameters
        ----------
        face : str, default: "-z"
            The face at which to place the plane. Options are
            (``'-z'``, ``'-y'``, ``'-x'``, ``'+z'``, ``'+y'``, and
            ``'+z'``). Where the ``-/+`` sign indicates on which side of
            the axis the plane will lie.  For example, ``'-z'`` would
            generate a floor on the XY-plane and the bottom of the
            scene (minimum z).

        i_resolution : int, default: 10
            Number of points on the plane in the i direction.

        j_resolution : int, default: 10
            Number of points on the plane in the j direction.

        color : ColorLike, optional
            Color of all labels and axis titles.  Default gray.
            Either a string, rgb list, or hex color string.

        line_width : int, optional
            Thickness of the edges. Only if ``show_edges`` is
            ``True``.

        opacity : float, default: 1.0
            The opacity of the generated surface.

        show_edges : bool, default: False
            Flag on whether to show the mesh edges for tiling.

        line_width : float, default: False
            Thickness of lines.  Only valid for wireframe and surface
            representations.

        lighting : bool, default: False
            Enable or disable view direction lighting.

        edge_color : ColorLike, optional
            Color of the edges of the mesh.

        reset_camera : bool, optional
            Resets the camera when ``True`` after adding the floor.

        pad : float, default: 0.0
            Percentage padding between 0 and 1.

        offset : float, default: 0.0
            Percentage offset along plane normal.

        pickable : bool, default: false
            Make this floor actor pickable in the renderer.

        store_floor_kwargs : bool, default: True
            Stores the keyword arguments used when adding this floor.
            Useful when updating the bounds and regenerating the
            floor.

        Returns
        -------
        vtk.vtkActor
            VTK actor of the floor.

        Examples
        --------
        Add a floor below a sphere and plot it.

        >>> import pyvista
        >>> pl = pyvista.Plotter()
        >>> actor = pl.add_mesh(pyvista.Sphere())
        >>> actor = pl.add_floor()
        >>> pl.show()

        """
        if store_floor_kwargs:
            kwargs = locals()
            kwargs.pop('self')
            self._floor_kwargs.append(kwargs)
        ranges = np.array(self.bounds).reshape(-1, 2).ptp(axis=1)
        ranges += ranges * pad
        center = np.array(self.center)
        if face.lower() in '-z':
            center[2] = self.bounds[4] - (ranges[2] * offset)
            normal = (0, 0, 1)
            i_size = ranges[0]
            j_size = ranges[1]
        elif face.lower() in '-y':
            center[1] = self.bounds[2] - (ranges[1] * offset)
            normal = (0, 1, 0)
            i_size = ranges[0]
            j_size = ranges[2]
        elif face.lower() in '-x':
            center[0] = self.bounds[0] - (ranges[0] * offset)
            normal = (1, 0, 0)
            i_size = ranges[2]
            j_size = ranges[1]
        elif face.lower() in '+z':
            center[2] = self.bounds[5] + (ranges[2] * offset)
            normal = (0, 0, -1)
            i_size = ranges[0]
            j_size = ranges[1]
        elif face.lower() in '+y':
            center[1] = self.bounds[3] + (ranges[1] * offset)
            normal = (0, -1, 0)
            i_size = ranges[0]
            j_size = ranges[2]
        elif face.lower() in '+x':
            center[0] = self.bounds[1] + (ranges[0] * offset)
            normal = (-1, 0, 0)
            i_size = ranges[2]
            j_size = ranges[1]
        else:
            raise NotImplementedError(f'Face ({face}) not implementd')
        self._floor = pyvista.Plane(
            center=center,
            direction=normal,
            i_size=i_size,
            j_size=j_size,
            i_resolution=i_resolution,
            j_resolution=j_resolution,
        )
        self._floor.clear_data()

        if lighting is None:
            lighting = self._theme.lighting

        self.remove_bounding_box()
        mapper = _vtk.vtkDataSetMapper()
        mapper.SetInputData(self._floor)
        actor, prop = self.add_actor(
            mapper, reset_camera=reset_camera, name=f'Floor({face})', pickable=pickable
        )

        prop.SetColor(Color(color, default_color=self._theme.floor_color).float_rgb)
        prop.SetOpacity(opacity)

        # edge display style
        if show_edges:
            prop.EdgeVisibilityOn()
        prop.SetEdgeColor(Color(edge_color, default_color=self._theme.edge_color).float_rgb)

        # lighting display style
        if lighting is False:
            prop.LightingOff()

        # set line thickness
        if line_width:
            prop.SetLineWidth(line_width)

        prop.SetRepresentationToSurface()
        self._floors.append(actor)
        return actor

    def remove_floors(self, clear_kwargs=True, render=True):
        """Remove all floor actors.

        Parameters
        ----------
        clear_kwargs : bool, default: True
            Clear default floor arguments.

        render : bool, default: True
            Render upon removing the floor.

        Examples
        --------
        Add a floor below a sphere, remove it, and then plot it.

        >>> import pyvista
        >>> pl = pyvista.Plotter()
        >>> actor = pl.add_mesh(pyvista.Sphere())
        >>> actor = pl.add_floor()
        >>> pl.remove_floors()
        >>> pl.show()

        """
        if getattr(self, '_floor', None) is not None:
            self._floor.ReleaseData()
            self._floor = None
        for actor in self._floors:
            self.remove_actor(actor, reset_camera=False, render=render)
        self._floors.clear()
        if clear_kwargs:
            self._floor_kwargs.clear()

    def remove_bounds_axes(self):
        """Remove bounds axes.

        Examples
        --------
        >>> import pyvista
        >>> pl = pyvista.Plotter(shape=(1, 2))
        >>> pl.subplot(0, 0)
        >>> actor = pl.add_mesh(pyvista.Sphere())
        >>> actor = pl.show_bounds(grid='front', location='outer')
        >>> pl.subplot(0, 1)
        >>> actor = pl.add_mesh(pyvista.Sphere())
        >>> actor = pl.show_bounds(grid='front', location='outer')
        >>> actor = pl.remove_bounds_axes()
        >>> pl.show()

        """
        if self.cube_axes_actor is not None:
            self.remove_actor(self.cube_axes_actor)
            self.cube_axes_actor = None
            self.Modified()

    def add_light(self, light):
        """Add a light to the renderer.

        Parameters
        ----------
        light : vtk.vtkLight or pyvista.Light
            Light to add.

        """
        # convert from a vtk type if applicable
        if isinstance(light, _vtk.vtkLight) and not isinstance(light, pyvista.Light):
            light = pyvista.Light.from_vtk(light)

        if not isinstance(light, pyvista.Light):
            raise TypeError(f'Expected Light instance, got {type(light).__name__} instead.')
        self._lights.append(light)
        self.AddLight(light)
        self.Modified()

        # we add the renderer to add/remove the light actor if
        # positional or cone angle is modified
        light.add_renderer(self)

    @property
    def lights(self):  # numpydoc ignore=RT01
        """Return a list of all lights in the renderer.

        Returns
        -------
        list
            Lights in the renderer.

        Examples
        --------
        >>> import pyvista
        >>> pl = pyvista.Plotter()
        >>> pl.renderer.lights  # doctest:+SKIP
        [<Light (Headlight) at ...>,
         <Light (Camera Light) at 0x7f1dd8155760>,
         <Light (Camera Light) at 0x7f1dd8155340>,
         <Light (Camera Light) at 0x7f1dd8155460>,
         <Light (Camera Light) at 0x7f1dd8155f40>]

        """
        return list(self.GetLights())

    def remove_all_lights(self):
        """Remove all lights from the renderer."""
        self.RemoveAllLights()
        self._lights.clear()

    def clear_actors(self):
        """Remove all actors (keep lights and properties)."""
        if self._actors:
            for actor in list(self._actors):
                try:
                    self.remove_actor(actor, reset_camera=False, render=False)
                except KeyError:
                    pass
            self.Modified()

    def clear(self):
        """Remove all actors and properties."""
        self.clear_actors()
        if self.__charts is not None:
            self._charts.deep_clean()
        self.remove_all_lights()
        self.RemoveAllViewProps()
        self.Modified()

        self._scalar_bar_slots = set(range(MAX_N_COLOR_BARS))
        self._scalar_bar_slot_lookup = {}

    def set_focus(self, point):
        """Set focus to a point.

        Parameters
        ----------
        point : sequence[float]
            Cartesian point to focus on in the form of ``[x, y, z]``.

        Examples
        --------
        >>> import pyvista
        >>> mesh = pyvista.Cube()
        >>> pl = pyvista.Plotter()
        >>> _ = pl.add_mesh(mesh, show_edges=True)
        >>> _ = pl.add_point_labels([mesh.points[1]], ["Focus"])
        >>> _ = pl.camera  # this initializes the camera
        >>> pl.set_focus(mesh.points[1])
        >>> pl.show()

        """
        if isinstance(point, np.ndarray):
            if point.ndim != 1:
                point = point.ravel()
        self.camera.focal_point = scale_point(self.camera, point, invert=False)
        self.camera_set = True
        self.Modified()

    def set_position(self, point, reset=False, render=True):
        """Set camera position to a point.

        Parameters
        ----------
        point : sequence
            Cartesian point to focus on in the form of ``[x, y, z]``.

        reset : bool, default: False
            Whether to reset the camera after setting the camera
            position.

        render : bool, default: True
            If the render window is being shown, trigger a render
            after setting the position.

        Examples
        --------
        Move the camera far away to ``[7, 7, 7]``.

        >>> import pyvista
        >>> mesh = pyvista.Cube()
        >>> pl = pyvista.Plotter()
        >>> _ = pl.add_mesh(mesh, show_edges=True)
        >>> pl.set_position([7, 7, 7])
        >>> pl.show()

        """
        if isinstance(point, np.ndarray):
            if point.ndim != 1:
                point = point.ravel()
        self.camera.position = scale_point(self.camera, point, invert=False)
        if reset:
            self.reset_camera(render=render)
        self.camera_set = True
        self.Modified()

    def set_viewup(self, vector, reset=True, render=True):
        """Set camera viewup vector.

        Parameters
        ----------
        vector : sequence[float]
            New camera viewup vector.

        reset : bool, default: True
            Whether to reset the camera after setting the camera
            position.

        render : bool, default: True
            If the render window is being shown, trigger a render
            after setting the viewup.

        Examples
        --------
        Look from the top down by setting view up to ``[0, 1, 0]``.
        Notice how the Y axis appears vertical.

        >>> from pyvista import demos
        >>> pl = demos.orientation_plotter()
        >>> pl.set_viewup([0, 1, 0])
        >>> pl.show()

        """
        if isinstance(vector, np.ndarray):
            if vector.ndim != 1:
                vector = vector.ravel()

        self.camera.up = vector
        if reset:
            self.reset_camera(render=render)

        self.camera_set = True
        self.Modified()

    def enable_parallel_projection(self):
        """Enable parallel projection.

        The camera will have a parallel projection. Parallel projection is
        often useful when viewing images or 2D datasets.

        Examples
        --------
        >>> import pyvista
        >>> from pyvista import demos
        >>> pl = pyvista.demos.orientation_plotter()
        >>> pl.enable_parallel_projection()
        >>> pl.show()

        """
        # Fix the 'reset camera' effect produced by the VTK when parallel
        # projection is enabled.
        angle = np.radians(self.camera.view_angle)
        self.camera.parallel_scale = self.camera.distance * np.sin(0.5 * angle)

        self.camera.enable_parallel_projection()
        self.Modified()

    def disable_parallel_projection(self):
        """Reset the camera to use perspective projection.

        Examples
        --------
        >>> import pyvista
        >>> from pyvista import demos
        >>> pl = pyvista.demos.orientation_plotter()
        >>> pl.disable_parallel_projection()
        >>> pl.show()

        """
        # Fix the 'reset camera' effect produced by the VTK when parallel
        # projection is disabled.
        focus = self.camera.focal_point
        angle = np.radians(self.camera.view_angle)
        distance = self.camera.parallel_scale / np.sin(0.5 * angle)
        direction = self.camera.direction
        x = focus[0] - distance * direction[0]
        y = focus[1] - distance * direction[1]
        z = focus[2] - distance * direction[2]
        self.camera.position = (x, y, z)
        self.ResetCameraClippingRange()

        self.camera.disable_parallel_projection()
        self.Modified()

    @property
    def parallel_projection(self):  # numpydoc ignore=RT01
        """Return parallel projection state of active render window.

        Examples
        --------
        >>> import pyvista
        >>> pl = pyvista.Plotter()
        >>> pl.parallel_projection = False
        >>> pl.parallel_projection
        False
        """
        return self.camera.parallel_projection

    @parallel_projection.setter
    def parallel_projection(self, state):  # numpydoc ignore=GL08
        self.camera.parallel_projection = state
        self.Modified()

    @property
    def parallel_scale(self):  # numpydoc ignore=RT01
        """Return parallel scale of active render window.

        Examples
        --------
        >>> import pyvista
        >>> pl = pyvista.Plotter()
        >>> pl.parallel_scale = 2
        """
        return self.camera.parallel_scale

    @parallel_scale.setter
    def parallel_scale(self, value):  # numpydoc ignore=GL08
        self.camera.parallel_scale = value
        self.Modified()

    def remove_actor(self, actor, reset_camera=False, render=True):
        """Remove an actor from the Renderer.

        Parameters
        ----------
        actor : str, vtk.vtkActor, list or tuple
            If the type is ``str``, removes the previously added actor
            with the given name. If the type is ``vtk.vtkActor``,
            removes the actor if it's previously added to the
            Renderer. If ``list`` or ``tuple``, removes iteratively
            each actor.

        reset_camera : bool, optional
            Resets camera so all actors can be seen.

        render : bool, optional
            Render upon actor removal.  Set this to ``False`` to stop
            the render window from rendering when an actor is removed.

        Returns
        -------
        bool
            ``True`` when actor removed.  ``False`` when actor has not
            been removed.

        Examples
        --------
        Add two meshes to a plotter and then remove the sphere actor.

        >>> import pyvista
        >>> mesh = pyvista.Cube()
        >>> pl = pyvista.Plotter()
        >>> cube_actor = pl.add_mesh(pyvista.Cube(), show_edges=True)
        >>> sphere_actor = pl.add_mesh(pyvista.Sphere(), show_edges=True)
        >>> _ = pl.remove_actor(cube_actor)
        >>> pl.show()

        """
        name = None
        if isinstance(actor, str):
            name = actor
            keys = list(self._actors.keys())
            names = []
            for k in keys:
                if k.startswith(f'{name}-'):
                    names.append(k)
            if len(names) > 0:
                self.remove_actor(names, reset_camera=reset_camera)
            try:
                actor = self._actors[name]
            except KeyError:
                # If actor of that name is not present then return success
                return False
        if isinstance(actor, collections.abc.Iterable):
            success = False
            for a in actor:
                rv = self.remove_actor(a, reset_camera=reset_camera)
                if rv or success:
                    success = True
            return success
        if actor is None:
            return False

        # remove any labels associated with the actor
        self._labels.pop(actor.GetAddressAsString(""), None)

        # ensure any scalar bars associated with this actor are removed
        try:
            self.parent.scalar_bars._remove_mapper_from_plotter(actor)
        except (AttributeError, ReferenceError):
            pass
        self.RemoveActor(actor)

        if name is None:
            for k, v in self._actors.items():
                if v == actor:
                    name = k
        self._actors.pop(name, None)
        self.update_bounds_axes()
        if reset_camera:
            self.reset_camera(render=render)
        elif not self.camera_set and reset_camera is None:
            self.reset_camera(render=render)
        elif render:
            self.parent.render()

        self.Modified()
        return True

    def set_scale(self, xscale=None, yscale=None, zscale=None, reset_camera=True, render=True):
        """Scale all the actors in the scene.

        Scaling in performed independently on the X, Y and Z axis.
        A scale of zero is illegal and will be replaced with one.

        .. warning::
            Setting the scale on the renderer is a convenience method to
            individually scale each of the actors in the scene. If a scale
            was set on an actor previously, it will be reset to the scale
            of this Renderer.

        Parameters
        ----------
        xscale : float, optional
            Scaling in the x direction.  Default is ``None``, which
            does not change existing scaling.

        yscale : float, optional
            Scaling in the y direction.  Default is ``None``, which
            does not change existing scaling.

        zscale : float, optional
            Scaling in the z direction.  Default is ``None``, which
            does not change existing scaling.

        reset_camera : bool, default: True
            Resets camera so all actors can be seen.

        render : bool, default: True
            If the render window is being shown, trigger a render
            after setting the scale.

        Examples
        --------
        Set the scale in the z direction to be 2 times that of
        nominal.  Leave the other axes unscaled.

        >>> import pyvista
        >>> pl = pyvista.Plotter()
        >>> pl.set_scale(zscale=2)
        >>> _ = pl.add_mesh(pyvista.Sphere())  # perfect sphere
        >>> pl.show()

        """
        if xscale is None:
            xscale = self.scale[0]
        if yscale is None:
            yscale = self.scale[1]
        if zscale is None:
            zscale = self.scale[2]
        self.scale = [xscale, yscale, zscale]

        # Reset all actors to match this scale
        for actor in self.actors.values():
            if hasattr(actor, 'SetScale'):
                actor.SetScale(self.scale)

        self.parent.render()
        if reset_camera:
            self.update_bounds_axes()
            self.reset_camera(render=render)
        self.Modified()

    def get_default_cam_pos(self, negative=False):
        """Return the default focal points and viewup.

        Uses ResetCamera to make a useful view.

        Parameters
        ----------
        negative : bool, default: False
            View from the opposite direction.

        Returns
        -------
        list
            List of camera position:

            * Position
            * Focal point
            * View up

        """
        focal_pt = self.center
        if any(np.isnan(focal_pt)):
            focal_pt = (0.0, 0.0, 0.0)
        position = np.array(self._theme.camera['position']).astype(float)
        if negative:
            position *= -1
        position = position / np.array(self.scale).astype(float)
        cpos = [position + np.array(focal_pt), focal_pt, self._theme.camera['viewup']]
        return cpos

    def update_bounds_axes(self):
        """Update the bounds axes of the render window."""
        if (
            hasattr(self, '_box_object')
            and self._box_object is not None
            and self.bounding_box_actor is not None
        ):
            if not np.allclose(self._box_object.bounds, self.bounds):
                color = self.bounding_box_actor.GetProperty().GetColor()
                self.remove_bounding_box()
                self.add_bounding_box(color=color)
                self.remove_floors(clear_kwargs=False)
                for floor_kwargs in self._floor_kwargs:
                    floor_kwargs['store_floor_kwargs'] = False
                    self.add_floor(**floor_kwargs)
        if self.cube_axes_actor is not None:
            self.cube_axes_actor.update_bounds(self.bounds)
            if not np.allclose(self.scale, [1.0, 1.0, 1.0]):
                self.cube_axes_actor.SetUse2DMode(True)
            else:
                self.cube_axes_actor.SetUse2DMode(False)
            self.Modified()

    def reset_camera(self, render=True, bounds=None):
        """Reset the camera of the active render window.

        The camera slides along the vector defined from camera
        position to focal point until all of the actors can be seen.

        Parameters
        ----------
        render : bool, default: True
            Trigger a render after resetting the camera.

        bounds : iterable(int), optional
            Automatically set up the camera based on a specified bounding box
            ``(xmin, xmax, ymin, ymax, zmin, zmax)``.

        Examples
        --------
        Add a mesh and place the camera position too close to the
        mesh.  Then reset the camera and show the mesh.

        >>> import pyvista
        >>> pl = pyvista.Plotter()
        >>> actor = pl.add_mesh(pyvista.Sphere(), show_edges=True)
        >>> pl.set_position((0, 0.1, 0.1))
        >>> pl.reset_camera()
        >>> pl.show()

        """
        if bounds is not None:
            self.ResetCamera(*bounds)
        else:
            self.ResetCamera()

        self.reset_camera_clipping_range()

        if render:
            self.parent.render()
        self.Modified()

    def isometric_view(self):
        """Reset the camera to a default isometric view.

        DEPRECATED: Please use ``view_isometric``.

        """
        self.view_isometric()

    def view_isometric(self, negative=False, render=True):
        """Reset the camera to a default isometric view.

        The view will show all the actors in the scene.

        Parameters
        ----------
        negative : bool, default: False
            View from the other isometric direction.

        render : bool, default: True
            If the render window is being shown, trigger a render
            after setting the camera position.

        Examples
        --------
        Isometric view.

        >>> from pyvista import demos
        >>> pl = demos.orientation_plotter()
        >>> pl.view_isometric()
        >>> pl.show()

        Negative isometric view.

        >>> from pyvista import demos
        >>> pl = demos.orientation_plotter()
        >>> pl.view_isometric(negative=True)
        >>> pl.show()

        """
        position = self.get_default_cam_pos(negative=negative)
        self.camera_position = CameraPosition(*position)
        self.camera_set = negative
        self.reset_camera(render=render)

    def view_vector(self, vector, viewup=None, render=True):
        """Point the camera in the direction of the given vector.

        Parameters
        ----------
        vector : sequence[float]
            Direction to point the camera in.

        viewup : sequence[float], optional
            Sequence describing the view up of the camera.

        render : bool, default: True
            If the render window is being shown, trigger a render
            after setting the camera position.

        """
        focal_pt = self.center
        if viewup is None:
            viewup = self._theme.camera['viewup']
        cpos = CameraPosition(vector + np.array(focal_pt), focal_pt, viewup)
        self.camera_position = cpos
        self.reset_camera(render=render)

    def view_xy(self, negative=False, render=True):
        """View the XY plane.

        Parameters
        ----------
        negative : bool, default: False
            View from the opposite direction.

        render : bool, default: True
            If the render window is being shown, trigger a render
            after setting the camera position.

        Examples
        --------
        View the XY plane of a built-in mesh example.

        >>> from pyvista import examples
        >>> import pyvista as pv
        >>> airplane = examples.load_airplane()
        >>> pl = pv.Plotter()
        >>> _ = pl.add_mesh(airplane)
        >>> pl.view_xy()
        >>> pl.show()

        """
        self.view_vector(*view_vectors('xy', negative=negative), render=render)

    def view_yx(self, negative=False, render=True):
        """View the YX plane.

        Parameters
        ----------
        negative : bool, default: False
            View from the opposite direction.

        render : bool, default: True
            If the render window is being shown, trigger a render
            after setting the camera position.

        Examples
        --------
        View the YX plane of a built-in mesh example.

        >>> from pyvista import examples
        >>> import pyvista as pv
        >>> airplane = examples.load_airplane()
        >>> pl = pv.Plotter()
        >>> _ = pl.add_mesh(airplane)
        >>> pl.view_yx()
        >>> pl.show()

        """
        self.view_vector(*view_vectors('yx', negative=negative), render=render)

    def view_xz(self, negative=False, render=True):
        """View the XZ plane.

        Parameters
        ----------
        negative : bool, default: False
            View from the opposite direction.

        render : bool, default: True
            If the render window is being shown, trigger a render
            after setting the camera position.

        Examples
        --------
        View the XZ plane of a built-in mesh example.

        >>> from pyvista import examples
        >>> import pyvista as pv
        >>> airplane = examples.load_airplane()
        >>> pl = pv.Plotter()
        >>> _ = pl.add_mesh(airplane)
        >>> pl.view_xz()
        >>> pl.show()

        """
        self.view_vector(*view_vectors('xz', negative=negative), render=render)

    def view_zx(self, negative=False, render=True):
        """View the ZX plane.

        Parameters
        ----------
        negative : bool, default: False
            View from the opposite direction.

        render : bool, default: True
            If the render window is being shown, trigger a render
            after setting the camera position.

        Examples
        --------
        View the ZX plane of a built-in mesh example.

        >>> from pyvista import examples
        >>> import pyvista as pv
        >>> airplane = examples.load_airplane()
        >>> pl = pv.Plotter()
        >>> _ = pl.add_mesh(airplane)
        >>> pl.view_zx()
        >>> pl.show()

        """
        self.view_vector(*view_vectors('zx', negative=negative), render=render)

    def view_yz(self, negative=False, render=True):
        """View the YZ plane.

        Parameters
        ----------
        negative : bool, default: False
            View from the opposite direction.

        render : bool, default: True
            If the render window is being shown, trigger a render
            after setting the camera position.

        Examples
        --------
        View the YZ plane of a built-in mesh example.

        >>> from pyvista import examples
        >>> import pyvista as pv
        >>> airplane = examples.load_airplane()
        >>> pl = pv.Plotter()
        >>> _ = pl.add_mesh(airplane)
        >>> pl.view_yz()
        >>> pl.show()

        """
        self.view_vector(*view_vectors('yz', negative=negative), render=render)

    def view_zy(self, negative=False, render=True):
        """View the ZY plane.

        Parameters
        ----------
        negative : bool, default: False
            View from the opposite direction.

        render : bool, default: True
            If the render window is being shown, trigger a render
            after setting the camera position.

        Examples
        --------
        View the ZY plane of a built-in mesh example.

        >>> from pyvista import examples
        >>> import pyvista as pv
        >>> airplane = examples.load_airplane()
        >>> pl = pv.Plotter()
        >>> _ = pl.add_mesh(airplane)
        >>> pl.view_zy()
        >>> pl.show()

        """
        self.view_vector(*view_vectors('zy', negative=negative), render=render)

    def disable(self):
        """Disable this renderer's camera from being interactive."""
        self.SetInteractive(0)

    def enable(self):
        """Enable this renderer's camera to be interactive."""
        self.SetInteractive(1)

    def add_blurring(self):
        """Add blurring.

        This can be added several times to increase the degree of blurring.

        Examples
        --------
        Add two blurring passes to the plotter and show it.

        >>> import pyvista as pv
        >>> pl = pv.Plotter()
        >>> _ = pl.add_mesh(pv.Sphere(), show_edges=True)
        >>> pl.add_blurring()
        >>> pl.add_blurring()
        >>> pl.show()

        See :ref:`blur_example` for a full example using this method.

        """
        self._render_passes.add_blur_pass()

    def remove_blurring(self):
        """Remove a single blurring pass.

        You will need to run this multiple times to remove all blurring passes.

        Examples
        --------
        >>> import pyvista as pv
        >>> pl = pv.Plotter()
        >>> _ = pl.add_mesh(pv.Sphere())
        >>> pl.add_blurring()
        >>> pl.remove_blurring()
        >>> pl.show()

        """
        self._render_passes.remove_blur_pass()

    def enable_depth_of_field(self, automatic_focal_distance=True):
        """Enable depth of field plotting.

        Parameters
        ----------
        automatic_focal_distance : bool, default: True
            Use automatic focal distance calculation. When enabled, the center
            of the viewport will always be in focus regardless of where the
            focal point is.

        Examples
        --------
        Create five spheres and demonstrate the effect of depth of field.

        >>> import pyvista as pv
        >>> from pyvista import examples
        >>> pl = pv.Plotter(lighting="three lights")
        >>> pl.background_color = "w"
        >>> for i in range(5):
        ...     mesh = pv.Sphere(center=(-i * 4, 0, 0))
        ...     color = [0, 255 - i * 20, 30 + i * 50]
        ...     _ = pl.add_mesh(
        ...         mesh,
        ...         show_edges=False,
        ...         pbr=True,
        ...         metallic=1.0,
        ...         color=color,
        ...     )
        ...
        >>> pl.camera.zoom(1.8)
        >>> pl.camera_position = [
        ...     (4.74, 0.959, 0.525),
        ...     (0.363, 0.3116, 0.132),
        ...     (-0.088, -0.0075, 0.996),
        ... ]
        >>> pl.enable_depth_of_field()
        >>> pl.show()

        See :ref:`depth_of_field_example` for a full example using this method.

        """
        self._render_passes.enable_depth_of_field_pass(automatic_focal_distance)

    def disable_depth_of_field(self):
        """Disable depth of field plotting.

        Examples
        --------
        >>> import pyvista as pv
        >>> pl = pv.Plotter(lighting="three lights")
        >>> pl.enable_depth_of_field()
        >>> pl.disable_depth_of_field()

        """
        self._render_passes.disable_depth_of_field_pass()

    def enable_eye_dome_lighting(self):
        """Enable eye dome lighting (EDL).

        Returns
        -------
        vtk.vtkOpenGLRenderer
            VTK renderer with eye dome lighting pass.

        Examples
        --------
        >>> import pyvista
        >>> pl = pyvista.Plotter()
        >>> _ = pl.enable_eye_dome_lighting()

        """
        self._render_passes.enable_edl_pass()

    def disable_eye_dome_lighting(self):
        """Disable eye dome lighting (EDL).

        Examples
        --------
        >>> import pyvista
        >>> pl = pyvista.Plotter()
        >>> pl.disable_eye_dome_lighting()

        """
        self._render_passes.disable_edl_pass()

    def enable_shadows(self):
        """Enable shadows.

        Examples
        --------
        First, plot without shadows enabled (default)

        >>> import pyvista
        >>> mesh = pyvista.Sphere()
        >>> pl = pyvista.Plotter(lighting='none', window_size=(1000, 1000))
        >>> light = pyvista.Light()
        >>> light.set_direction_angle(20, -20)
        >>> pl.add_light(light)
        >>> _ = pl.add_mesh(mesh, color='white', smooth_shading=True)
        >>> _ = pl.add_mesh(pyvista.Box((-1.2, -1, -1, 1, -1, 1)))
        >>> pl.show()

        Now, enable shadows.

        >>> import pyvista
        >>> mesh = pyvista.Sphere()
        >>> pl = pyvista.Plotter(lighting='none', window_size=(1000, 1000))
        >>> light = pyvista.Light()
        >>> light.set_direction_angle(20, -20)
        >>> pl.add_light(light)
        >>> _ = pl.add_mesh(mesh, color='white', smooth_shading=True)
        >>> _ = pl.add_mesh(pyvista.Box((-1.2, -1, -1, 1, -1, 1)))
        >>> pl.enable_shadows()
        >>> pl.show()

        """
        self._render_passes.enable_shadow_pass()

    def disable_shadows(self):
        """Disable shadows.

        Examples
        --------
        >>> import pyvista
        >>> pl = pyvista.Plotter()
        >>> pl.disable_shadows()

        """
        self._render_passes.disable_shadow_pass()

    def enable_ssao(self, radius=0.5, bias=0.005, kernel_size=256, blur=True):
        """Enable surface space ambient occlusion (SSAO).

        SSAO can approximate shadows more efficiently than ray-tracing
        and produce similar results. Use this when you wish to plot the
        occlusion effect that nearby meshes have on each other by blocking
        nearby light sources.

        See `Kitware: Screen-Space Ambient Occlusion
        <https://www.kitware.com/ssao/>`_ for more details

        Parameters
        ----------
        radius : float, default: 0.5
            Neighbor pixels considered when computing the occlusion.

        bias : float, default: 0.005
            Tolerance factor used when comparing pixel depth.

        kernel_size : int, default: 256
            Number of samples used. This controls the quality where a higher
            number increases the quality at the expense of computation time.

        blur : bool, default: True
            Controls if occlusion buffer should be blurred before combining it
            with the color buffer.

        Examples
        --------
        Generate a :class:`pyvista.UnstructuredGrid` with many tetrahedrons
        nearby each other and plot it without SSAO.

        >>> import pyvista as pv
        >>> ugrid = pv.ImageData(dimensions=(3, 2, 2)).to_tetrahedra(12)
        >>> exploded = ugrid.explode()
        >>> exploded.plot()

        Enable SSAO with the default parameters.

        >>> pl = pv.Plotter()
        >>> _ = pl.add_mesh(exploded)
        >>> pl.enable_ssao()
        >>> pl.show()

        """
        self._render_passes.enable_ssao_pass(radius, bias, kernel_size, blur)

    def disable_ssao(self):
        """Disable surface space ambient occlusion (SSAO)."""
        self._render_passes.disable_ssao_pass()

    def get_pick_position(self):
        """Get the pick position/area as ``x0, y0, x1, y1``.

        Returns
        -------
        tuple
            Pick position as ``x0, y0, x1, y1``.

        """
        x0 = int(self.GetPickX1())
        x1 = int(self.GetPickX2())
        y0 = int(self.GetPickY1())
        y1 = int(self.GetPickY2())
        return x0, y0, x1, y1

    def set_background(self, color, top=None):
        """Set the background color of this renderer.

        Parameters
        ----------
        color : ColorLike, optional
            Either a string, rgb list, or hex color string.  Defaults
            to theme default.  For example:

            * ``color='white'``
            * ``color='w'``
            * ``color=[1.0, 1.0, 1.0]``
            * ``color='#FFFFFF'``

        top : ColorLike, optional
            If given, this will enable a gradient background where the
            ``color`` argument is at the bottom and the color given in
            ``top`` will be the color at the top of the renderer.

        Examples
        --------
        Set the background color to black with a gradient to white at
        the top of the plot.

        >>> import pyvista
        >>> pl = pyvista.Plotter()
        >>> actor = pl.add_mesh(pyvista.Cone())
        >>> pl.set_background('black', top='white')
        >>> pl.show()

        """
        use_gradient = False
        if top is not None:
            use_gradient = True

        self.SetBackground(Color(color, default_color=self._theme.background).float_rgb)
        if use_gradient:
            self.SetGradientBackground(True)
            self.SetBackground2(Color(top).float_rgb)
        else:
            self.SetGradientBackground(False)
        self.Modified()

    def set_environment_texture(self, texture, is_srgb=False):
        """Set the environment texture used for image based lighting.

        This texture is supposed to represent the scene background. If
        it is not a cubemap, the texture is supposed to represent an
        equirectangular projection. If used with raytracing backends,
        the texture must be an equirectangular projection and must be
        constructed with a valid ``vtk.vtkImageData``.

        Parameters
        ----------
        texture : pyvista.Texture
            Texture.

        is_srgb : bool, default: False
            If the texture is in sRGB color space, set the color flag on the
            texture or set this parameter to ``True``. Textures are assumed
            to be in linear color space by default.

        Examples
        --------
        Add a skybox cubemap as an environment texture and show that the
        lighting from the texture is mapped on to a sphere dataset. Note how
        even when disabling the default lightkit, the scene lighting will still
        be mapped onto the actor.

        >>> from pyvista import examples
        >>> import pyvista as pv
        >>> pl = pv.Plotter(lighting=None)
        >>> cubemap = examples.download_sky_box_cube_map()
        >>> _ = pl.add_mesh(
        ...     pv.Sphere(), pbr=True, metallic=0.9, roughness=0.4
        ... )
        >>> pl.set_environment_texture(cubemap)
        >>> pl.camera_position = 'xy'
        >>> pl.show()

        """
        # cube_map textures cannot use spherical harmonics
        if texture.cube_map:
            self.AutomaticLightCreationOff()
            # disable spherical harmonics was added in 9.1.0
            if hasattr(self, 'UseSphericalHarmonicsOff'):
                self.UseSphericalHarmonicsOff()

        self.UseImageBasedLightingOn()
        self.SetEnvironmentTexture(texture, is_srgb)
        self.Modified()

    def remove_environment_texture(self):
        """Remove the environment texture.

        Examples
        --------
        >>> from pyvista import examples
        >>> import pyvista as pv
        >>> pl = pv.Plotter(lighting=None)
        >>> cubemap = examples.download_sky_box_cube_map()
        >>> _ = pl.add_mesh(
        ...     pv.Sphere(), pbr=True, metallic=0.9, roughness=0.4
        ... )
        >>> pl.set_environment_texture(cubemap)
        >>> pl.remove_environment_texture()
        >>> pl.camera_position = 'xy'
        >>> pl.show()

        """
        self.UseImageBasedLightingOff()
        self.SetEnvironmentTexture(None)
        self.Modified()

    def close(self):
        """Close out widgets and sensitive elements."""
        self.RemoveAllObservers()
        if hasattr(self, 'axes_widget'):
            self.hide_axes()  # Necessary to avoid segfault
            self.axes_actor = None
            del self.axes_widget

        if self._empty_str is not None:
            self._empty_str.SetReferenceCount(0)
            self._empty_str = None

    def on_plotter_render(self):
        """Notify renderer components of explicit plotter render call."""
        if self.__charts is not None:
            for chart in self.__charts:
                # Notify Charts that plotter.render() is called
                chart._render_event(plotter_render=True)

    def deep_clean(self, render=False):
        """Clean the renderer of the memory.

        Parameters
        ----------
        render : bool, optional
            Render the render window after removing the bounding box
            (if applicable).

        """
        if self.cube_axes_actor is not None:
            self.cube_axes_actor = None

        if hasattr(self, 'edl_pass'):
            del self.edl_pass
        if hasattr(self, '_box_object'):
            self.remove_bounding_box(render=render)
        if hasattr(self, '_shadow_pass') and self._shadow_pass is not None:
            self.disable_shadows()
        try:
            if self.__charts is not None:
                self.__charts.deep_clean()
                self.__charts = None
        except AttributeError:  # pragma: no cover
            pass

        self._render_passes.deep_clean()
        self.remove_floors(render=render)
        self.remove_legend(render=render)
        self.RemoveAllViewProps()
        self._actors = {}
        self._camera = None
        self._bounding_box = None
        self._marker_actor = None
        self._border_actor = None
        # remove reference to parent last
        self.parent = None

    def __del__(self):
        """Delete the renderer."""
        self.deep_clean()

    def enable_hidden_line_removal(self):
        """Enable hidden line removal."""
        self.UseHiddenLineRemovalOn()

    def disable_hidden_line_removal(self):
        """Disable hidden line removal."""
        self.UseHiddenLineRemovalOff()

    @property
    def layer(self):  # numpydoc ignore=RT01
        """Return or set the current layer of this renderer."""
        return self.GetLayer()

    @layer.setter
    def layer(self, layer):  # numpydoc ignore=GL08
        self.SetLayer(layer)

    @property
    def viewport(self):  # numpydoc ignore=RT01
        """Viewport of the renderer.

        Viewport describes the ``(xstart, ystart, xend, yend)`` square
        of the renderer relative to the main renderer window.

        For example, a renderer taking up the entire window will have
        a viewport of ``(0.0, 0.0, 1.0, 1.0)``, while the viewport of
        a renderer on the left-hand side of a horizontally split window
        would be ``(0.0, 0.0, 0.5, 1.0)``.

        Returns
        -------
        tuple
            Viewport in the form ``(xstart, ystart, xend, yend)``.

        Examples
        --------
        Show the viewport of a renderer taking up half the render
        window.

        >>> import pyvista
        >>> pl = pyvista.Plotter(shape=(1, 2))
        >>> pl.renderers[0].viewport
        (0.0, 0.0, 0.5, 1.0)

        """
        return self.GetViewport()

    @property
    def width(self):  # numpydoc ignore=RT01
        """Width of the renderer."""
        xmin, _, xmax, _ = self.viewport
        return self.parent.window_size[0] * (xmax - xmin)

    @property
    def height(self):  # numpydoc ignore=RT01
        """Height of the renderer."""
        _, ymin, _, ymax = self.viewport
        return self.parent.window_size[1] * (ymax - ymin)

    def add_legend(
        self,
        labels=None,
        bcolor=(0.5, 0.5, 0.5),
        border=False,
        size=(0.2, 0.2),
        name=None,
        loc='upper right',
        face='triangle',
    ):
        """Add a legend to render window.

        Entries must be a list containing one string and color entry for each
        item.

        Parameters
        ----------
        labels : list, optional
            When set to ``None``, uses existing labels as specified by

            - :func:`add_mesh <Plotter.add_mesh>`
            - :func:`add_lines <Plotter.add_lines>`
            - :func:`add_points <Plotter.add_points>`

            List containing one entry for each item to be added to the
            legend.  Each entry must contain two strings, [label,
            color], where label is the name of the item to add, and
            color is the color of the label to add.

        bcolor : ColorLike, default: (0.5, 0.5, 0.5)
            Background color, either a three item 0 to 1 RGB color
            list, or a matplotlib color string (e.g. ``'w'`` or ``'white'``
            for a white color).  If None, legend background is
            disabled.

        border : bool, default: False
            Controls if there will be a border around the legend.
            Default False.

        size : sequence[float], default: (0.2, 0.2)
            Two float sequence, each float between 0 and 1.  For example
            ``(0.1, 0.1)`` would make the legend 10% the size of the
            entire figure window.

        name : str, optional
            The name for the added actor so that it can be easily
            updated.  If an actor of this name already exists in the
            rendering window, it will be replaced by the new actor.

        loc : str, default: "upper right"
            Location string.  One of the following:

            * ``'upper right'``
            * ``'upper left'``
            * ``'lower left'``
            * ``'lower right'``
            * ``'center left'``
            * ``'center right'``
            * ``'lower center'``
            * ``'upper center'``
            * ``'center'``

        face : str | pyvista.PolyData | NoneType, default: "triangle"
            Face shape of legend face.  One of the following:

            * None: ``None``
            * Line: ``"-"`` or ``"line"``
            * Triangle: ``"^"`` or ``'triangle'``
            * Circle: ``"o"`` or ``'circle'``
            * Rectangle: ``"r"`` or ``'rectangle'``
            * Custom: :class:`pyvista.PolyData`

            Passing ``None`` removes the legend face.  A custom face can be
            created using :class:`pyvista.PolyData`.  This will be rendered
            from the XY plane.

        Returns
        -------
        vtk.vtkLegendBoxActor
            Actor for the legend.

        Examples
        --------
        Create a legend by labeling the meshes when using ``add_mesh``

        >>> import pyvista
        >>> from pyvista import examples
        >>> sphere = pyvista.Sphere(center=(0, 0, 1))
        >>> cube = pyvista.Cube()
        >>> plotter = pyvista.Plotter()
        >>> _ = plotter.add_mesh(
        ...     sphere, 'grey', smooth_shading=True, label='Sphere'
        ... )
        >>> _ = plotter.add_mesh(cube, 'r', label='Cube')
        >>> _ = plotter.add_legend(bcolor='w', face=None)
        >>> plotter.show()

        Alternatively provide labels in the plotter.

        >>> plotter = pyvista.Plotter()
        >>> _ = plotter.add_mesh(sphere, 'grey', smooth_shading=True)
        >>> _ = plotter.add_mesh(cube, 'r')
        >>> legend_entries = []
        >>> legend_entries.append(['My Mesh', 'w'])
        >>> legend_entries.append(['My Other Mesh', 'k'])
        >>> _ = plotter.add_legend(legend_entries)
        >>> plotter.show()

        """
        if self.legend is not None:
            self.remove_legend()
        self._legend = _vtk.vtkLegendBoxActor()

        if labels is None:
            # use existing labels
            if not self._labels:
                raise ValueError(
                    'No labels input.\n\n'
                    'Add labels to individual items when adding them to'
                    'the plotting object with the "label=" parameter.  '
                    'or enter them as the "labels" parameter.'
                )

            self._legend.SetNumberOfEntries(len(self._labels))
            for i, (vtk_object, text, color) in enumerate(self._labels.values()):
                if face is None:
                    # dummy vtk object
                    vtk_object = pyvista.PolyData([0.0, 0.0, 0.0])

                self._legend.SetEntry(i, vtk_object, text, color.float_rgb)

        else:
            self._legend.SetNumberOfEntries(len(labels))

            legend_face = make_legend_face(face)
            for i, (text, color) in enumerate(labels):
                self._legend.SetEntry(i, legend_face, text, Color(color).float_rgb)

        if loc is not None:
            if loc not in ACTOR_LOC_MAP:
                allowed = '\n'.join([f'\t * "{item}"' for item in ACTOR_LOC_MAP])
                raise ValueError(f'Invalid loc "{loc}".  Expected one of the following:\n{allowed}')
            x, y, size = map_loc_to_pos(loc, size, border=0.05)
            self._legend.SetPosition(x, y)
            self._legend.SetPosition2(size[0], size[1])

        if bcolor is None:
            self._legend.SetUseBackground(False)
        else:
            self._legend.SetUseBackground(True)
            self._legend.SetBackgroundColor(Color(bcolor).float_rgb)

        self._legend.SetBorder(border)

        self.add_actor(self._legend, reset_camera=False, name=name, pickable=False)
        return self._legend

    def remove_legend(self, render=True):
        """Remove the legend actor.

        Parameters
        ----------
        render : bool, default: True
            Render upon actor removal.  Set this to ``False`` to stop
            the render window from rendering when a the legend is removed.

        Examples
        --------
        >>> import pyvista
        >>> mesh = pyvista.Sphere()
        >>> pl = pyvista.Plotter()
        >>> _ = pl.add_mesh(mesh, label='sphere')
        >>> _ = pl.add_legend()
        >>> pl.remove_legend()

        """
        if self.legend is not None:
            self.remove_actor(self.legend, reset_camera=False, render=render)
            self._legend = None

    @property
    def legend(self):  # numpydoc ignore=RT01
        """Legend actor."""
        return self._legend

    def add_ruler(
        self,
        pointa,
        pointb,
        flip_range=False,
        number_labels=5,
        show_labels=True,
        font_size_factor=0.6,
        label_size_factor=1.0,
        label_format=None,
        title="Distance",
        number_minor_ticks=0,
        tick_length=5,
        minor_tick_length=3,
        show_ticks=True,
        tick_label_offset=2,
        label_color=None,
        tick_color=None,
    ):
        """Add ruler.

        The ruler is a 2D object that is not occluded by 3D objects.
        To avoid issues with perspective, it is recommended to use
        parallel projection, i.e. :func:`Plotter.enable_parallel_projection`,
        and place the ruler orthogonal to the viewing direction.

        The title and labels are placed to the right of ruler moving from
        ``pointa`` to ``pointb``. Use ``flip_range`` to flip the ``0`` location,
        if needed.

        Since the ruler is placed in an overlay on the viewing scene, the camera
        does not automatically reset to include the ruler in the view.

        Parameters
        ----------
        pointa : sequence[float]
            Starting point for ruler.

        pointb : sequence[float]
            Ending point for ruler.

        flip_range : bool, default: False
            If ``True``, the distance range goes from ``pointb`` to ``pointa``.

        number_labels : int, default: 5
            Number of labels to place on ruler.

        show_labels : bool, default: True
            Whether to show labels.

        font_size_factor : float, default: 0.6
            Factor to scale font size overall.

        label_size_factor : float, default: 1.0
            Factor to scale label size relative to title size.

        label_format : str, optional
            A printf style format for labels, e.g. '%E'.

        title : str, default: "Distance"
            The title to display.

        number_minor_ticks : int, default: 0
            Number of minor ticks between major ticks.

        tick_length : int, default: 5
            Length of ticks in pixels.

        minor_tick_length : int, default: 3
            Length of minor ticks in pixels.

        show_ticks : bool, default: True
            Whether to show the ticks.

        tick_label_offset : int, default: 2
            Offset between tick and label in pixels.

        label_color : ColorLike, optional
            Either a string, rgb list, or hex color string for
            label and title colors.

            .. warning::
                This is either white or black.

        tick_color : ColorLike, optional
            Either a string, rgb list, or hex color string for
            tick line colors.

        Returns
        -------
        vtk.vtkActor
            VTK actor of the ruler.

        Examples
        --------
        >>> import pyvista as pv
        >>> cone = pv.Cone(height=2.0, radius=0.5)
        >>> plotter = pv.Plotter()
        >>> _ = plotter.add_mesh(cone)

        Measure x direction of cone and place ruler slightly below.

        >>> _ = plotter.add_ruler(
        ...     pointa=[cone.bounds[0], cone.bounds[2] - 0.1, 0.0],
        ...     pointb=[cone.bounds[1], cone.bounds[2] - 0.1, 0.0],
        ...     title="X Distance",
        ... )

        Measure y direction of cone and place ruler slightly to left.
        The title and labels are placed to the right of the ruler when
        traveling from ``pointa`` to ``pointb``.

        >>> _ = plotter.add_ruler(
        ...     pointa=[cone.bounds[0] - 0.1, cone.bounds[3], 0.0],
        ...     pointb=[cone.bounds[0] - 0.1, cone.bounds[2], 0.0],
        ...     flip_range=True,
        ...     title="Y Distance",
        ... )
        >>> plotter.enable_parallel_projection()
        >>> plotter.view_xy()
        >>> plotter.show()

        """
        label_color = Color(label_color, default_color=self._theme.font.color)
        tick_color = Color(tick_color, default_color=self._theme.font.color)

        ruler = _vtk.vtkAxisActor2D()

        ruler.GetPositionCoordinate().SetCoordinateSystemToWorld()
        ruler.GetPosition2Coordinate().SetCoordinateSystemToWorld()
        ruler.GetPositionCoordinate().SetReferenceCoordinate(None)
        ruler.GetPositionCoordinate().SetValue(pointa[0], pointa[1], pointa[2])
        ruler.GetPosition2Coordinate().SetValue(pointb[0], pointb[1], pointb[2])

        distance = np.linalg.norm(np.asarray(pointa) - np.asarray(pointb))
        if flip_range:
            ruler.SetRange(distance, 0)
        else:
            ruler.SetRange(0, distance)

        ruler.SetTitle(title)
        ruler.SetFontFactor(font_size_factor)
        ruler.SetLabelFactor(label_size_factor)
        ruler.SetNumberOfLabels(number_labels)
        ruler.SetLabelVisibility(show_labels)
        if label_format:
            ruler.SetLabelFormat(label_format)
        ruler.GetProperty().SetColor(*tick_color.int_rgb)
        if label_color != Color('white'):
            # This property turns black if set
            ruler.GetLabelTextProperty().SetColor(*label_color.int_rgb)
            ruler.GetTitleTextProperty().SetColor(*label_color.int_rgb)
        ruler.SetNumberOfMinorTicks(number_minor_ticks)
        ruler.SetTickVisibility(show_ticks)
        ruler.SetTickLength(tick_length)
        ruler.SetMinorTickLength(minor_tick_length)
        ruler.SetTickOffset(tick_label_offset)

        self.add_actor(ruler, reset_camera=True, pickable=False)
        return ruler

    def add_legend_scale(
        self,
        corner_offset_factor=2.0,
        bottom_border_offset=30,
        top_border_offset=30,
        left_border_offset=30,
        right_border_offset=30,
        bottom_axis_visibility=True,
        top_axis_visibility=True,
        left_axis_visibility=True,
        right_axis_visibility=True,
        legend_visibility=True,
        xy_label_mode=False,
        render=True,
        color=None,
        font_size_factor=0.6,
        label_size_factor=1.0,
        label_format=None,
        number_minor_ticks=0,
        tick_length=5,
        minor_tick_length=3,
        show_ticks=True,
        tick_label_offset=2,
    ):
        """Annotate the render window with scale and distance information.

        Its basic goal is to provide an indication of the scale of the scene.
        Four axes surrounding the render window indicate (in a variety of ways)
        the scale of what the camera is viewing. An option also exists for
        displaying a scale legend.

        Parameters
        ----------
        corner_offset_factor : float, default: 2.0
            The corner offset value.

        bottom_border_offset : int, default: 30
            Bottom border offset. Recommended value ``50``.

        top_border_offset : int, default: 30
            Top border offset. Recommended value ``50``.

        left_border_offset : int, default: 30
            Left border offset. Recommended value ``100``.

        right_border_offset : int, default: 30
            Right border offset. Recommended value ``100``.

        bottom_axis_visibility : bool, default: True
            Whether the bottom axis is visible.

        top_axis_visibility : bool, default: True
            Whether the top axis is visible.

        left_axis_visibility : bool, default: True
            Whether the left axis is visible.

        right_axis_visibility : bool, default: True
            Whether the right axis is visible.

        legend_visibility : bool, default: True
            Whether the legend scale is visible.

        xy_label_mode : bool, default: False
            The axes can be programmed either to display distance scales
            or x-y coordinate values. By default,
            the scales display a distance. However, if you know that the
            view is down the z-axis, the scales can be programmed to display
            x-y coordinate values.

        render : bool, default: True
            Whether to render when the actor is added.

        color : ColorLike, optional
            Either a string, rgb list, or hex color string for tick text
            and tick line colors.

            .. warning::
                The axis labels tend to be either white or black.

        font_size_factor : float, default: 0.6
            Factor to scale font size overall.

        label_size_factor : float, default: 1.0
            Factor to scale label size relative to title size.

        label_format : str, optional
            A printf style format for labels, e.g. ``'%E'``.
            See :ref:`old-string-formatting`.

        number_minor_ticks : int, default: 0
            Number of minor ticks between major ticks.

        tick_length : int, default: 5
            Length of ticks in pixels.

        minor_tick_length : int, default: 3
            Length of minor ticks in pixels.

        show_ticks : bool, default: True
            Whether to show the ticks.

        tick_label_offset : int, default: 2
            Offset between tick and label in pixels.

        Returns
        -------
        vtk.vtkActor
            The actor for the added ``vtkLegendScaleActor``.

        Warnings
        --------
        Please be aware that the axes and scale values are subject to perspective
        effects. The distances are computed in the focal plane of the camera. When
        there are large view angles (i.e., perspective projection), the computed
        distances may provide users the wrong sense of scale. These effects are not
        present when parallel projection is enabled.

        Examples
        --------
        >>> import pyvista as pv
        >>> cone = pv.Cone(height=2.0, radius=0.5)
        >>> pl = pv.Plotter()
        >>> _ = pl.add_mesh(cone)
        >>> _ = pl.add_legend_scale()
        >>> pl.show()

        """
        color = Color(color, default_color=self._theme.font.color)

        legend_scale = _vtk.vtkLegendScaleActor()
        legend_scale.SetCornerOffsetFactor(corner_offset_factor)
        legend_scale.SetLegendVisibility(legend_visibility)
        if xy_label_mode:
            legend_scale.SetLabelModeToXYCoordinates()
        else:
            legend_scale.SetLabelModeToDistance()
        legend_scale.SetBottomAxisVisibility(bottom_axis_visibility)
        legend_scale.SetBottomBorderOffset(bottom_border_offset)
        legend_scale.SetLeftAxisVisibility(left_axis_visibility)
        legend_scale.SetLeftBorderOffset(left_border_offset)
        legend_scale.SetRightAxisVisibility(right_axis_visibility)
        legend_scale.SetRightBorderOffset(right_border_offset)
        legend_scale.SetTopAxisVisibility(top_axis_visibility)
        legend_scale.SetTopBorderOffset(top_border_offset)

        for text in ['Label', 'Title']:
            prop = getattr(legend_scale, f'GetLegend{text}Property')()
            if color != Color('white'):
                # This property turns black if set
                prop.SetColor(*color.int_rgb)
            prop.SetFontSize(
                int(font_size_factor * 20)
            )  # hack to avoid multiple font size arguments

        for ax in ['Bottom', 'Left', 'Right', 'Top']:
            axis = getattr(legend_scale, f'Get{ax}Axis')()
            axis.GetProperty().SetColor(*color.int_rgb)
            if color != Color('white'):
                # This label property turns black if set
                axis.GetLabelTextProperty().SetColor(*color.int_rgb)
            axis.SetFontFactor(font_size_factor)
            axis.SetLabelFactor(label_size_factor)
            if label_format:
                axis.SetLabelFormat(label_format)
            axis.SetNumberOfMinorTicks(number_minor_ticks)
            axis.SetTickLength(tick_length)
            axis.SetMinorTickLength(minor_tick_length)
            axis.SetTickVisibility(show_ticks)
            axis.SetTickOffset(tick_label_offset)

        return self.add_actor(
            legend_scale,
            reset_camera=False,
            name='_vtkLegendScaleActor',
            culling=False,
            pickable=False,
            render=render,
        )


def _line_for_legend():
    """Create a simple line-like rectangle for the legend."""
    points = [
        [0, 0, 0],
        [0.4, 0, 0],
        [0.4, 0.07, 0],
        [0, 0.07, 0],
        [
            0.5,
            0,
            0,
        ],  # last point needed to expand the bounds of the PolyData to be rendered smaller
    ]
    legendface = pyvista.PolyData()
    legendface.points = np.array(points)
    legendface.faces = [4, 0, 1, 2, 3]
    return legendface


# pyvista/plotting/renderers.py

"""Organize Renderers for ``pyvista.Plotter``."""
import collections
from weakref import proxy

import numpy as np

import pyvista

from .background_renderer import BackgroundRenderer
from .renderer import Renderer


class Renderers:
    """Organize Renderers for ``pyvista.Plotter``.

    Parameters
    ----------
    plotter : str
        The PyVista plotter.

    shape : tuple[int], optional
        The initial shape of the PyVista plotter, (rows, columns).

    splitting_position : float, optional
        The position to place the splitting line between plots.

    row_weights : sequence, optional
        The weights of the rows when the plot window is resized.

    col_weights : sequence, optional
        The weights of the columns when the plot window is resized.

    groups : list, optional
        A list of sequences that defines the grouping of the sub-datasets.

    border : bool, optional
        Whether or not a border should be added around each subplot.

    border_color : str, optional
        The color of the border around each subplot.

    border_width : float, optional
        The width of the border around each subplot.
    """

    def __init__(
        self,
        plotter,
        shape=(1, 1),
        splitting_position=None,
        row_weights=None,
        col_weights=None,
        groups=None,
        border=None,
        border_color='k',
        border_width=2.0,
    ):
        """Initialize renderers."""
        self._active_index = 0  # index of the active renderer
        self._plotter = proxy(plotter)
        self._renderers = []
        self._shadow_renderer = None

        # by default add border for multiple plots
        if border is None:
            if shape != (1, 1):
                border = True
            else:
                border = False

        self.groups = np.empty((0, 4), dtype=int)

        if isinstance(shape, str):
            if '|' in shape:
                n = int(shape.split('|')[0])
                m = int(shape.split('|')[1])
                rangen = reversed(range(n))
                rangem = reversed(range(m))
            else:
                m = int(shape.split('/')[0])
                n = int(shape.split('/')[1])
                rangen = range(n)
                rangem = range(m)

            if splitting_position is None:
                splitting_position = pyvista.global_theme.multi_rendering_splitting_position

            if splitting_position is None:
                if n >= m:
                    xsplit = m / (n + m)
                else:
                    xsplit = 1 - n / (n + m)
            else:
                xsplit = splitting_position

            for i in rangen:
                arenderer = Renderer(self._plotter, border, border_color, border_width)
                if '|' in shape:
                    arenderer.SetViewport(0, i / n, xsplit, (i + 1) / n)
                else:
                    arenderer.SetViewport(i / n, 0, (i + 1) / n, xsplit)
                self._renderers.append(arenderer)
            for i in rangem:
                arenderer = Renderer(self._plotter, border, border_color, border_width)
                if '|' in shape:
                    arenderer.SetViewport(xsplit, i / m, 1, (i + 1) / m)
                else:
                    arenderer.SetViewport(i / m, xsplit, (i + 1) / m, 1)
                self._renderers.append(arenderer)

            self._shape = (n + m,)
            self._render_idxs = np.arange(n + m)

        else:
            if not isinstance(shape, (np.ndarray, collections.abc.Sequence)):
                raise TypeError('"shape" should be a list, tuple or string descriptor')
            if len(shape) != 2:
                raise ValueError('"shape" must have length 2.')
            shape = np.asarray(shape)
            if not np.issubdtype(shape.dtype, np.integer) or (shape <= 0).any():
                raise ValueError('"shape" must contain only positive integers.')
            # always assign shape as a tuple
            self._shape = tuple(shape)
            self._render_idxs = np.empty(self._shape, dtype=int)
            # Check if row and col weights correspond to given shape,
            # or initialize them to defaults (equally weighted).

            # and convert to normalized offsets
            if row_weights is None:
                row_weights = np.ones(shape[0])
            if col_weights is None:
                col_weights = np.ones(shape[1])

            # also make flattening and abs explicit
            row_weights = np.abs(np.asanyarray(row_weights).ravel())
            col_weights = np.abs(np.asanyarray(col_weights).ravel())
            if row_weights.size != shape[0]:
                raise ValueError(
                    f'"row_weights" must have {shape[0]} items '
                    f'for {shape[0]} rows of subplots, not '
                    f'{row_weights.size}.'
                )
            if col_weights.size != shape[1]:
                raise ValueError(
                    f'"col_weights" must have {shape[1]} items '
                    f'for {shape[1]} columns of subplots, not '
                    f'{col_weights.size}.'
                )
            row_off = np.cumsum(row_weights) / np.sum(row_weights)
            row_off = 1 - np.concatenate(([0], row_off))
            col_off = np.cumsum(col_weights) / np.sum(col_weights)
            col_off = np.concatenate(([0], col_off))

            # Check and convert groups to internal format (Nx4 matrix
            # where every row contains the row and col index of the
            # top left cell)

            if groups is not None:
                if not isinstance(groups, collections.abc.Sequence):
                    raise TypeError(
                        f'"groups" should be a list or tuple, not {type(groups).__name__}.'
                    )
                for group in groups:
                    if not isinstance(group, collections.abc.Sequence):
                        raise TypeError(
                            'Each group entry should be a list or '
                            f'tuple, not {type(group).__name__}.'
                        )
                    if len(group) != 2:
                        raise ValueError('Each group entry must have length 2.')

                    rows = group[0]
                    if isinstance(rows, slice):
                        rows = np.arange(self.shape[0], dtype=int)[rows]
                    cols = group[1]
                    if isinstance(cols, slice):
                        cols = np.arange(self.shape[1], dtype=int)[cols]
                    # Get the normalized group, i.e. extract top left corner
                    # and bottom right corner from the given rows and cols
                    norm_group = [np.min(rows), np.min(cols), np.max(rows), np.max(cols)]
                    # Check for overlap with already defined groups:
                    for i in range(norm_group[0], norm_group[2] + 1):
                        for j in range(norm_group[1], norm_group[3] + 1):
                            if self.loc_to_group((i, j)) is not None:
                                raise ValueError(
                                    f'Groups cannot overlap. Overlap found at position {(i, j)}.'
                                )
                    self.groups = np.concatenate(
                        (self.groups, np.array([norm_group], dtype=int)), axis=0
                    )
            # Create subplot renderers
            for row in range(shape[0]):
                for col in range(shape[1]):
                    group = self.loc_to_group((row, col))
                    nb_rows = None
                    nb_cols = None
                    if group is not None:
                        if row == self.groups[group, 0] and col == self.groups[group, 1]:
                            # Only add renderer for first location of the group
                            nb_rows = 1 + self.groups[group, 2] - self.groups[group, 0]
                            nb_cols = 1 + self.groups[group, 3] - self.groups[group, 1]
                    else:
                        nb_rows = 1
                        nb_cols = 1
                    if nb_rows is not None:
                        renderer = Renderer(self._plotter, border, border_color, border_width)
                        x0 = col_off[col]
                        y0 = row_off[row + nb_rows]
                        x1 = col_off[col + nb_cols]
                        y1 = row_off[row]
                        renderer.SetViewport(x0, y0, x1, y1)
                        self._render_idxs[row, col] = len(self)
                        self._renderers.append(renderer)
                    else:
                        self._render_idxs[row, col] = self._render_idxs[
                            self.groups[group, 0], self.groups[group, 1]
                        ]

        # each render will also have an associated background renderer
        self._background_renderers = [None for _ in range(len(self))]

        # create a shadow renderer that lives on top of all others
        self._shadow_renderer = Renderer(self._plotter, border, border_color, border_width)
        self._shadow_renderer.SetViewport(0, 0, 1, 1)
        self._shadow_renderer.SetDraw(False)

    def loc_to_group(self, loc):
        """Return index of the render window given a location index.

        Parameters
        ----------
        loc : int | sequence[int]
            Index of the renderer to add the actor to.  For example, ``loc=2``
            or ``loc=(1, 1)``.

        Returns
        -------
        int
            Index of the render window.
        """
        group_idxs = np.arange(self.groups.shape[0])
        index = (
            (loc[0] >= self.groups[:, 0])
            & (loc[0] <= self.groups[:, 2])
            & (loc[1] >= self.groups[:, 1])
            & (loc[1] <= self.groups[:, 3])
        )
        group = group_idxs[index]
        return None if group.size == 0 else group[0]

    def loc_to_index(self, loc):
        """Return index of the render window given a location index.

        Parameters
        ----------
        loc : int | sequence[int]
            Index of the renderer to add the actor to. For example, ``loc=2``
            or ``loc=(1, 1)``.

        Returns
        -------
        int
            Index of the render window.

        """
        if isinstance(loc, (int, np.integer)):
            return loc
        elif isinstance(loc, (np.ndarray, collections.abc.Sequence)):
            if not len(loc) == 2:
                raise ValueError('"loc" must contain two items')
            index_row = loc[0]
            index_column = loc[1]
            if index_row < 0 or index_row >= self.shape[0]:
                raise IndexError(f'Row index is out of range ({self.shape[0]})')
            if index_column < 0 or index_column >= self.shape[1]:
                raise IndexError(f'Column index is out of range ({self.shape[1]})')
            return self._render_idxs[index_row, index_column]
        else:
            raise TypeError('"loc" must be an integer or a sequence.')

    def __getitem__(self, index):
        """Return a renderer based on an index."""
        return self._renderers[index]

    def __len__(self):
        """Return number of renderers."""
        return len(self._renderers)

    def __iter__(self):
        """Return a iterable of renderers."""
        yield from self._renderers

    @property
    def active_index(self):  # numpydoc ignore=RT01
        """Return the active index.

        Returns
        -------
        int
            Active index.
        """
        return self._active_index

    def index_to_loc(self, index):
        """Convert a 1D index location to the 2D location on the plotting grid.

        Parameters
        ----------
        index : int
            A scalar integer that refers to the 1D location index.

        Returns
        -------
        numpy.ndarray
            2D location on the plotting grid.
        """
        if not isinstance(index, (int, np.integer)):
            raise TypeError('"index" must be a scalar integer.')
        if len(self.shape) == 1:
            return index
        args = np.argwhere(self._render_idxs == index)
        if len(args) < 1:
            raise IndexError(f'Index ({index}) is out of range.')
        return args[0]

    @property
    def active_renderer(self):  # numpydoc ignore=RT01
        """Return the active renderer.

        Returns
        -------
        Renderer
            Active renderer.
        """
        return self._renderers[self._active_index]

    @property
    def shape(self):  # numpydoc ignore=RT01
        """Return the shape of the renderers.

        Returns
        -------
        tuple
            Shape of the renderers.
        """
        return self._shape

    def set_active_renderer(self, index_row, index_column=None):
        """Set the index of the active renderer.

        Parameters
        ----------
        index_row : int
            Index of the subplot to activate along the rows.

        index_column : int, optional
            Index of the subplot to activate along the columns.

        """
        if len(self.shape) == 1:
            self._active_index = index_row
            return

        if index_row < 0 or index_row >= self.shape[0]:
            raise IndexError(f'Row index is out of range ({self.shape[0]})')
        if index_column < 0 or index_column >= self.shape[1]:
            raise IndexError(f'Column index is out of range ({self.shape[1]})')
        self._active_index = self.loc_to_index((index_row, index_column))

    def set_chart_interaction(self, interactive, toggle=False):
        """
        Set or toggle interaction with charts for the active renderer.

        Interaction with other charts in other renderers is disabled.
        Interaction with other charts in the active renderer is only disabled
        when ``toggle`` is ``False``.

        Parameters
        ----------
        interactive : bool | Chart | int | sequence[Chart] | sequence[int]
            Following parameter values are accepted:

            * A boolean to enable (``True``) or disable (``False``) interaction
              with all charts in the active renderer.
            * The chart or its index to enable interaction with. Interaction
              with multiple charts can be enabled by passing a list of charts
              or indices.

        toggle : bool, default: False
            Instead of enabling interaction with the provided chart(s), interaction
            with the provided chart(s) is toggled. Only applicable when ``interactive``
            is not a boolean.

        Returns
        -------
        list of Chart
            The list of all interactive charts for the active renderer.

        """
        interactive_scene, interactive_charts = None, []
        if self.active_renderer.has_charts:
            interactive_scene = self.active_renderer._charts._scene
            interactive_charts = self.active_renderer.set_chart_interaction(interactive, toggle)
        # Disable chart interaction for other renderers
        for renderer in self:
            if renderer is not self.active_renderer:
                renderer.set_chart_interaction(False)
        # Setup the context interactor style based on the resulting amount of interactive charts.
        self._plotter.iren._set_context_style(interactive_scene if interactive_charts else None)
        return interactive_charts

    def on_plotter_render(self):
        """Notify all renderers of explicit plotter render call."""
        for renderer in self:
            renderer.on_plotter_render()

    def deep_clean(self):
        """Clean all renderers."""
        # Do not remove the renderers on the clean
        for renderer in self:
            renderer.deep_clean()
        if self._shadow_renderer is not None:
            self._shadow_renderer.deep_clean()
        if hasattr(self, '_background_renderers'):
            for renderer in self._background_renderers:
                if renderer is not None:
                    renderer.deep_clean()

    def add_background_renderer(self, image_path, scale, as_global):
        """Add a background image to the renderers.

        Parameters
        ----------
        image_path : str
            Path to an image file.

        scale : float
            Scale the image larger or smaller relative to the size of
            the window.  For example, a scale size of 2 will make the
            largest dimension of the image twice as large as the
            largest dimension of the render window.  Defaults to 1.

        as_global : bool
            When multiple render windows are present, setting
            ``as_global=False`` will cause the background to only
            appear in one window.

        Returns
        -------
        pyvista.BackgroundRenderer
            Newly created background renderer.

        """
        # verify no render exists
        if as_global:
            for renderer in self:
                renderer.layer = 2
            view_port = None
        else:
            self.active_renderer.layer = 2
            view_port = self.active_renderer.GetViewport()

        renderer = BackgroundRenderer(self._plotter, image_path, scale, view_port)
        renderer.layer = 1
        self._background_renderers[self.active_index] = renderer
        return renderer

    @property
    def has_active_background_renderer(self):  # numpydoc ignore=RT01
        """Return ``True`` when Renderer has an active background renderer.

        Returns
        -------
        bool
            Whether or not the active renderer has a background renderer.

        """
        return self._background_renderers[self.active_index] is not None

    def clear_background_renderers(self):
        """Clear all background renderers."""
        for renderer in self._background_renderers:
            if renderer is not None:
                renderer.clear()

    def clear_actors(self):
        """Clear actors from all renderers."""
        for renderer in self:
            renderer.clear_actors()

    def clear(self):
        """Clear all renders."""
        for renderer in self:
            renderer.clear()
        self._shadow_renderer.clear()
        self.clear_background_renderers()

    def close(self):
        """Close all renderers."""
        for renderer in self:
            renderer.close()

        self._shadow_renderer.close()

        for renderer in self._background_renderers:
            if renderer is not None:
                renderer.close()

    def remove_all_lights(self):
        """Remove all lights from all renderers."""
        for renderer in self:
            renderer.remove_all_lights()

    @property
    def shadow_renderer(self):  # numpydoc ignore=RT01
        """Shadow renderer.

        Returns
        -------
        pyvista.plotting.renderer.Renderer
            Shadow renderer.
        """
        return self._shadow_renderer

    def set_background(self, color, top=None, all_renderers=True):
        """Set the background color.

        Parameters
        ----------
        color : ColorLike, optional
            Either a string, rgb list, or hex color string.  Defaults
            to current theme parameters.  For example:

            * ``color='white'``
            * ``color='w'``
            * ``color=[1.0, 1.0, 1.0]``
            * ``color='#FFFFFF'``

        top : ColorLike, optional
            If given, this will enable a gradient background where the
            ``color`` argument is at the bottom and the color given in ``top``
            will be the color at the top of the renderer.

        all_renderers : bool, default: True
            If ``True``, applies to all renderers in subplots. If ``False``,
            then only applies to the active renderer.

        Examples
        --------
        Set the background color to black.

        >>> import pyvista
        >>> plotter = pyvista.Plotter()
        >>> plotter.set_background('black')
        >>> plotter.background_color
        Color(name='black', hex='#000000ff', opacity=255)
        >>> plotter.close()

        Set the background color at the bottom to black and white at
        the top.  Display a cone as well.

        >>> import pyvista
        >>> pl = pyvista.Plotter()
        >>> actor = pl.add_mesh(pyvista.Cone())
        >>> pl.set_background('black', top='white')
        >>> pl.show()

        """
        if all_renderers:
            for renderer in self:
                renderer.set_background(color, top=top)
            self._shadow_renderer.set_background(color)
        else:
            self.active_renderer.set_background(color, top=top)

    def set_color_cycler(self, color_cycler, all_renderers=True):
        """Set or reset the color cycler.

        This color cycler is iterated over by each sequential :class:`add_mesh() <pyvista.Plotter.add_mesh>`
        call to set the default color of the dataset being plotted.

        When setting, the value must be either a list of color-like objects,
        or a cycler of color-like objects. If the value passed is a single
        string, it must be one of:

            * ``'default'`` - Use the default color cycler (matches matplotlib's default)
            * ``'matplotlib`` - Dynamically get matplotlib's current theme's color cycler.
            * ``'all'`` - Cycle through all of the available colors in ``pyvista.plotting.colors.hexcolors``

        Setting to ``None`` will disable the use of the color cycler on this
        renderer.

        Parameters
        ----------
        color_cycler : str | cycler.Cycler | sequence[ColorLike]
            The colors to cycle through.

        all_renderers : bool, default: True
            If ``True``, applies to all renderers in subplots. If ``False``,
            then only applies to the active renderer.

        Examples
        --------
        Set the default color cycler to iterate through red, green, and blue.

        >>> import pyvista as pv
        >>> pl = pv.Plotter()
        >>> pl.set_color_cycler(['red', 'green', 'blue'])
        >>> _ = pl.add_mesh(pv.Cone(center=(0, 0, 0)))  # red
        >>> _ = pl.add_mesh(pv.Cube(center=(1, 0, 0)))  # green
        >>> _ = pl.add_mesh(pv.Sphere(center=(1, 1, 0)))  # blue
        >>> _ = pl.add_mesh(pv.Cylinder(center=(0, 1, 0)))  # red again
        >>> pl.show()

        """
        if all_renderers:
            for renderer in self:
                renderer.set_color_cycler(color_cycler)
        else:
            self.active_renderer.set_color_cycler(color_cycler)

    def remove_background_image(self):
        """Remove the background image at the current renderer.

        Examples
        --------
        >>> import pyvista
        >>> from pyvista import examples
        >>> pl = pyvista.Plotter(shape=(1, 2))
        >>> pl.subplot(0, 0)
        >>> actor = pl.add_mesh(pyvista.Sphere())
        >>> pl.add_background_image(examples.mapfile, as_global=False)
        >>> pl.subplot(0, 1)
        >>> actor = pl.add_mesh(pyvista.Cube())
        >>> pl.add_background_image(examples.mapfile, as_global=False)
        >>> pl.remove_background_image()
        >>> pl.show()

        """
        renderer = self._background_renderers[self.active_index]
        if renderer is None:
            raise RuntimeError('No background image to remove at this subplot')
        renderer.deep_clean()
        self._background_renderers[self.active_index] = None

    def __del__(self):
        """Destructor."""
        self._shadow_renderer = None


# pyvista/plotting/scalar_bars.py

"""PyVista Scalar bar module."""
import weakref

import numpy as np

import pyvista
from pyvista import MAX_N_COLOR_BARS

from . import _vtk
from .colors import Color
from .tools import parse_font_family


class ScalarBars:
    """Plotter Scalar Bars.

    Parameters
    ----------
    plotter : pyvista.Plotter
        Plotter that the scalar bars are associated with.

    """

    def __init__(self, plotter):
        """Initialize ScalarBars."""
        self._plotter = weakref.proxy(plotter)
        self._scalar_bar_ranges = {}
        self._scalar_bar_mappers = {}
        self._scalar_bar_actors = {}
        self._scalar_bar_widgets = {}

    def clear(self):
        """Remove all scalar bars and resets all scalar bar properties."""
        self._scalar_bar_ranges = {}
        self._scalar_bar_mappers = {}
        self._scalar_bar_actors = {}
        self._scalar_bar_widgets = {}

    def __repr__(self):
        """Nice representation of this class."""
        lines = []
        lines.append('Scalar Bar Title     Interactive')
        for title in self._scalar_bar_actors:
            interactive = title in self._scalar_bar_widgets
            title = f'"{title}"'
            lines.append(f'{title:20} {str(interactive):5}')
        return '\n'.join(lines)

    def _remove_mapper_from_plotter(
        self, actor, reset_camera=False, render=False
    ):  # numpydoc ignore=PR01,RT01
        """Remove an actor's mapper from the given plotter's _scalar_bar_mappers.

        This ensures that when actors are removed, their corresponding
        scalar bars are removed.

        """
        try:
            mapper = actor.GetMapper()
        except AttributeError:
            return

        # NOTE: keys to list to prevent iterator changing during loop
        for name in list(self._scalar_bar_mappers):
            try:
                self._scalar_bar_mappers[name].remove(mapper)
            except ValueError:
                pass

            if not self._scalar_bar_mappers[name]:
                slot = self._plotter._scalar_bar_slot_lookup.pop(name, None)
                if slot is not None:
                    self._scalar_bar_mappers.pop(name)
                    self._scalar_bar_ranges.pop(name)
                    self._plotter.remove_actor(
                        self._scalar_bar_actors.pop(name), reset_camera=reset_camera, render=render
                    )
                    self._plotter._scalar_bar_slots.add(slot)
            return

    def remove_scalar_bar(self, title=None, render=True):
        """Remove a scalar bar.

        Parameters
        ----------
        title : str, optional
            Title of the scalar bar to remove.  Required if there is
            more than one scalar bar.

        render : bool, default: True
            Render upon scalar bar removal.  Set this to ``False`` to
            stop the render window from rendering when a scalar bar
            is removed.

        Examples
        --------
        Remove a scalar bar from a plotter.

        >>> import pyvista as pv
        >>> mesh = pv.Sphere()
        >>> mesh['data'] = mesh.points[:, 2]
        >>> pl = pv.Plotter()
        >>> _ = pl.add_mesh(mesh, cmap='coolwarm')
        >>> pl.remove_scalar_bar()
        >>> pl.show()

        """
        if title is None:
            if len(self) > 1:
                titles = ', '.join(f'"{key}"' for key in self._scalar_bar_actors)
                raise ValueError(
                    'Multiple scalar bars found.  Pick title of the'
                    f'scalar bar from one of the following:\n{titles}'
                )
            else:
                title = list(self._scalar_bar_actors.keys())[0]

        actor = self._scalar_bar_actors.pop(title)
        self._plotter.remove_actor(actor, render=render)
        self._scalar_bar_ranges.pop(title)
        self._scalar_bar_mappers.pop(title)

        # add back in the scalar bar slot
        slot = self._plotter._scalar_bar_slot_lookup.pop(title, None)
        if slot is not None:
            self._plotter._scalar_bar_slots.add(slot)

        widget = self._scalar_bar_widgets.pop(title, None)
        if widget is not None:
            widget.SetEnabled(0)

    def __len__(self):
        """Return the number of scalar bar actors."""
        return len(self._scalar_bar_actors)

    def __getitem__(self, index):
        """Return a scalar bar actor."""
        return self._scalar_bar_actors[index]

    def keys(self):
        """Scalar bar keys."""
        return self._scalar_bar_actors.keys()

    def values(self):
        """Scalar bar values."""
        return self._scalar_bar_actors.values()

    def items(self):
        """Scalar bar items."""
        return self._scalar_bar_actors.items()

    def __contains__(self, key):
        """Check if a title is a valid actors."""
        return key in self._scalar_bar_actors

    def add_scalar_bar(
        self,
        title='',
        mapper=None,
        n_labels=5,
        italic=False,
        bold=False,
        title_font_size=None,
        label_font_size=None,
        color=None,
        font_family=None,
        shadow=False,
        width=None,
        height=None,
        position_x=None,
        position_y=None,
        vertical=None,
        interactive=None,
        fmt=None,
        use_opacity=True,
        outline=False,
        nan_annotation=False,
        below_label=None,
        above_label=None,
        background_color=None,
        n_colors=None,
        fill=False,
        render=False,
        theme=None,
    ):
        """Create scalar bar using the ranges as set by the last input mesh.

        Parameters
        ----------
        title : str, default: ""
            Title of the scalar bar.  Default is rendered as an empty title.

        mapper : vtkMapper, optional
            Mapper used for the scalar bar.  Defaults to the last
            mapper created by the plotter.

        n_labels : int, default: 5
            Number of labels to use for the scalar bar.

        italic : bool, default: False
            Italicises title and bar labels.

        bold : bool, default: False
            Bolds title and bar labels.

        title_font_size : float, optional
            Sets the size of the title font.  Defaults to ``None`` and is sized
            according to :attr:`pyvista.plotting.themes.Theme.font`.

        label_font_size : float, optional
            Sets the size of the title font.  Defaults to ``None`` and is sized
            according to :attr:`pyvista.plotting.themes.Theme.font`.

        color : ColorLike, optional
            Either a string, rgb list, or hex color string.  Default
            set by :attr:`pyvista.plotting.themes.Theme.font`.  Can be
            in one of the following formats:

            * ``color='white'``
            * ``color='w'``
            * ``color=[1.0, 1.0, 1.0]``
            * ``color='#FFFFFF'``

        font_family : {'courier', 'times', 'arial'}
            Font family.  Default is set by
            :attr:`pyvista.plotting.themes.Theme.font`.

        shadow : bool, default: False
            Adds a black shadow to the text.

        width : float, optional
            The percentage (0 to 1) width of the window for the colorbar.
            Default set by
            :attr:`pyvista.plotting.themes.Theme.colorbar_vertical` or
            :attr:`pyvista.plotting.themes.Theme.colorbar_horizontal`
            depending on the value of ``vertical``.

        height : float, optional
            The percentage (0 to 1) height of the window for the
            colorbar.  Default set by
            :attr:`pyvista.plotting.themes.Theme.colorbar_vertical` or
            :attr:`pyvista.plotting.themes.Theme.colorbar_horizontal`
            depending on the value of ``vertical``.

        position_x : float, optional
            The percentage (0 to 1) along the windows's horizontal
            direction to place the bottom left corner of the colorbar.
            Default set by
            :attr:`pyvista.plotting.themes.Theme.colorbar_vertical` or
            :attr:`pyvista.plotting.themes.Theme.colorbar_horizontal`
            depending on the value of ``vertical``.

        position_y : float, optional
            The percentage (0 to 1) along the windows's vertical
            direction to place the bottom left corner of the colorbar.
            Default set by
            :attr:`pyvista.plotting.themes.Theme.colorbar_vertical` or
            :attr:`pyvista.plotting.themes.Theme.colorbar_horizontal`
            depending on the value of ``vertical``.

        vertical : bool, optional
            Use vertical or horizontal scalar bar.  Default set by
            :attr:`pyvista.plotting.themes.Theme.colorbar_orientation`.

        interactive : bool, optional
            Use a widget to control the size and location of the scalar bar.
            Default set by :attr:`pyvista.plotting.themes.Theme.interactive`.

        fmt : str, optional
            ``printf`` format for labels.
            Default set by :attr:`pyvista.plotting.themes.Theme.font`.

        use_opacity : bool, default: True
            Optionally display the opacity mapping on the scalar bar.

        outline : bool, default: False
            Optionally outline the scalar bar to make opacity mappings more
            obvious.

        nan_annotation : bool, default: False
            Annotate the NaN color.

        below_label : str, optional
            String annotation for values below the scalars range.

        above_label : str, optional
            String annotation for values above the scalars range.

        background_color : ColorLike, optional
            The color used for the background in RGB format.

        n_colors : int, optional
            The maximum number of color displayed in the scalar bar.

        fill : bool, default: False
            Draw a filled box behind the scalar bar with the
            ``background_color``.

        render : bool, default: False
            Force a render when True.

        theme : pyvista.plotting.themes.Theme, optional
            Plot-specific theme.  By default, calling from the
            ``Plotter``, will use the plotter theme.  Setting to
            ``None`` will use the global theme.

        Returns
        -------
        vtk.vtkScalarBarActor
            Scalar bar actor.

        Notes
        -----
        Setting ``title_font_size``, or ``label_font_size`` disables
        automatic font sizing for both the title and label.

        Examples
        --------
        Add a custom interactive scalar bar that is horizontal, has an
        outline, and has a custom formatting.

        >>> import pyvista as pv
        >>> sphere = pv.Sphere()
        >>> sphere['Data'] = sphere.points[:, 2]
        >>> plotter = pv.Plotter()
        >>> _ = plotter.add_mesh(sphere, show_scalar_bar=False)
        >>> _ = plotter.add_scalar_bar(
        ...     'Data',
        ...     interactive=True,
        ...     vertical=False,
        ...     title_font_size=35,
        ...     label_font_size=30,
        ...     outline=True,
        ...     fmt='%10.5f',
        ... )
        >>> plotter.show()

        """
        if mapper is None:
            raise ValueError('Mapper cannot be ``None`` when creating a scalar bar')

        if theme is None:
            theme = pyvista.global_theme

        if interactive is None:
            interactive = theme.interactive
        if font_family is None:
            font_family = theme.font.family
        if label_font_size is None:
            label_font_size = theme.font.label_size
        if title_font_size is None:
            title_font_size = theme.font.title_size
        if fmt is None:
            fmt = theme.font.fmt
        if vertical is None:
            if theme.colorbar_orientation.lower() == 'vertical':
                vertical = True

        # Automatically choose size if not specified
        if width is None:
            if vertical:
                width = theme.colorbar_vertical.width
            else:
                width = theme.colorbar_horizontal.width
        if height is None:
            if vertical:
                height = theme.colorbar_vertical.height
            else:
                height = theme.colorbar_horizontal.height

        # Check that this data hasn't already been plotted
        if title in list(self._scalar_bar_ranges.keys()):
            clim = list(self._scalar_bar_ranges[title])
            newrng = mapper.scalar_range
            oldmappers = self._scalar_bar_mappers[title]
            # get max for range and reset everything
            if newrng[0] < clim[0]:
                clim[0] = newrng[0]
            if newrng[1] > clim[1]:
                clim[1] = newrng[1]
            for mh in oldmappers:
                mh.scalar_range = clim[0], clim[1]
            mapper.scalar_range = clim[0], clim[1]
            self._scalar_bar_mappers[title].append(mapper)
            self._scalar_bar_ranges[title] = clim
            self._scalar_bar_actors[title].SetLookupTable(mapper.lookup_table)
            # Color bar already present and ready to be used so returning
            return

        # Automatically choose location if not specified
        if position_x is None or position_y is None:
            if not self._plotter._scalar_bar_slots:
                raise RuntimeError(f'Maximum number of color bars ({MAX_N_COLOR_BARS}) reached.')

            slot = min(self._plotter._scalar_bar_slots)
            self._plotter._scalar_bar_slots.remove(slot)
            self._plotter._scalar_bar_slot_lookup[title] = slot

            if position_x is None:
                if vertical:
                    position_x = theme.colorbar_vertical.position_x
                    position_x -= slot * (width + 0.2 * width)
                else:
                    position_x = theme.colorbar_horizontal.position_x

            if position_y is None:
                if vertical:
                    position_y = theme.colorbar_vertical.position_y
                else:
                    position_y = theme.colorbar_horizontal.position_y
                    position_y += slot * height

        # parse color
        color = Color(color, default_color=theme.font.color)

        # Create scalar bar
        scalar_bar = _vtk.vtkScalarBarActor()
        # self._scalar_bars.append(scalar_bar)

        if background_color is not None:
            background_color = np.array(Color(background_color).int_rgba)
            scalar_bar.GetBackgroundProperty().SetColor(background_color[0:3])

            if fill:
                scalar_bar.DrawBackgroundOn()

            lut = pyvista.LookupTable()
            lut.DeepCopy(mapper.lookup_table)
            ctable = _vtk.vtk_to_numpy(lut.GetTable())
            alphas = ctable[:, -1][:, np.newaxis] / 255.0
            use_table = ctable.copy()
            use_table[:, -1] = 255.0
            ctable = (use_table * alphas) + background_color * (1 - alphas)
            lut.SetTable(_vtk.numpy_to_vtk(ctable, array_type=_vtk.VTK_UNSIGNED_CHAR))
        else:
            lut = mapper.lookup_table

        scalar_bar.SetLookupTable(lut)
        if n_colors is None:
            # ensure the number of colors in the scalarbar's lookup table is at
            # least the number in the mapper
            n_colors = mapper.lookup_table.n_values

        scalar_bar.SetMaximumNumberOfColors(n_colors)

        if n_labels < 1:
            scalar_bar.SetDrawTickLabels(False)
        else:
            scalar_bar.SetDrawTickLabels(True)
            scalar_bar.SetNumberOfLabels(n_labels)

        if nan_annotation:
            scalar_bar.DrawNanAnnotationOn()

        if above_label is not None:
            scalar_bar.DrawAboveRangeSwatchOn()
            scalar_bar.SetAboveRangeAnnotation(above_label)
        elif lut.above_range_color:
            scalar_bar.DrawAboveRangeSwatchOn()
            scalar_bar.SetAboveRangeAnnotation('above')
        if below_label is not None:
            scalar_bar.DrawBelowRangeSwatchOn()
            scalar_bar.SetBelowRangeAnnotation(below_label)
        elif lut.below_range_color:
            scalar_bar.DrawBelowRangeSwatchOn()
            scalar_bar.SetBelowRangeAnnotation('below')

        # edit the size of the colorbar
        scalar_bar.SetHeight(height)
        scalar_bar.SetWidth(width)
        scalar_bar.SetPosition(position_x, position_y)

        if fmt is not None:
            scalar_bar.SetLabelFormat(fmt)

        if vertical:
            scalar_bar.SetOrientationToVertical()
        else:
            scalar_bar.SetOrientationToHorizontal()

        if label_font_size is not None or title_font_size is not None:
            scalar_bar.SetUnconstrainedFontSize(True)
            scalar_bar.SetAnnotationTextScaling(False)
        else:
            scalar_bar.SetAnnotationTextScaling(True)

        label_text = scalar_bar.GetLabelTextProperty()
        anno_text = scalar_bar.GetAnnotationTextProperty()
        label_text.SetColor(color.float_rgb)
        anno_text.SetColor(color.float_rgb)
        label_text.SetShadow(shadow)
        anno_text.SetShadow(shadow)

        # Set font
        label_text.SetFontFamily(parse_font_family(font_family))
        anno_text.SetFontFamily(parse_font_family(font_family))
        label_text.SetItalic(italic)
        anno_text.SetItalic(italic)
        label_text.SetBold(bold)
        anno_text.SetBold(bold)
        if label_font_size:
            label_text.SetFontSize(label_font_size)
            anno_text.SetFontSize(label_font_size)

        # Set properties
        self._scalar_bar_ranges[title] = mapper.scalar_range
        self._scalar_bar_mappers[title] = [mapper]

        scalar_bar.SetTitle(title)
        title_text = scalar_bar.GetTitleTextProperty()

        title_text.SetJustificationToCentered()

        title_text.SetItalic(italic)
        title_text.SetBold(bold)
        title_text.SetShadow(shadow)
        if title_font_size:
            title_text.SetFontSize(title_font_size)

        # Set font
        title_text.SetFontFamily(parse_font_family(font_family))

        # set color
        title_text.SetColor(color.float_rgb)

        self._scalar_bar_actors[title] = scalar_bar
        if interactive:
            scalar_widget = _vtk.vtkScalarBarWidget()
            scalar_widget.SetScalarBarActor(scalar_bar)
            scalar_widget.SetInteractor(self._plotter.iren.interactor)
            scalar_widget.SetEnabled(1)
            rep = scalar_widget.GetRepresentation()

            scalar_widget.On()
            if vertical is True or vertical is None:
                rep.SetOrientation(1)  # 0 = Horizontal, 1 = Vertical
            else:
                # y position determined empirically
                y = -position_y / 2 - height - scalar_bar.GetPosition()[1]
                rep.GetPositionCoordinate().SetValue(width, y)
                rep.GetPosition2Coordinate().SetValue(height, width)
                rep.SetOrientation(0)  # 0 = Horizontal, 1 = Vertical
            self._scalar_bar_widgets[title] = scalar_widget

        if use_opacity:
            scalar_bar.SetUseOpacity(True)

        if outline:
            scalar_bar.SetDrawFrame(True)
            frame_prop = scalar_bar.GetFrameProperty()
            frame_prop.SetColor(color.float_rgb)
        else:
            scalar_bar.SetDrawFrame(False)

        # finally, add to the actor and return the scalar bar
        self._plotter.add_actor(scalar_bar, reset_camera=False, pickable=False, render=render)

        return scalar_bar


# pyvista/plotting/texture.py

"""This module provides a wrapper for vtk.vtkTexture."""

from collections.abc import Sequence
from typing import Union
import warnings

import numpy as np

import pyvista as pv
from pyvista.core.dataset import DataObject
from pyvista.core.errors import PyVistaDeprecationWarning
from pyvista.core.utilities.fileio import _try_imageio_imread
from pyvista.core.utilities.misc import AnnotatedIntEnum

from . import _vtk


class Texture(_vtk.vtkTexture, DataObject):
    """Wrap vtkTexture.

    Textures can be used to apply images to surfaces, as in the case of
    :ref:`ref_texture_example`.

    They can also be used for environment textures to affect the lighting of
    the scene, or even as a environment cubemap as in the case of
    :ref:`pbr_example` and :ref:`planets_example`.

    Parameters
    ----------
    uinput : str, vtkImageData, vtkTexture, sequence[pyvista.ImageData], optional
        Filename, ``vtkImageData``, ``vtkTexture``, :class:`numpy.ndarray` or a
        sequence of images to create a cubemap. If a sequence of images, must
        be of the same size and in the following order:

        * +X
        * -X
        * +Y
        * -Y
        * +Z
        * -Z

    **kwargs : dict, optional
        Optional arguments when reading from a file. Generally unused.

    Examples
    --------
    Load a texture from file. File should be a "image" or "image-like" file.

    >>> import os
    >>> import pyvista as pv
    >>> from pyvista import examples
    >>> path = examples.download_masonry_texture(load=False)
    >>> os.path.basename(path)
    'masonry.bmp'
    >>> texture = pv.Texture(path)
    >>> texture
    Texture (...)
      Components:   3
      Cube Map:     False
      Dimensions:   256, 256

    Create a texture from an RGB array. Note how this is colored per "point"
    rather than per "pixel".

    >>> import numpy as np
    >>> arr = np.array(
    ...     [
    ...         [255, 255, 255],
    ...         [255, 0, 0],
    ...         [0, 255, 0],
    ...         [0, 0, 255],
    ...     ],
    ...     dtype=np.uint8,
    ... )
    >>> arr = arr.reshape((2, 2, 3))
    >>> texture = pv.Texture(arr)
    >>> texture.plot()

    Create a cubemap from 6 images.

    >>> px = examples.download_sky(direction='posx')  # doctest:+SKIP
    >>> nx = examples.download_sky(direction='negx')  # doctest:+SKIP
    >>> py = examples.download_sky(direction='posy')  # doctest:+SKIP
    >>> ny = examples.download_sky(direction='negy')  # doctest:+SKIP
    >>> pz = examples.download_sky(direction='posz')  # doctest:+SKIP
    >>> nz = examples.download_sky(direction='negz')  # doctest:+SKIP
    >>> texture = pyvista.Texture(
    ...     [px, nx, py, ny, pz, nz]
    ... )  # doctest:+SKIP
    >>> texture.cube_map  # doctest:+SKIP
    True

    """

    class WrapType(AnnotatedIntEnum):
        """Types of wrapping a texture can support.

        Wrap mode for the texture coordinates valid values are:

        * CLAMP_TO_EDGE
        * REPEAT (Default in :class:`pyvista.Texture`)
        * MIRRORED_REPEAT
        * CLAMP_TO_BORDER

        See :attr:`Texture.wrap` for usage.

        """

        CLAMP_TO_EDGE = (0, 'Clamp to edge')
        REPEAT = (1, 'Repeat')
        MIRRORED_REPEAT = (2, 'Mirrored repeat')
        CLAMP_TO_BORDER = (3, 'Clamp to border')

    def __init__(self, uinput=None, **kwargs):
        """Initialize the texture."""
        super().__init__(uinput, **kwargs)

        if isinstance(uinput, _vtk.vtkTexture):
            self._from_texture(uinput)
        elif isinstance(uinput, np.ndarray):
            self._from_array(uinput)
        elif isinstance(uinput, _vtk.vtkImageData):
            self._from_image_data(uinput)
        elif isinstance(uinput, str):
            self._from_file(filename=uinput, **kwargs)
        elif isinstance(uinput, Sequence) and len(uinput) == 6:
            # Create a cubemap
            self.mipmap = True
            self.interpolate = True
            self.cube_map = True  # Must be set prior to setting images

            # add each image to the cubemap
            for i, image in enumerate(uinput):
                if not isinstance(image, pv.ImageData):
                    raise TypeError(
                        'If a sequence, the each item in the first argument must be a '
                        'pyvista.ImageData'
                    )
                # must flip y for cubemap to display properly
                self.SetInputDataObject(i, image._flip_uniform(1))
        elif uinput is None:
            pass
        else:
            raise TypeError(f'Cannot create a pyvista.Texture from ({type(uinput)})')

    def _from_file(self, filename, **kwargs):
        try:
            image = pv.read(filename, **kwargs)
            if image.n_points < 2:
                raise RuntimeError("Problem reading the image with VTK.")  # pragma: no cover
            self._from_image_data(image)
        except (KeyError, ValueError, OSError):
            self._from_array(_try_imageio_imread(filename))  # pragma: no cover

    def _from_texture(self, texture):
        image = texture.GetInput()
        self._from_image_data(image)

    @property
    def interpolate(self) -> bool:  # numpydoc ignore=RT01
        """Return if interpolate is enabled or disabled.

        Examples
        --------
        Show the masonry texture without interpolation. Here, we zoom to show
        the individual pixels.

        >>> from pyvista import examples
        >>> texture = examples.download_masonry_texture()
        >>> texture.interpolation = False
        >>> texture.plot(cpos='xy', zoom=3)

        Plot the same texture with interpolation.

        >>> texture.interpolation = True
        >>> texture.plot(cpos='xy', zoom=3)

        """
        return bool(self.GetInterpolate())

    @interpolate.setter
    def interpolate(self, value: bool):  # numpydoc ignore=GL08
        self.SetInterpolate(value)

    @property
    def mipmap(self) -> bool:  # numpydoc ignore=RT01
        """Return if mipmap is enabled or disabled."""
        return bool(self.GetMipmap())

    @mipmap.setter
    def mipmap(self, value: bool):  # numpydoc ignore=GL08
        self.SetMipmap(value)

    def _from_image_data(self, image):
        if not isinstance(image, pv.ImageData):
            image = pv.ImageData(image)
        self.SetInputDataObject(image)
        self.Update()

    def _from_array(self, image):
        """Create a texture from a np.ndarray."""
        if image.ndim not in [2, 3]:
            # we support 2 [single component image] or 3 [e.g. rgb or rgba] dims
            raise ValueError('Input image must be nn by nm by RGB[A]')

        if image.ndim == 3:
            if image.shape[2] not in [1, 3, 4]:
                raise ValueError('Third dimension of the array must be of size 3 (RGB) or 4 (RGBA)')
            n_components = image.shape[2]
        elif image.ndim == 2:
            n_components = 1

        grid = pv.ImageData(dimensions=(image.shape[1], image.shape[0], 1))
        grid.point_data['Image'] = np.flip(image.swapaxes(0, 1), axis=1).reshape(
            (-1, n_components), order='F'
        )
        grid.set_active_scalars('Image')
        self._from_image_data(grid)

    @property
    def repeat(self) -> bool:  # numpydoc ignore=RT01
        """Repeat the texture.

        This is provided for convenience and backwards compatibility.

        For new code, use :func:`Texture.wrap`.

        Examples
        --------
        Load the masonry texture and create a simple :class:`pyvista.PolyData`
        with texture coordinates using :func:`pyvista.Plane`. By default the
        texture coordinates are between 0 and 1. Let's raise these values over
        1 by multiplying them in place. This will allow us to wrap the texture.

        >>> import pyvista as pv
        >>> from pyvista import examples
        >>> texture = examples.download_masonry_texture()
        >>> plane = pv.Plane()
        >>> plane.active_t_coords *= 2

        This is the texture plotted with repeat set to ``False``.

        >>> texture.repeat = False
        >>> pl = pv.Plotter()
        >>> actor = pl.add_mesh(plane, texture=texture)
        >>> pl.camera.zoom('tight')
        >>> pl.show()

        This is the texture plotted with repeat set to ``True``.

        >>> texture.repeat = True
        >>> pl = pv.Plotter()
        >>> actor = pl.add_mesh(plane, texture=texture)
        >>> pl.camera.zoom('tight')
        >>> pl.show()

        """
        return bool(self.GetRepeat())

    @repeat.setter
    def repeat(self, flag: bool):  # numpydoc ignore=GL08
        self.SetRepeat(flag)

    def flip(self, axis):
        """Flip this texture inplace along the specified axis.

        0 for X and 1 for Y.

        .. deprecated:: 0.37.0
           ``flip`` is deprecated. Use :func:`Texture.flip_x` or
           :func:`Texture.flip_y` instead.

        """
        warnings.warn(
            '`flip` is deprecated. Use `flip_x` or `flip_y` instead',
            PyVistaDeprecationWarning,
        )

        if not 0 <= axis <= 1:
            raise ValueError(f"Axis {axis} out of bounds")  # pragma: no cover
        array = self.to_array()
        array = np.flip(array, axis=1 - axis)
        self._from_array(array)

    def flip_x(self) -> 'Texture':
        """Flip the texture in the x direction.

        Returns
        -------
        pyvista.Texture
            Flipped texture.

        Examples
        --------
        >>> from pyvista import examples
        >>> texture = examples.download_puppy_texture()
        >>> flipped = texture.flip_x()
        >>> flipped.plot()

        """
        return Texture(self.to_image()._flip_uniform(0))

    def flip_y(self) -> 'Texture':
        """Flip the texture in the y direction.

        Returns
        -------
        pyvista.Texture
            Flipped texture.

        Examples
        --------
        >>> from pyvista import examples
        >>> texture = examples.download_puppy_texture()
        >>> flipped = texture.flip_y()
        >>> flipped.plot()

        """
        return Texture(self.to_image()._flip_uniform(1))

    def to_image(self):
        """Return the texture as an image.

        Returns
        -------
        pyvista.ImageData
            Texture represented as a uniform grid.

        """
        return self.GetInput()

    def to_array(self) -> np.ndarray:
        """Return the texture as an array.

        Notes
        -----
        The shape of the array's first two dimensions will be swapped. For
        example, a ``(300, 200)`` image will return an array of ``(200, 300)``.

        Returns
        -------
        numpy.ndarray
            Texture as a numpy array.

        Examples
        --------
        >>> from pyvista import examples
        >>> texture = examples.download_puppy_texture()
        >>> texture
        Texture (...)
          Components:   3
          Cube Map:     False
          Dimensions:   1600, 1200
        >>> texture.to_array().shape
        (1200, 1600, 3)
        >>> texture.to_array().dtype
        dtype('uint8')

        """
        return self.to_image().active_scalars.reshape(
            list(self.dimensions)[::-1] + [self.n_components]
        )[::-1]

    def rotate_cw(self) -> 'Texture':
        """Rotate this texture 90 degrees clockwise.

        Returns
        -------
        pyvista.Texture
            Rotated texture.

        Examples
        --------
        >>> from pyvista import examples
        >>> texture = examples.download_puppy_texture()
        >>> rotated = texture.rotate_cw()
        >>> rotated.plot()

        """
        return Texture(np.rot90(self.to_array()))

    def rotate_ccw(self) -> 'Texture':
        """Rotate this texture 90 degrees counter-clockwise.

        Returns
        -------
        pyvista.Texture
            Rotated texture.

        Examples
        --------
        >>> from pyvista import examples
        >>> texture = examples.download_puppy_texture()
        >>> rotated = texture.rotate_ccw()
        >>> rotated.plot()

        """
        return Texture(np.rot90(self.to_array(), k=3))

    @property
    def cube_map(self) -> bool:  # numpydoc ignore=RT01
        """Return ``True`` if cube mapping is enabled and ``False`` otherwise."""
        return self.GetCubeMap()

    @cube_map.setter
    def cube_map(self, flag: bool):  # numpydoc ignore=GL08
        self.SetCubeMap(flag)

    def copy(self):
        """Make a copy of this texture.

        Returns
        -------
        pyvista.Texture
            Copied texture.
        """
        return Texture(self.to_image().copy())

    def to_skybox(self):
        """Return the texture as a ``vtkSkybox`` if cube mapping is enabled.

        Returns
        -------
        vtk.vtkSkybox
            Skybox if cube mapping is enabled.  Otherwise, ``None``.

        """
        if self.cube_map:
            skybox = _vtk.vtkSkybox()
            skybox.SetTexture(self)
            return skybox

    def __repr__(self):
        """Return the object representation."""
        return pv.DataSet.__repr__(self)

    def _get_attrs(self):
        """Return the representation methods (internal helper)."""
        attrs = []
        attrs.append(("Components", self.n_components, "{:d}"))
        attrs.append(("Cube Map", self.cube_map, "{:}"))
        attrs.append(("Dimensions", self.dimensions, "{:d}, {:d}"))
        return attrs

    @property
    def n_components(self) -> int:  # numpydoc ignore=RT01
        """Return the number of components in the image.

        In textures, 3 or 4 components are used for representing RGB and RGBA
        images.

        Examples
        --------
        Show the number of components in the example masonry texture.

        >>> from pyvista import examples
        >>> texture = examples.download_masonry_texture()
        >>> texture.n_components
        3

        """
        input_data = self.GetInput()
        if input_data is None:
            return 0
        return input_data.GetPointData().GetScalars().GetNumberOfComponents()

    @property
    def dimensions(self) -> tuple:  # numpydoc ignore=RT01
        """Dimensions of the texture.

        Examples
        --------
        >>> from pyvista import examples
        >>> texture = examples.download_masonry_texture()
        >>> texture.dimensions
        (256, 256)

        """
        input_data = self.GetInput()
        if input_data is None:
            return (0, 0)
        return input_data.GetDimensions()[:2]

    def plot(self, **kwargs):
        """Plot the texture as an image.

        If the texture is a cubemap, it will be displayed as a skybox with a
        sphere in the center reflecting the environment.

        Parameters
        ----------
        **kwargs : dict, optional
            Optional keyworld arguments. See :func:`pyvista.plot`.

        Returns
        -------
        various or None
            See the returns section of :func:`pyvista.plot`.

        Examples
        --------
        Plot a simple texture.

        >>> from pyvista import examples
        >>> texture = examples.download_masonry_texture()
        >>> texture.plot()

        Plot a cubemap as a skybox.

        >>> cube_map = examples.download_dikhololo_night()
        >>> cube_map.plot()

        """
        if self.cube_map:
            return self._plot_skybox(**kwargs)
        kwargs.setdefault('zoom', 'tight')
        kwargs.setdefault('lighting', False)
        kwargs.setdefault('show_axes', False)
        kwargs.setdefault('show_scalar_bar', False)
        mesh = pv.Plane(i_size=self.dimensions[0], j_size=self.dimensions[1])
        return mesh.plot(texture=self, **kwargs)

    def _plot_skybox(self, **kwargs):
        """Plot this texture as a skybox."""
        cpos = kwargs.pop('cpos', 'xy')
        zoom = kwargs.pop('zoom', 0.5)
        show_axes = kwargs.pop('show_axes', True)
        lighting = kwargs.pop('lighting', None)
        pl = pv.Plotter(lighting=lighting)
        pl.add_actor(self.to_skybox())
        pl.set_environment_texture(self, True)
        pl.add_mesh(pv.Sphere(), pbr=True, roughness=0.5, metallic=1.0)
        pl.camera_position = cpos
        pl.camera.zoom(zoom)
        if show_axes:
            pl.show_axes()
        pl.show(**kwargs)

    @property
    def wrap(self) -> 'Texture.WrapType':  # numpydoc ignore=RT01
        """Return or set the Wrap mode for the texture coordinates.

        Wrap mode for the texture coordinates valid values are:

        * ``0`` - CLAMP_TO_EDGE
        * ``1`` - REPEAT
        * ``2`` - MIRRORED_REPEAT
        * ``3`` - CLAMP_TO_BORDER

        Notes
        -----
        CLAMP_TO_BORDER is not supported with OpenGL ES <= 3.2. Wrap will
        default to CLAMP_TO_EDGE if it is set to CLAMP_TO_BORDER in this case.

        Requires ``vtk`` v9.1.0 or newer.

        Examples
        --------
        Load the masonry texture and create a simple :class:`pyvista.PolyData`
        with texture coordinates using :func:`pyvista.Plane`. By default the
        texture coordinates are between 0 and 1. Let's raise these values over
        1 by multiplying them in place. This will allow us to wrap the texture.

        >>> import pyvista as pv
        >>> from pyvista import examples
        >>> texture = examples.download_masonry_texture()
        >>> plane = pv.Plane()
        >>> plane.active_t_coords *= 2

        Let's now set the texture wrap to clamp to edge and visualize it.

        >>> texture.wrap = pv.Texture.WrapType.CLAMP_TO_EDGE
        >>> pl = pv.Plotter()
        >>> actor = pl.add_mesh(plane, texture=texture)
        >>> pl.camera.zoom('tight')
        >>> pl.show()

        Here is the default repeat:

        >>> texture.wrap = pv.Texture.WrapType.REPEAT
        >>> pl = pv.Plotter()
        >>> actor = pl.add_mesh(plane, texture=texture)
        >>> pl.camera.zoom('tight')
        >>> pl.show()

        And here is mirrored repeat:

        >>> texture.wrap = pv.Texture.WrapType.MIRRORED_REPEAT
        >>> pl = pv.Plotter()
        >>> actor = pl.add_mesh(plane, texture=texture)
        >>> pl.camera.zoom('tight')
        >>> pl.show()

        Finally, this is clamp to border:

        >>> texture.wrap = pv.Texture.WrapType.CLAMP_TO_BORDER
        >>> pl = pv.Plotter()
        >>> actor = pl.add_mesh(plane, texture=texture)
        >>> pl.camera.zoom('tight')
        >>> pl.show()

        """
        if not hasattr(self, 'GetWrap'):  # pragma: no cover
            from pyvista.core.errors import VTKVersionError

            raise VTKVersionError('`wrap` requires VTK v9.1.0 or newer.')

        return Texture.WrapType(self.GetWrap())  # type: ignore

    @wrap.setter
    def wrap(self, value: Union['Texture.WrapType', int]):  # numpydoc ignore=GL08
        if not hasattr(self, 'SetWrap'):  # pragma: no cover
            from pyvista.core.errors import VTKVersionError

            raise VTKVersionError('`wrap` requires VTK v9.1.0 or newer.')

        self.SetWrap(value)

    def to_grayscale(self) -> 'Texture':
        """Convert this texture as a single component (grayscale) texture.

        Returns
        -------
        pyvista.Texture
            Texture converted to grayscale. If already grayscale, the original
            texture itself is returned.

        Notes
        -----
        The transparency channel (if available) will be dropped.

        Follows the `CCIR 601 <https://en.wikipedia.org/wiki/Rec._601>`_ luma
        calculation equation of ``Y = 0.299*R + 0.587*G + 0.114*B``.

        Examples
        --------
        >>> from pyvista import examples
        >>> texture = examples.download_masonry_texture()
        >>> bw_texture = texture.to_grayscale()
        >>> bw_texture
        Texture (...)
          Components:   1
          Cube Map:     False
          Dimensions:   256, 256
        >>> bw_texture.plot()

        """
        if self.n_components == 1:
            return self.copy()

        data = self.to_array()
        r, g, b = data[..., 0], data[..., 1], data[..., 2]
        data = (0.299 * r + 0.587 * g + 0.114 * b).round().astype(np.uint8)
        return Texture(data)


def image_to_texture(image):
    """Convert :class:`pyvista.ImageData` to a :class:`pyvista.Texture`.

    Parameters
    ----------
    image : pyvista.ImageData | vtkImageData
        Image to convert.

    Returns
    -------
    pyvista.Texture
        The texture.

    """
    return Texture(image)


def numpy_to_texture(image):
    """Convert a NumPy image array to a :class:`pyvista.Texture`.

    Parameters
    ----------
    image : numpy.ndarray
        Numpy image array. Texture datatype expected to be ``np.uint8``.

    Returns
    -------
    pyvista.Texture
        PyVista texture.

    Examples
    --------
    Create an all white texture.

    >>> import pyvista as pv
    >>> import numpy as np
    >>> tex_arr = np.ones((1024, 1024, 3), dtype=np.uint8) * 255
    >>> tex = pv.numpy_to_texture(tex_arr)

    """
    if image.dtype != np.uint8:
        image = image.astype(np.uint8)
        warnings.warn(
            'Expected `image` dtype to be ``np.uint8``. `image` has been copied '
            'and converted to np.uint8.',
            UserWarning,
        )

    return Texture(image)


# pyvista/plotting/themes.py

"""API description for managing plotting theme parameters in pyvista.

Examples
--------
Apply a built-in theme

>>> import pyvista as pv
>>> pv.set_plot_theme('default')
>>> pv.set_plot_theme('document')
>>> pv.set_plot_theme('dark')
>>> pv.set_plot_theme('paraview')

Load a theme into pyvista

>>> from pyvista.plotting.themes import DocumentTheme
>>> theme = DocumentTheme()
>>> theme.save('my_theme.json')  # doctest:+SKIP
>>> loaded_theme = pv.load_theme('my_theme.json')  # doctest:+SKIP

Create a custom theme from the default theme and load it into
pyvista.

>>> my_theme = DocumentTheme()
>>> my_theme.font.size = 20
>>> my_theme.font.title_size = 40
>>> my_theme.cmap = 'jet'
>>> pv.global_theme.load_theme(my_theme)
>>> pv.global_theme.font.size
20

"""

from enum import Enum
import json
import os
from typing import Callable, List, Optional, Union
import warnings

import pyvista
from pyvista.core._typing_core import Number
from pyvista.core.errors import PyVistaDeprecationWarning
from pyvista.core.utilities.misc import _check_range

from ._typing import ColorLike
from .colors import Color, get_cmap_safe, get_cycler
from .opts import InterpolationType
from .tools import parse_font_family


def _set_plot_theme_from_env():
    """Set plot theme from an environment variable."""
    if 'PYVISTA_PLOT_THEME' in os.environ:
        try:
            theme = os.environ['PYVISTA_PLOT_THEME']
            set_plot_theme(theme.lower())
        except ValueError:
            allowed = ', '.join([item.name for item in _NATIVE_THEMES])
            warnings.warn(
                f'\n\nInvalid PYVISTA_PLOT_THEME environment variable "{theme}". '
                f'Should be one of the following: {allowed}'
            )


def load_theme(filename):
    """Load a theme from a file.

    Parameters
    ----------
    filename : str
        Theme file. Must be json.

    Returns
    -------
    pyvista.Theme
        The loaded theme.

    Examples
    --------
    >>> import pyvista as pv
    >>> from pyvista.plotting.themes import DocumentTheme
    >>> theme = DocumentTheme()
    >>> theme.save('my_theme.json')  # doctest:+SKIP
    >>> loaded_theme = pv.load_theme('my_theme.json')  # doctest:+SKIP

    """
    with open(filename) as f:
        theme_dict = json.load(f)
    return Theme.from_dict(theme_dict)


def set_plot_theme(theme):
    """Set the plotting parameters to a predefined theme using a string.

    Parameters
    ----------
    theme : str
        Theme name.  Either ``'default'``, ``'document'``, ``'dark'``,
        or ``'paraview'``.

    Examples
    --------
    Set to the default theme.

    >>> import pyvista as pv
    >>> pv.set_plot_theme('default')

    Set to the document theme.

    >>> pv.set_plot_theme('document')

    Set to the dark theme.

    >>> pv.set_plot_theme('dark')

    Set to the ParaView theme.

    >>> pv.set_plot_theme('paraview')

    """
    import pyvista

    if isinstance(theme, str):
        theme = theme.lower()
        try:
            new_theme_type = _NATIVE_THEMES[theme].value
        except KeyError:
            raise ValueError(f"Theme {theme} not found in PyVista's native themes.")
        pyvista.global_theme.load_theme(new_theme_type())
    elif isinstance(theme, Theme):
        pyvista.global_theme.load_theme(theme)
    else:
        raise TypeError(
            f'Expected a ``pyvista.plotting.themes.Theme`` or ``str``, not {type(theme).__name__}'
        )


class _ThemeConfig:
    """Provide common methods for theme configuration classes."""

    __slots__: List[str] = []

    @classmethod
    def from_dict(cls, dict_):
        """Create from a dictionary."""
        inst = cls()
        for key, value in dict_.items():
            attr = getattr(inst, key)
            if hasattr(attr, 'from_dict'):
                setattr(inst, key, attr.from_dict(value))
            else:
                setattr(inst, key, value)
        return inst

    def to_dict(self) -> dict:
        """Return theme config parameters as a dictionary.

        Returns
        -------
        dict
            This theme parameter represented as a dictionary.

        """
        # remove the first underscore in each entry
        dict_ = {}
        for key in self.__slots__:
            value = getattr(self, key)
            key = key[1:]
            if hasattr(value, 'to_dict'):
                dict_[key] = value.to_dict()
            else:
                dict_[key] = value
        return dict_

    def __eq__(self, other):
        if not isinstance(other, _ThemeConfig):
            return False

        for attr_name in other.__slots__:
            attr = getattr(self, attr_name)
            other_attr = getattr(other, attr_name)
            if isinstance(attr, (tuple, list)):
                if tuple(attr) != tuple(other_attr):
                    return False
            else:
                if not attr == other_attr:
                    return False

        return True

    def __getitem__(self, key):
        """Get a value via a key.

        Implemented here for backwards compatibility.
        """
        return getattr(self, key)

    def __setitem__(self, key, value):
        """Set a value via a key.

        Implemented here for backwards compatibility.
        """
        setattr(self, key, value)


class _LightingConfig(_ThemeConfig):
    """PyVista lighting configuration.

    This will control the lighting interpolation type, parameters,
    and Physically Based Rendering (PBR) options

    Examples
    --------
    Set global PBR parameters.

    >>> import pyvista as pv
    >>> pv.global_theme.lighting_params.interpolation = 'pbr'
    >>> pv.global_theme.lighting_params.metallic = 0.5
    >>> pv.global_theme.lighting_params.roughness = 0.25

    """

    __slots__ = [
        '_interpolation',
        '_metallic',
        '_roughness',
        '_ambient',
        '_diffuse',
        '_specular',
        '_specular_power',
        '_emissive',
    ]

    def __init__(self):
        self._interpolation = InterpolationType.FLAT.value
        self._metallic = 0.0
        self._roughness = 0.5
        self._ambient = 0.0
        self._diffuse = 1.0
        self._specular = 0.0
        self._specular_power = 100.0
        self._emissive = False

    @property
    def interpolation(self) -> InterpolationType:  # numpydoc ignore=RT01
        """Return or set the default interpolation type.

        See :class:`pyvista.plotting.opts.InterpolationType`.

        Options are:

        * ``'Phong'``
        * ``'Flat'``
        * ``'Physically based rendering'``

        This is stored as an integer value of the ``InterpolationType``
        so that the theme can be JSON-serializable.

        Examples
        --------
        >>> import pyvista as pv
        >>> pv.global_theme.lighting_params.interpolation = 'Phong'
        >>> pv.global_theme.lighting_params.interpolation
        <InterpolationType.PHONG: 2>


        """
        return InterpolationType.from_any(self._interpolation)

    @interpolation.setter
    def interpolation(
        self, interpolation: Union[str, int, InterpolationType]
    ):  # numpydoc ignore=GL08
        self._interpolation = InterpolationType.from_any(interpolation).value

    @property
    def metallic(self) -> float:  # numpydoc ignore=RT01
        """Return or set the metallic value.

        This requires that the interpolation be set to ``'Physically based
        rendering'``. Must be between 0 and 1.

        Examples
        --------
        Set the global metallic value used in physically based rendering to
        ``0.5``.

        >>> import pyvista as pv
        >>> pv.global_theme.lighting_params.metallic = 0.5
        >>> pv.global_theme.lighting_params.metallic
        0.5

        """
        return self._metallic

    @metallic.setter
    def metallic(self, metallic: float):  # numpydoc ignore=GL08
        _check_range(metallic, (0, 1), 'metallic')
        self._metallic = metallic

    @property
    def roughness(self) -> float:  # numpydoc ignore=RT01
        """Return or set the roughness value.

        This value has to be between 0 (glossy) and 1 (rough). A glossy
        material has reflections and a high specular part. This parameter is
        only used by PBR interpolation.

        Examples
        --------
        Set the global roughness value used in physically based rendering to
        ``0.25``.

        >>> import pyvista as pv
        >>> pv.global_theme.lighting_params.roughness = 0.25
        >>> pv.global_theme.lighting_params.roughness
        0.25

        """
        return self._roughness

    @roughness.setter
    def roughness(self, roughness: float):  # numpydoc ignore=GL08
        _check_range(roughness, (0, 1), 'roughness')
        self._roughness = roughness

    @property
    def ambient(self) -> float:  # numpydoc ignore=RT01
        """Return or set the ambient value.

        When lighting is enabled, this is the amount of light in the range of 0
        to 1 that reaches the actor when not directed at the light source
        emitted from the viewer.

        Examples
        --------
        Set the global ambient lighting value to ``0.2``.

        >>> import pyvista as pv
        >>> pv.global_theme.lighting_params.ambient = 0.2
        >>> pv.global_theme.lighting_params.ambient
        0.2

        """
        return self._ambient

    @ambient.setter
    def ambient(self, ambient: float):  # numpydoc ignore=GL08
        _check_range(ambient, (0, 1), 'ambient')
        self._ambient = ambient

    @property
    def diffuse(self) -> float:  # numpydoc ignore=RT01
        """Return or set the diffuse value.

        This is the scattering of light by reflection or
        transmission. Diffuse reflection results when light strikes an
        irregular surface such as a frosted window or the surface of a
        frosted or coated light bulb. Must be between 0 and 1.

        Examples
        --------
        Set the global diffuse lighting value to ``0.5``.

        >>> import pyvista as pv
        >>> pv.global_theme.lighting_params.diffuse = 0.5
        >>> pv.global_theme.lighting_params.diffuse
        0.5

        """
        return self._diffuse

    @diffuse.setter
    def diffuse(self, diffuse: float):  # numpydoc ignore=GL08
        _check_range(diffuse, (0, 1), 'diffuse')
        self._diffuse = diffuse

    @property
    def specular(self) -> float:  # numpydoc ignore=RT01
        """Return or set the specular value.

        Specular lighting simulates the bright spot of a light that appears
        on shiny objects. Must be between 0 and 1.

        Examples
        --------
        Set the global specular value to ``0.1``.

        >>> import pyvista as pv
        >>> pv.global_theme.lighting_params.specular = 0.1
        >>> pv.global_theme.lighting_params.specular
        0.1

        """
        return self._specular

    @specular.setter
    def specular(self, specular: float):  # numpydoc ignore=GL08
        _check_range(specular, (0, 1), 'specular')
        self._specular = specular

    @property
    def specular_power(self) -> float:  # numpydoc ignore=RT01
        """Return or set the specular power value.

        Must be between 0.0 and 128.0.

        Examples
        --------
        Set the global specular power value to ``50``.

        >>> import pyvista as pv
        >>> pv.global_theme.lighting_params.specular_power = 50
        >>> pv.global_theme.lighting_params.specular_power
        50

        """
        return self._specular_power

    @specular_power.setter
    def specular_power(self, specular_power: float):  # numpydoc ignore=GL08
        _check_range(specular_power, (0, 128), 'specular_power')
        self._specular_power = specular_power

    @property
    def emissive(self) -> bool:  # numpydoc ignore=RT01
        """Return or set if emissive is used with point Gaussian style.

        Examples
        --------
        Globally enable emissive lighting when using the point Gaussian style.

        >>> import pyvista as pv
        >>> pv.global_theme.lighting_params.emissive = True
        >>> pv.global_theme.lighting_params.emissive
        True

        """
        return self._emissive

    @emissive.setter
    def emissive(self, emissive: bool):  # numpydoc ignore=GL08
        self._emissive = bool(emissive)


class _DepthPeelingConfig(_ThemeConfig):
    """PyVista depth peeling configuration.

    Examples
    --------
    Set global depth peeling parameters.

    >>> import pyvista as pv
    >>> pv.global_theme.depth_peeling.number_of_peels = 1
    >>> pv.global_theme.depth_peeling.occlusion_ratio = 0.0
    >>> pv.global_theme.depth_peeling.enabled = True

    """

    __slots__ = ['_number_of_peels', '_occlusion_ratio', '_enabled']

    def __init__(self):
        self._number_of_peels = 4
        self._occlusion_ratio = 0.0
        self._enabled = False

    @property
    def number_of_peels(self) -> int:  # numpydoc ignore=RT01
        """Return or set the number of peels in depth peeling.

        Examples
        --------
        >>> import pyvista as pv
        >>> pv.global_theme.depth_peeling.number_of_peels = 1

        """
        return self._number_of_peels

    @number_of_peels.setter
    def number_of_peels(self, number_of_peels: int):  # numpydoc ignore=GL08
        self._number_of_peels = int(number_of_peels)

    @property
    def occlusion_ratio(self) -> float:  # numpydoc ignore=RT01
        """Return or set the occlusion ratio in depth peeling.

        Examples
        --------
        >>> import pyvista as pv
        >>> pv.global_theme.depth_peeling.occlusion_ratio = 0.0

        """
        return self._occlusion_ratio

    @occlusion_ratio.setter
    def occlusion_ratio(self, occlusion_ratio: float):  # numpydoc ignore=GL08
        self._occlusion_ratio = float(occlusion_ratio)

    @property
    def enabled(self) -> bool:  # numpydoc ignore=RT01
        """Return or set if depth peeling is enabled.

        Examples
        --------
        >>> import pyvista as pv
        >>> pv.global_theme.depth_peeling.enabled = True

        """
        return self._enabled

    @enabled.setter
    def enabled(self, enabled: bool):  # numpydoc ignore=GL08
        self._enabled = bool(enabled)

    def __repr__(self):
        txt = ['']
        parm = {
            'Number': 'number_of_peels',
            'Occlusion ratio': 'occlusion_ratio',
            'Enabled': 'enabled',
        }
        for name, attr in parm.items():
            setting = getattr(self, attr)
            txt.append(f'    {name:<21}: {setting}')
        return '\n'.join(txt)


class _SilhouetteConfig(_ThemeConfig):
    """PyVista silhouette configuration.

    Examples
    --------
    Set global silhouette parameters.

    >>> import pyvista as pv
    >>> pv.global_theme.silhouette.enabled = True
    >>> pv.global_theme.silhouette.color = 'grey'
    >>> pv.global_theme.silhouette.line_width = 2
    >>> pv.global_theme.silhouette.feature_angle = 20

    """

    __slots__ = ['_color', '_line_width', '_opacity', '_feature_angle', '_decimate', '_enabled']

    def __init__(self):
        self._color = Color('black')
        self._line_width = 2
        self._opacity = 1.0
        self._feature_angle = None
        self._decimate = None
        self._enabled = False

    @property
    def enabled(self) -> bool:  # numpydoc ignore=RT01
        """Return or set whether silhouette is on or off."""
        return self._enabled

    @enabled.setter
    def enabled(self, enabled: bool):  # numpydoc ignore=GL08
        self._enabled = bool(enabled)

    @property
    def color(self) -> Color:  # numpydoc ignore=RT01
        """Return or set the silhouette color.

        Examples
        --------
        >>> import pyvista as pv
        >>> pv.global_theme.silhouette.color = 'red'

        """
        return self._color

    @color.setter
    def color(self, color: ColorLike):  # numpydoc ignore=GL08
        self._color = Color(color)

    @property
    def line_width(self) -> float:  # numpydoc ignore=RT01
        """Return or set the silhouette line width.

        Examples
        --------
        >>> import pyvista as pv
        >>> pv.global_theme.silhouette.line_width = 2.0

        """
        return self._line_width

    @line_width.setter
    def line_width(self, line_width: float):  # numpydoc ignore=GL08
        self._line_width = float(line_width)

    @property
    def opacity(self) -> float:  # numpydoc ignore=RT01
        """Return or set the silhouette opacity.

        Examples
        --------
        >>> import pyvista as pv
        >>> pv.global_theme.silhouette.opacity = 1.0

        """
        return self._opacity

    @opacity.setter
    def opacity(self, opacity: float):  # numpydoc ignore=GL08
        _check_range(opacity, (0, 1), 'opacity')
        self._opacity = float(opacity)

    @property
    def feature_angle(self) -> Union[float, None]:  # numpydoc ignore=RT01
        """Return or set the silhouette feature angle.

        Examples
        --------
        >>> import pyvista as pv
        >>> pv.global_theme.silhouette.feature_angle = 20.0

        """
        return self._feature_angle

    @feature_angle.setter
    def feature_angle(self, feature_angle: Union[float, None]):  # numpydoc ignore=GL08
        self._feature_angle = feature_angle

    @property
    def decimate(self) -> float:  # numpydoc ignore=RT01
        """Return or set the amount to decimate the silhouette.

        Parameter must be between 0 and 1.

        Examples
        --------
        >>> import pyvista as pv
        >>> pv.global_theme.silhouette.decimate = 0.9

        """
        return self._decimate

    @decimate.setter
    def decimate(self, decimate: float):  # numpydoc ignore=GL08
        if decimate is None:
            self._decimate = None
        else:
            _check_range(decimate, (0, 1), 'decimate')
            self._decimate = float(decimate)

    def __repr__(self):
        txt = ['']
        parm = {
            'Color': 'color',
            'Line width': 'line_width',
            'Opacity': 'opacity',
            'Feature angle': 'feature_angle',
            'Decimate': 'decimate',
        }
        for name, attr in parm.items():
            setting = getattr(self, attr)
            txt.append(f'    {name:<21}: {setting}')
        return '\n'.join(txt)


class _ColorbarConfig(_ThemeConfig):
    """PyVista colorbar configuration.

    Examples
    --------
    Set the colorbar width.

    >>> import pyvista as pv
    >>> pv.global_theme.colorbar_horizontal.width = 0.2

    """

    __slots__ = ['_width', '_height', '_position_x', '_position_y']

    def __init__(self):
        self._width = None
        self._height = None
        self._position_x = None
        self._position_y = None

    @property
    def width(self) -> float:  # numpydoc ignore=RT01
        """Return or set colorbar width.

        Examples
        --------
        >>> import pyvista as pv
        >>> pv.global_theme.colorbar_horizontal.width = 0.2

        """
        return self._width

    @width.setter
    def width(self, width: float):  # numpydoc ignore=GL08
        self._width = float(width)

    @property
    def height(self) -> float:  # numpydoc ignore=RT01
        """Return or set colorbar height.

        Examples
        --------
        >>> import pyvista as pv
        >>> pv.global_theme.colorbar_horizontal.height = 0.2

        """
        return self._height

    @height.setter
    def height(self, height: float):  # numpydoc ignore=GL08
        self._height = float(height)

    @property
    def position_x(self) -> float:  # numpydoc ignore=RT01
        """Return or set colorbar x position.

        Examples
        --------
        >>> import pyvista as pv
        >>> pv.global_theme.colorbar_horizontal.position_x = 0.2

        """
        return self._position_x

    @position_x.setter
    def position_x(self, position_x: float):  # numpydoc ignore=GL08
        self._position_x = float(position_x)

    @property
    def position_y(self) -> float:  # numpydoc ignore=RT01
        """Return or set colorbar y position.

        Examples
        --------
        >>> import pyvista as pv
        >>> pv.global_theme.colorbar_horizontal.position_y = 0.2

        """
        return self._position_y

    @position_y.setter
    def position_y(self, position_y: float):  # numpydoc ignore=GL08
        self._position_y = float(position_y)

    def __repr__(self):
        txt = ['']
        parm = {
            'Width': 'width',
            'Height': 'height',
            'X Position': 'position_x',
            'Y Position': 'position_y',
        }
        for name, attr in parm.items():
            setting = getattr(self, attr)
            txt.append(f'    {name:<21}: {setting}')

        return '\n'.join(txt)


class _AxesConfig(_ThemeConfig):
    """PyVista axes configuration.

    Examples
    --------
    Set the x axis color to black.

    >>> import pyvista as pv
    >>> pv.global_theme.axes.x_color = 'black'

    Show axes by default.

    >>> pv.global_theme.axes.show = True

    Use the ``vtk.vtkCubeAxesActor``.

    >>> pv.global_theme.axes.box = True

    """

    __slots__ = ['_x_color', '_y_color', '_z_color', '_box', '_show']

    def __init__(self):
        self._x_color = Color('tomato')
        self._y_color = Color('seagreen')
        self._z_color = Color('mediumblue')
        self._box = False
        self._show = True

    def __repr__(self):
        txt = ['Axes configuration']
        parm = {
            'X Color': 'x_color',
            'Y Color': 'y_color',
            'Z Color': 'z_color',
            'Use Box': 'box',
            'Show': 'show',
        }
        for name, attr in parm.items():
            setting = getattr(self, attr)
            txt.append(f'    {name:<21}: {setting}')

        return '\n'.join(txt)

    @property
    def x_color(self) -> Color:  # numpydoc ignore=RT01
        """Return or set x axis color.

        Examples
        --------
        >>> import pyvista as pv
        >>> pv.global_theme.axes.x_color = 'red'
        """
        return self._x_color

    @x_color.setter
    def x_color(self, color: ColorLike):  # numpydoc ignore=GL08
        self._x_color = Color(color)

    @property
    def y_color(self) -> Color:  # numpydoc ignore=RT01
        """Return or set y axis color.

        Examples
        --------
        >>> import pyvista as pv
        >>> pv.global_theme.axes.y_color = 'red'
        """
        return self._y_color

    @y_color.setter
    def y_color(self, color: ColorLike):  # numpydoc ignore=GL08
        self._y_color = Color(color)

    @property
    def z_color(self) -> Color:  # numpydoc ignore=RT01
        """Return or set z axis color.

        Examples
        --------
        >>> import pyvista as pv
        >>> pv.global_theme.axes.z_color = 'red'
        """
        return self._z_color

    @z_color.setter
    def z_color(self, color: ColorLike):  # numpydoc ignore=GL08
        self._z_color = Color(color)

    @property
    def box(self) -> bool:  # numpydoc ignore=RT01
        """Use the ``vtk.vtkCubeAxesActor`` instead of the default ``vtk.vtkAxesActor``.

        Examples
        --------
        >>> import pyvista as pv
        >>> pv.global_theme.axes.box = True

        """
        return self._box

    @box.setter
    def box(self, box: bool):  # numpydoc ignore=GL08
        self._box = bool(box)

    @property
    def show(self) -> bool:  # numpydoc ignore=RT01
        """Show or hide the axes actor.

        Examples
        --------
        Hide the axes by default.

        >>> import pyvista as pv
        >>> pv.global_theme.axes.show = False

        """
        return self._show

    @show.setter
    def show(self, show: bool):  # numpydoc ignore=GL08
        self._show = bool(show)


class _Font(_ThemeConfig):
    """PyVista plotter font configuration.

    Examples
    --------
    Set the default font family to 'arial'.  Must be either
    'arial', 'courier', or 'times'.

    >>> import pyvista as pv
    >>> pv.global_theme.font.family = 'arial'

    Set the default font size to 20.

    >>> pv.global_theme.font.size = 20

    Set the default title size to 40

    >>> pv.global_theme.font.title_size = 40

    Set the default label size to 10

    >>> pv.global_theme.font.label_size = 10

    Set the default text color to 'grey'

    >>> pv.global_theme.font.color = 'grey'

    Set the string formatter used to format numerical data to '%.6e'

    >>> pv.global_theme.font.fmt = '%.6e'

    """

    __slots__ = ['_family', '_size', '_title_size', '_label_size', '_color', '_fmt']

    def __init__(self):
        self._family = 'arial'
        self._size = 12
        self._title_size = None
        self._label_size = None
        self._color = Color('white')
        self._fmt = None

    def __repr__(self):
        txt = ['']
        parm = {
            'Family': 'family',
            'Size': 'size',
            'Title size': 'title_size',
            'Label size': 'label_size',
            'Color': 'color',
            'Float format': 'fmt',
        }
        for name, attr in parm.items():
            setting = getattr(self, attr)
            txt.append(f'    {name:<21}: {setting}')

        return '\n'.join(txt)

    @property
    def family(self) -> str:  # numpydoc ignore=RT01
        """Return or set the font family.

        Must be one of the following:

        * ``"arial"``
        * ``"courier"``
        * ``"times"``

        Examples
        --------
        Set the default global font family to 'courier'.

        >>> import pyvista as pv
        >>> pv.global_theme.font.family = 'courier'

        """
        return self._family

    @family.setter
    def family(self, family: str):  # numpydoc ignore=GL08
        parse_font_family(family)  # check valid font
        self._family = family

    @property
    def size(self) -> int:  # numpydoc ignore=RT01
        """Return or set the font size.

        Examples
        --------
        >>> import pyvista as pv
        >>> pv.global_theme.font.size = 20

        """
        return self._size

    @size.setter
    def size(self, size: int):  # numpydoc ignore=GL08
        self._size = int(size)

    @property
    def title_size(self) -> int:  # numpydoc ignore=RT01
        """Return or set the title size.

        If ``None``, then VTK uses ``UnconstrainedFontSizeOn`` for titles.

        Examples
        --------
        >>> import pyvista as pv
        >>> pv.global_theme.font.title_size = 20
        """
        return self._title_size

    @title_size.setter
    def title_size(self, title_size: int):  # numpydoc ignore=GL08
        if title_size is None:
            self._title_size = None
        else:
            self._title_size = int(title_size)

    @property
    def label_size(self) -> int:  # numpydoc ignore=RT01
        """Return or set the label size.

        If ``None``, then VTK uses ``UnconstrainedFontSizeOn`` for labels.

        Examples
        --------
        >>> import pyvista as pv
        >>> pv.global_theme.font.label_size = 20
        """
        return self._label_size

    @label_size.setter
    def label_size(self, label_size: int):  # numpydoc ignore=GL08
        if label_size is None:
            self._label_size = None
        else:
            self._label_size = int(label_size)

    @property
    def color(self) -> Color:  # numpydoc ignore=RT01
        """Return or set the font color.

        Examples
        --------
        >>> import pyvista as pv
        >>> pv.global_theme.font.color = 'black'
        """
        return self._color

    @color.setter
    def color(self, color: ColorLike):  # numpydoc ignore=GL08
        self._color = Color(color)

    @property
    def fmt(self) -> str:  # numpydoc ignore=RT01
        """Return or set the string formatter used to format numerical data.

        Examples
        --------
        Set the string formatter used to format numerical data to '%.6e'.

        >>> import pyvista as pv
        >>> pv.global_theme.font.fmt = '%.6e'

        """
        return self._fmt

    @fmt.setter
    def fmt(self, fmt: str):  # numpydoc ignore=GL08
        self._fmt = fmt


class _SliderStyleConfig(_ThemeConfig):
    """PyVista configuration for a single slider style."""

    __slots__ = [
        '_name',
        '_slider_length',
        '_slider_width',
        '_slider_color',
        '_tube_width',
        '_tube_color',
        '_cap_opacity',
        '_cap_length',
        '_cap_width',
    ]

    def __init__(self):
        """Initialize the slider style configuration."""
        self._name = None
        self._slider_length = None
        self._slider_width = None
        self._slider_color = None
        self._tube_width = None
        self._tube_color = None
        self._cap_opacity = None
        self._cap_length = None
        self._cap_width = None

    @property
    def name(self) -> str:  # numpydoc ignore=RT01
        """Return the name of the slider style configuration."""
        return self._name

    @name.setter
    def name(self, name: str):  # numpydoc ignore=GL08
        self._name = name

    @property
    def cap_width(self) -> float:  # numpydoc ignore=RT01
        """Return or set the cap width.

        Examples
        --------
        >>> import pyvista as pv
        >>> pv.global_theme.slider_styles.modern.cap_width = 0.02

        """
        return self._cap_width

    @cap_width.setter
    def cap_width(self, cap_width: float):  # numpydoc ignore=GL08
        self._cap_width = float(cap_width)

    @property
    def cap_length(self) -> float:  # numpydoc ignore=RT01
        """Return or set the cap length.

        Examples
        --------
        >>> import pyvista as pv
        >>> pv.global_theme.slider_styles.modern.cap_length = 0.01

        """
        return self._cap_length

    @cap_length.setter
    def cap_length(self, cap_length: float):  # numpydoc ignore=GL08
        self._cap_length = float(cap_length)

    @property
    def cap_opacity(self) -> float:  # numpydoc ignore=RT01
        """Return or set the cap opacity.

        Examples
        --------
        >>> import pyvista as pv
        >>> pv.global_theme.slider_styles.modern.cap_opacity = 1.0

        """
        return self._cap_opacity

    @cap_opacity.setter
    def cap_opacity(self, cap_opacity: float):  # numpydoc ignore=GL08
        _check_range(cap_opacity, (0, 1), 'cap_opacity')
        self._cap_opacity = float(cap_opacity)

    @property
    def tube_color(self) -> Color:  # numpydoc ignore=RT01
        """Return or set the tube color.

        Examples
        --------
        >>> import pyvista as pv
        >>> pv.global_theme.slider_styles.modern.tube_color = 'black'
        """
        return self._tube_color

    @tube_color.setter
    def tube_color(self, tube_color: ColorLike):  # numpydoc ignore=GL08
        self._tube_color = Color(tube_color)

    @property
    def tube_width(self) -> float:  # numpydoc ignore=RT01
        """Return or set the tube_width.

        Examples
        --------
        >>> import pyvista as pv
        >>> pv.global_theme.slider_styles.modern.tube_width = 0.005

        """
        return self._tube_width

    @tube_width.setter
    def tube_width(self, tube_width: float):  # numpydoc ignore=GL08
        self._tube_width = float(tube_width)

    @property
    def slider_color(self) -> Color:  # numpydoc ignore=RT01
        """Return or set the slider color.

        Examples
        --------
        >>> import pyvista as pv
        >>> pv.global_theme.slider_styles.modern.slider_color = 'grey'

        """
        return self._slider_color

    @slider_color.setter
    def slider_color(self, slider_color: ColorLike):  # numpydoc ignore=GL08
        self._slider_color = Color(slider_color)

    @property
    def slider_width(self) -> float:  # numpydoc ignore=RT01
        """Return or set the slider width.

        Examples
        --------
        >>> import pyvista as pv
        >>> pv.global_theme.slider_styles.modern.slider_width = 0.04

        """
        return self._slider_width

    @slider_width.setter
    def slider_width(self, slider_width: float):  # numpydoc ignore=GL08
        self._slider_width = float(slider_width)

    @property
    def slider_length(self) -> float:  # numpydoc ignore=RT01
        """Return or set the slider_length.

        Examples
        --------
        >>> import pyvista as pv
        >>> pv.global_theme.slider_styles.modern.slider_length = 0.02

        """
        return self._slider_length

    @slider_length.setter
    def slider_length(self, slider_length: float):  # numpydoc ignore=GL08
        self._slider_length = float(slider_length)

    def __repr__(self):
        txt = ['']
        parm = {
            'Slider length': 'slider_length',
            'Slider width': 'slider_width',
            'Slider color': 'slider_color',
            'Tube width': 'tube_width',
            'Tube color': 'tube_color',
            'Cap opacity': 'cap_opacity',
            'Cap length': 'cap_length',
            'Cap width': 'cap_width',
        }
        for name, attr in parm.items():
            setting = getattr(self, attr)
            txt.append(f'        {name:<17}: {setting}')
        return '\n'.join(txt)


class _SliderConfig(_ThemeConfig):
    """PyVista configuration encompassing all slider styles.

    Examples
    --------
    Set the classic slider configuration.

    >>> import pyvista as pv
    >>> slider_styles = pv.global_theme.slider_styles
    >>> slider_styles.classic.slider_length = 0.02
    >>> slider_styles.classic.slider_width = 0.04
    >>> slider_styles.classic.slider_color = (0.5, 0.5, 0.5)
    >>> slider_styles.classic.tube_width = 0.005
    >>> slider_styles.classic.tube_color = (1.0, 1.0, 1.0)
    >>> slider_styles.classic.cap_opacity = 1
    >>> slider_styles.classic.cap_length = 0.01
    >>> slider_styles.classic.cap_width = 0.02

    Set the modern slider configuration.

    >>> slider_styles.modern.slider_length = 0.02
    >>> slider_styles.modern.slider_width = 0.04
    >>> slider_styles.modern.slider_color = (0.43, 0.44, 0.45)
    >>> slider_styles.modern.tube_width = 0.04
    >>> slider_styles.modern.tube_color = (0.69, 0.70, 0.709)
    >>> slider_styles.modern.cap_opacity = 0
    >>> slider_styles.modern.cap_length = 0.01
    >>> slider_styles.modern.cap_width = 0.02

    """

    __slots__ = ['_classic', '_modern']

    def __init__(self):
        """Initialize the slider configuration."""
        self._classic = _SliderStyleConfig()
        self._classic.name = 'classic'
        self._classic.slider_length = 0.02
        self._classic.slider_width = 0.04
        self._classic.slider_color = 'gray'
        self._classic.tube_width = 0.005
        self._classic.tube_color = 'white'
        self._classic.cap_opacity = 1
        self._classic.cap_length = 0.01
        self._classic.cap_width = 0.02

        self._modern = _SliderStyleConfig()
        self._modern.name = 'modern'
        self._modern.slider_length = 0.02
        self._modern.slider_width = 0.04
        self._modern.slider_color = (110, 113, 117)
        self._modern.tube_width = 0.04
        self._modern.tube_color = (178, 179, 181)
        self._modern.cap_opacity = 0
        self._modern.cap_length = 0.01
        self._modern.cap_width = 0.02

    @property
    def classic(self) -> _SliderStyleConfig:  # numpydoc ignore=RT01
        """Return the Classic slider configuration."""
        return self._classic

    @classic.setter
    def classic(self, config: _SliderStyleConfig):  # numpydoc ignore=GL08
        if not isinstance(config, _SliderStyleConfig):
            raise TypeError('Configuration type must be `_SliderStyleConfig`')
        self._classic = config

    @property
    def modern(self) -> _SliderStyleConfig:  # numpydoc ignore=RT01
        """Return the Modern slider configuration."""
        return self._modern

    @modern.setter
    def modern(self, config: _SliderStyleConfig):  # numpydoc ignore=GL08
        if not isinstance(config, _SliderStyleConfig):
            raise TypeError('Configuration type must be `_SliderStyleConfig`')
        self._modern = config

    def __repr__(self):
        txt = ['']
        parm = {
            'Classic': 'classic',
            'Modern': 'modern',
        }
        for name, attr in parm.items():
            setting = getattr(self, attr)
            txt.append(f'    {name:<21}: {setting}')
        return '\n'.join(txt)

    def __iter__(self):
        for style in [self._classic, self._modern]:
            yield style.name


class _TrameConfig(_ThemeConfig):
    """PyVista Trame configuration.

    Examples
    --------
    Set global trame view parameters.

    >>> import pyvista as pv
    >>> pv.global_theme.trame.interactive_ratio = 2
    >>> pv.global_theme.trame.still_ratio = 2

    """

    __slots__ = [
        '_interactive_ratio',
        '_still_ratio',
        '_jupyter_server_name',
        '_jupyter_server_port',
        '_server_proxy_enabled',
        '_server_proxy_prefix',
        '_default_mode',
    ]

    def __init__(self):
        self._interactive_ratio = 1
        self._still_ratio = 1
        self._jupyter_server_name = 'pyvista-jupyter'
        self._jupyter_server_port = 0
        self._server_proxy_enabled = 'PYVISTA_TRAME_SERVER_PROXY_PREFIX' in os.environ
        # default for ``jupyter-server-proxy``
        service = os.environ.get('JUPYTERHUB_SERVICE_PREFIX', '')
        prefix = os.environ.get('PYVISTA_TRAME_SERVER_PROXY_PREFIX', '/proxy/')
        if service and not prefix.startswith('http'):  # pragma: no cover
            self._server_proxy_prefix = os.path.join(service, prefix.lstrip('/'))
            self._server_proxy_enabled = True
        else:
            self._server_proxy_prefix = prefix
        self._default_mode = 'trame'

    @property
    def interactive_ratio(self) -> Number:  # numpydoc ignore=RT01
        """Return or set the interactive ratio for PyVista Trame views.

        Examples
        --------
        >>> import pyvista as pv
        >>> pv.global_theme.trame.interactive_ratio = 2

        """
        return self._interactive_ratio

    @interactive_ratio.setter
    def interactive_ratio(self, interactive_ratio: Number):  # numpydoc ignore=GL08
        self._interactive_ratio = interactive_ratio

    @property
    def still_ratio(self) -> Number:  # numpydoc ignore=RT01
        """Return or set the still ratio for PyVista Trame views.

        Examples
        --------
        >>> import pyvista as pv
        >>> pv.global_theme.trame.still_ratio = 2

        """
        return self._still_ratio

    @still_ratio.setter
    def still_ratio(self, still_ratio: Number):  # numpydoc ignore=GL08
        self._still_ratio = still_ratio

    @property
    def jupyter_server_name(self):  # numpydoc ignore=RT01
        """Return or set the trame server name PyVista uses in Jupyter.

        This defaults to ``'pyvista-jupyter'``.

        This must be set before running :func:`pyvista.set_jupyter_backend`
        to ensure a server of this name is launched.

        Most users should not need to modify this.

        """
        return self._jupyter_server_name

    @jupyter_server_name.setter
    def jupyter_server_name(self, name: str):  # numpydoc ignore=GL08
        self._jupyter_server_name = name

    @property
    def jupyter_server_port(self) -> int:  # numpydoc ignore=RT01
        """Return or set the port for the Trame Jupyter server."""
        return self._jupyter_server_port

    @jupyter_server_port.setter
    def jupyter_server_port(self, port: int):  # numpydoc ignore=GL08
        self._jupyter_server_port = port

    @property
    def server_proxy_enabled(self) -> bool:  # numpydoc ignore=RT01
        """Return or set if use of relative URLs is enabled for the Jupyter interface."""
        return self._server_proxy_enabled

    @server_proxy_enabled.setter
    def server_proxy_enabled(self, enabled: bool):  # numpydoc ignore=GL08
        self._server_proxy_enabled = bool(enabled)

    @property
    def server_proxy_prefix(self):  # numpydoc ignore=RT01
        """Return or set URL prefix when using relative URLs with the Jupyter interface."""
        return self._server_proxy_prefix

    @server_proxy_prefix.setter
    def server_proxy_prefix(self, prefix: str):  # numpydoc ignore=GL08
        self._server_proxy_prefix = prefix

    @property
    def default_mode(self):  # numpydoc ignore=RT01
        """Return or set the default mode of the Trame backend.

        * ``'trame'``: Uses a view that can switch between client and server
          rendering modes.
        * ``'server'``: Uses a view that is purely server rendering.
        * ``'client'``: Uses a view that is purely client rendering (generally
          safe without a virtual frame buffer)

        """
        return self._default_mode

    @default_mode.setter
    def default_mode(self, mode: str):  # numpydoc ignore=GL08
        self._default_mode = mode


class Theme(_ThemeConfig):
    """Base VTK theme.

    Examples
    --------
    Change the global default background color to white.

    >>> import pyvista as pv
    >>> pv.global_theme.color = 'white'

    Show edges by default.

    >>> pv.global_theme.show_edges = True

    Create a new theme from the default theme and apply it globally.

    >>> from pyvista.plotting.themes import DocumentTheme
    >>> my_theme = DocumentTheme()
    >>> my_theme.color = 'red'
    >>> my_theme.background = 'white'
    >>> pv.global_theme.load_theme(my_theme)

    """

    __slots__ = [
        '_name',
        '_background',
        '_jupyter_backend',
        '_trame',
        '_full_screen',
        '_window_size',
        '_image_scale',
        '_camera',
        '_notebook',
        '_font',
        '_auto_close',
        '_cmap',
        '_color',
        '_color_cycler',
        '_above_range_color',
        '_below_range_color',
        '_nan_color',
        '_edge_color',
        '_line_width',
        '_point_size',
        '_outline_color',
        '_floor_color',
        '_colorbar_orientation',
        '_colorbar_horizontal',
        '_colorbar_vertical',
        '_show_scalar_bar',
        '_show_edges',
        '_show_vertices',
        '_lighting',
        '_interactive',
        '_render_points_as_spheres',
        '_render_lines_as_tubes',
        '_transparent_background',
        '_title',
        '_axes',
        '_multi_samples',
        '_multi_rendering_splitting_position',
        '_volume_mapper',
        '_smooth_shading',
        '_depth_peeling',
        '_silhouette',
        '_slider_styles',
        '_return_cpos',
        '_hidden_line_removal',
        '_anti_aliasing',
        '_enable_camera_orientation_widget',
        '_split_sharp_edges',
        '_sharp_edges_feature_angle',
        '_before_close_callback',
        '_lighting_params',
        '_interpolate_before_map',
        '_opacity',
    ]

    def __init__(self):
        """Initialize the theme."""
        self._name = 'default'
        self._background = Color([0.3, 0.3, 0.3])
        self._full_screen = False
        self._camera = {
            'position': [1, 1, 1],
            'viewup': [0, 0, 1],
        }

        self._notebook = None
        self._window_size = [1024, 768]
        self._image_scale = 1
        self._font = _Font()
        self._cmap = 'viridis'
        self._color = Color('white')
        self._color_cycler = None
        self._nan_color = Color('darkgray')
        self._above_range_color = Color('grey')
        self._below_range_color = Color('grey')
        self._edge_color = Color('black')
        self._line_width = 1.0
        self._point_size = 5.0
        self._outline_color = Color('white')
        self._floor_color = Color('gray')
        self._colorbar_orientation = 'horizontal'

        self._colorbar_horizontal = _ColorbarConfig()
        self._colorbar_horizontal.width = 0.6
        self._colorbar_horizontal.height = 0.08
        self._colorbar_horizontal.position_x = 0.35
        self._colorbar_horizontal.position_y = 0.05

        self._colorbar_vertical = _ColorbarConfig()
        self._colorbar_vertical.width = 0.08
        self._colorbar_vertical.height = 0.45
        self._colorbar_vertical.position_x = 0.9
        self._colorbar_vertical.position_y = 0.02

        self._show_scalar_bar = True
        self._show_edges = False
        self._show_vertices = False
        self._lighting = True
        self._interactive = False
        self._render_points_as_spheres = False
        self._render_lines_as_tubes = False
        self._transparent_background = False
        self._title = 'PyVista'
        self._axes = _AxesConfig()
        self._split_sharp_edges = False
        self._sharp_edges_feature_angle = 30.0
        self._before_close_callback = None

        # Grab system flag for anti-aliasing
        # Use a default value of 8 multi-samples as this is default for VTK
        try:
            self._multi_samples = int(os.environ.get('PYVISTA_MULTI_SAMPLES', 8))
        except ValueError:  # pragma: no cover
            self._multi_samples = 8

        # Grab system flag for auto-closing
        self._auto_close = os.environ.get('PYVISTA_AUTO_CLOSE', '').lower() != 'false'

        self._jupyter_backend = os.environ.get('PYVISTA_JUPYTER_BACKEND', 'trame')
        self._trame = _TrameConfig()

        self._multi_rendering_splitting_position = None
        self._volume_mapper = 'fixed_point' if os.name == 'nt' else 'smart'
        self._smooth_shading = False
        self._depth_peeling = _DepthPeelingConfig()
        self._silhouette = _SilhouetteConfig()
        self._slider_styles = _SliderConfig()
        self._return_cpos = True
        self._hidden_line_removal = False
        self._anti_aliasing = 'msaa'
        self._enable_camera_orientation_widget = False

        self._lighting_params = _LightingConfig()
        self._interpolate_before_map = True
        self._opacity = 1.0

    @property
    def hidden_line_removal(self) -> bool:  # numpydoc ignore=RT01
        """Return or set hidden line removal.

        Wireframe geometry will be drawn using hidden line removal if
        the rendering engine supports it.

        See Also
        --------
        pyvista.Plotter.enable_hidden_line_removal

        Examples
        --------
        Enable hidden line removal.

        >>> import pyvista as pv
        >>> pv.global_theme.hidden_line_removal = True
        >>> pv.global_theme.hidden_line_removal
        True

        """
        return self._hidden_line_removal

    @hidden_line_removal.setter
    def hidden_line_removal(self, value: bool):  # numpydoc ignore=GL08
        self._hidden_line_removal = value

    @property
    def interpolate_before_map(self) -> bool:  # numpydoc ignore=RT01
        """Return or set whether to interpolate colors before mapping.

        If the ``interpolate_before_map`` is turned off, the color
        mapping occurs at polygon points and colors are interpolated,
        which is generally less accurate whereas if the
        ``interpolate_before_map`` is on (the default), then the scalars
        will be interpolated across the topology of the dataset which is
        more accurate.

        See also :ref:`interpolate_before_mapping_example`.

        Examples
        --------
        Enable hidden line removal.

        >>> import pyvista as pv

        Load a cylinder which has cells with a wide spread

        >>> cyl = pv.Cylinder(direction=(0, 0, 1), height=2).elevation()

        Common display argument to make sure all else is constant

        >>> dargs = dict(
        ...     scalars='Elevation', cmap='rainbow', show_edges=True
        ... )

        >>> p = pv.Plotter(shape=(1, 2))
        >>> _ = p.add_mesh(
        ...     cyl,
        ...     interpolate_before_map=False,
        ...     scalar_bar_args={'title': 'Elevation - interpolated'},
        ...     **dargs
        ... )
        >>> p.subplot(0, 1)
        >>> _ = p.add_mesh(
        ...     cyl,
        ...     interpolate_before_map=True,
        ...     scalar_bar_args={'title': 'Elevation - interpolated'},
        ...     **dargs
        ... )
        >>> p.link_views()
        >>> p.camera_position = [
        ...     (-1.67, -5.10, 2.06),
        ...     (0.0, 0.0, 0.0),
        ...     (0.00, 0.37, 0.93),
        ... ]
        >>> p.show()  # doctest: +SKIP

        """
        return self._interpolate_before_map

    @interpolate_before_map.setter
    def interpolate_before_map(self, value: bool):  # numpydoc ignore=GL08
        self._interpolate_before_map = value

    @property
    def opacity(self) -> float:  # numpydoc ignore=RT01
        """Return or set the opacity.

        Examples
        --------
        >>> import pyvista as pv
        >>> pv.global_theme.opacity = 0.5

        """
        return self._opacity

    @opacity.setter
    def opacity(self, opacity: float):  # numpydoc ignore=GL08
        _check_range(opacity, (0, 1), 'opacity')
        self._opacity = float(opacity)

    @property
    def above_range_color(self) -> Color:  # numpydoc ignore=RT01
        """Return or set the default above range color.

        Examples
        --------
        Set the above range color to red.

        >>> import pyvista as pv
        >>> pv.global_theme.above_range_color = 'r'
        >>> pv.global_theme.above_range_color
        Color(name='red', hex='#ff0000ff', opacity=255)

        """
        return self._above_range_color

    @above_range_color.setter
    def above_range_color(self, value: ColorLike):  # numpydoc ignore=GL08
        self._above_range_color = Color(value)

    @property
    def below_range_color(self) -> Color:  # numpydoc ignore=RT01
        """Return or set the default below range color.

        Examples
        --------
        Set the below range color to blue.

        >>> import pyvista as pv
        >>> pv.global_theme.below_range_color = 'b'
        >>> pv.global_theme.below_range_color
        Color(name='blue', hex='#0000ffff', opacity=255)

        """
        return self._below_range_color

    @below_range_color.setter
    def below_range_color(self, value: ColorLike):  # numpydoc ignore=GL08
        self._below_range_color = Color(value)

    @property
    def return_cpos(self) -> bool:  # numpydoc ignore=RT01
        """Return or set the default behavior of returning the camera position.

        Examples
        --------
        Disable returning camera position by ``show`` and ``plot`` methods.

        >>> import pyvista as pv
        >>> pv.global_theme.return_cpos = False
        """
        return self._return_cpos

    @return_cpos.setter
    def return_cpos(self, value: bool):  # numpydoc ignore=GL08
        self._return_cpos = value

    @property
    def background(self) -> Color:  # numpydoc ignore=RT01
        """Return or set the default background color of pyvista plots.

        Examples
        --------
        Set the default global background of all plots to white.

        >>> import pyvista as pv
        >>> pv.global_theme.background = 'white'
        """
        return self._background

    @background.setter
    def background(self, new_background: ColorLike):  # numpydoc ignore=GL08
        self._background = Color(new_background)

    @property
    def jupyter_backend(self) -> str:  # numpydoc ignore=RT01
        """Return or set the jupyter notebook plotting backend.

        Jupyter backend to use when plotting.  Must be one of the
        following:

        * ``'static'`` : Display a single static image within the
          Jupyterlab environment.  Still requires that a virtual
          framebuffer be set up when displaying on a headless server,
          but does not require any additional modules to be installed.

        * ``'client'`` : Export/serialize the scene graph to be rendered
          with VTK.js client-side through ``trame``. Requires ``trame``
          and ``jupyter-server-proxy`` to be installed.

        * ``'server'``: Render remotely and stream the resulting VTK
          images back to the client using ``trame``. This replaces the
          ``'ipyvtklink'`` backend with better performance.
          Supports the most VTK features, but suffers from minor lag due
          to remote rendering. Requires that a virtual framebuffer be set
          up when displaying on a headless server. Must have at least ``trame``
          and ``jupyter-server-proxy`` installed for cloud/remote Jupyter
          instances. This mode is also aliased by ``'trame'``.

        * ``'trame'``: The full Trame-based backend that combines both
          ``'server'`` and ``'client'`` into one backend. This requires a
          virtual frame buffer.

        * ``'none'`` : Do not display any plots within jupyterlab,
          instead display using dedicated VTK render windows.  This
          will generate nothing on headless servers even with a
          virtual framebuffer.

        Examples
        --------
        Just show static images.

        >>> pv.set_jupyter_backend('static')  # doctest:+SKIP

        Disable all plotting within JupyterLab and display using a
        standard desktop VTK render window.

        >>> pv.set_jupyter_backend(None)  # doctest:+SKIP

        """
        return self._jupyter_backend

    @jupyter_backend.setter
    def jupyter_backend(self, backend: 'str'):  # numpydoc ignore=GL08
        from pyvista.jupyter import _validate_jupyter_backend

        self._jupyter_backend = _validate_jupyter_backend(backend)

    @property
    def trame(self) -> _TrameConfig:  # numpydoc ignore=RT01
        """Return or set the default trame parameters."""
        return self._trame

    @trame.setter
    def trame(self, config: _TrameConfig):  # numpydoc ignore=GL08
        if not isinstance(config, _TrameConfig):
            raise TypeError('Configuration type must be `_TrameConfig`.')
        self._trame = config

    @property
    def auto_close(self) -> bool:  # numpydoc ignore=RT01
        """Automatically close the figures when finished plotting.

        .. DANGER::
           Set to ``False`` with extreme caution.

        Examples
        --------
        >>> import pyvista as pv
        >>> pv.global_theme.auto_close = False

        """
        return self._auto_close

    @auto_close.setter
    def auto_close(self, value: bool):  # numpydoc ignore=GL08
        self._auto_close = value

    @property
    def full_screen(self) -> bool:  # numpydoc ignore=RT01
        """Return if figures are shown in full screen.

        Examples
        --------
        Set windows to be full screen by default.

        >>> import pyvista as pv
        >>> pv.global_theme.full_screen = True
        """
        return self._full_screen

    @full_screen.setter
    def full_screen(self, value: bool):  # numpydoc ignore=GL08
        self._full_screen = value

    @property
    def enable_camera_orientation_widget(self) -> bool:  # numpydoc ignore=RT01
        """Enable the camera orientation widget in all plotters.

        Examples
        --------
        >>> import pyvista as pv
        >>> pv.global_theme.enable_camera_orientation_widget = True
        >>> pv.global_theme.enable_camera_orientation_widget
        True

        """
        return self._enable_camera_orientation_widget

    @enable_camera_orientation_widget.setter
    def enable_camera_orientation_widget(self, value: bool):  # numpydoc ignore=GL08
        self._enable_camera_orientation_widget = value

    @property
    def camera(self):  # numpydoc ignore=RT01
        """Return or set the default camera position.

        Examples
        --------
        Set both the position and view of the camera.

        >>> import pyvista as pv
        >>> pv.global_theme.camera = {
        ...     'position': [1, 1, 1],
        ...     'viewup': [0, 0, 1],
        ... }

        Set the default position of the camera.

        >>> pv.global_theme.camera['position'] = [1, 1, 1]

        Set the default view of the camera.

        >>> pv.global_theme.camera['viewup'] = [0, 0, 1]

        """
        return self._camera

    @camera.setter
    def camera(self, camera):  # numpydoc ignore=GL08
        if not isinstance(camera, dict):
            raise TypeError(f'Expected ``camera`` to be a dict, not {type(camera).__name__}.')

        if 'position' not in camera:
            raise KeyError('Expected the "position" key in the camera dict.')
        if 'viewup' not in camera:
            raise KeyError('Expected the "viewup" key in the camera dict.')

        self._camera = camera

    @property
    def notebook(self) -> Union[bool, None]:  # numpydoc ignore=RT01
        """Return or set the state of notebook plotting.

        Setting this to ``True`` always enables notebook plotting,
        while setting it to ``False`` disables plotting even when
        plotting within a jupyter notebook and plots externally.

        Examples
        --------
        Disable all jupyter notebook plotting.

        >>> import pyvista as pv
        >>> pv.global_theme.notebook = False

        """
        return self._notebook

    @notebook.setter
    def notebook(self, value: Union[bool, None]):  # numpydoc ignore=GL08
        self._notebook = value

    @property
    def window_size(self) -> List[int]:  # numpydoc ignore=RT01
        """Return or set the default render window size.

        Examples
        --------
        Set window size to ``[400, 400]``.

        >>> import pyvista as pv
        >>> pv.global_theme.window_size = [400, 400]

        """
        return self._window_size

    @window_size.setter
    def window_size(self, window_size: List[int]):  # numpydoc ignore=GL08
        if len(window_size) != 2:
            raise ValueError('Expected a length 2 iterable for ``window_size``.')

        # ensure positive size
        if window_size[0] < 0 or window_size[1] < 0:
            raise ValueError('Window size must be a positive value.')

        self._window_size = window_size

    @property
    def image_scale(self) -> int:  # numpydoc ignore=RT01
        """Return or set the default image scale factor."""
        return self._image_scale

    @image_scale.setter
    def image_scale(self, value: int):  # numpydoc ignore=GL08
        value = int(value)
        if value < 1:
            raise ValueError('Scale factor must be a positive integer.')
        self._image_scale = int(value)

    @property
    def font(self) -> _Font:  # numpydoc ignore=RT01
        """Return or set the default font size, family, and/or color.

        Examples
        --------
        Set the default font family to 'arial'.  Must be either
        'arial', 'courier', or 'times'.

        >>> import pyvista as pv
        >>> pv.global_theme.font.family = 'arial'

        Set the default font size to 20.

        >>> pv.global_theme.font.size = 20

        Set the default title size to 40.

        >>> pv.global_theme.font.title_size = 40

        Set the default label size to 10.

        >>> pv.global_theme.font.label_size = 10

        Set the default text color to 'grey'.

        >>> pv.global_theme.font.color = 'grey'

        String formatter used to format numerical data to '%.6e'.

        >>> pv.global_theme.font.fmt = '%.6e'

        """
        return self._font

    @font.setter
    def font(self, config: _Font):  # numpydoc ignore=GL08
        if not isinstance(config, _Font):
            raise TypeError('Configuration type must be `_Font`.')
        self._font = config

    @property
    def cmap(self):  # numpydoc ignore=RT01
        """Return or set the default colormap of pyvista.

        See available Matplotlib colormaps.  Only applicable for when
        displaying ``scalars``.  If ``colorcet`` or ``cmocean`` are
        installed, their colormaps can be specified by name.

        You can also specify a list of colors to override an existing
        colormap with a custom one.  For example, to create a three
        color colormap you might specify ``['green', 'red', 'blue']``

        Examples
        --------
        Set the default global colormap to 'jet'.

        >>> import pyvista as pv
        >>> pv.global_theme.cmap = 'jet'

        """
        return self._cmap

    @cmap.setter
    def cmap(self, cmap):  # numpydoc ignore=GL08
        out = get_cmap_safe(cmap)  # for validation
        if out is None:
            raise ValueError(f'Invalid color map {cmap}')
        self._cmap = cmap

    @property
    def color(self) -> Color:  # numpydoc ignore=RT01
        """Return or set the default color of meshes in pyvista.

        Used for meshes without ``scalars``.

        When setting, the value must be either a string, rgb list,
        or hex color string.  For example:

        * ``color='white'``
        * ``color='w'``
        * ``color=[1.0, 1.0, 1.0]``
        * ``color='#FFFFFF'``

        Examples
        --------
        Set the default mesh color to 'red'.

        >>> import pyvista as pv
        >>> pv.global_theme.color = 'red'

        """
        return self._color

    @color.setter
    def color(self, color: ColorLike):  # numpydoc ignore=GL08
        self._color = Color(color)

    @property
    def color_cycler(self):  # numpydoc ignore=RT01
        """Return or set the default color cycler used to color meshes.

        This color cycler is iterated over by each renderer to sequentially
        color datasets when displaying them through ``add_mesh``.

        When setting, the value must be either a list of color-like objects,
        or a cycler of color-like objects. If the value passed is a single
        string, it must be one of:

            * ``'default'`` - Use the default color cycler (matches matplotlib's default)
            * ``'matplotlib`` - Dynamically get matplotlib's current theme's color cycler.
            * ``'all'`` - Cycle through all of the available colors in ``pyvista.plotting.colors.hexcolors``

        Setting to ``None`` will disable the use of the color cycler.

        Examples
        --------
        Set the default color cycler to iterate through red, green, and blue.

        >>> import pyvista as pv
        >>> pv.global_theme.color_cycler = ['red', 'green', 'blue']

        >>> pl = pv.Plotter()
        >>> _ = pl.add_mesh(pv.Cone(center=(0, 0, 0)))  # red
        >>> _ = pl.add_mesh(pv.Cube(center=(1, 0, 0)))  # green
        >>> _ = pl.add_mesh(pv.Sphere(center=(1, 1, 0)))  # blue
        >>> _ = pl.add_mesh(pv.Cylinder(center=(0, 1, 0)))  # red again
        >>> pl.show()  # doctest: +SKIP

        """
        return self._color_cycler

    @color_cycler.setter
    def color_cycler(self, color_cycler):  # numpydoc ignore=GL08
        self._color_cycler = get_cycler(color_cycler)

    @property
    def nan_color(self) -> Color:  # numpydoc ignore=RT01
        """Return or set the default NaN color.

        This color is used to plot all NaN values.

        Examples
        --------
        >>> import pyvista as pv
        >>> pv.global_theme.nan_color = 'darkgray'

        """
        return self._nan_color

    @nan_color.setter
    def nan_color(self, nan_color: ColorLike):  # numpydoc ignore=GL08
        self._nan_color = Color(nan_color)

    @property
    def edge_color(self) -> Color:  # numpydoc ignore=RT01
        """Return or set the default edge color.

        Examples
        --------
        Set the global edge color to 'blue'.

        >>> import pyvista as pv
        >>> pv.global_theme.edge_color = 'blue'

        """
        return self._edge_color

    @edge_color.setter
    def edge_color(self, edge_color: ColorLike):  # numpydoc ignore=GL08
        self._edge_color = Color(edge_color)

    @property
    def line_width(self) -> float:  # numpydoc ignore=RT01
        """Return or set the default line width.

        Examples
        --------
        >>> import pyvista as pv
        >>> pv.global_theme.line_width = 2.0

        """
        return self._line_width

    @line_width.setter
    def line_width(self, line_width: float):  # numpydoc ignore=GL08
        self._line_width = float(line_width)

    @property
    def point_size(self) -> float:  # numpydoc ignore=RT01
        """Return or set the default point size.

        Examples
        --------
        >>> import pyvista as pv
        >>> pv.global_theme.line_width = 10.0

        """
        return self._point_size

    @point_size.setter
    def point_size(self, point_size: float):  # numpydoc ignore=GL08
        self._point_size = float(point_size)

    @property
    def outline_color(self) -> Color:  # numpydoc ignore=RT01
        """Return or set the default outline color.

        Examples
        --------
        >>> import pyvista as pv
        >>> pv.global_theme.outline_color = 'white'

        """
        return self._outline_color

    @outline_color.setter
    def outline_color(self, outline_color: ColorLike):  # numpydoc ignore=GL08
        self._outline_color = Color(outline_color)

    @property
    def floor_color(self) -> Color:  # numpydoc ignore=RT01
        """Return or set the default floor color.

        Examples
        --------
        >>> import pyvista as pv
        >>> pv.global_theme.floor_color = 'black'

        """
        return self._floor_color

    @floor_color.setter
    def floor_color(self, floor_color: ColorLike):  # numpydoc ignore=GL08
        self._floor_color = Color(floor_color)

    @property
    def colorbar_orientation(self) -> str:  # numpydoc ignore=RT01
        """Return or set the default colorbar orientation.

        Must be either ``'vertical'`` or ``'horizontal'``.

        Examples
        --------
        >>> import pyvista as pv
        >>> pv.global_theme.colorbar_orientation = 'horizontal'

        """
        return self._colorbar_orientation

    @colorbar_orientation.setter
    def colorbar_orientation(self, colorbar_orientation: str):  # numpydoc ignore=GL08
        if colorbar_orientation not in ['vertical', 'horizontal']:
            raise ValueError('Colorbar orientation must be either "vertical" or "horizontal"')
        self._colorbar_orientation = colorbar_orientation

    @property
    def colorbar_horizontal(self) -> _ColorbarConfig:  # numpydoc ignore=RT01
        """Return or set the default parameters of a horizontal colorbar.

        Examples
        --------
        Set the default horizontal colorbar width to 0.6.

        >>> import pyvista as pv
        >>> pv.global_theme.colorbar_horizontal.width = 0.6

        Set the default horizontal colorbar height to 0.2.

        >>> pv.global_theme.colorbar_horizontal.height = 0.2

        """
        return self._colorbar_horizontal

    @colorbar_horizontal.setter
    def colorbar_horizontal(self, config: _ColorbarConfig):  # numpydoc ignore=GL08
        if not isinstance(config, _ColorbarConfig):
            raise TypeError('Configuration type must be `_ColorbarConfig`.')
        self._colorbar_horizontal = config

    @property
    def colorbar_vertical(self) -> _ColorbarConfig:  # numpydoc ignore=RT01
        """Return or set the default parameters of a vertical colorbar.

        Examples
        --------
        Set the default colorbar width to 0.45.

        >>> import pyvista as pv
        >>> pv.global_theme.colorbar_vertical.width = 0.45

        Set the default colorbar height to 0.8.

        >>> import pyvista as pv
        >>> pv.global_theme.colorbar_vertical.height = 0.8

        """
        return self._colorbar_vertical

    @colorbar_vertical.setter
    def colorbar_vertical(self, config: _ColorbarConfig):  # numpydoc ignore=GL08
        if not isinstance(config, _ColorbarConfig):
            raise TypeError('Configuration type must be `_ColorbarConfig`.')
        self._colorbar_vertical = config

    @property
    def show_scalar_bar(self) -> bool:  # numpydoc ignore=RT01
        """Return or set the default color bar visibility.

        Examples
        --------
        Show the scalar bar by default when scalars are available.

        >>> import pyvista as pv
        >>> pv.global_theme.show_scalar_bar = True

        """
        return self._show_scalar_bar

    @show_scalar_bar.setter
    def show_scalar_bar(self, show_scalar_bar: bool):  # numpydoc ignore=GL08
        self._show_scalar_bar = bool(show_scalar_bar)

    @property
    def show_edges(self) -> bool:  # numpydoc ignore=RT01
        """Return or set the default edge visibility.

        Examples
        --------
        Show edges globally by default.

        >>> import pyvista as pv
        >>> pv.global_theme.show_edges = True

        """
        return self._show_edges

    @show_edges.setter
    def show_edges(self, show_edges: bool):  # numpydoc ignore=GL08
        self._show_edges = bool(show_edges)

    @property
    def show_vertices(self) -> bool:  # numpydoc ignore=RT01
        """Return or set the default vertex visibility.

        Examples
        --------
        Show vertices globally by default.

        >>> import pyvista as pv
        >>> pv.global_theme.show_vertices = True

        """
        return self._show_vertices

    @show_vertices.setter
    def show_vertices(self, show_vertices: bool):  # numpydoc ignore=GL08
        self._show_vertices = bool(show_vertices)

    @property
    def lighting(self) -> bool:  # numpydoc ignore=RT01
        """Return or set the default ``lighting``.

        Examples
        --------
        Disable lighting globally.

        >>> import pyvista as pv
        >>> pv.global_theme.lighting = False
        """
        return self._lighting

    @lighting.setter
    def lighting(self, lighting: bool):  # numpydoc ignore=GL08
        self._lighting = lighting

    @property
    def interactive(self) -> bool:  # numpydoc ignore=RT01
        """Return or set the default ``interactive`` parameter.

        Examples
        --------
        Make all plots non-interactive globally.

        >>> import pyvista as pv
        >>> pv.global_theme.interactive = False
        """
        return self._interactive

    @interactive.setter
    def interactive(self, interactive: bool):  # numpydoc ignore=GL08
        self._interactive = bool(interactive)

    @property
    def render_points_as_spheres(self) -> bool:  # numpydoc ignore=RT01
        """Return or set the default ``render_points_as_spheres`` parameter.

        Examples
        --------
        Render points as spheres by default globally.

        >>> import pyvista as pv
        >>> pv.global_theme.render_points_as_spheres = True
        """
        return self._render_points_as_spheres

    @render_points_as_spheres.setter
    def render_points_as_spheres(self, render_points_as_spheres: bool):  # numpydoc ignore=GL08
        self._render_points_as_spheres = bool(render_points_as_spheres)

    @property
    def render_lines_as_tubes(self) -> bool:  # numpydoc ignore=RT01
        """Return or set the default ``render_lines_as_tubes`` parameter.

        Examples
        --------
        Render points as spheres by default globally.

        >>> import pyvista as pv
        >>> pv.global_theme.render_lines_as_tubes = True
        """
        return self._render_lines_as_tubes

    @render_lines_as_tubes.setter
    def render_lines_as_tubes(self, render_lines_as_tubes: bool):  # numpydoc ignore=GL08
        self._render_lines_as_tubes = bool(render_lines_as_tubes)

    @property
    def transparent_background(self) -> bool:  # numpydoc ignore=RT01
        """Return or set the default ``transparent_background`` parameter.

        Examples
        --------
        Set transparent_background globally to ``True``.

        >>> import pyvista as pv
        >>> pv.global_theme.transparent_background = True

        """
        return self._transparent_background

    @transparent_background.setter
    def transparent_background(self, transparent_background: bool):  # numpydoc ignore=GL08
        self._transparent_background = transparent_background

    @property
    def title(self) -> str:  # numpydoc ignore=RT01
        """Return or set the default ``title`` parameter.

        This is the VTK render window title.

        Examples
        --------
        Set title globally to 'plot'.

        >>> import pyvista as pv
        >>> pv.global_theme.title = 'plot'

        """
        return self._title

    @title.setter
    def title(self, title: str):  # numpydoc ignore=GL08
        self._title = title

    @property
    def anti_aliasing(self) -> Optional[str]:  # numpydoc ignore=RT01
        """Enable or disable anti-aliasing.

        Should be either ``"ssaa"``, ``"msaa"``, ``"fxaa"``, or ``None``.

        Examples
        --------
        Use super-sampling anti-aliasing in the global theme.

        >>> import pyvista as pv
        >>> pv.global_theme.anti_aliasing = 'ssaa'
        >>> pv.global_theme.anti_aliasing
        'ssaa'

        Disable anti-aliasing in the global theme.

        >>> import pyvista as pv
        >>> pv.global_theme.anti_aliasing = None

        See :ref:`anti_aliasing_example` for more information regarding
        anti-aliasing.

        """
        return self._anti_aliasing

    @anti_aliasing.setter
    def anti_aliasing(self, anti_aliasing: Union[str, None]):  # numpydoc ignore=GL08
        if isinstance(anti_aliasing, str):
            if anti_aliasing not in ['ssaa', 'msaa', 'fxaa']:
                raise ValueError('anti_aliasing must be either "ssaa", "msaa", or "fxaa"')
        elif anti_aliasing is not None:
            raise TypeError('anti_aliasing must be either "ssaa", "msaa", "fxaa", or None')

        self._anti_aliasing = anti_aliasing

    @property
    def multi_samples(self) -> int:  # numpydoc ignore=RT01
        """Return or set the default ``multi_samples`` parameter.

        Set the number of multisamples to used with hardware anti_aliasing. This
        is only used when :attr:`anti_aliasing <Theme.anti_aliasing>` is
        set to ``"msaa"``.

        Examples
        --------
        Set the default number of multisamples to 2 and enable ``"msaa"``

        >>> import pyvista as pv
        >>> pv.global_theme.anti_aliasing = 'msaa'
        >>> pv.global_theme.multi_samples = 2

        """
        return self._multi_samples

    @multi_samples.setter
    def multi_samples(self, multi_samples: int):  # numpydoc ignore=GL08
        self._multi_samples = int(multi_samples)

    @property
    def multi_rendering_splitting_position(self) -> float:  # numpydoc ignore=RT01
        """Return or set the default ``multi_rendering_splitting_position`` parameter.

        Examples
        --------
        Set multi_rendering_splitting_position globally to 0.5 (the
        middle of the window).

        >>> import pyvista as pv
        >>> pv.global_theme.multi_rendering_splitting_position = 0.5

        """
        return self._multi_rendering_splitting_position

    @multi_rendering_splitting_position.setter
    def multi_rendering_splitting_position(
        self, multi_rendering_splitting_position: float
    ):  # numpydoc ignore=GL08
        self._multi_rendering_splitting_position = multi_rendering_splitting_position

    @property
    def volume_mapper(self) -> str:  # numpydoc ignore=RT01
        """Return or set the default ``volume_mapper`` parameter.

        Must be one of the following strings, which are mapped to the
        following VTK volume mappers.

        * ``'fixed_point'`` : ``vtk.vtkFixedPointVolumeRayCastMapper``
        * ``'gpu'`` : ``vtk.vtkGPUVolumeRayCastMapper``
        * ``'open_gl'`` : ``vtk.vtkOpenGLGPUVolumeRayCastMapper``
        * ``'smart'`` : ``vtk.vtkSmartVolumeMapper``

        Examples
        --------
        Set default volume mapper globally to 'gpu'.

        >>> import pyvista as pv
        >>> pv.global_theme.volume_mapper = 'gpu'

        """
        return self._volume_mapper

    @volume_mapper.setter
    def volume_mapper(self, mapper: str):  # numpydoc ignore=GL08
        mappers = ['fixed_point', 'gpu', 'open_gl', 'smart']
        if mapper not in mappers:
            raise ValueError(
                f"Mapper ({mapper}) unknown. Available volume mappers "
                f"include:\n {', '.join(mappers)}"
            )

        self._volume_mapper = mapper

    @property
    def smooth_shading(self) -> bool:  # numpydoc ignore=RT01
        """Return or set the default ``smooth_shading`` parameter.

        Examples
        --------
        Set the global smooth_shading parameter default to ``True``.

        >>> import pyvista as pv
        >>> pv.global_theme.smooth_shading = True

        """
        return self._smooth_shading

    @smooth_shading.setter
    def smooth_shading(self, smooth_shading: bool):  # numpydoc ignore=GL08
        self._smooth_shading = bool(smooth_shading)

    @property
    def depth_peeling(self) -> _DepthPeelingConfig:  # numpydoc ignore=RT01
        """Return or set the default depth peeling parameters.

        Examples
        --------
        Set the global depth_peeling parameter default to be enabled
        with 8 peels.

        >>> import pyvista as pv
        >>> pv.global_theme.depth_peeling.number_of_peels = 8
        >>> pv.global_theme.depth_peeling.occlusion_ratio = 0.0
        >>> pv.global_theme.depth_peeling.enabled = True

        """
        return self._depth_peeling

    @depth_peeling.setter
    def depth_peeling(self, config: _DepthPeelingConfig):  # numpydoc ignore=GL08
        if not isinstance(config, _DepthPeelingConfig):
            raise TypeError('Configuration type must be `_DepthPeelingConfig`.')
        self._depth_peeling = config

    @property
    def silhouette(self) -> _SilhouetteConfig:  # numpydoc ignore=RT01
        """Return or set the default ``silhouette`` configuration.

        Examples
        --------
        Set parameters of the silhouette.

        >>> import pyvista as pv
        >>> pv.global_theme.silhouette.color = 'grey'
        >>> pv.global_theme.silhouette.line_width = 2.0
        >>> pv.global_theme.silhouette.feature_angle = 20

        """
        return self._silhouette

    @silhouette.setter
    def silhouette(self, config: _SilhouetteConfig):  # numpydoc ignore=GL08
        if not isinstance(config, _SilhouetteConfig):
            raise TypeError('Configuration type must be `_SilhouetteConfig`')
        self._silhouette = config

    @property
    def slider_styles(self) -> _SliderConfig:  # numpydoc ignore=RT01
        """Return the default slider style configurations."""
        return self._slider_styles

    @slider_styles.setter
    def slider_styles(self, config: _SliderConfig):  # numpydoc ignore=GL08
        if not isinstance(config, _SliderConfig):
            raise TypeError('Configuration type must be `_SliderConfig`.')
        self._slider_styles = config

    @property
    def axes(self) -> _AxesConfig:  # numpydoc ignore=RT01
        """Return or set the default ``axes`` configuration.

        Examples
        --------
        Set the x axis color to black.

        >>> import pyvista as pv
        >>> pv.global_theme.axes.x_color = 'black'

        Show axes by default.

        >>> pv.global_theme.axes.show = True

        Use the ``vtk.vtkCubeAxesActor``.

        >>> pv.global_theme.axes.box = True

        """
        return self._axes

    @axes.setter
    def axes(self, config: _AxesConfig):  # numpydoc ignore=GL08
        if not isinstance(config, _AxesConfig):
            raise TypeError('Configuration type must be `_AxesConfig`.')
        self._axes = config

    @property
    def before_close_callback(self) -> Callable[['pyvista.Plotter'], None]:  # numpydoc ignore=RT01
        """Return the default before_close_callback function for Plotter."""
        return self._before_close_callback

    @before_close_callback.setter
    def before_close_callback(
        self, value: Callable[['pyvista.Plotter'], None]
    ):  # numpydoc ignore=GL08
        self._before_close_callback = value

    def restore_defaults(self):  # numpydoc ignore=GL08
        """Restore the theme defaults.

        Examples
        --------
        >>> import pyvista as pv
        >>> pv.global_theme.restore_defaults()

        """
        self.__init__()

    def __repr__(self):
        """User friendly representation of the current theme."""
        txt = [f'{self.name.capitalize()} Theme']
        txt.append('-' * len(txt[0]))
        parm = {
            'Background': 'background',
            'Jupyter backend': 'jupyter_backend',
            'Full screen': 'full_screen',
            'Window size': 'window_size',
            'Camera': 'camera',
            'Notebook': 'notebook',
            'Font': 'font',
            'Auto close': 'auto_close',
            'Colormap': 'cmap',
            'Color': 'color',
            'Color Cycler': 'color_cycler',
            'NaN color': 'nan_color',
            'Edge color': 'edge_color',
            'Outline color': 'outline_color',
            'Floor color': 'floor_color',
            'Colorbar orientation': 'colorbar_orientation',
            'Colorbar - horizontal': 'colorbar_horizontal',
            'Colorbar - vertical': 'colorbar_vertical',
            'Show scalar bar': 'show_scalar_bar',
            'Show edges': 'show_edges',
            'Lighting': 'lighting',
            'Interactive': 'interactive',
            'Render points as spheres': 'render_points_as_spheres',
            'Transparent Background': 'transparent_background',
            'Title': 'title',
            'Axes': 'axes',
            'Multi-samples': 'multi_samples',
            'Multi-renderer Split Pos': 'multi_rendering_splitting_position',
            'Volume mapper': 'volume_mapper',
            'Smooth shading': 'smooth_shading',
            'Depth peeling': 'depth_peeling',
            'Silhouette': 'silhouette',
            'Slider Styles': 'slider_styles',
            'Return Camera Position': 'return_cpos',
            'Hidden Line Removal': 'hidden_line_removal',
            'Anti-Aliasing': '_anti_aliasing',
            'Split sharp edges': '_split_sharp_edges',
            'Sharp edges feat. angle': '_sharp_edges_feature_angle',
            'Before close callback': '_before_close_callback',
        }
        for name, attr in parm.items():
            setting = getattr(self, attr)
            txt.append(f'{name:<25}: {setting}')

        return '\n'.join(txt)

    @property
    def name(self) -> str:  # numpydoc ignore=RT01
        """Return or set the name of the theme."""
        return self._name

    @name.setter
    def name(self, name: str):  # numpydoc ignore=GL08
        self._name = name

    def load_theme(self, theme):
        """Overwrite the current theme with a theme.

        Parameters
        ----------
        theme : pyvista.plotting.themes.Theme
            Theme to use to overwrite this theme.

        Examples
        --------
        Create a custom theme from the default theme and load it into
        the global theme of pyvista.

        >>> import pyvista as pv
        >>> from pyvista.plotting.themes import DocumentTheme
        >>> my_theme = DocumentTheme()
        >>> my_theme.font.size = 20
        >>> my_theme.font.title_size = 40
        >>> my_theme.cmap = 'jet'
        >>> pv.global_theme.load_theme(my_theme)
        >>> pv.global_theme.font.size
        20

        Create a custom theme from the dark theme and load it into
        pyvista.

        >>> from pyvista.plotting.themes import DarkTheme
        >>> my_theme = DarkTheme()
        >>> my_theme.show_edges = True
        >>> pv.global_theme.load_theme(my_theme)
        >>> pv.global_theme.show_edges
        True

        """
        if isinstance(theme, str):
            theme = load_theme(theme)

        if not isinstance(theme, Theme):
            raise TypeError(
                '``theme`` must be a pyvista theme like ``pyvista.plotting.themes.Theme``.'
            )

        for attr_name in theme.__slots__:
            setattr(self, attr_name, getattr(theme, attr_name))

    def save(self, filename):
        """Serialize this theme to a json file.

        ``before_close_callback`` is non-serializable and is omitted.

        Parameters
        ----------
        filename : str
            Path to save the theme to.  Should end in ``'.json'``.

        Examples
        --------
        Export and then load back in a theme.

        >>> import pyvista as pv
        >>> theme = pv.themes.DocumentTheme()
        >>> theme.background = 'white'
        >>> theme.save('my_theme.json')  # doctest:+SKIP
        >>> loaded_theme = pv.load_theme('my_theme.json')  # doctest:+SKIP

        """
        data = self.to_dict()
        # functions are not serializable
        del data["before_close_callback"]
        with open(filename, 'w') as f:
            json.dump(data, f)

    @property
    def split_sharp_edges(self) -> bool:  # numpydoc ignore=RT01
        """Set or return splitting sharp edges.

        See :ref:`shading_example` for an example showing split sharp edges.

        Examples
        --------
        Enable the splitting of sharp edges globally.

        >>> import pyvista as pv
        >>> pv.global_theme.split_sharp_edges = True
        >>> pv.global_theme.split_sharp_edges
        True

        Disable the splitting of sharp edges globally.

        >>> import pyvista as pv
        >>> pv.global_theme.split_sharp_edges = False
        >>> pv.global_theme.split_sharp_edges
        False

        """
        return self._split_sharp_edges

    @split_sharp_edges.setter
    def split_sharp_edges(self, value: bool):  # numpydoc ignore=GL08
        self._split_sharp_edges = value

    @property
    def sharp_edges_feature_angle(self) -> float:  # numpydoc ignore=RT01
        """Set or return the angle of the sharp edges feature angle.

        See :ref:`shading_example` for an example showing split sharp edges.

        Examples
        --------
        Change the sharp edges feature angle to 45 degrees.

        >>> import pyvista as pv
        >>> pv.global_theme.sharp_edges_feature_angle = 45.0
        >>> pv.global_theme.sharp_edges_feature_angle
        45.0

        """
        return self._sharp_edges_feature_angle

    @sharp_edges_feature_angle.setter
    def sharp_edges_feature_angle(self, value: float):  # numpydoc ignore=GL08
        self._sharp_edges_feature_angle = float(value)

    @property
    def lighting_params(self) -> _LightingConfig:  # numpydoc ignore=RT01
        """Return or set the default lighting configuration."""
        return self._lighting_params

    @lighting_params.setter
    def lighting_params(self, config: _LightingConfig):  # numpydoc ignore=GL08
        if not isinstance(config, _LightingConfig):
            raise TypeError('Configuration type must be `_LightingConfig`.')
        self._lighting_params = config


class DefaultTheme(Theme):
    """Deprecated default theme.

    .. deprecated:: 0.40.0
        Deprecated and renamed to ``Theme``. No longer the default.

    """

    def __init__(self):
        """Initialize the theme."""
        super().__init__()
        warnings.warn(
            '`DefaultTheme` has been deprecated and renamed `Theme`. Further, `DocumentTheme` is now the PyVista default theme.',
            PyVistaDeprecationWarning,
        )


class DarkTheme(Theme):
    """Dark mode theme.

    Black background, "viridis" colormap, tan meshes, white (hidden) edges.

    Examples
    --------
    Make the dark theme the global default.

    >>> import pyvista as pv
    >>> from pyvista import themes
    >>> pv.set_plot_theme(themes.DarkTheme())

    Alternatively, set via a string.

    >>> pv.set_plot_theme('dark')

    """

    def __init__(self):
        """Initialize the theme."""
        super().__init__()
        self.name = 'dark'
        self.background = 'black'
        self.cmap = 'viridis'
        self.font.color = 'white'
        self.show_edges = False
        self.color = 'lightblue'
        self.outline_color = 'white'
        self.edge_color = 'white'
        self.axes.x_color = 'tomato'
        self.axes.y_color = 'seagreen'
        self.axes.z_color = 'blue'


class ParaViewTheme(Theme):
    """A paraview-like theme.

    Examples
    --------
    Make the paraview-like theme the global default.

    >>> import pyvista as pv
    >>> from pyvista import themes
    >>> pv.set_plot_theme(themes.ParaViewTheme())

    Alternatively, set via a string.

    >>> pv.set_plot_theme('paraview')

    """

    def __init__(self):
        """Initialize theme."""
        super().__init__()
        self.name = 'paraview'
        self.background = 'paraview'
        self.cmap = 'coolwarm'
        self.font.family = 'arial'
        self.font.label_size = 16
        self.font.color = 'white'
        self.show_edges = False
        self.color = 'white'
        self.outline_color = 'white'
        self.edge_color = 'black'
        self.axes.x_color = 'tomato'
        self.axes.y_color = 'gold'
        self.axes.z_color = 'green'


class DocumentTheme(Theme):
    """A document theme well suited for papers and presentations.

    This theme uses:

    * A white background
    * Black fonts
    * The "viridis" colormap
    * disables edges for surface plots
    * Hidden edge removal

    Best used for presentations, papers, etc.

    Examples
    --------
    Make the document theme the global default.

    >>> import pyvista as pv
    >>> from pyvista import themes
    >>> pv.set_plot_theme(themes.DocumentTheme())

    Alternatively, set via a string.

    >>> pv.set_plot_theme('document')

    """

    def __init__(self):
        """Initialize the theme."""
        super().__init__()
        self.name = 'document'
        self.background = 'white'
        self.cmap = 'viridis'
        self.font.size = 18
        self.font.title_size = 18
        self.font.label_size = 18
        self.font.color = 'black'
        self.show_edges = False
        self.color = 'lightblue'
        self.outline_color = 'black'
        self.edge_color = 'black'
        self.axes.x_color = 'tomato'
        self.axes.y_color = 'seagreen'
        self.axes.z_color = 'blue'


class DocumentProTheme(DocumentTheme):
    """A more professional document theme.

    This theme extends the base document theme with:

    * Default color cycling
    * Rendering points as spheres
    * MSAA anti aliassing
    * Depth peeling

    """

    def __init__(self):
        """Initialize the theme."""
        super().__init__()
        self.anti_aliasing = 'ssaa'
        self.color_cycler = get_cycler('default')
        self.render_points_as_spheres = True
        self.multi_samples = 8
        self.depth_peeling.number_of_peels = 4
        self.depth_peeling.occlusion_ratio = 0.0
        self.depth_peeling.enabled = True


class _TestingTheme(Theme):
    """Low resolution testing theme for ``pytest``.

    Necessary for image regression.  Xvfb doesn't support
    multi-sampling, it's disabled for consistency between desktops and
    remote testing.

    Also disables ``return_cpos`` to make it easier for us to write
    examples without returning camera positions.

    """

    def __init__(self):
        super().__init__()
        self.name = 'testing'
        self.multi_samples = 1
        self.window_size = [400, 400]
        self.axes.show = False
        self.return_cpos = False


class _NATIVE_THEMES(Enum):
    """Global built-in themes available to PyVista."""

    paraview = ParaViewTheme
    document = DocumentTheme
    document_pro = DocumentProTheme
    dark = DarkTheme
    default = DocumentTheme
    testing = _TestingTheme
    vtk = Theme


# pyvista/plotting/tools.py

"""Module containing useful plotting tools."""

from enum import Enum
import os
import platform
from subprocess import PIPE, Popen, TimeoutExpired

import numpy as np

import pyvista

from . import _vtk
from .colors import Color


class FONTS(Enum):
    """Font families available to PyVista."""

    arial = _vtk.VTK_ARIAL
    courier = _vtk.VTK_COURIER
    times = _vtk.VTK_TIMES


# Track render window support and plotting
SUPPORTS_OPENGL = None
SUPPORTS_PLOTTING = None


def supports_open_gl():
    """
    Return if the system supports OpenGL.

    This function checks if the system supports OpenGL by creating a VTK render
    window and querying its OpenGL support.

    Returns
    -------
    bool
        ``True`` if the system supports OpenGL, ``False`` otherwise.
    """
    global SUPPORTS_OPENGL
    if SUPPORTS_OPENGL is None:
        ren_win = _vtk.vtkRenderWindow()
        SUPPORTS_OPENGL = bool(ren_win.SupportsOpenGL())
    return SUPPORTS_OPENGL


def _system_supports_plotting():
    """Check if the environment supports plotting on Windows, Linux, or Mac OS.

    Returns
    -------
    system_supports_plotting : bool
        ``True`` when system supports plotting.

    """
    if os.environ.get('ALLOW_PLOTTING', '').lower() == 'true':
        return True

    # Windows case
    if os.name == 'nt':
        # actually have to check here.  Somewhat expensive.
        return supports_open_gl()

    # mac case
    if platform.system() == 'Darwin':
        # check if finder available
        proc = Popen(["pgrep", "-qx", "Finder"], stdout=PIPE, stderr=PIPE, encoding="utf8")
        try:
            proc.communicate(timeout=10)
        except TimeoutExpired:
            return False
        if proc.returncode == 0:
            return True

        # display variable set, likely available
        return 'DISPLAY' in os.environ

    # Linux case
    try:
        proc = Popen(["xset", "-q"], stdout=PIPE, stderr=PIPE, encoding="utf8")
        proc.communicate(timeout=10)
        return proc.returncode == 0
    except (OSError, TimeoutExpired):
        return False


def system_supports_plotting():
    """Check if the environment supports plotting.

    Returns
    -------
    bool
        ``True`` when system supports plotting.

    """
    global SUPPORTS_PLOTTING
    if SUPPORTS_PLOTTING is None:
        SUPPORTS_PLOTTING = _system_supports_plotting()

    # always use the cached response
    return SUPPORTS_PLOTTING


def _update_axes_label_color(axes_actor, color=None):
    """Set the axes label color (internal helper)."""
    color = Color(color, default_color=pyvista.global_theme.font.color)
    if isinstance(axes_actor, _vtk.vtkAxesActor):
        prop_x = axes_actor.GetXAxisCaptionActor2D().GetCaptionTextProperty()
        prop_y = axes_actor.GetYAxisCaptionActor2D().GetCaptionTextProperty()
        prop_z = axes_actor.GetZAxisCaptionActor2D().GetCaptionTextProperty()
        for prop in [prop_x, prop_y, prop_z]:
            prop.SetColor(color.float_rgb)
            prop.SetShadow(False)
    elif isinstance(axes_actor, _vtk.vtkAnnotatedCubeActor):
        axes_actor.GetTextEdgesProperty().SetColor(color.float_rgb)


def create_axes_marker(
    label_color=None,
    x_color=None,
    y_color=None,
    z_color=None,
    xlabel='X',
    ylabel='Y',
    zlabel='Z',
    labels_off=False,
    line_width=2,
    cone_radius=0.4,
    shaft_length=0.8,
    tip_length=0.2,
    ambient=0.5,
    label_size=(0.25, 0.1),
):
    """Create an axis actor.

    Parameters
    ----------
    label_color : ColorLike, optional
        Color of the label text.

    x_color : ColorLike, optional
        Color of the x axis text.

    y_color : ColorLike, optional
        Color of the y axis text.

    z_color : ColorLike, optional
        Color of the z axis text.

    xlabel : str, default: "X"
        Text used for the x axis.

    ylabel : str, default: "Y"
        Text used for the y axis.

    zlabel : str, default: "Z"
        Text used for the z axis.

    labels_off : bool, default: False
        Enable or disable the text labels for the axes.

    line_width : float, default: 2
        The width of the marker lines.

    cone_radius : float, default: 0.4
        The radius of the axes arrow tips.

    shaft_length : float, default: 0.8
        The length of the axes arrow shafts.

    tip_length : float, default: 0.2
        Length of the tip.

    ambient : float, default: 0.5
        The ambient of the axes arrows. Value should be between 0 and 1.

    label_size : sequence[float], default: (0.25, 0.1)
        The width and height of the axes label actors. Values should be between
        0 and 1. For example ``(0.2, 0.1)``.

    Returns
    -------
    vtk.vtkAxesActor
        Axes actor.

    Examples
    --------
    Create the default axes marker.

    >>> import pyvista as pv
    >>> marker = pv.create_axes_marker()
    >>> pl = pv.Plotter()
    >>> _ = pl.add_actor(marker)
    >>> pl.show()

    Create an axes marker at the origin with custom colors and axis labels.

    >>> import pyvista as pv
    >>> marker = pv.create_axes_marker(
    ...     line_width=4,
    ...     ambient=0.0,
    ...     x_color="#378df0",
    ...     y_color="#ab2e5d",
    ...     z_color="#f7fb9a",
    ...     xlabel="X Axis",
    ...     ylabel="Y Axis",
    ...     zlabel="Z Axis",
    ...     label_size=(0.1, 0.1),
    ... )
    >>> pl = pv.Plotter()
    >>> _ = pl.add_actor(marker)
    >>> pl.show()

    """
    x_color = Color(x_color, default_color=pyvista.global_theme.axes.x_color)
    y_color = Color(y_color, default_color=pyvista.global_theme.axes.y_color)
    z_color = Color(z_color, default_color=pyvista.global_theme.axes.z_color)
    axes_actor = _vtk.vtkAxesActor()
    axes_actor.GetXAxisShaftProperty().SetColor(x_color.float_rgb)
    axes_actor.GetXAxisTipProperty().SetColor(x_color.float_rgb)
    axes_actor.GetYAxisShaftProperty().SetColor(y_color.float_rgb)
    axes_actor.GetYAxisTipProperty().SetColor(y_color.float_rgb)
    axes_actor.GetZAxisShaftProperty().SetColor(z_color.float_rgb)
    axes_actor.GetZAxisTipProperty().SetColor(z_color.float_rgb)
    # Set labels
    axes_actor.SetXAxisLabelText(xlabel)
    axes_actor.SetYAxisLabelText(ylabel)
    axes_actor.SetZAxisLabelText(zlabel)
    if labels_off:
        axes_actor.AxisLabelsOff()
    # Set Line width
    axes_actor.GetXAxisShaftProperty().SetLineWidth(line_width)
    axes_actor.GetYAxisShaftProperty().SetLineWidth(line_width)
    axes_actor.GetZAxisShaftProperty().SetLineWidth(line_width)

    axes_actor.SetConeRadius(cone_radius)
    axes_actor.SetNormalizedShaftLength([shaft_length] * 3)
    axes_actor.SetNormalizedTipLength([tip_length] * 3)
    axes_actor.GetXAxisShaftProperty().SetAmbient(ambient)
    axes_actor.GetYAxisShaftProperty().SetAmbient(ambient)
    axes_actor.GetZAxisShaftProperty().SetAmbient(ambient)
    axes_actor.GetXAxisTipProperty().SetAmbient(ambient)
    axes_actor.GetYAxisTipProperty().SetAmbient(ambient)
    axes_actor.GetZAxisTipProperty().SetAmbient(ambient)

    for label_actor in [
        axes_actor.GetXAxisCaptionActor2D(),
        axes_actor.GetYAxisCaptionActor2D(),
        axes_actor.GetZAxisCaptionActor2D(),
    ]:
        label_actor.SetWidth(label_size[0])
        label_actor.SetHeight(label_size[1])

    _update_axes_label_color(axes_actor, label_color)

    return axes_actor


def create_axes_orientation_box(
    line_width=1,
    text_scale=0.366667,
    edge_color='black',
    x_color=None,
    y_color=None,
    z_color=None,
    xlabel='X',
    ylabel='Y',
    zlabel='Z',
    x_face_color='red',
    y_face_color='green',
    z_face_color='blue',
    color_box=False,
    label_color=None,
    labels_off=False,
    opacity=0.5,
):
    """Create a Box axes orientation widget with labels.

    Parameters
    ----------
    line_width : float, optional
        The width of the marker lines.

    text_scale : float, optional
        Size of the text relative to the faces.

    edge_color : ColorLike, optional
        Color of the edges.

    x_color : ColorLike, optional
        Color of the x axis text.

    y_color : ColorLike, optional
        Color of the y axis text.

    z_color : ColorLike, optional
        Color of the z axis text.

    xlabel : str, optional
        Text used for the x axis.

    ylabel : str, optional
        Text used for the y axis.

    zlabel : str, optional
        Text used for the z axis.

    x_face_color : ColorLike, optional
        Color used for the x axis arrow.  Defaults to theme axes
        parameters.

    y_face_color : ColorLike, optional
        Color used for the y axis arrow.  Defaults to theme axes
        parameters.

    z_face_color : ColorLike, optional
        Color used for the z axis arrow.  Defaults to theme axes
        parameters.

    color_box : bool, optional
        Enable or disable the face colors.  Otherwise, box is white.

    label_color : ColorLike, optional
        Color of the labels.

    labels_off : bool, optional
        Enable or disable the text labels for the axes.

    opacity : float, optional
        Opacity in the range of ``[0, 1]`` of the orientation box.

    Returns
    -------
    vtk.vtkAnnotatedCubeActor
        Annotated cube actor.

    Examples
    --------
    Create and plot an orientation box

    >>> import pyvista
    >>> actor = pyvista.create_axes_orientation_box(
    ...     line_width=1,
    ...     text_scale=0.53,
    ...     edge_color='black',
    ...     x_color='k',
    ...     y_color=None,
    ...     z_color=None,
    ...     xlabel='X',
    ...     ylabel='Y',
    ...     zlabel='Z',
    ...     color_box=False,
    ...     labels_off=False,
    ...     opacity=1.0,
    ... )
    >>> pl = pyvista.Plotter()
    >>> _ = pl.add_actor(actor)
    >>> pl.show()

    """
    x_color = Color(x_color, default_color=pyvista.global_theme.axes.x_color)
    y_color = Color(y_color, default_color=pyvista.global_theme.axes.y_color)
    z_color = Color(z_color, default_color=pyvista.global_theme.axes.z_color)
    edge_color = Color(edge_color, default_color=pyvista.global_theme.edge_color)
    x_face_color = Color(x_face_color)
    y_face_color = Color(y_face_color)
    z_face_color = Color(z_face_color)
    axes_actor = _vtk.vtkAnnotatedCubeActor()
    axes_actor.SetFaceTextScale(text_scale)
    if xlabel is not None:
        axes_actor.SetXPlusFaceText(f"+{xlabel}")
        axes_actor.SetXMinusFaceText(f"-{xlabel}")
    if ylabel is not None:
        axes_actor.SetYPlusFaceText(f"+{ylabel}")
        axes_actor.SetYMinusFaceText(f"-{ylabel}")
    if zlabel is not None:
        axes_actor.SetZPlusFaceText(f"+{zlabel}")
        axes_actor.SetZMinusFaceText(f"-{zlabel}")
    axes_actor.SetFaceTextVisibility(not labels_off)
    axes_actor.SetTextEdgesVisibility(False)
    # axes_actor.GetTextEdgesProperty().SetColor(edge_color.float_rgb)
    # axes_actor.GetTextEdgesProperty().SetLineWidth(line_width)
    axes_actor.GetXPlusFaceProperty().SetColor(x_color.float_rgb)
    axes_actor.GetXMinusFaceProperty().SetColor(x_color.float_rgb)
    axes_actor.GetYPlusFaceProperty().SetColor(y_color.float_rgb)
    axes_actor.GetYMinusFaceProperty().SetColor(y_color.float_rgb)
    axes_actor.GetZPlusFaceProperty().SetColor(z_color.float_rgb)
    axes_actor.GetZMinusFaceProperty().SetColor(z_color.float_rgb)

    axes_actor.GetCubeProperty().SetOpacity(opacity)
    # axes_actor.GetCubeProperty().SetEdgeColor(edge_color.float_rgb)
    axes_actor.GetCubeProperty().SetEdgeVisibility(True)
    axes_actor.GetCubeProperty().BackfaceCullingOn()
    if opacity < 1.0:
        # Hide the text edges
        axes_actor.GetTextEdgesProperty().SetOpacity(0)

    if color_box:
        # Hide the cube so we can color each face
        axes_actor.GetCubeProperty().SetOpacity(0)
        axes_actor.GetCubeProperty().SetEdgeVisibility(False)

        cube = pyvista.Cube()
        cube.clear_data()  # remove normals
        face_colors = np.array(
            [
                x_face_color.int_rgb,
                x_face_color.int_rgb,
                y_face_color.int_rgb,
                y_face_color.int_rgb,
                z_face_color.int_rgb,
                z_face_color.int_rgb,
            ],
            np.uint8,
        )
        cube.cell_data['face_colors'] = face_colors

        cube_mapper = _vtk.vtkPolyDataMapper()
        cube_mapper.SetInputData(cube)
        cube_mapper.SetColorModeToDirectScalars()
        cube_mapper.Update()

        cube_actor = pyvista.Actor(mapper=cube_mapper)
        cube_actor.prop.culling = 'back'
        cube_actor.prop.opacity = opacity

        prop_assembly = _vtk.vtkPropAssembly()
        prop_assembly.AddPart(axes_actor)
        prop_assembly.AddPart(cube_actor)
        actor = prop_assembly
    else:
        actor = axes_actor

    _update_axes_label_color(actor, label_color)

    return actor


def normalize(x, minimum=None, maximum=None):
    """
    Normalize the given value between [minimum, maximum].

    Parameters
    ----------
    x : numpy.ndarray
        The array of values to normalize.
    minimum : float, optional
        The minimum value to which ``x`` should be normalized. If not specified,
        the minimum value in ``x`` will be used.
    maximum : float, optional
        The maximum value to which ``x`` should be normalized. If not specified,
        the maximum value in ``x`` will be used.

    Returns
    -------
    numpy.ndarray
        The normalized array of values, where the values are scaled to the
        range ``[minimum, maximum]``.
    """
    if minimum is None:
        minimum = np.nanmin(x)
    if maximum is None:
        maximum = np.nanmax(x)
    return (x - minimum) / (maximum - minimum)


def opacity_transfer_function(mapping, n_colors, interpolate=True, kind='quadratic'):
    """Get the opacity transfer function for a mapping.

    These values will map on to a scalar bar range and thus the number of
    colors (``n_colors``) must correspond to the number of colors in the color
    mapping that these opacities are associated to.

    If interpolating, ``scipy.interpolate.interp1d`` is used if available,
    otherwise ``np.interp`` is used. The ``kind`` argument controls the kind of
    interpolation for ``interp1d``.

    This returns the opacity range from 0 to 255, where 0 is totally
    transparent and 255 is totally opaque.

    The equation to create the sigmoid mapping is: ``1 / (1 + exp(-x))`` where
    ``x`` is the range from ``-a`` to ``+a`` and ``a`` is the value given in
    the ``mapping`` string. Default is ``a=10`` for 'sigmoid' mapping.

    Parameters
    ----------
    mapping : list(float) or str
        The opacity mapping to use. Can be a ``str`` name of a predefined
        mapping including ``'linear'``, ``'geom'``, ``'sigmoid'``,
        ``'sigmoid_1-10'``, and ``foreground``. Append an ``'_r'`` to any
        of those names (except ``foreground``) to reverse that mapping.
        The mapping can also be a custom user-defined array/list of values
        that will be interpolated across the ``n_color`` range.

    n_colors : int
        The number of colors that the opacities must be mapped to.

    interpolate : bool
        Flag on whether or not to interpolate the opacity mapping for all
        colors.

    kind : str
        The interpolation kind if ``interpolate`` is ``True`` and ``scipy``
        is available. If ``scipy`` is not available, linear interpolation
        is always used. Options are:

        - ``'linear'``
        - ``'nearest'``
        - ``'zero'``
        - ``'slinear'``
        - ``'quadratic'``
        - ``'cubic'``
        - ``'previous'``
        - ``'next'``

    Returns
    -------
    numpy.ndarray
        Array of ``numpy.uint8`` values ``n_colors`` long containing the
        [0-255] opacity mapping values.

    Examples
    --------
    >>> import pyvista as pv
    >>> # Fetch the `sigmoid` mapping between 0 and 255
    >>> tf = pv.opacity_transfer_function("sigmoid", 256)
    >>> # Fetch the `geom_r` mapping between 0 and 1
    >>> tf = (
    ...     pv.opacity_transfer_function("geom_r", 256).astype(float)
    ...     / 255.0
    ... )
    >>> # Interpolate a user defined opacity mapping
    >>> opacity = [0, 0.2, 0.9, 0.6, 0.3]
    >>> tf = pv.opacity_transfer_function(opacity, 256)

    """
    sigmoid = lambda x: np.array(1 / (1 + np.exp(-x)) * 255, dtype=np.uint8)
    transfer_func = {
        'linear': np.linspace(0, 255, n_colors, dtype=np.uint8),
        'geom': np.geomspace(1e-6, 255, n_colors, dtype=np.uint8),
        'geom_r': np.geomspace(255, 1e-6, n_colors, dtype=np.uint8),
        'sigmoid': sigmoid(np.linspace(-10.0, 10.0, n_colors)),
        'sigmoid_1': sigmoid(np.linspace(-1.0, 1.0, n_colors)),
        'sigmoid_2': sigmoid(np.linspace(-2.0, 2.0, n_colors)),
        'sigmoid_3': sigmoid(np.linspace(-3.0, 3.0, n_colors)),
        'sigmoid_4': sigmoid(np.linspace(-4.0, 4.0, n_colors)),
        'sigmoid_5': sigmoid(np.linspace(-5.0, 5.0, n_colors)),
        'sigmoid_6': sigmoid(np.linspace(-6.0, 6.0, n_colors)),
        'sigmoid_7': sigmoid(np.linspace(-7.0, 7.0, n_colors)),
        'sigmoid_8': sigmoid(np.linspace(-8.0, 8.0, n_colors)),
        'sigmoid_9': sigmoid(np.linspace(-9.0, 9.0, n_colors)),
        'sigmoid_10': sigmoid(np.linspace(-10.0, 10.0, n_colors)),
        'foreground': np.hstack((0, [255] * (n_colors - 1))).astype(np.uint8),
    }
    transfer_func['linear_r'] = transfer_func['linear'][::-1]
    transfer_func['sigmoid_r'] = transfer_func['sigmoid'][::-1]
    for i in range(3, 11):
        k = f'sigmoid_{i}'
        rk = f'{k}_r'
        transfer_func[rk] = transfer_func[k][::-1]
    if isinstance(mapping, str):
        try:
            return transfer_func[mapping]
        except KeyError:
            raise ValueError(
                f'Opacity transfer function ({mapping}) unknown. '
                f'Valid options: {list(transfer_func.keys())}'
            ) from None
    elif isinstance(mapping, (np.ndarray, list, tuple)):
        mapping = np.array(mapping)
        if mapping.size == n_colors:
            # User could pass transfer function ready for lookup table
            pass
        elif mapping.size < n_colors:
            # User pass custom transfer function to be linearly interpolated
            if np.max(mapping) > 1.0 or np.min(mapping) < 0.0:
                mapping = normalize(mapping)
            # Interpolate transfer function to match lookup table
            xo = np.linspace(0, n_colors, len(mapping), dtype=np.int_)
            xx = np.linspace(0, n_colors, n_colors, dtype=np.int_)
            try:
                if not interpolate:
                    raise ValueError('No interpolation.')
                # Use a quadratic interp if scipy is available
                from scipy.interpolate import interp1d

                # quadratic has best/smoothest results
                f = interp1d(xo, mapping, kind=kind)
                vals = f(xx)
                vals[vals < 0] = 0.0
                vals[vals > 1.0] = 1.0
                mapping = (vals * 255.0).astype(np.uint8)

            except (ImportError, ValueError):
                # Otherwise use simple linear interp
                mapping = (np.interp(xx, xo, mapping) * 255).astype(np.uint8)
        else:
            raise RuntimeError(
                f'Transfer function cannot have more values than `n_colors`. This has {mapping.size} elements'
            )
        return mapping
    raise TypeError(f'Transfer function type ({type(mapping)}) not understood')


def parse_font_family(font_family: str) -> int:
    """
    Check and validate the given font family name.

    Parameters
    ----------
    font_family : str
        Font family name to validate. Must be one of the font names defined in
        the ``FONTS`` enum class.

    Returns
    -------
    int
        Corresponding integer value of the valid font family name in the
        ``FONTS`` enum class.

    Raises
    ------
    ValueError
        If the font_family is not one of the defined font names in the ``FONTS``
        enum class.
    """
    font_family = font_family.lower()
    fonts = [font.name for font in FONTS]
    if font_family not in fonts:
        raise ValueError(f'Font must one of the following:\n{", ".join(fonts)}')
    return FONTS[font_family].value


def check_matplotlib_vtk_compatibility():
    """
    Check if VTK and Matplotlib versions are compatible for MathText rendering.

    This function is primarily geared towards checking if MathText rendering is
    supported with the given versions of VTK and Matplotlib. It follows the
    version constraints:

    * VTK <= 9.2.2 requires Matplotlib < 3.6
    * VTK > 9.2.2 requires Matplotlib >= 3.6

    Other version combinations of VTK and Matplotlib will work without
    errors, but some features (like MathText/LaTeX rendering) may
    silently fail.

    Returns
    -------
    bool
        True if the versions of VTK and Matplotlib are compatible for MathText
        rendering, False otherwise.

    Raises
    ------
    RuntimeError
        If the versions of VTK and Matplotlib cannot be checked.

    """
    import matplotlib

    mpl_vers = tuple(map(int, matplotlib.__version__.split('.')[:2]))
    if pyvista.vtk_version_info <= (9, 2, 2):
        if mpl_vers >= (3, 6):
            return False
        return True
    elif pyvista.vtk_version_info > (9, 2, 2):
        if mpl_vers >= (3, 6):
            return True
        return False  # pragma: no cover
    raise RuntimeError('Uncheckable versions.')  # pragma: no cover


def check_math_text_support():
    """Check if MathText and LaTeX symbols are supported.

    Returns
    -------
    bool
        ``True`` if both MathText and LaTeX symbols are supported, ``False``
        otherwise.
    """
    return (
        _vtk.vtkMathTextFreeTypeTextRenderer().MathTextIsSupported()
        and check_matplotlib_vtk_compatibility()
    )


# pyvista/plotting/volume.py

"""PyVista volume module."""
from . import _vtk
from ._property import Property
from .mapper import _BaseMapper
from .prop3d import Prop3D


class Volume(Prop3D, _vtk.vtkVolume):
    """Wrapper class for VTK volume.

    This class represents a volume in a rendered scene. It inherits
    functions related to the volume's position, orientation and origin
    from Prop3D.

    """

    def __init__(self):
        """Initialize volume."""
        super().__init__()

    @property
    def mapper(self) -> _BaseMapper:  # numpydoc ignore=RT01
        """Return or set the mapper of the volume.

        Examples
        --------
        Add a volume to a :class:`pyvista.Plotter` and get its mapper.

        >>> import pyvista as pv
        >>> vol = pv.ImageData(dimensions=(10, 10, 10))
        >>> vol['scalars'] = 255 - vol.z * 25
        >>> pl = pv.Plotter()
        >>> actor = pl.add_volume(vol)
        >>> actor.mapper.bounds
        (0.0, 9.0, 0.0, 9.0, 0.0, 9.0)
        """
        return self.GetMapper()

    @mapper.setter
    def mapper(self, obj):  # numpydoc ignore=GL08
        return self.SetMapper(obj)

    @property
    def prop(self):  # numpydoc ignore=RT01
        """Return or set the property of this actor.

        Examples
        --------
        Create an volume and get its properties.

        >>> import pyvista as pv
        >>> vol = pv.ImageData(dimensions=(10, 10, 10))
        >>> vol['scalars'] = 255 - vol.z * 25
        >>> pl = pv.Plotter()
        >>> actor = pl.add_volume(vol)
        >>> actor.prop.GetShade()
        0

        """
        return self.GetProperty()

    @prop.setter
    def prop(self, obj: Property):  # numpydoc ignore=GL08
        self.SetProperty(obj)


# pyvista/plotting/volume_property.py

"""This module contains the VolumeProperty class."""
import pyvista as pv
from pyvista.core.utilities.misc import no_new_attr

from . import _vtk


@no_new_attr
class VolumeProperty(_vtk.vtkVolumeProperty):
    """Wrap the VTK class vtkVolumeProperty.

    This class is used to represent common properties associated with volume
    rendering. This includes properties for determining the type of
    interpolation to use when sampling a volume, the color of a volume, the
    scalar opacity of a volume, the gradient opacity of a volume, and the
    shading parameters of a volume.

    Parameters
    ----------
    lookup_table : pyvista.LookupTable, optional
        Lookup table to set the color and opacity transfer functions.

    interpolation_type : str, optional
        Value must be either ``'linear'`` or ``'nearest'``.

    ambient : float, optional
        When lighting is enabled, this is the amount of light in
        the range of 0 to 1 (default 0.0) that reaches the actor
        when not directed at the light source emitted from the
        viewer.

    diffuse : float, optional
        The diffuse lighting coefficient.

    specular : float, optional
        The specular lighting coefficient.

    specular_power : float, optional
        The specular power. Between 0.0 and 128.0.

    shade : bool, optional
        Enable or disable volume shading.  If shading is turned off, then the
        mapper for the volume will not perform shading calculations. If shading
        is turned on, the mapper may perform shading calculations - in some
        cases shading does not apply (for example, in a maximum intensity
        projection) and therefore shading will not be performed even if this
        flag is on. For a compositing type of mapper, turning shading off is
        generally the same as setting ``ambient=1``, ``diffuse=0``,
        ``specular=0``. Shading can be independently turned on/off per
        component.

    opacity_unit_distance : float, optional
        This is the unit distance on which the scalar opacity transfer function
        is defined. By default this is 1.0, meaning that over a distance of 1.0
        units, a given opacity (from the transfer function) is
        accumulated. This is adjusted for the actual sampling distance during
        rendering.

    Examples
    --------
    Create a sample dataset from perlin noise and apply a lookup table to the
    :class:`VolumeProperty`.

    >>> import pyvista as pv
    >>> noise = pv.perlin_noise(1, (1, 3, 5), (0, 0, 0))
    >>> grid = pv.sample_function(
    ...     noise, [0, 3.0, -0, 1.0, 0, 1.0], dim=(40, 40, 40)
    ... )
    >>> grid['scalars'] -= grid['scalars'].min()
    >>> grid['scalars'] *= 255 / grid['scalars'].max()
    >>> pl = pv.Plotter()
    >>> actor = pl.add_volume(grid, show_scalar_bar=False)
    >>> lut = pv.LookupTable(cmap='bwr')
    >>> lut.apply_opacity([1.0, 0.0, 0.0, 0.3, 0.0, 0.0, 0.0, 0.3])
    >>> actor.prop.apply_lookup_table(lut)
    >>> pl.show()


    """

    def __init__(
        self,
        lookup_table=None,
        interpolation_type=None,
        ambient=None,
        diffuse=None,
        specular=None,
        specular_power=None,
        shade=None,
        opacity_unit_distance=None,
    ):
        """Initialize the vtkVolumeProperty class."""
        super().__init__()
        if lookup_table is not None:
            self.apply_lookup_table(lookup_table)
        if interpolation_type is not None:
            self.interpolation_type = interpolation_type
        if ambient is not None:
            self.ambient = ambient
        if diffuse is not None:
            self.diffuse = diffuse
        if specular is not None:
            self.specular = specular
        if specular_power is not None:
            self.specular_power = specular_power
        if shade is not None:
            self.shade = shade
        if opacity_unit_distance is not None:
            self.opacity_unit_distance = opacity_unit_distance

    def apply_lookup_table(self, lookup_table: 'pv.LookupTable'):
        """Apply a lookup table to the volume property.

        Applies both the color and opacity of the lookup table as transfer
        functions.

        Parameters
        ----------
        lookup_table : pyvista.LookupTable, optional
            Lookup table to set the color and opacity transfer functions.

        Examples
        --------
        Plot perlin noise volumetrically using a custom lookup table.

        >>> import pyvista as pv
        >>> noise = pv.perlin_noise(1, (1, 3, 5), (0, 0, 0))
        >>> grid = pv.sample_function(
        ...     noise, [0, 3.0, -0, 1.0, 0, 1.0], dim=(40, 40, 40)
        ... )
        >>> grid['scalars'] -= grid['scalars'].min()
        >>> grid['scalars'] *= 255 / grid['scalars'].max()
        >>> pl = pv.Plotter()
        >>> actor = pl.add_volume(grid, show_scalar_bar=False)
        >>> lut = pv.LookupTable(cmap='bwr')
        >>> lut.apply_opacity([1.0, 0.0, 0.0, 0.3, 0.0, 0.0, 0.0, 0.3])
        >>> actor.prop.apply_lookup_table(lut)
        >>> pl.show()

        """
        if not isinstance(lookup_table, pv.LookupTable):
            raise TypeError('`lookup_table` must be a `pyvista.LookupTable`')

        self.SetColor(lookup_table.to_color_tf())
        self.SetScalarOpacity(lookup_table.to_opacity_tf())

    @property
    def interpolation_type(self) -> str:  # numpydoc ignore=RT01
        """Return or set the interpolation type.

        Value must be either ``'linear'`` or ``'nearest'``.

        Examples
        --------
        Create a sample :class:`pyvista.ImageData` dataset.

        >>> import numpy as np
        >>> import pyvista as pv
        >>> n = 21
        >>> c = -(n - 1) / 2
        >>> vol = pv.ImageData(dimensions=(n, n, n), origin=(c, c, c))
        >>> scalars = np.linalg.norm(vol.points, axis=1)
        >>> scalars *= 255 / scalars.max()
        >>> vol['scalars'] = scalars

        Demonstrate nearest (default) interpolation.

        >>> pl = pv.Plotter()
        >>> actor = pl.add_volume(
        ...     vol,
        ...     show_scalar_bar=False,
        ...     opacity=[0.3, 0.0, 0.05, 0.0, 0.0, 0.0, 1.0, 0.0],
        ...     cmap='plasma',
        ... )
        >>> actor.prop.interpolation_type = 'nearest'
        >>> pl.show()

        Demonstrate linear interpolation.

        >>> pl = pv.Plotter()
        >>> actor = pl.add_volume(
        ...     vol,
        ...     show_scalar_bar=False,
        ...     opacity=[0.3, 0.0, 0.05, 0.0, 0.0, 0.0, 1.0, 0.0],
        ...     cmap='plasma',
        ... )
        >>> actor.prop.interpolation_type = 'linear'
        >>> pl.show()

        """
        return self.GetInterpolationTypeAsString().split()[0].lower()

    @interpolation_type.setter
    def interpolation_type(self, value: str):  # numpydoc ignore=GL08
        if value == 'linear':
            self.SetInterpolationTypeToLinear()
        elif value == 'nearest':
            self.SetInterpolationTypeToNearest()
        else:
            raise ValueError('`interpolation_type` must be either "linear" or "nearest"')

    @property
    def opacity_unit_distance(self) -> float:  # numpydoc ignore=RT01
        """Return or set the opacity unit distance.

        This is the unit distance on which the scalar opacity transfer function
        is defined.

        By default this is 1.0, meaning that over a distance of 1.0 units, a
        given opacity (from the transfer function) is accumulated. This is
        adjusted for the actual sampling distance during rendering.
        """
        return self.GetScalarOpacityUnitDistance()

    @opacity_unit_distance.setter
    def opacity_unit_distance(self, value: float):  # numpydoc ignore=GL08
        self.SetScalarOpacityUnitDistance(value)

    @property
    def shade(self) -> bool:  # numpydoc ignore=RT01
        """Return or set shading of a volume.

        If shading is turned off, then the mapper for the volume will not
        perform shading calculations. If shading is turned on, the mapper may
        perform shading calculations - in some cases shading does not apply
        (for example, in a maximum intensity projection) and therefore shading
        will not be performed even if this flag is on. For a compositing type
        of mapper, turning shading off is generally the same as setting
        ``ambient=1``, ``diffuse=0``, ``specular=0``. Shading can be
        independently turned on/off per component.

        """
        return bool(self.GetShade())

    @shade.setter
    def shade(self, value: bool):  # numpydoc ignore=GL08
        self.SetShade(value)

    @property
    def independent_components(self) -> bool:  # numpydoc ignore=RT01
        """Return or set independent components.

        If ``False``, then you must have either 2 or 4 component data.
        For 2 component data, the first is passed through the
        first color transfer function and the second component is passed
        through the first scalar opacity (and gradient opacity) transfer
        function. Normals will be generated off of the second component. When
        using gradient based opacity modulation, the gradients are computed off
        of the second component.

        For 4 component data, the first three will directly represent RGB (no
        lookup table). The fourth component will be passed through the first
        scalar opacity transfer function for opacity and first gradient opacity
        transfer function for gradient based opacity modulation. Normals will
        be generated from the fourth component. When using gradient based
        opacity modulation, the gradients are computed off of the fourth
        component.
        """
        return bool(self.GetIndependentComponents())

    @independent_components.setter
    def independent_components(self, value: bool):  # numpydoc ignore=GL08
        self.SetIndependentComponents(value)

    @property
    def ambient(self) -> float:  # numpydoc ignore=RT01
        """Return or set ambient lighting coefficient.

        This is the amount of light in the range of 0 to 1 (default 0.0) that
        reaches the actor when not directed at the light source emitted from
        the viewer.

        Changing attribute has no effect unless :attr:`VolumeProperty.shade` is
        set to ``True``.

        """
        return self.GetAmbient()

    @ambient.setter
    def ambient(self, value: float):  # numpydoc ignore=GL08
        self.SetAmbient(value)

    @property
    def diffuse(self) -> float:  # numpydoc ignore=RT01
        """Return or set the diffuse lighting coefficient.

        This is the scattering of light by reflection or transmission. Diffuse
        reflection results when light strikes an irregular surface such as a
        frosted window or the surface of a frosted or coated light bulb.

        Changing attribute has no effect unless :attr:`VolumeProperty.shade` is
        set to ``True``.

        """
        return self.GetDiffuse()

    @diffuse.setter
    def diffuse(self, value: float):  # numpydoc ignore=GL08
        self.SetDiffuse(value)

    @property
    def specular(self) -> float:  # numpydoc ignore=RT01
        """Return or set specular.

        Default 0.0

        Specular lighting simulates the bright spot of a light that appears on
        shiny objects.

        Changing attribute has no effect unless :attr:`VolumeProperty.shade` is
        set to ``True``.

        """
        return self.GetSpecular()

    @specular.setter
    def specular(self, value: float):  # numpydoc ignore=GL08
        self.SetSpecular(value)

    @property
    def specular_power(self) -> float:  # numpydoc ignore=RT01
        """Return or set specular power.

        The specular power. Between 0.0 and 128.0. Default 10.0

        """
        return self.GetSpecularPower()

    @specular_power.setter
    def specular_power(self, value: float):  # numpydoc ignore=GL08
        self.SetSpecularPower(value)

    def copy(self) -> 'VolumeProperty':
        """Create a deep copy of this property.

        Returns
        -------
        pyvista.plotting.volume_property.VolumeProperty
            Deep copy of this property.

        """
        new_prop = VolumeProperty()
        new_prop.DeepCopy(self)
        return new_prop

    def __repr__(self):
        """Representation of this property."""
        props = [
            f'{type(self).__name__} ({hex(id(self))})',
        ]

        for attr in dir(self):
            if not attr.startswith('_') and attr[0].islower():
                name = ' '.join(attr.split('_')).capitalize() + ':'
                value = getattr(self, attr)
                if callable(value):
                    continue
                if isinstance(value, str):
                    value = f'"{value}"'
                props.append(f'  {name:28s} {value}')

        return '\n'.join(props)


# pyvista/plotting/widgets.py

"""Module dedicated to widgets."""

import numpy as np

import pyvista
from pyvista.core.utilities.arrays import get_array, get_array_association
from pyvista.core.utilities.geometric_objects import NORMALS
from pyvista.core.utilities.helpers import generate_plane
from pyvista.core.utilities.misc import assert_empty_kwargs, try_callback

from . import _vtk
from .affine_widget import AffineWidget3D
from .colors import Color
from .opts import PickerType
from .utilities.algorithms import (
    add_ids_algorithm,
    algorithm_to_mesh_handler,
    crinkle_algorithm,
    outline_algorithm,
    pointset_to_polydata_algorithm,
    set_algorithm_input,
)


def _parse_interaction_event(interaction_event):
    """Parse the interaction event.

    Parameters
    ----------
    interaction_event : vtk.vtkCommand.EventIds, str, optional
        The VTK interaction event to use for triggering the callback. Accepts
        either the strings ``'start'``, ``'end'``, ``'always'`` or a
        ``vtk.vtkCommand.EventIds``.

    Returns
    -------
    vtk.vtkCommand.EventIds
        VTK Event type.

    """
    if interaction_event == 'start':
        interaction_event = _vtk.vtkCommand.StartInteractionEvent
    elif interaction_event == 'end':
        interaction_event = _vtk.vtkCommand.EndInteractionEvent
    elif interaction_event == 'always':
        interaction_event = _vtk.vtkCommand.InteractionEvent
    elif isinstance(interaction_event, str):
        raise ValueError(
            "Expected value for `interaction_event` is 'start', "
            f"'end', or 'always'. {interaction_event} was given."
        )
    elif not isinstance(interaction_event, _vtk.vtkCommand.EventIds):
        raise TypeError(
            "Expected type for `interaction_event` is either a str "
            "or an instance of `vtk.vtkCommand.EventIds`."
            f" ({type(interaction_event)}) was given."
        )
    return interaction_event


class WidgetHelper:
    """An internal class to manage widgets.

    It also manages and other helper methods involving widgets.

    """

    def __init__(self, *args, **kwargs):
        """Initialize widget helper."""
        super().__init__(*args, **kwargs)
        self.camera_widgets = []
        self.box_widgets = []
        self.box_clipped_meshes = []
        self.plane_widgets = []
        self.plane_clipped_meshes = []
        self.plane_sliced_meshes = []
        self.line_widgets = []
        self.slider_widgets = []
        self.threshold_meshes = []
        self.isovalue_meshes = []
        self.spline_widgets = []
        self.spline_sliced_meshes = []
        self.sphere_widgets = []
        self.button_widgets = []
        self.distance_widgets = []

    def add_box_widget(
        self,
        callback,
        bounds=None,
        factor=1.25,
        rotation_enabled=True,
        color=None,
        use_planes=False,
        outline_translation=True,
        pass_widget=False,
        interaction_event='end',
    ):
        """Add a box widget to the scene.

        This is useless without a callback function. You can pass a
        callable function that takes a single argument, the PolyData
        box output from this widget, and performs a task with that
        box.

        Parameters
        ----------
        callback : callable
            The method called every time the box is updated. This has
            two options: Take a single argument, the ``PolyData`` box
            (default) or if ``use_planes=True``, then it takes a
            single argument of the plane collection as a ``vtkPlanes``
            object.

        bounds : tuple(float)
            Length 6 tuple of the bounding box where the widget is
            placed.

        factor : float, optional
            An inflation factor to expand on the bounds when placing.

        rotation_enabled : bool, optional
            If ``False``, the box widget cannot be rotated and is
            strictly orthogonal to the Cartesian axes.

        color : ColorLike, optional
            Either a string, rgb sequence, or hex color string.
            Defaults to :attr:`pyvista.global_theme.font.color
            <pyvista.plotting.themes._Font.color>`.

        use_planes : bool, optional
            Changes the arguments passed to the callback to the planes
            that make up the box.

        outline_translation : bool, optional
            If ``False``, the box widget cannot be translated and is
            strictly placed at the given bounds.

        pass_widget : bool, optional
            If ``True``, the widget will be passed as the last
            argument of the callback.

        interaction_event : vtk.vtkCommand.EventIds, str, optional
            The VTK interaction event to use for triggering the
            callback. Accepts either the strings ``'start'``, ``'end'``,
            ``'always'`` or a ``vtk.vtkCommand.EventIds``.

            .. versionchanged:: 0.38.0
               Now accepts either strings or ``vtk.vtkCommand.EventIds``.

        Returns
        -------
        vtk.vtkBoxWidget
            Box widget.

        Examples
        --------
        Shows an interactive clip box.

        >>> import pyvista as pv
        >>> mesh = pv.ParametricConicSpiral()
        >>> pl = pv.Plotter()
        >>> _ = pl.add_mesh_clip_box(mesh, color='white')
        >>> pl.show()

        For a full example see :ref:`box_widget_example`.

        """
        interaction_event = _parse_interaction_event(interaction_event)

        if bounds is None:
            bounds = self.bounds

        def _the_callback(box_widget, event_id):
            the_box = pyvista.PolyData()
            box_widget.GetPolyData(the_box)
            planes = _vtk.vtkPlanes()
            box_widget.GetPlanes(planes)
            if callable(callback):
                if use_planes:
                    args = [planes]
                else:
                    args = [the_box]
                if pass_widget:
                    args.append(box_widget)
                try_callback(callback, *args)
            return

        box_widget = _vtk.vtkBoxWidget()
        box_widget.GetOutlineProperty().SetColor(
            Color(color, default_color=pyvista.global_theme.font.color).float_rgb
        )
        box_widget.SetInteractor(self.iren.interactor)
        box_widget.SetCurrentRenderer(self.renderer)
        box_widget.SetPlaceFactor(factor)
        box_widget.SetRotationEnabled(rotation_enabled)
        box_widget.SetTranslationEnabled(outline_translation)
        box_widget.PlaceWidget(bounds)
        box_widget.On()
        box_widget.AddObserver(interaction_event, _the_callback)
        _the_callback(box_widget, None)

        self.box_widgets.append(box_widget)
        return box_widget

    def clear_box_widgets(self):
        """Remove all of the box widgets."""
        self.box_widgets.clear()

    def add_mesh_clip_box(
        self,
        mesh,
        invert=False,
        rotation_enabled=True,
        widget_color=None,
        outline_translation=True,
        merge_points=True,
        crinkle=False,
        interaction_event='end',
        **kwargs,
    ):
        """Clip a mesh using a box widget.

        Add a mesh to the scene with a box widget that is used to clip
        the mesh interactively.

        The clipped mesh is saved to the ``.box_clipped_meshes`` attribute on
        the plotter.

        Parameters
        ----------
        mesh : pyvista.DataSet or vtk.vtkAlgorithm
            The input dataset to add to the scene and clip or algorithm that
            produces said mesh.

        invert : bool, optional
            Flag on whether to flip/invert the clip.

        rotation_enabled : bool, optional
            If ``False``, the box widget cannot be rotated and is strictly
            orthogonal to the cartesian axes.

        widget_color : ColorLike, optional
            Color of the widget.  Either a string, RGB sequence, or
            hex color string.  For example:

            * ``color='white'``
            * ``color='w'``
            * ``color=[1.0, 1.0, 1.0]``
            * ``color='#FFFFFF'``

        outline_translation : bool, optional
            If ``False``, the plane widget cannot be translated and is
            strictly placed at the given bounds.

        merge_points : bool, optional
            If ``True`` (default), coinciding points of independently
            defined mesh elements will be merged.

        crinkle : bool, optional
            Crinkle the clip by extracting the entire cells along the clip.

        interaction_event : vtk.vtkCommand.EventIds, str, optional
            The VTK interaction event to use for triggering the
            callback. Accepts either the strings ``'start'``, ``'end'``,
            ``'always'`` or a ``vtk.vtkCommand.EventIds``.

            .. versionchanged:: 0.38.0
               Changed from ``event_type`` to ``interaction_event`` and now
               accepts either strings and ``vtk.vtkCommand.EventIds``.

        **kwargs : dict, optional
            All additional keyword arguments are passed to
            :func:`Plotter.add_mesh` to control how the mesh is
            displayed.

        Returns
        -------
        vtk.vtkActor
            VTK actor of the mesh.

        """
        from pyvista.core.filters import _get_output  # avoids circular import

        mesh, algo = algorithm_to_mesh_handler(
            add_ids_algorithm(mesh, point_ids=False, cell_ids=True)
        )

        name = kwargs.get('name', mesh.memory_address)
        rng = mesh.get_data_range(kwargs.get('scalars', None))
        kwargs.setdefault('clim', kwargs.pop('rng', rng))
        mesh.set_active_scalars(kwargs.get('scalars', mesh.active_scalars_name))

        self.add_mesh(outline_algorithm(algo), name=f"{name}-outline", opacity=0.0)

        port = 1 if invert else 0

        clipper = _vtk.vtkBoxClipDataSet()
        if not merge_points:
            # vtkBoxClipDataSet uses vtkMergePoints by default
            clipper.SetLocator(_vtk.vtkNonMergingPointLocator())
        set_algorithm_input(clipper, algo)
        clipper.GenerateClippedOutputOn()

        if crinkle:
            crinkler = crinkle_algorithm(clipper.GetOutputPort(port), algo)
            box_clipped_mesh = _get_output(crinkler)
        else:
            box_clipped_mesh = _get_output(clipper, oport=port)

        self.box_clipped_meshes.append(box_clipped_mesh)

        def callback(planes):  # numpydoc ignore=GL08
            bounds = []
            for i in range(planes.GetNumberOfPlanes()):
                plane = planes.GetPlane(i)
                bounds.append(plane.GetNormal())
                bounds.append(plane.GetOrigin())

            clipper.SetBoxClip(*bounds)
            clipper.Update()
            if crinkle:
                clipped = pyvista.wrap(crinkler.GetOutputDataObject(0))
            else:
                clipped = _get_output(clipper, oport=port)
            box_clipped_mesh.shallow_copy(clipped)

        self.add_box_widget(
            callback=callback,
            bounds=mesh.bounds,
            factor=1.25,
            rotation_enabled=rotation_enabled,
            use_planes=True,
            color=widget_color,
            outline_translation=outline_translation,
            interaction_event=interaction_event,
        )

        if crinkle:
            return self.add_mesh(crinkler, reset_camera=False, **kwargs)
        return self.add_mesh(clipper.GetOutputPort(port), reset_camera=False, **kwargs)

    def add_plane_widget(
        self,
        callback,
        normal='x',
        origin=None,
        bounds=None,
        factor=1.25,
        color=None,
        assign_to_axis=None,
        tubing=False,
        outline_translation=False,
        origin_translation=True,
        implicit=True,
        pass_widget=False,
        test_callback=True,
        normal_rotation=True,
        interaction_event='end',
    ):
        """Add a plane widget to the scene.

        This is useless without a callback function. You can pass a
        callable function that takes two arguments, the normal and
        origin of the plane in that order output from this widget, and
        performs a task with that plane.

        Parameters
        ----------
        callback : callable
            The method called every time the plane is updated. Takes
            two arguments, the normal and origin of the plane in that
            order.

        normal : str or tuple(float)
            The starting normal vector of the plane.

        origin : tuple(float)
            The starting coordinate of the center of the plane.

        bounds : tuple(float)
            Length 6 tuple of the bounding box where the widget is placed.

        factor : float, optional
            An inflation factor to expand on the bounds when placing.

        color : ColorLike, optional
            Either a string, rgb list, or hex color string.

        assign_to_axis : str or int, optional
            Assign the normal of the plane to be parallel with a given
            axis: options are ``(0, 'x')``, ``(1, 'y')``, or ``(2,
            'z')``.

        tubing : bool, optional
            When using an implicit plane wiget, this controls whether
            or not tubing is shown around the plane's boundaries.

        outline_translation : bool, optional
            If ``False``, the plane widget cannot be translated and is
            strictly placed at the given bounds. Only valid when using
            an implicit plane.

        origin_translation : bool, optional
            If ``False``, the plane widget cannot be translated by its
            origin and is strictly placed at the given origin. Only
            valid when using an implicit plane.

        implicit : bool, optional
            When ``True``, a ``vtkImplicitPlaneWidget`` is used and
            when ``False``, a ``vtkPlaneWidget`` is used.

        pass_widget : bool, optional
            If ``True``, the widget will be passed as the last
            argument of the callback.

        test_callback : bool, optional
            If ``True``, run the callback function after the widget is
            created.

        normal_rotation : bool, optional
            Set the opacity of the normal vector arrow to 0 such that
            it is effectively disabled. This prevents the user from
            rotating the normal. This is forced to ``False`` when
            ``assign_to_axis`` is set.

        interaction_event : vtk.vtkCommand.EventIds, str, optional
            The VTK interaction event to use for triggering the
            callback. Accepts either the strings ``'start'``, ``'end'``,
            ``'always'`` or a ``vtk.vtkCommand.EventIds``.

            .. versionchanged:: 0.38.0
               Now accepts either strings and ``vtk.vtkCommand.EventIds``.

        Returns
        -------
        vtk.vtkImplicitPlaneWidget or vtk.vtkPlaneWidget
            Plane widget.

        """
        interaction_event = _parse_interaction_event(interaction_event)

        if origin is None:
            origin = self.center
        if bounds is None:
            bounds = self.bounds

        if isinstance(normal, str):
            normal = NORMALS[normal.lower()]

        color = Color(color, default_color=pyvista.global_theme.font.color)

        if assign_to_axis:
            normal_rotation = False

        def _the_callback(widget, event_id):
            the_plane = _vtk.vtkPlane()
            widget.GetPlane(the_plane)
            normal = the_plane.GetNormal()
            origin = the_plane.GetOrigin()
            if callable(callback):
                if pass_widget:
                    try_callback(callback, normal, origin, widget)
                else:
                    try_callback(callback, normal, origin)
            return

        if implicit:
            plane_widget = _vtk.vtkImplicitPlaneWidget()
            plane_widget.GetNormalProperty().SetColor(color.float_rgb)
            plane_widget.GetOutlineProperty().SetColor(color.float_rgb)
            plane_widget.GetOutlineProperty().SetColor(color.float_rgb)
            plane_widget.GetOutlineProperty().SetOpacity(color.opacity)
            plane_widget.SetTubing(tubing)
            plane_widget.SetOutlineTranslation(outline_translation)
            plane_widget.SetOriginTranslation(origin_translation)

            _start_interact = lambda plane_widget, event: plane_widget.SetDrawPlane(True)
            _stop_interact = lambda plane_widget, event: plane_widget.SetDrawPlane(False)

            plane_widget.SetDrawPlane(False)
            plane_widget.AddObserver(_vtk.vtkCommand.StartInteractionEvent, _start_interact)
            plane_widget.AddObserver(_vtk.vtkCommand.EndInteractionEvent, _stop_interact)
            plane_widget.SetPlaceFactor(factor)
            plane_widget.PlaceWidget(bounds)
            plane_widget.SetOrigin(origin)

            if not normal_rotation:
                plane_widget.GetNormalProperty().SetOpacity(0)

        else:
            # Position of the small plane
            source = _vtk.vtkPlaneSource()
            source.SetNormal(normal)
            source.SetCenter(origin)
            source.SetPoint1(
                origin[0] + (bounds[1] - bounds[0]) * 0.01,
                origin[1] - (bounds[3] - bounds[2]) * 0.01,
                origin[2],
            )
            source.SetPoint2(
                origin[0] - (bounds[1] - bounds[0]) * 0.01,
                origin[1] + (bounds[3] - bounds[2]) * 0.01,
                origin[2],
            )
            source.Update()
            plane_widget = _vtk.vtkPlaneWidget()
            plane_widget.SetHandleSize(0.01)
            # Position of the widget
            plane_widget.SetInputData(source.GetOutput())
            plane_widget.SetRepresentationToOutline()
            plane_widget.SetPlaceFactor(factor)
            plane_widget.PlaceWidget(bounds)
            plane_widget.SetCenter(origin)  # Necessary
            plane_widget.GetPlaneProperty().SetColor(color.float_rgb)  # self.C_LOT[fn])
            plane_widget.GetHandleProperty().SetColor(color.float_rgb)

            if not normal_rotation:
                plane_widget.GetHandleProperty().SetOpacity(0)

        plane_widget.GetPlaneProperty().SetOpacity(0.5)
        plane_widget.SetInteractor(self.iren.interactor)
        plane_widget.SetCurrentRenderer(self.renderer)

        if assign_to_axis:
            # Note that normal_rotation was forced to False
            if assign_to_axis in [0, "x", "X"]:
                plane_widget.NormalToXAxisOn()
                plane_widget.SetNormal(NORMALS["x"])
            elif assign_to_axis in [1, "y", "Y"]:
                plane_widget.NormalToYAxisOn()
                plane_widget.SetNormal(NORMALS["y"])
            elif assign_to_axis in [2, "z", "Z"]:
                plane_widget.NormalToZAxisOn()
                plane_widget.SetNormal(NORMALS["z"])
            else:
                raise RuntimeError("assign_to_axis not understood")
        else:
            plane_widget.SetNormal(normal)

        plane_widget.Modified()
        plane_widget.UpdatePlacement()
        plane_widget.On()
        plane_widget.AddObserver(
            interaction_event,
            # _vtk.vtkCommand.InteractionEvent,
            _the_callback,
        )
        if test_callback:
            _the_callback(plane_widget, None)  # Trigger immediate update

        self.plane_widgets.append(plane_widget)
        return plane_widget

    def clear_plane_widgets(self):
        """Remove all of the plane widgets."""
        self.plane_widgets.clear()

    def add_mesh_clip_plane(
        self,
        mesh,
        normal='x',
        invert=False,
        widget_color=None,
        value=0.0,
        assign_to_axis=None,
        tubing=False,
        origin_translation=True,
        outline_translation=False,
        implicit=True,
        normal_rotation=True,
        crinkle=False,
        interaction_event='end',
        origin=None,
        **kwargs,
    ):
        """Clip a mesh using a plane widget.

        Add a mesh to the scene with a plane widget that is used to clip
        the mesh interactively.

        The clipped mesh is saved to the ``.plane_clipped_meshes``
        attribute on the plotter.

        Parameters
        ----------
        mesh : pyvista.DataSet or vtk.vtkAlgorithm
            The input dataset to add to the scene and clip or algorithm that
            produces said mesh.

        normal : str or tuple(float), optional
            The starting normal vector of the plane.

        invert : bool, optional
            Flag on whether to flip/invert the clip.

        widget_color : ColorLike, optional
            Either a string, RGB list, or hex color string.

        value : float, optional
            Set the clipping value along the normal direction.
            The default value is 0.0.

        assign_to_axis : str or int, optional
            Assign the normal of the plane to be parallel with a given
            axis.  Options are ``(0, 'x')``, ``(1, 'y')``, or ``(2,
            'z')``.

        tubing : bool, optional
            When using an implicit plane wiget, this controls whether
            or not tubing is shown around the plane's boundaries.

        origin_translation : bool, optional
            If ``False``, the plane widget cannot be translated by its
            origin and is strictly placed at the given origin. Only
            valid when using an implicit plane.

        outline_translation : bool, optional
            If ``False``, the box widget cannot be translated and is
            strictly placed at the given bounds.

        implicit : bool, optional
            When ``True``, a ``vtkImplicitPlaneWidget`` is used and
            when ``False``, a ``vtkPlaneWidget`` is used.

        normal_rotation : bool, optional
            Set the opacity of the normal vector arrow to 0 such that
            it is effectively disabled. This prevents the user from
            rotating the normal. This is forced to ``False`` when
            ``assign_to_axis`` is set.

        crinkle : bool, optional
            Crinkle the clip by extracting the entire cells along the clip.

        interaction_event : vtk.vtkCommand.EventIds, str, optional
            The VTK interaction event to use for triggering the
            callback. Accepts either the strings ``'start'``, ``'end'``,
            ``'always'`` or a ``vtk.vtkCommand.EventIds``.

            .. versionchanged:: 0.38.0
               Now accepts either strings or ``vtk.vtkCommand.EventIds``.

        origin : tuple(float), optional
            The starting coordinate of the center of the plane.

        **kwargs : dict, optional
            All additional keyword arguments are passed to
            :func:`Plotter.add_mesh` to control how the mesh is
            displayed.

        Returns
        -------
        vtk.vtkActor
            VTK actor of the mesh.

        """
        from pyvista.core.filters import _get_output  # avoids circular import

        mesh, algo = algorithm_to_mesh_handler(
            add_ids_algorithm(mesh, point_ids=False, cell_ids=True)
        )

        name = kwargs.get('name', mesh.memory_address)
        rng = mesh.get_data_range(kwargs.get('scalars', None))
        kwargs.setdefault('clim', kwargs.pop('rng', rng))
        mesh.set_active_scalars(kwargs.get('scalars', mesh.active_scalars_name))
        if origin is None:
            origin = mesh.center

        self.add_mesh(outline_algorithm(algo), name=f"{name}-outline", opacity=0.0)

        if isinstance(mesh, _vtk.vtkPolyData):
            clipper = _vtk.vtkClipPolyData()
        # elif isinstance(mesh, vtk.vtkImageData):
        #     clipper = vtk.vtkClipVolume()
        #     clipper.SetMixed3DCellGeneration(True)
        else:
            clipper = _vtk.vtkTableBasedClipDataSet()
        set_algorithm_input(clipper, algo)
        clipper.SetValue(value)
        clipper.SetInsideOut(invert)  # invert the clip if needed

        if crinkle:
            crinkler = crinkle_algorithm(clipper, algo)
            plane_clipped_mesh = _get_output(crinkler)
        else:
            plane_clipped_mesh = _get_output(clipper)
        self.plane_clipped_meshes.append(plane_clipped_mesh)

        def callback(normal, loc):  # numpydoc ignore=GL08
            function = generate_plane(normal, loc)
            clipper.SetClipFunction(function)  # the implicit function
            clipper.Update()  # Perform the Cut
            if crinkle:
                clipped = pyvista.wrap(crinkler.GetOutputDataObject(0))
            else:
                clipped = pyvista.wrap(clipper.GetOutput())
            plane_clipped_mesh.shallow_copy(clipped)

        self.add_plane_widget(
            callback=callback,
            bounds=mesh.bounds,
            factor=1.25,
            normal=normal,
            color=widget_color,
            tubing=tubing,
            assign_to_axis=assign_to_axis,
            origin_translation=origin_translation,
            outline_translation=outline_translation,
            implicit=implicit,
            origin=origin,
            normal_rotation=normal_rotation,
            interaction_event=interaction_event,
        )

        if crinkle:
            return self.add_mesh(crinkler, **kwargs)
        return self.add_mesh(clipper, **kwargs)

    def add_volume_clip_plane(
        self,
        volume,
        normal='x',
        invert=False,
        widget_color=None,
        value=0.0,
        assign_to_axis=None,
        tubing=False,
        origin_translation=True,
        outline_translation=False,
        implicit=True,
        normal_rotation=True,
        interaction_event='end',
        origin=None,
        **kwargs,
    ):
        """Clip a volume using a plane widget.

        Parameters
        ----------
        volume : pyvista.plotting.volume.Volume or pyvista.ImageData or pyvista.RectilinearGrid
            New dataset of type :class:`pyvista.ImageData` or
            :class:`pyvista.RectilinearGrid`, or the return value from
            :class:`pyvista.plotting.volume.Volume` from :func:`Plotter.add_volume`.

        normal : str or tuple(float), optional
            The starting normal vector of the plane.

        invert : bool, optional
            Flag on whether to flip/invert the clip.

        widget_color : ColorLike, optional
            Either a string, RGB list, or hex color string.

        value : float, optional
            Set the clipping value along the normal direction.
            The default value is 0.0.

        assign_to_axis : str or int, optional
            Assign the normal of the plane to be parallel with a given
            axis.  Options are ``(0, 'x')``, ``(1, 'y')``, or ``(2,
            'z')``.

        tubing : bool, optional
            When using an implicit plane wiget, this controls whether
            or not tubing is shown around the plane's boundaries.

        origin_translation : bool, optional
            If ``False``, the plane widget cannot be translated by its
            origin and is strictly placed at the given origin. Only
            valid when using an implicit plane.

        outline_translation : bool, optional
            If ``False``, the box widget cannot be translated and is
            strictly placed at the given bounds.

        implicit : bool, optional
            When ``True``, a ``vtkImplicitPlaneWidget`` is used and
            when ``False``, a ``vtkPlaneWidget`` is used.

        normal_rotation : bool, optional
            Set the opacity of the normal vector arrow to 0 such that
            it is effectively disabled. This prevents the user from
            rotating the normal. This is forced to ``False`` when
            ``assign_to_axis`` is set.

        interaction_event : vtk.vtkCommand.EventIds, optional
            The VTK interaction event to use for triggering the callback.

        origin : tuple(float), optional
            The starting coordinate of the center of the plane.

        **kwargs : dict, optional
            All additional keyword arguments are passed to
            :func:`Plotter.add_volume` to control how the volume is
            displayed. Only applicable if ``volume`` is either a
            :class:`pyvista.ImageData` and :class:`pyvista.RectilinearGrid`.

        Returns
        -------
        vtk.vtkPlaneWidget or vtk.vtkImplicitPlaneWidget
            The VTK plane widget depending on the value of ``implicit``.

        """
        if isinstance(volume, (pyvista.ImageData, pyvista.RectilinearGrid)):
            volume = self.add_volume(volume, **kwargs)
        elif not isinstance(volume, pyvista.plotting.volume.Volume):
            raise TypeError(
                'The `volume` parameter type must be either pyvista.ImageData, '
                'pyvista.RectilinearGrid, or a pyvista.plotting.volume.Volume '
                'from `Plotter.add_volume`.'
            )
        else:
            assert_empty_kwargs(**kwargs)

        plane = _vtk.vtkPlane()

        def callback(normal, origin):  # numpydoc ignore=PR01
            """Update the plane used to clip the volume."""
            plane.SetNormal(normal)
            plane.SetOrigin(origin)

        widget = self.add_plane_widget(
            callback=callback,
            bounds=volume.bounds,
            factor=1.25,
            normal=normal,
            color=widget_color,
            tubing=tubing,
            assign_to_axis=assign_to_axis,
            origin_translation=origin_translation,
            outline_translation=outline_translation,
            implicit=implicit,
            origin=origin,
            normal_rotation=normal_rotation,
            interaction_event=interaction_event,
        )
        widget.GetPlane(plane)
        volume.mapper.AddClippingPlane(plane)
        self.plane_widgets.append(widget)

        return widget

    def add_mesh_slice(
        self,
        mesh,
        normal='x',
        generate_triangles=False,
        widget_color=None,
        assign_to_axis=None,
        tubing=False,
        origin_translation=True,
        outline_translation=False,
        implicit=True,
        normal_rotation=True,
        interaction_event=_vtk.vtkCommand.EndInteractionEvent,
        origin=None,
        **kwargs,
    ):
        """Slice a mesh using a plane widget.

        Add a mesh to the scene with a plane widget that is used to slice
        the mesh interactively.

        The sliced mesh is saved to the ``.plane_sliced_meshes`` attribute on
        the plotter.

        Parameters
        ----------
        mesh : pyvista.DataSet or vtk.vtkAlgorithm
            The input dataset to add to the scene and slice or algorithm that
            produces said mesh.

        normal : str or tuple(float), optional
            The starting normal vector of the plane.

        generate_triangles : bool, optional
            If this is enabled (``False`` by default), the output will be
            triangles otherwise, the output will be the intersection polygons.

        widget_color : ColorLike, optional
            Either a string, RGB sequence, or hex color string.  Defaults
            to ``'white'``.

        assign_to_axis : str or int, optional
            Assign the normal of the plane to be parallel with a given axis:
            options are (0, 'x'), (1, 'y'), or (2, 'z').

        tubing : bool, optional
            When using an implicit plane wiget, this controls whether or not
            tubing is shown around the plane's boundaries.

        origin_translation : bool, optional
            If ``False``, the plane widget cannot be translated by its origin
            and is strictly placed at the given origin. Only valid when using
            an implicit plane.

        outline_translation : bool, optional
            If ``False``, the box widget cannot be translated and is strictly
            placed at the given bounds.

        implicit : bool, optional
            When ``True``, a ``vtkImplicitPlaneWidget`` is used and when
            ``False``, a ``vtkPlaneWidget`` is used.

        normal_rotation : bool, optional
            Set the opacity of the normal vector arrow to 0 such that it is
            effectively disabled. This prevents the user from rotating the
            normal. This is forced to ``False`` when ``assign_to_axis`` is set.

        interaction_event : vtk.vtkCommand.EventIds, optional
            The VTK interaction event to use for triggering the callback.

        origin : tuple(float), optional
            The starting coordinate of the center of the plane.

        **kwargs : dict, optional
            All additional keyword arguments are passed to
            :func:`Plotter.add_mesh` to control how the mesh is
            displayed.

        Returns
        -------
        vtk.vtkActor
            VTK actor of the mesh.

        """
        mesh, algo = algorithm_to_mesh_handler(mesh)

        name = kwargs.get('name', mesh.memory_address)
        rng = mesh.get_data_range(kwargs.get('scalars', None))
        kwargs.setdefault('clim', kwargs.pop('rng', rng))
        mesh.set_active_scalars(kwargs.get('scalars', mesh.active_scalars_name))
        if origin is None:
            origin = mesh.center

        self.add_mesh(outline_algorithm(algo or mesh), name=f"{name}-outline", opacity=0.0)

        alg = _vtk.vtkCutter()  # Construct the cutter object
        set_algorithm_input(alg, algo or mesh)
        if not generate_triangles:
            alg.GenerateTrianglesOff()

        plane_sliced_mesh = pyvista.wrap(alg.GetOutput())
        self.plane_sliced_meshes.append(plane_sliced_mesh)

        def callback(normal, origin):  # numpydoc ignore=GL08
            # create the plane for clipping
            plane = generate_plane(normal, origin)
            alg.SetCutFunction(plane)  # the cutter to use the plane we made
            alg.Update()  # Perform the Cut
            plane_sliced_mesh.shallow_copy(alg.GetOutput())

        self.add_plane_widget(
            callback=callback,
            bounds=mesh.bounds,
            factor=1.25,
            normal=normal,
            color=widget_color,
            tubing=tubing,
            assign_to_axis=assign_to_axis,
            origin_translation=origin_translation,
            outline_translation=outline_translation,
            implicit=implicit,
            origin=origin,
            normal_rotation=normal_rotation,
            interaction_event=interaction_event,
        )

        return self.add_mesh(alg, **kwargs)

    def add_mesh_slice_orthogonal(
        self,
        mesh,
        generate_triangles=False,
        widget_color=None,
        tubing=False,
        interaction_event=_vtk.vtkCommand.EndInteractionEvent,
        **kwargs,
    ):
        """Slice a mesh with three interactive planes.

        Adds three interactive plane slicing widgets for orthogonal slicing
        along each cartesian axis.

        Parameters
        ----------
        mesh : pyvista.DataSet or vtk.vtkAlgorithm
            The input dataset to add to the scene and threshold or algorithm
            that produces said mesh.

        generate_triangles : bool, optional
            If this is enabled (``False`` by default), the output will be
            triangles otherwise, the output will be the intersection polygons.

        widget_color : ColorLike, optional
            Color of the widget.  Either a string, RGB sequence, or
            hex color string.  For example:

            * ``color='white'``
            * ``color='w'``
            * ``color=[1.0, 1.0, 1.0]``
            * ``color='#FFFFFF'``

        tubing : bool, optional
            When using an implicit plane wiget, this controls whether or not
            tubing is shown around the plane's boundaries.

        interaction_event : vtk.vtkCommand.EventIds, optional
            The VTK interaction event to use for triggering the callback.

        **kwargs : dict, optional
            All additional keyword arguments are passed to
            :func:`Plotter.add_mesh` to control how the mesh is
            displayed.

        Returns
        -------
        list
            List of vtk.vtkActor(s).

        """
        actors = []
        name = kwargs.pop("name", None)
        for ax in ["x", "y", "z"]:
            axkwargs = kwargs.copy()
            if name:
                axkwargs["name"] = f"{name}-{ax}"
            a = self.add_mesh_slice(
                mesh,
                assign_to_axis=ax,
                origin_translation=False,
                outline_translation=False,
                generate_triangles=generate_triangles,
                widget_color=widget_color,
                tubing=tubing,
                interaction_event=interaction_event,
                **axkwargs,
            )
            actors.append(a)

        return actors

    def add_line_widget(
        self,
        callback,
        bounds=None,
        factor=1.25,
        resolution=100,
        color=None,
        use_vertices=False,
        pass_widget=False,
        interaction_event=_vtk.vtkCommand.EndInteractionEvent,
    ):
        """Add a line widget to the scene.

        This is useless without a callback function. You can pass a
        callable function that takes a single argument, the PolyData
        line output from this widget, and performs a task with that
        line.

        Parameters
        ----------
        callback : callable
            The method called every time the line is updated. This has
            two options: Take a single argument, the ``PolyData`` line
            (default) or if ``use_vertices=True``, then it can take
            two arguments of the coordinates of the line's end points.

        bounds : tuple(float), optional
            Length 6 tuple of the bounding box where the widget is
            placed.

        factor : float, optional
            An inflation factor to expand on the bounds when placing.

        resolution : int, optional
            The number of points in the line created.

        color : ColorLike, optional
            Either a string, rgb sequence, or hex color string.

        use_vertices : bool, optional
            Changes the arguments of the callback method to take the end
            points of the line instead of a PolyData object.

        pass_widget : bool, default: False
            If ``True``, the widget will be passed as the last
            argument of the callback.

        interaction_event : vtk.vtkCommand.EventIds, optional
            The VTK interaction event to use for triggering the callback.

        Returns
        -------
        vtk.vtkLineWidget
            Created line widget.

        """
        if bounds is None:
            bounds = self.bounds

        color = Color(color, default_color=pyvista.global_theme.font.color)

        def _the_callback(widget, event_id):
            pointa = widget.GetPoint1()
            pointb = widget.GetPoint2()
            if callable(callback):
                if use_vertices:
                    args = [pointa, pointb]
                else:
                    the_line = pyvista.Line(pointa, pointb, resolution=resolution)
                    args = [the_line]
                if pass_widget:
                    args.append(widget)
                try_callback(callback, *args)

        line_widget = _vtk.vtkLineWidget()
        line_widget.GetLineProperty().SetColor(color.float_rgb)
        line_widget.SetInteractor(self.iren.interactor)
        line_widget.SetCurrentRenderer(self.renderer)
        line_widget.SetPlaceFactor(factor)
        line_widget.PlaceWidget(bounds)
        line_widget.SetResolution(resolution)
        line_widget.Modified()
        line_widget.On()
        line_widget.AddObserver(interaction_event, _the_callback)
        _the_callback(line_widget, None)

        self.line_widgets.append(line_widget)
        return line_widget

    def clear_line_widgets(self):
        """Remove all of the line widgets."""
        self.line_widgets.clear()

    def add_text_slider_widget(
        self,
        callback,
        data,
        value=None,
        pointa=(0.4, 0.9),
        pointb=(0.9, 0.9),
        color=None,
        interaction_event='end',
        style=None,
        **kwargs,
    ):
        """Add a text slider bar widget.

        This is useless without a callback function. You can pass a callable
        function that takes a single argument, the value of this slider widget,
        and performs a task with that value.

        Parameters
        ----------
        callback : callable
            The method called every time the slider is updated. This should take
            a single parameter: the float value of the slider.

        data : list
            The list of possible values displayed on the slider bar.

        value : float, optional
            The starting value of the slider.

        pointa : tuple(float), optional
            The relative coordinates of the left point of the slider on the
            display port.

        pointb : tuple(float), optional
            The relative coordinates of the right point of the slider on the
            display port.

        color : ColorLike, optional
            Either a string, RGB list, or hex color string.  Defaults
            to :attr:`pyvista.global_theme.font.color
            <pyvista.plotting.themes._Font.color>`.

        interaction_event : vtk.vtkCommand.EventIds, str, optional
            The VTK interaction event to use for triggering the
            callback. Accepts either the strings ``'start'``, ``'end'``,
            ``'always'`` or a ``vtk.vtkCommand.EventIds``.

            .. versionchanged:: 0.38.0
               Changed from ``event_type`` to ``interaction_event`` and now
               accepts either strings or ``vtk.vtkCommand.EventIds``.

        style : str, optional
            The name of the slider style. The list of available styles
            are in ``pyvista.global_theme.slider_styles``. Defaults to
            ``None``.

        **kwargs : dict, optional
            Deprecated keyword arguments.

            .. deprecated:: 0.38.0
               Keyword argument ``event_type`` deprecated in favor of
               ``interaction_event``.

        Returns
        -------
        vtk.vtkSliderWidget
            The VTK slider widget configured to display text.

        """
        if not isinstance(data, list):
            raise TypeError(
                f"The `data` parameter must be a list but {type(data).__name__} was passed instead"
            )
        n_states = len(data)
        if n_states == 0:
            raise ValueError("The input list of values is empty")
        delta = (n_states - 1) / float(n_states)
        # avoid division by zero in case there is only one element
        delta = 1 if delta == 0 else delta

        def _the_callback(value):
            if isinstance(value, float):
                idx = int(value / delta)
                # handle limit index
                if idx == n_states:
                    idx = n_states - 1
                if callable(callback):
                    try_callback(callback, data[idx])
            return

        slider_widget = self.add_slider_widget(
            callback=_the_callback,
            rng=[0, n_states - 1],
            value=value,
            pointa=pointa,
            pointb=pointb,
            color=color,
            interaction_event=interaction_event,
            style=style,
        )
        slider_rep = slider_widget.GetRepresentation()
        slider_rep.ShowSliderLabelOff()

        def title_callback(widget, event):  # numpydoc ignore=GL08
            value = widget.GetRepresentation().GetValue()
            idx = int(value / delta)
            # handle limit index
            if idx == n_states:
                idx = n_states - 1
            slider_rep.SetTitleText(data[idx])

        slider_widget.AddObserver(_parse_interaction_event(interaction_event), title_callback)
        title_callback(slider_widget, None)
        return slider_widget

    def add_slider_widget(
        self,
        callback,
        rng,
        value=None,
        title=None,
        pointa=(0.4, 0.9),
        pointb=(0.9, 0.9),
        color=None,
        pass_widget=False,
        interaction_event='end',
        style=None,
        title_height=0.03,
        title_opacity=1.0,
        title_color=None,
        fmt=None,
        slider_width=None,
        tube_width=None,
        **kwargs,
    ):
        """Add a slider bar widget.

        This is useless without a callback function. You can pass a
        callable function that takes a single argument, the value of
        this slider widget, and performs a task with that value.

        Parameters
        ----------
        callback : callable
            Called every time the slider is updated. This should take a single
            parameter: the float value of the slider. If ``pass_widget=True``,
            callable should take two parameters: the float value of the slider
            and the widget itself.

        rng : tuple(float)
            Length two tuple of the minimum and maximum ranges of the
            slider.

        value : float, optional
            The starting value of the slider.

        title : str, optional
            The string label of the slider widget.

        pointa : tuple(float), optional
            The relative coordinates of the left point of the slider
            on the display port.

        pointb : tuple(float), optional
            The relative coordinates of the right point of the slider
            on the display port.

        color : ColorLike, optional
            Either a string, RGB list, or hex color string.  Defaults
            to :attr:`pyvista.global_theme.font.color
            <pyvista.plotting.themes._Font.color>`.

        pass_widget : bool, optional
            If ``True``, the widget will be passed as the last
            argument of the callback.

        interaction_event : vtk.vtkCommand.EventIds, str, optional
            The VTK interaction event to use for triggering the
            callback. Accepts either the strings ``'start'``, ``'end'``,
            ``'always'`` or a ``vtk.vtkCommand.EventIds``.

            .. versionchanged:: 0.38.0
               Changed from ``event_type`` to ``interaction_event`` and now accepts
               either strings or ``vtk.vtkCommand.EventIds``.

        style : str, optional
            The name of the slider style. The list of available styles
            are in ``pyvista.global_theme.slider_styles``. Defaults to
            ``None``.

        title_height : float, optional
            Relative height of the title as compared to the length of
            the slider.

        title_opacity : float, optional
            Opacity of title. Defaults to 1.0.

        title_color : ColorLike, optional
            Either a string, RGB sequence, or hex color string.  Defaults
            to the value given in ``color``.

        fmt : str, optional
            String formatter used to format numerical data. Defaults
            to ``None``.

        slider_width : float, optional
            Normalized width of the slider. Defaults to the theme's slider width.

        tube_width : float, optional
            Normalized width of the tube. Defaults to the theme's tube width.

        **kwargs : dict, optional
            Deprecated keyword arguments.

            .. deprecated:: 0.38.0
               Keyword argument ``event_type`` deprecated in favor of
               ``interaction_event``.

        Returns
        -------
        vtk.vtkSliderWidget
            Slider widget.

        Examples
        --------
        >>> import pyvista as pv
        >>> pl = pv.Plotter()
        >>> def create_mesh(value):
        ...     res = int(value)
        ...     sphere = pv.Sphere(
        ...         phi_resolution=res, theta_resolution=res
        ...     )
        ...     pl.add_mesh(sphere, name="sphere", show_edges=True)
        ...
        >>> slider = pl.add_slider_widget(
        ...     create_mesh,
        ...     [5, 100],
        ...     title="Resolution",
        ...     title_opacity=0.5,
        ...     title_color="red",
        ...     fmt="%0.9f",
        ...     title_height=0.08,
        ... )
        >>> pl.show()
        """
        if self.iren is None:
            raise RuntimeError('Cannot add a widget to a closed plotter.')

        if value is None:
            value = ((rng[1] - rng[0]) / 2) + rng[0]

        color = Color(color, default_color=pyvista.global_theme.font.color)
        title_color = Color(title_color, default_color=color)

        if fmt is None:
            fmt = pyvista.global_theme.font.fmt

        def normalize(point, viewport):  # numpydoc ignore=GL08
            return (point[0] * (viewport[2] - viewport[0]), point[1] * (viewport[3] - viewport[1]))

        pointa = normalize(pointa, self.renderer.GetViewport())
        pointb = normalize(pointb, self.renderer.GetViewport())

        slider_rep = _vtk.vtkSliderRepresentation2D()
        slider_rep.SetPickable(False)
        slider_rep.SetMinimumValue(rng[0])
        slider_rep.SetMaximumValue(rng[1])
        slider_rep.SetValue(value)
        slider_rep.SetTitleText(title)
        slider_rep.GetTitleProperty().SetColor(color.float_rgb)
        slider_rep.GetSliderProperty().SetColor(color.float_rgb)
        slider_rep.GetCapProperty().SetColor(color.float_rgb)
        slider_rep.GetLabelProperty().SetColor(color.float_rgb)
        slider_rep.GetTubeProperty().SetColor(color.float_rgb)
        slider_rep.GetPoint1Coordinate().SetCoordinateSystemToNormalizedDisplay()
        slider_rep.GetPoint1Coordinate().SetValue(pointa[0], pointa[1])
        slider_rep.GetPoint2Coordinate().SetCoordinateSystemToNormalizedDisplay()
        slider_rep.GetPoint2Coordinate().SetValue(pointb[0], pointb[1])
        slider_rep.SetSliderLength(0.05)
        slider_rep.SetSliderWidth(0.05)
        slider_rep.SetEndCapLength(0.01)

        if style is not None:
            if not isinstance(style, str):
                raise TypeError(
                    f"Expected type for ``style`` is str but {type(style).__name__} was given."
                )
            slider_style = getattr(pyvista.global_theme.slider_styles, style)
            slider_rep.SetSliderLength(slider_style.slider_length)
            slider_rep.SetSliderWidth(slider_style.slider_width)
            slider_rep.GetSliderProperty().SetColor(slider_style.slider_color.float_rgb)
            slider_rep.SetTubeWidth(slider_style.tube_width)
            slider_rep.GetTubeProperty().SetColor(slider_style.tube_color.float_rgb)
            slider_rep.GetCapProperty().SetOpacity(slider_style.cap_opacity)
            slider_rep.SetEndCapLength(slider_style.cap_length)
            slider_rep.SetEndCapWidth(slider_style.cap_width)

        if slider_width is not None:
            slider_rep.SetSliderWidth(slider_width)
        if tube_width is not None:
            slider_rep.SetTubeWidth(tube_width)

        def _the_callback(widget, event):
            value = widget.GetRepresentation().GetValue()
            if callable(callback):
                if pass_widget:
                    try_callback(callback, value, widget)
                else:
                    try_callback(callback, value)
            return

        slider_widget = _vtk.vtkSliderWidget()
        slider_widget.SetInteractor(self.iren.interactor)
        slider_widget.SetCurrentRenderer(self.renderer)
        slider_widget.SetRepresentation(slider_rep)
        slider_widget.GetRepresentation().SetTitleHeight(title_height)
        slider_widget.GetRepresentation().GetTitleProperty().SetOpacity(title_opacity)
        slider_widget.GetRepresentation().GetTitleProperty().SetColor(title_color.float_rgb)
        if fmt is not None:
            slider_widget.GetRepresentation().SetLabelFormat(fmt)
        slider_widget.On()
        slider_widget.AddObserver(_parse_interaction_event(interaction_event), _the_callback)
        _the_callback(slider_widget, None)

        self.slider_widgets.append(slider_widget)
        return slider_widget

    def clear_slider_widgets(self):
        """Remove all of the slider widgets."""
        self.slider_widgets.clear()

    def add_mesh_threshold(
        self,
        mesh,
        scalars=None,
        invert=False,
        widget_color=None,
        preference='cell',
        title=None,
        pointa=(0.4, 0.9),
        pointb=(0.9, 0.9),
        continuous=False,
        all_scalars=False,
        method='upper',
        **kwargs,
    ):
        """Apply a threshold on a mesh with a slider.

        Add a mesh to the scene with a slider widget that is used to
        threshold the mesh interactively.

        The threshold mesh is saved to the ``.threshold_meshes`` attribute on
        the plotter.

        Parameters
        ----------
        mesh : pyvista.DataSet or vtk.vtkAlgorithm
            The input dataset to add to the scene and threshold or algorithm
            that produces said mesh.

        scalars : str, optional
            The string name of the scalars on the mesh to threshold and display.

        invert : bool, default: False
            Invert the threshold results. That is, cells that would have been
            in the output with this option off are excluded, while cells that
            would have been excluded from the output are included.

        widget_color : ColorLike, optional
            Color of the widget.  Either a string, RGB sequence, or
            hex color string.  For example:

            * ``color='white'``
            * ``color='w'``
            * ``color=[1.0, 1.0, 1.0]``
            * ``color='#FFFFFF'``

        preference : str, default: 'cell'
            When ``mesh.n_points == mesh.n_cells`` and setting
            scalars, this parameter sets how the scalars will be
            mapped to the mesh.  Default ``'cell'``, causes the
            scalars to be associated with the mesh cells.  Can be
            either ``'point'`` or ``'cell'``.

        title : str, optional
            The string label of the slider widget.

        pointa : sequence, default: (0.4, 0.9)
            The relative coordinates of the left point of the slider
            on the display port.

        pointb : sequence, default: (0.9, 0.9)
            The relative coordinates of the right point of the slider
            on the display port.

        continuous : bool, default: False
            If this is enabled (default is ``False``), use the continuous
            interval ``[minimum cell scalar, maximum cell scalar]``
            to intersect the threshold bound, rather than the set of
            discrete scalar values from the vertices.

        all_scalars : bool, default: False
            If using scalars from point data, all
            points in a cell must satisfy the threshold when this
            value is ``True``.  When ``False``, any point of the cell
            with a scalar value satisfying the threshold criterion
            will extract the cell. Has no effect when using cell data.

        method : str, default: 'upper'
            Set the threshold method for single-values, defining which
            threshold bounds to use. If the ``value`` is a range, this
            parameter will be ignored, extracting data between the two
            values. For single values, ``'lower'`` will extract data
            lower than the  ``value``. ``'upper'`` will extract data
            larger than the ``value``.

        **kwargs : dict, optional
            All additional keyword arguments are passed to ``add_mesh`` to
            control how the mesh is displayed.

        Returns
        -------
        vtk.vtkActor
            VTK actor of the mesh.

        """
        # avoid circular import
        from pyvista.core.filters.data_set import _set_threshold_limit

        mesh, algo = algorithm_to_mesh_handler(mesh)

        if isinstance(mesh, pyvista.PointSet):
            # vtkThreshold is CELL-wise and PointSets have no cells
            algo = pointset_to_polydata_algorithm(algo or mesh)
            mesh, algo = algorithm_to_mesh_handler(algo)

        if isinstance(mesh, pyvista.MultiBlock):
            raise TypeError('MultiBlock datasets are not supported for threshold widget.')
        name = kwargs.get('name', mesh.memory_address)
        if scalars is None:
            field, scalars = mesh.active_scalars_info
        arr = get_array(mesh, scalars, preference=preference)
        if arr is None:
            raise ValueError('No arrays present to threshold.')
        field = get_array_association(mesh, scalars, preference=preference)

        rng = mesh.get_data_range(scalars)
        kwargs.setdefault('clim', kwargs.pop('rng', rng))
        if title is None:
            title = scalars
        mesh.set_active_scalars(scalars)

        self.add_mesh(outline_algorithm(algo or mesh), name=f"{name}-outline", opacity=0.0)

        alg = _vtk.vtkThreshold()
        set_algorithm_input(alg, algo or mesh)
        alg.SetInputArrayToProcess(
            0, 0, 0, field.value, scalars
        )  # args: (idx, port, connection, field, name)
        alg.SetUseContinuousCellRange(continuous)
        alg.SetAllScalars(all_scalars)

        threshold_mesh = pyvista.wrap(alg.GetOutput())
        self.threshold_meshes.append(threshold_mesh)

        def callback(value):  # numpydoc ignore=GL08
            _set_threshold_limit(alg, value, method, invert)
            alg.Update()
            threshold_mesh.shallow_copy(alg.GetOutput())

        self.add_slider_widget(
            callback=callback,
            rng=rng,
            title=title,
            color=widget_color,
            pointa=pointa,
            pointb=pointb,
        )

        kwargs.setdefault("reset_camera", False)
        return self.add_mesh(alg, scalars=scalars, **kwargs)

    def add_mesh_isovalue(
        self,
        mesh,
        scalars=None,
        compute_normals=False,
        compute_gradients=False,
        compute_scalars=True,
        preference='point',
        title=None,
        pointa=(0.4, 0.9),
        pointb=(0.9, 0.9),
        widget_color=None,
        **kwargs,
    ):
        """Create a contour of a mesh with a slider.

        Add a mesh to the scene with a slider widget that is used to
        contour at an isovalue of the *point* data on the mesh
        interactively.

        The isovalue mesh is saved to the ``.isovalue_meshes``
        attribute on the plotter.

        .. warning::
            This will not work with :class:`pyvista.PointSet` as
            creating an isovalue is a dimension reducing operation
            on the geometry and point clouds are zero dimensional.
            This will similarly fail for point clouds in
            :class:`pyvista.PolyData`.

        Parameters
        ----------
        mesh : pyvista.DataSet or vtk.vtkAlgorithm
            The input dataset to add to the scene and contour or algorithm
            that produces said mesh.

        scalars : str, optional
            The string name of the scalars on the mesh to contour and display.

        compute_normals : bool, optional
            Enable or disable the computation of normals.  If the
            output data will be processed by filters that modify
            topology or geometry, it may be wise to disable computing
            normals.

        compute_gradients : bool, optional
            Enable or disable the computation of gradients.  If the
            output data will be processed by filters that modify
            topology or geometry, it may be wise to disable computing
            gradients.

        compute_scalars : bool, optional
            Enable or disable the computation of scalars.

        preference : str, optional
            When ``mesh.n_points == mesh.n_cells`` and setting
            scalars, this parameter sets how the scalars will be
            mapped to the mesh.  Default ``'point'``, causes the
            scalars will be associated with the mesh points.  Can be
            either ``'point'`` or ``'cell'``.

        title : str, optional
            The string label of the slider widget.

        pointa : sequence, optional
            The relative coordinates of the left point of the slider
            on the display port.

        pointb : sequence
            The relative coordinates of the right point of the slider
            on the display port.

        widget_color : ColorLike, optional
            Color of the widget.  Either a string, RGB sequence, or
            hex color string.  For example:

            * ``color='white'``
            * ``color='w'``
            * ``color=[1.0, 1.0, 1.0]``
            * ``color='#FFFFFF'``

        **kwargs : dict, optional
            All additional keyword arguments are passed to
            :func:`Plotter.add_mesh` to control how the mesh is
            displayed.

        Returns
        -------
        vtk.vtkActor
            VTK actor of the mesh.

        """
        mesh, algo = algorithm_to_mesh_handler(mesh)
        if isinstance(mesh, pyvista.PointSet):
            raise TypeError('PointSets are 0-dimensional and thus cannot produce contours.')
        if isinstance(mesh, pyvista.MultiBlock):
            raise TypeError('MultiBlock datasets are not supported for this widget.')
        name = kwargs.get('name', mesh.memory_address)
        # set the array to contour on
        if mesh.n_arrays < 1:
            raise ValueError('Input dataset for the contour filter must have data arrays.')
        if scalars is None:
            field, scalars = mesh.active_scalars_info
        else:
            field = get_array_association(mesh, scalars, preference=preference)
        # NOTE: only point data is allowed? well cells works but seems buggy?
        if field != pyvista.FieldAssociation.POINT:
            raise TypeError(
                f'Contour filter only works on Point data. Array ({scalars}) is in the Cell data.'
            )

        rng = mesh.get_data_range(scalars)
        kwargs.setdefault('clim', kwargs.pop('rng', rng))
        if title is None:
            title = scalars
        mesh.set_active_scalars(scalars)

        alg = _vtk.vtkContourFilter()
        set_algorithm_input(alg, algo or mesh)
        alg.SetComputeNormals(compute_normals)
        alg.SetComputeGradients(compute_gradients)
        alg.SetComputeScalars(compute_scalars)
        alg.SetInputArrayToProcess(0, 0, 0, field.value, scalars)
        alg.SetNumberOfContours(1)  # Only one contour level

        self.add_mesh(outline_algorithm(algo or mesh), name=f"{name}-outline", opacity=0.0)

        isovalue_mesh = pyvista.wrap(alg.GetOutput())
        self.isovalue_meshes.append(isovalue_mesh)

        def callback(value):  # numpydoc ignore=GL08
            alg.SetValue(0, value)
            alg.Update()
            isovalue_mesh.shallow_copy(alg.GetOutput())

        self.add_slider_widget(
            callback=callback,
            rng=rng,
            title=title,
            color=widget_color,
            pointa=pointa,
            pointb=pointb,
        )

        kwargs.setdefault("reset_camera", False)
        return self.add_mesh(alg, scalars=scalars, **kwargs)

    def add_spline_widget(
        self,
        callback,
        bounds=None,
        factor=1.25,
        n_handles=5,
        resolution=25,
        color="yellow",
        show_ribbon=False,
        ribbon_color="pink",
        ribbon_opacity=0.5,
        pass_widget=False,
        closed=False,
        initial_points=None,
        interaction_event=_vtk.vtkCommand.EndInteractionEvent,
    ):
        """Create and add a spline widget to the scene.

        Use the bounds argument to place this widget. Several "handles" are
        used to control a parametric function for building this spline. Click
        directly on the line to translate the widget.

        Parameters
        ----------
        callback : callable
            The method called every time the spline is updated. This passes a
            :class:`pyvista.PolyData` object to the callback function of the
            generated spline.

        bounds : sequence[float], optional
            Length 6 sequence of the bounding box where the widget is placed.

        factor : float, optional
            An inflation factor to expand on the bounds when placing.

        n_handles : int, optional
            The number of interactive spheres to control the spline's
            parametric function.

        resolution : int, optional
            The number of points in the spline created between all the handles.

        color : ColorLike, optional
            Either a string, RGB sequence, or hex color string.

        show_ribbon : bool, optional
            If ``True``, the poly plane used for slicing will also be shown.

        ribbon_color : ColorLike, optional
            Color of the ribbon.  Either a string, RGB sequence, or
            hex color string.

        ribbon_opacity : float, optional
            Opacity of ribbon. Defaults to 1.0 and must be between
            ``[0, 1]``.

        pass_widget : bool, optional
            If ``True``, the widget will be passed as the last argument of the
            callback.

        closed : bool, optional
            Make the spline a closed loop.

        initial_points : sequence, optional
            The points to initialize the widget placement. Must have
            same number of elements as ``n_handles``. If the first and
            last point are the same, this will be a closed loop
            spline.

        interaction_event : vtk.vtkCommand.EventIds, optional
            The VTK interaction event to use for triggering the callback.

        Returns
        -------
        vtk.vtkSplineWidget
            The newly created spline widget.

        Notes
        -----
        This widget has trouble displaying certain colors. Use only simple
        colors (white, black, yellow).

        """
        if initial_points is not None and len(initial_points) != n_handles:
            raise ValueError("`initial_points` must be length `n_handles`.")

        color = Color(color, default_color=pyvista.global_theme.color)

        if bounds is None:
            bounds = self.bounds

        ribbon = pyvista.PolyData()

        def _the_callback(widget, event_id):
            para_source = _vtk.vtkParametricFunctionSource()
            para_source.SetParametricFunction(widget.GetParametricSpline())
            para_source.Update()
            polyline = pyvista.wrap(para_source.GetOutput())
            ribbon.shallow_copy(polyline.ribbon(normal=(0, 0, 1), angle=90.0))
            if callable(callback):
                if pass_widget:
                    try_callback(callback, polyline, widget)
                else:
                    try_callback(callback, polyline)
            return

        spline_widget = _vtk.vtkSplineWidget()
        spline_widget.GetLineProperty().SetColor(color.float_rgb)
        spline_widget.SetNumberOfHandles(n_handles)
        spline_widget.SetInteractor(self.iren.interactor)
        spline_widget.SetCurrentRenderer(self.renderer)
        spline_widget.SetPlaceFactor(factor)
        spline_widget.PlaceWidget(bounds)
        spline_widget.SetResolution(resolution)
        if initial_points is not None:
            spline_widget.InitializeHandles(pyvista.vtk_points(initial_points))
        else:
            spline_widget.SetClosed(closed)
        spline_widget.Modified()
        spline_widget.On()
        spline_widget.AddObserver(interaction_event, _the_callback)
        _the_callback(spline_widget, None)

        if show_ribbon:
            self.add_mesh(ribbon, color=ribbon_color, opacity=ribbon_opacity)

        self.spline_widgets.append(spline_widget)
        return spline_widget

    def clear_spline_widgets(self):
        """Remove all of the spline widgets."""
        self.spline_widgets.clear()

    def add_mesh_slice_spline(
        self,
        mesh,
        generate_triangles=False,
        n_handles=5,
        resolution=25,
        widget_color=None,
        show_ribbon=False,
        ribbon_color="pink",
        ribbon_opacity=0.5,
        initial_points=None,
        closed=False,
        interaction_event=_vtk.vtkCommand.EndInteractionEvent,
        **kwargs,
    ):
        """Slice a mesh with a spline widget.

        Add a mesh to the scene with a spline widget that is used to slice
        the mesh interactively.

        The sliced mesh is saved to the ``.spline_sliced_meshes`` attribute on
        the plotter.

        Parameters
        ----------
        mesh : pyvista.DataSet or vtk.vtkAlgorithm
            The input dataset to add to the scene and slice along the spline
            or algorithm that produces said mesh.

        generate_triangles : bool, optional
            If this is enabled (``False`` by default), the output will be
            triangles otherwise, the output will be the intersection polygons.

        n_handles : int, optional
            The number of interactive spheres to control the spline's
            parametric function.

        resolution : int, optional
            The number of points to generate on the spline.

        widget_color : ColorLike, optional
            Color of the widget.  Either a string, RGB sequence, or
            hex color string.  For example:

            * ``color='white'``
            * ``color='w'``
            * ``color=[1.0, 1.0, 1.0]``
            * ``color='#FFFFFF'``

        show_ribbon : bool, optional
            If ``True``, the poly plane used for slicing will also be shown.

        ribbon_color : ColorLike, optional
            Color of the ribbon.  Either a string, RGB sequence, or
            hex color string.

        ribbon_opacity : float, optional
            Opacity of ribbon. Defaults to 1.0 and must be between
            ``[0, 1]``.

        initial_points : sequence, optional
            The points to initialize the widget placement. Must have same
            number of elements as ``n_handles``. If the first and last point
            are the same, this will be a closed loop spline.

        closed : bool, optional
            Make the spline a closed loop.

        interaction_event : vtk.vtkCommand.EventIds, optional
            The VTK interaction event to use for triggering the callback.

        **kwargs : dict, optional
            All additional keyword arguments are passed to
            :func:`Plotter.add_mesh` to control how the mesh is
            displayed.

        Returns
        -------
        vtk.vtkActor
            VTK actor of the mesh.

        """
        mesh, algo = algorithm_to_mesh_handler(mesh)
        name = kwargs.get('name', None)
        if name is None:
            name = mesh.memory_address
        rng = mesh.get_data_range(kwargs.get('scalars', None))
        kwargs.setdefault('clim', kwargs.pop('rng', rng))
        mesh.set_active_scalars(kwargs.get('scalars', mesh.active_scalars_name))

        self.add_mesh(outline_algorithm(algo or mesh), name=f"{name}-outline", opacity=0.0)

        alg = _vtk.vtkCutter()  # Construct the cutter object
        # Use the grid as the data we desire to cut
        set_algorithm_input(alg, algo or mesh)
        if not generate_triangles:
            alg.GenerateTrianglesOff()

        spline_sliced_mesh = pyvista.wrap(alg.GetOutput())
        self.spline_sliced_meshes.append(spline_sliced_mesh)

        def callback(spline):  # numpydoc ignore=GL08
            polyline = spline.GetCell(0)
            # create the plane for clipping
            polyplane = _vtk.vtkPolyPlane()
            polyplane.SetPolyLine(polyline)
            alg.SetCutFunction(polyplane)  # the cutter to use the poly planes
            alg.Update()  # Perform the Cut
            spline_sliced_mesh.shallow_copy(alg.GetOutput())

        self.add_spline_widget(
            callback=callback,
            bounds=mesh.bounds,
            factor=1.25,
            color=widget_color,
            n_handles=n_handles,
            resolution=resolution,
            show_ribbon=show_ribbon,
            ribbon_color=ribbon_color,
            ribbon_opacity=ribbon_opacity,
            initial_points=initial_points,
            closed=closed,
            interaction_event=interaction_event,
        )

        return self.add_mesh(alg, **kwargs)

    def add_measurement_widget(
        self,
        callback=None,
        color=None,
    ):
        """Interactively measure distance with a distance widget.

        Creates an overlay documenting the selected line and total
        distance between two mouse left-click interactions.

        The measurement overlay stays on the rendering until the
        widget is deleted. Only one measurement can be added by each
        widget instance.

        Parameters
        ----------
        callback : Callable[[Tuple[float, float, float], [Tuple[float, float, float], int], float]
            The method called every time the widget calculates a
            distance measurement. This callback receives the start
            point and end point as cartesian coordinate tuples
            and the calculated distance between the two points.

        color : ColorLike, optional
            The color of the measurement widget.

        Returns
        -------
        vtk.vtkDistanceWidget
            The newly created distance widget.

        """
        if self.iren is None:
            raise RuntimeError('Cannot add a widget to a closed plotter.')

        if color is None:
            color = pyvista.global_theme.font.color.float_rgb
        color = Color(color)

        compute = lambda a, b: np.sqrt(np.sum((np.array(b) - np.array(a)) ** 2))

        handle = _vtk.vtkPointHandleRepresentation3D()
        representation = _vtk.vtkDistanceRepresentation3D()
        representation.SetHandleRepresentation(handle)
        widget = _vtk.vtkDistanceWidget()
        widget.SetInteractor(self.iren.interactor)
        widget.SetRepresentation(representation)

        handle.GetProperty().SetColor(*color.float_rgb)
        representation.GetLabelProperty().SetColor(*color.float_rgb)
        representation.GetLineProperty().SetColor(*color.float_rgb)

        self.iren.picker = PickerType.POINT

        def place_point(*_):  # numpydoc ignore=GL08
            p1 = [0, 0, 0]
            p2 = [0, 0, 0]
            representation.GetPoint1DisplayPosition(p1)
            representation.GetPoint2DisplayPosition(p2)
            if self.iren.picker.Pick(p1, self.renderer):
                pos1 = self.iren.picker.GetPickPosition()
                representation.GetPoint1Representation().SetWorldPosition(pos1)
            if self.iren.picker.Pick(p2, self.renderer):
                pos2 = self.iren.picker.GetPickPosition()
                representation.GetPoint2Representation().SetWorldPosition(pos2)
            representation.BuildRepresentation()

            a = representation.GetPoint1Representation().GetWorldPosition()
            b = representation.GetPoint2Representation().GetWorldPosition()
            if callable(callback):
                try_callback(callback, a, b, compute(a, b))
            return

        widget.AddObserver(_vtk.vtkCommand.EndInteractionEvent, place_point)

        widget.On()
        self.distance_widgets.append(widget)
        return widget

    def clear_measure_widgets(self):
        """Remove all of the measurement widgets."""
        self.distance_widgets.clear()

    def add_sphere_widget(
        self,
        callback,
        center=(0, 0, 0),
        radius=0.5,
        theta_resolution=30,
        phi_resolution=30,
        color=None,
        style="surface",
        selected_color="pink",
        indices=None,
        pass_widget=False,
        test_callback=True,
        interaction_event=_vtk.vtkCommand.EndInteractionEvent,
    ):
        """Add one or many sphere widgets to a scene.

        Use a sphere widget to control a vertex location.

        Parameters
        ----------
        callback : callable
            The function to call back when the widget is modified. It takes a
            single argument: the center of the sphere as an XYZ coordinate (a
            3-length sequence), unless ``pass_widget=True``, in which case the
            callback must accept the widget object as the second parameter.  If
            multiple centers are passed in the ``center`` parameter, the
            callback must also accept an index of that widget.

        center : sequence[float], optional
            The cartesian coordinate of the sphere's center when placing it in
            the scene. If more than one location is passed, then that many
            widgets will be added and the callback will also be passed the
            integer index of that widget.

        radius : float, optional
            The radius of the sphere.

        theta_resolution : int, optional
            Set the number of points in the longitude direction.

        phi_resolution : int, optional
            Set the number of points in the latitude direction.

        color : ColorLike, optional
            The color of the sphere's surface.  If multiple centers
            are passed, then this must be a list of colors.  Each
            color is either a string, rgb list, or hex color string.
            For example:

            * ``color='white'``
            * ``color='w'``
            * ``color=[1.0, 1.0, 1.0]``
            * ``color='#FFFFFF'``

        style : str, optional
            Representation style: ``'surface'`` or ``'wireframe'``.

        selected_color : ColorLike, optional
            Color of the widget when selected during interaction.

        indices : sequence[int], optional
            Indices to assign the sphere widgets.

        pass_widget : bool, optional
            If ``True``, the widget will be passed as the last
            argument of the callback.

        test_callback : bool, optional
            If ``True``, run the callback function after the widget is
            created.

        interaction_event : vtk.vtkCommand.EventIds, optional
            The VTK interaction event to use for triggering the callback.

        Returns
        -------
        vtk.vtkSphereWidget
            The sphere widget.

        """
        if color is None:
            color = pyvista.global_theme.color.float_rgb
        selected_color = Color(selected_color)

        center = np.array(center)
        num = 1
        if center.ndim > 1:
            num = len(center)

        if isinstance(color, (list, tuple, np.ndarray)):
            if len(color) == num and not isinstance(color[0], float):
                colors = color
            else:
                colors = [color] * num
        else:
            colors = [color] * num

        def _the_callback(widget, event_id):
            point = widget.GetCenter()
            index = widget.WIDGET_INDEX
            if callable(callback):
                if num > 1:
                    args = [point, index]
                else:
                    args = [point]
                if pass_widget:
                    args.append(widget)
                try_callback(callback, *args)
            return

        if indices is None:
            indices = [x for x in range(num)]

        for i in range(num):
            if center.ndim > 1:
                loc = center[i]
            else:
                loc = center
            sphere_widget = _vtk.vtkSphereWidget()
            sphere_widget.WIDGET_INDEX = indices[i]  # Monkey patch the index
            if style in "wireframe":
                sphere_widget.SetRepresentationToWireframe()
            else:
                sphere_widget.SetRepresentationToSurface()
            sphere_widget.GetSphereProperty().SetColor(Color(colors[i]).float_rgb)
            sphere_widget.GetSelectedSphereProperty().SetColor(selected_color.float_rgb)
            sphere_widget.SetInteractor(self.iren.interactor)
            sphere_widget.SetCurrentRenderer(self.renderer)
            sphere_widget.SetRadius(radius)
            sphere_widget.SetCenter(loc)
            sphere_widget.SetThetaResolution(theta_resolution)
            sphere_widget.SetPhiResolution(phi_resolution)
            sphere_widget.Modified()
            sphere_widget.On()
            sphere_widget.AddObserver(interaction_event, _the_callback)
            self.sphere_widgets.append(sphere_widget)

        if test_callback is True:
            # Test call back in the last
            _the_callback(sphere_widget, None)
        if num > 1:
            return self.sphere_widgets

        return sphere_widget

    def clear_sphere_widgets(self):
        """Remove all of the sphere widgets."""
        self.sphere_widgets.clear()

    def add_affine_transform_widget(
        self,
        actor,
        origin=None,
        start=True,
        scale=0.15,
        line_radius=0.02,
        always_visible=True,
        axes_colors=None,
        axes=None,
        release_callback=None,
        interact_callback=None,
    ):
        """Add a 3D affine transform widget.

        This widget allows interactive transformations including translation and
        rotation using the left mouse button.

        Parameters
        ----------
        actor : pyvista.Actor
            The actor to which the widget is attached to.
        origin : sequence[float], optional
            Origin of the widget. Default is the origin of the main actor.
        start : bool, default: True
            If True, start the widget immediately.
        scale : float, default: 0.15
            Scale factor for the widget relative to the length of the actor.
        line_radius : float, default: 0.02
            Relative radius of the lines composing the widget.
        always_visible : bool, default: True
            Make the widget always visible. Setting this to ``False`` will cause
            the widget geometry to be hidden by other actors in the plotter.
        axes_colors : tuple[ColorLike], optional
            Uses the theme by default. Configure the individual axis colors by
            modifying either the theme with ``pv.global_theme.axes.x_color =
            <COLOR>`` or setting this with a ``tuple`` as in ``('r', 'g', 'b')``.
        axes : numpy.ndarray, optional
            ``(3, 3)`` Numpy array defining the X, Y, and Z axes. By default
            this matches the default coordinate system.
        release_callback : callable, optional
            Call this method when releasing the left mouse button. It is passed
            the ``user_matrix`` of the actor.
        interact_callback : callable, optional
            Call this method when moving the mouse with the left mouse button
            pressed down and a valid movement actor selected. It is passed the
            ``user_matrix`` of the actor.

        Returns
        -------
        pyvista.widgets.AffineWidget3D
            The affine widget.

        Notes
        -----
        After interacting with the actor, the transform will be stored within
        :attr:`pyvista.Actor.user_matrix` but will not be applied to the
        dataset. Use this matrix in conjunction with
        :func:`pyvista.DataSetFilters.transform` to transform the dataset.

        Examples
        --------
        Add the 3d affine widget.

        >>> import pyvista as pv
        >>> pl = pv.Plotter()
        >>> actor = pl.add_mesh(pv.Sphere())
        >>> widget = pl.add_affine_transform_widget(actor)
        >>> pl.show()

        Access the transform from the actor.

        >>> actor.user_matrix
        array([[1., 0., 0., 0.],
               [0., 1., 0., 0.],
               [0., 0., 1., 0.],
               [0., 0., 0., 1.]])
        """
        return AffineWidget3D(
            self,
            actor,
            origin,
            start,
            scale,
            line_radius,
            always_visible,
            axes_colors,
            axes,
            release_callback,
            interact_callback,
        )

    def add_checkbox_button_widget(
        self,
        callback,
        value=False,
        position=(10.0, 10.0),
        size=50,
        border_size=5,
        color_on='blue',
        color_off='grey',
        background_color='white',
    ):
        """Add a checkbox button widget to the scene.

        This is useless without a callback function. You can pass a callable
        function that takes a single argument, the state of this button widget
        and performs a task with that value.

        Parameters
        ----------
        callback : callable
            The method called every time the button is clicked. This should take
            a single parameter: the bool value of the button.

        value : bool, default: False
            The default state of the button.

        position : sequence[float], default: (10.0, 10.0)
            The absolute coordinates of the bottom left point of the button.

        size : int, default: 50
            The size of the button in number of pixels.

        border_size : int, default: 5
            The size of the borders of the button in pixels.

        color_on : ColorLike, optional
            The color used when the button is checked. Default is ``'blue'``.

        color_off : ColorLike, optional
            The color used when the button is not checked. Default is ``'grey'``.

        background_color : ColorLike, optional
            The background color of the button. Default is ``'white'``.

        Returns
        -------
        vtk.vtkButtonWidget
            The VTK button widget configured as a checkbox button.

        Examples
        --------
        The following example generates a static image of the widget.

        >>> import pyvista as pv
        >>> mesh = pv.Sphere()
        >>> p = pv.Plotter()
        >>> actor = p.add_mesh(mesh)
        >>> def toggle_vis(flag):
        ...     actor.SetVisibility(flag)
        ...
        >>> _ = p.add_checkbox_button_widget(toggle_vis, value=True)
        >>> p.show()

        Download the interactive example at :ref:`checkbox_widget_example`.

        """
        if self.iren is None:  # pragma: no cover
            raise RuntimeError('Cannot add a widget to a closed plotter.')

        def create_button(color1, color2, color3, dims=(size, size, 1)):  # numpydoc ignore=GL08
            color1 = np.array(Color(color1).int_rgb)
            color2 = np.array(Color(color2).int_rgb)
            color3 = np.array(Color(color3).int_rgb)

            n_points = dims[0] * dims[1]
            button = pyvista.ImageData(dimensions=dims)
            arr = np.array([color1] * n_points).reshape(dims[0], dims[1], 3)  # fill with color1
            arr[1 : dims[0] - 1, 1 : dims[1] - 1] = color2  # apply color2
            arr[
                border_size : dims[0] - border_size, border_size : dims[1] - border_size
            ] = color3  # apply color3
            button.point_data['texture'] = arr.reshape(n_points, 3).astype(np.uint8)
            return button

        button_on = create_button(color_on, background_color, color_on)
        button_off = create_button(color_on, background_color, color_off)

        bounds = [position[0], position[0] + size, position[1], position[1] + size, 0.0, 0.0]

        button_rep = _vtk.vtkTexturedButtonRepresentation2D()
        button_rep.SetNumberOfStates(2)
        button_rep.SetState(value)
        button_rep.SetButtonTexture(0, button_off)
        button_rep.SetButtonTexture(1, button_on)
        button_rep.SetPlaceFactor(1)
        button_rep.PlaceWidget(bounds)

        button_widget = _vtk.vtkButtonWidget()
        button_widget.SetInteractor(self.iren.interactor)
        button_widget.SetRepresentation(button_rep)
        button_widget.SetCurrentRenderer(self.renderer)
        button_widget.On()

        def _the_callback(widget, event):
            state = widget.GetRepresentation().GetState()
            if callable(callback):
                try_callback(callback, bool(state))

        button_widget.AddObserver(_vtk.vtkCommand.StateChangedEvent, _the_callback)
        self.button_widgets.append(button_widget)
        return button_widget

    def add_camera_orientation_widget(self, animate=True, n_frames=20):
        """Add a camera orientation widget to the active renderer.

        .. note::
           This widget requires ``vtk>=9.1.0``.

        Parameters
        ----------
        animate : bool, default: True
            Enable or disable jump-to-axis-view animation.

        n_frames : int, default: 20
            The number of frames to animate the jump-to-axis-viewpoint feature.

        Returns
        -------
        vtkCameraOrientationWidget
            Camera orientation widget.

        Examples
        --------
        Add a camera orientation widget to the scene.

        >>> import pyvista
        >>> mesh = pyvista.Cube()
        >>> plotter = pyvista.Plotter()
        >>> _ = plotter.add_mesh(
        ...     mesh, scalars=range(6), show_scalar_bar=False
        ... )
        >>> _ = plotter.add_camera_orientation_widget()
        >>> plotter.show()

        """
        try:
            from vtkmodules.vtkInteractionWidgets import vtkCameraOrientationWidget
        except ImportError:  # pragma: no cover
            from pyvista.core.errors import VTKVersionError

            raise VTKVersionError('vtkCameraOrientationWidget requires vtk>=9.1.0')

        widget = vtkCameraOrientationWidget()
        widget.SetParentRenderer(self.renderer)
        widget.SetAnimate(animate)
        widget.SetAnimatorTotalFrames(n_frames)
        widget.On()
        self.camera_widgets.append(widget)
        return widget

    def clear_camera_widgets(self):
        """Remove all of the camera widgets."""
        self.camera_widgets.clear()

    def clear_button_widgets(self):
        """Remove all of the button widgets."""
        self.button_widgets.clear()

    def close(self):
        """Close the widgets."""
        self.clear_box_widgets()
        self.clear_plane_widgets()
        self.clear_line_widgets()
        self.clear_slider_widgets()
        self.clear_sphere_widgets()
        self.clear_spline_widgets()
        self.clear_button_widgets()
        self.clear_camera_widgets()
        self.clear_measure_widgets()


# pyvista/utilities/__init__.py

"""Deprecated utilities subpackage."""
import importlib
import inspect
import warnings

# Places to look for the utility
_MODULES = [
    'pyvista.core.utilities',
    'pyvista.core.errors',
    'pyvista.core',
    'pyvista.plotting.utilities',
    'pyvista.plotting.errors',
    'pyvista.plotting.texture',
    'pyvista.plotting',
    'pyvista.report',
    'pyvista.plotting.themes',
]


def _try_import(module, name):
    """Attempt to import a module."""
    _module = importlib.import_module(module)
    try:
        feature = inspect.getattr_static(_module, name)
        import_path = f'from {module} import {name}'
    except AttributeError:
        return None, None
    return feature, import_path


def __getattr__(name):
    """Fetch an attribute ``name`` from ``globals()`` and warn if it's from a deprecated module.

    Note that ``__getattr__()`` only gets called when ``name`` is missing
    from the module's globals. The trick is that we want to import this
    function into other deprecated modules, and we want to carry this
    subpackage's globals along to prevent some spurious warnings.

    Raises
    ------
    AttributeError
        If the attribute is not found in ``globals()`` and also could not be
        imported from the modules in ``_MODULES``.

    PyVistaDeprecationWarning
        If the attribute has been found via importing from the modules in
        ``_MODULES``, as this implies that the feature has been moved from
        pyvista.utilities.

    """
    from pyvista.core.errors import PyVistaDeprecationWarning

    try:
        return globals()[name]
    except KeyError:
        pass

    for module in _MODULES:
        feature, import_path = _try_import(module, name)
        if feature is not None:
            break
    else:
        raise AttributeError(
            f'Module `pyvista.utilities` has been deprecated and we could not automatically find `{name}`. This feature has moved.'
        ) from None

    message = f'The `pyvista.utilities` module has been deprecated. `{name}` is now imported as: `{import_path}`.'

    warnings.warn(
        message,
        PyVistaDeprecationWarning,
    )

    return feature


# pyvista/utilities/algorithms.py

"""Deprecated module."""
from . import __getattr__  # noqa: F401


# pyvista/utilities/arrays.py

"""Deprecated module."""
from . import __getattr__  # noqa: F401


# pyvista/utilities/cell_type_helper.py

"""Deprecated module."""
from . import __getattr__  # noqa: F401


# pyvista/utilities/cells.py

"""Deprecated module."""
from . import __getattr__  # noqa: F401


# pyvista/utilities/common.py

"""Deprecated module."""
from . import __getattr__  # noqa: F401


# pyvista/utilities/docs.py

"""Deprecated module."""
from . import __getattr__  # noqa: F401


# pyvista/utilities/errors.py

"""Deprecated module."""
from . import __getattr__  # noqa: F401


# pyvista/utilities/features.py

"""Deprecated module."""
from . import __getattr__  # noqa: F401


# pyvista/utilities/fileio.py

"""Deprecated module."""
from . import __getattr__  # noqa: F401


# pyvista/utilities/geometric_objects.py

"""Deprecated module."""
from . import __getattr__  # noqa: F401


# pyvista/utilities/helpers.py

"""Deprecated module."""
from . import __getattr__  # noqa: F401


# pyvista/utilities/misc.py

"""Deprecated module."""
from . import __getattr__  # noqa: F401


# pyvista/utilities/parametric_objects.py

"""Deprecated module."""
from . import __getattr__  # noqa: F401


# pyvista/utilities/reader.py

"""Deprecated module."""
from . import __getattr__  # noqa: F401


# pyvista/utilities/regression.py

"""Deprecated module."""
from . import __getattr__  # noqa: F401


# pyvista/utilities/sphinx_gallery.py

"""Deprecated module."""
from . import __getattr__  # noqa: F401


# pyvista/utilities/transformations.py

"""Deprecated module."""
from . import __getattr__  # noqa: F401


# pyvista/utilities/wrappers.py

"""Deprecated module."""
from . import __getattr__  # noqa: F401


# pyvista/utilities/xvfb.py

"""Deprecated module."""
from . import __getattr__  # noqa: F401


# setup.py

"""See pyproject.toml for project metadata."""
from setuptools import setup

setup()


# pyvista/__init__.py

"""PyVista package for 3D plotting and mesh analysis."""
# flake8: noqa: F401
import os
import sys
import warnings

from pyvista._plot import plot
from pyvista._version import __version__
from pyvista.core import *
from pyvista.core.cell import _get_vtk_id_type
from pyvista.core.utilities.observers import send_errors_to_logging
from pyvista.core.wrappers import _wrappers
from pyvista.jupyter import set_jupyter_backend
from pyvista.report import GPUInfo, Report, get_gpu_info, vtk_version_info

# get the int type from vtk
ID_TYPE = _get_vtk_id_type()

# determine if using at least vtk 9.0.0
if vtk_version_info.major < 9:  # pragma: no cover
    from pyvista.core.errors import VTKVersionError

    raise VTKVersionError('VTK version must be 9.0.0 or greater.')

# catch annoying numpy/vtk future warning:
warnings.simplefilter(action='ignore', category=FutureWarning)

# A simple flag to set when generating the documentation
OFF_SCREEN = os.environ.get("PYVISTA_OFF_SCREEN", "false").lower() == "true"

# flag for when building the sphinx_gallery
BUILDING_GALLERY = False
if 'PYVISTA_BUILDING_GALLERY' in os.environ:
    if os.environ['PYVISTA_BUILDING_GALLERY'].lower() == 'true':
        BUILDING_GALLERY = True

# A threshold for the max cells to compute a volume for when repr-ing
REPR_VOLUME_MAX_CELLS = 1e6

# Set where figures are saved
FIGURE_PATH = None

# Send VTK messages to the logging module:
send_errors_to_logging()

# theme to use by default for the plot directive
PLOT_DIRECTIVE_THEME = None

# Set a parameter to control default print format for floats outside
# of the plotter
FLOAT_FORMAT = "{:.3e}"

# Serialization format to be used when pickling `DataObject`
PICKLE_FORMAT = 'xml'

# Name used for unnamed scalars
DEFAULT_SCALARS_NAME = 'Data'

MAX_N_COLOR_BARS = 10


# Lazily import/access the plotting module
def __getattr__(name):
    """Fetch an attribute ``name`` from ``globals()`` or the ``pyvista.plotting`` module.

    This override is implemented to prevent importing all of the plotting module
    and GL-dependent VTK modules when importing PyVista.

    Raises
    ------
    AttributeError
        If the attribute is not found.

    """
    import importlib
    import inspect

    allow = {
        'demos',
        'examples',
        'ext',
        'trame',
        'utilities',
    }
    if name in allow:
        return importlib.import_module(f'pyvista.{name}')

    # avoid recursive import
    if 'pyvista.plotting' not in sys.modules:
        import pyvista.plotting

    try:
        feature = inspect.getattr_static(sys.modules['pyvista.plotting'], name)
    except AttributeError as e:
        raise AttributeError(f"module 'pyvista' has no attribute '{name}'") from None

    return feature


# pyvista/_plot.py

"""PyVista's famous ``plot()`` helper method.

This method is placed at the top-level to allow us to easily bind
the method to all of the core datatypes before importing the
``pyvista.plotting`` module and libGL dependent VTK modules.
This is necessary for future versions of PyVista that will fully
decouple the ``core`` and ``plotting`` APIs.

"""
import numpy as np

import pyvista


def plot(
    var_item,
    off_screen=None,
    full_screen=None,
    screenshot=None,
    interactive=True,
    cpos=None,
    window_size=None,
    show_bounds=False,
    show_axes=None,
    notebook=None,
    background=None,
    text='',
    return_img=False,
    eye_dome_lighting=False,
    volume=False,
    parallel_projection=False,
    jupyter_backend=None,
    return_viewer=False,
    return_cpos=False,
    jupyter_kwargs=None,
    theme=None,
    hidden_line_removal=None,
    anti_aliasing=None,
    zoom=None,
    border=False,
    border_color='k',
    border_width=2.0,
    ssao=False,
    **kwargs,
):
    """Plot a PyVista, numpy, or vtk object.

    Parameters
    ----------
    var_item : pyvista.DataSet
        See :func:`Plotter.add_mesh <pyvista.Plotter.add_mesh>` for all
        supported types.

    off_screen : bool, optional
        Plots off screen when ``True``.  Helpful for saving
        screenshots without a window popping up.  Defaults to the
        global setting ``pyvista.OFF_SCREEN``.

    full_screen : bool, default: :attr:`pyvista.plotting.themes.Theme.full_screen`
        Opens window in full screen.  When enabled, ignores
        ``window_size``.

    screenshot : str or bool, optional
        Saves screenshot to file when enabled.  See:
        :func:`Plotter.screenshot() <pyvista.Plotter.screenshot>`.
        Default ``False``.

        When ``True``, takes screenshot and returns ``numpy`` array of
        image.

    interactive : bool, default: :attr:`pyvista.plotting.themes.Theme.interactive`
        Allows user to pan and move figure.

    cpos : list, optional
        List of camera position, focal point, and view up.

    window_size : sequence, default: :attr:`pyvista.plotting.themes.Theme.window_size`
        Window size in pixels.

    show_bounds : bool, default: False
        Shows mesh bounds when ``True``.

    show_axes : bool, default: :attr:`pyvista.plotting.themes._AxesConfig.show`
        Shows a vtk axes widget.

    notebook : bool, default: :attr:`pyvista.plotting.themes.Theme.notebook`
        When ``True``, the resulting plot is placed inline a jupyter
        notebook.  Assumes a jupyter console is active.

    background : ColorLike, default: :attr:`pyvista.plotting.themes.Theme.background`
        Color of the background.

    text : str, optional
        Adds text at the bottom of the plot.

    return_img : bool, default: False
        Returns numpy array of the last image rendered.

    eye_dome_lighting : bool, optional
        Enables eye dome lighting.

    volume : bool, default: False
        Use the :func:`Plotter.add_volume()
        <pyvista.Plotter.add_volume>` method for volume rendering.

    parallel_projection : bool, default: False
        Enable parallel projection.

    jupyter_backend : str, default: :attr:`pyvista.plotting.themes.Theme.jupyter_backend`
        Jupyter notebook plotting backend to use.  One of the
        following:

        * ``'none'`` : Do not display in the notebook.
        * ``'static'`` : Display a static figure.
        * ``'trame'`` : Display using ``trame``.

        This can also be set globally with
        :func:`pyvista.set_jupyter_backend`.

    return_viewer : bool, default: False
        Return the jupyterlab viewer, scene, or display object
        when plotting with jupyter notebook.

    return_cpos : bool, default: False
        Return the last camera position from the render window
        when enabled.  Defaults to value in theme settings.

    jupyter_kwargs : dict, optional
        Keyword arguments for the Jupyter notebook plotting backend.

    theme : pyvista.plotting.themes.Theme, optional
        Plot-specific theme.

    hidden_line_removal : bool, default: :attr:`pyvista.plotting.themes.Theme.hidden_line_removal`
        Wireframe geometry will be drawn using hidden line removal if
        the rendering engine supports it.  See
        :func:`Plotter.enable_hidden_line_removal
        <Plotter.enable_hidden_line_removal>`.

    anti_aliasing : str | bool, default: :attr:`pyvista.plotting.themes.Theme.anti_aliasing`
        Enable or disable anti-aliasing. If ``True``, uses ``"msaa"``. If False,
        disables anti_aliasing. If a string, should be either ``"fxaa"`` or
        ``"ssaa"``.

    zoom : float, str, optional
        Camera zoom.  Either ``'tight'`` or a float. A value greater than 1
        is a zoom-in, a value less than 1 is a zoom-out.  Must be greater
        than 0.

    border : bool, default: False
        Draw a border around each render window.

    border_color : ColorLike, default: "k"
        Either a string, rgb list, or hex color string.  For example:

            * ``color='white'``
            * ``color='w'``
            * ``color=[1.0, 1.0, 1.0]``
            * ``color='#FFFFFF'``

    border_width : float, default: 2.0
        Width of the border in pixels when enabled.

    ssao : bool, optional
        Enable surface space ambient occlusion (SSAO). See
        :func:`Plotter.enable_ssao` for more details.

    **kwargs : dict, optional
        See :func:`pyvista.Plotter.add_mesh` for additional options.

    Returns
    -------
    cpos : list
        List of camera position, focal point, and view up.
        Returned only when ``return_cpos=True`` or set in the
        default global or plot theme.  Not returned when in a
        jupyter notebook and ``return_viewer=True``.

    image : np.ndarray
        Numpy array of the last image when either ``return_img=True``
        or ``screenshot=True`` is set. Not returned when in a
        jupyter notebook with ``return_viewer=True``. Optionally
        contains alpha values. Sized:

        * [Window height x Window width x 3] if the theme sets
          ``transparent_background=False``.
        * [Window height x Window width x 4] if the theme sets
          ``transparent_background=True``.

    widget : ipywidgets.Widget
        IPython widget when ``return_viewer=True``.

    Examples
    --------
    Plot a simple sphere while showing its edges.

    >>> import pyvista as pv
    >>> mesh = pv.Sphere()
    >>> mesh.plot(show_edges=True)

    Plot a volume mesh. Color by distance from the center of the
    ImageData. Note ``volume=True`` is passed.

    >>> import numpy as np
    >>> grid = pv.ImageData(
    ...     dimensions=(32, 32, 32), spacing=(0.5, 0.5, 0.5)
    ... )
    >>> grid['data'] = np.linalg.norm(grid.center - grid.points, axis=1)
    >>> grid['data'] = np.abs(grid['data'] - grid['data'].max()) ** 3
    >>> grid.plot(volume=True)

    """
    if jupyter_kwargs is None:
        jupyter_kwargs = {}

    # undocumented kwarg used within pytest to run a function before closing
    before_close_callback = kwargs.pop('before_close_callback', None)

    # pop from kwargs here to avoid including them in add_mesh or add_volume
    eye_dome_lighting = kwargs.pop("edl", eye_dome_lighting)
    show_grid = kwargs.pop('show_grid', False)
    auto_close = kwargs.get('auto_close')

    pl = pyvista.Plotter(
        window_size=window_size,
        off_screen=off_screen,
        notebook=notebook,
        theme=theme,
        border=border,
        border_color=border_color,
        border_width=border_width,
    )

    if show_axes is None:
        show_axes = pl.theme.axes.show
    if show_axes:
        pl.add_axes()

    if anti_aliasing:
        if anti_aliasing is True:
            pl.enable_anti_aliasing('msaa', multi_samples=pyvista.global_theme.multi_samples)
        else:
            pl.enable_anti_aliasing(anti_aliasing)
    elif anti_aliasing is False:
        pl.disable_anti_aliasing()

    pl.set_background(background)

    if isinstance(var_item, list):
        if len(var_item) == 2:  # might be arrows
            isarr_0 = isinstance(var_item[0], np.ndarray)
            isarr_1 = isinstance(var_item[1], np.ndarray)
            if isarr_0 and isarr_1:
                pl.add_arrows(var_item[0], var_item[1])
            else:
                for item in var_item:
                    if volume or (isinstance(item, np.ndarray) and item.ndim == 3):
                        pl.add_volume(item, **kwargs)
                    else:
                        pl.add_mesh(item, **kwargs)
        else:
            for item in var_item:
                if volume or (isinstance(item, np.ndarray) and item.ndim == 3):
                    pl.add_volume(item, **kwargs)
                else:
                    pl.add_mesh(item, **kwargs)
    else:
        if volume or (isinstance(var_item, np.ndarray) and var_item.ndim == 3):
            pl.add_volume(var_item, **kwargs)
        elif isinstance(var_item, pyvista.MultiBlock):
            pl.add_composite(var_item, **kwargs)
        else:
            pl.add_mesh(var_item, **kwargs)

    if text:
        pl.add_text(text)

    if show_grid:
        pl.show_grid()
    elif show_bounds:
        pl.show_bounds()

    if cpos is None:
        cpos = pl.get_default_cam_pos()
        pl.camera_position = cpos
        pl.camera_set = False
    else:
        pl.camera_position = cpos

    if eye_dome_lighting:
        pl.enable_eye_dome_lighting()

    if parallel_projection:
        pl.enable_parallel_projection()

    if ssao:
        pl.enable_ssao()

    if zoom is not None:
        pl.camera.zoom(zoom)

    return pl.show(
        auto_close=auto_close,
        interactive=interactive,
        full_screen=full_screen,
        screenshot=screenshot,
        return_img=return_img,
        jupyter_backend=jupyter_backend,
        before_close_callback=before_close_callback,
        jupyter_kwargs=jupyter_kwargs,
        return_viewer=return_viewer,
        return_cpos=return_cpos,
    )


# pyvista/_version.py

"""Version info for pyvista.

On the ``main`` branch, use 'dev0' to denote a development version.
For example:

version_info = 0, 27, 'dev0'

When generating pre-release wheels, use '0rcN', for example:

version_info = 0, 28, '0rc1'

Denotes the first release candidate.

"""
# major, minor, patch
version_info = 0, 42, 'dev0'

# Nice string for the version
__version__ = '.'.join(map(str, version_info))


# pyvista/conftest.py

"""Close all plotters to help control memory usage for our doctests."""

import pytest

import pyvista


@pytest.fixture(autouse=True)
def autoclose_plotters():
    """Close all plotters."""
    yield
    pyvista.close_all()


@pytest.fixture(autouse=True)
def reset_gloal_theme():
    """Reset global_theme."""
    # this stops any doctest-module tests from overriding the global theme and
    # creating test side effects
    yield
    pyvista.global_theme.restore_defaults()


# pyvista/errors.py

"""Deprecated utilities subpackage."""
import importlib
import inspect
import warnings

# Places to look for the utility
_MODULES = [
    'pyvista.core.errors',
    'pyvista.plotting.errors',
]


def _try_import(module, name):
    """Attempt to import a module."""
    _module = importlib.import_module(module)
    try:
        feature = inspect.getattr_static(_module, name)
        import_path = f'from {module} import {name}'
    except AttributeError:
        return None, None
    return feature, import_path


def __getattr__(name):
    """Fetch an attribute ``name`` from ``globals()`` and warn if it's from a deprecated module.

    Note that ``__getattr__()`` only gets called when ``name`` is missing
    from the module's globals. The trick is that we want to import this
    function into other deprecated modules, and we want to carry this
    subpackage's globals along to prevent some spurious warnings.

    Raises
    ------
    AttributeError
        If the attribute is not found in ``globals()`` and also could not be
        imported from the modules in ``_MODULES``.

    Warns
    -----
    PyVistaDeprecationWarning
        If the attribute has been found via importing from the modules in
        ``_MODULES``, as this implies that the feature has been moved from
        ``pyvista.utilities``.

    """
    from pyvista.core.errors import PyVistaDeprecationWarning

    for module in _MODULES:
        feature, import_path = _try_import(module, name)
        if feature is not None:
            break
    else:
        raise AttributeError(
            f'Module `pyvista.errors` has been deprecated and we could not automatically find `{name}`. This feature has moved.'
        ) from None  # pragma: no cover

    message = f'The `pyvista.errors` module has been deprecated. `{name}` is now imported as: `{import_path}`.'

    warnings.warn(
        message,
        PyVistaDeprecationWarning,
    )

    return feature


# pyvista/report.py

"""Module managing errors."""
from collections import namedtuple
import re
import subprocess
import sys
import warnings

import scooby
from vtkmodules.vtkCommonCore import vtkVersion


def VTKVersionInfo():
    """Return the vtk version as a namedtuple.

    Returns
    -------
    collections.namedtuple
        Version information as a named tuple.

    """
    version_info = namedtuple('VTKVersionInfo', ['major', 'minor', 'micro'])

    try:
        ver = vtkVersion()
        major = ver.GetVTKMajorVersion()
        minor = ver.GetVTKMinorVersion()
        micro = ver.GetVTKBuildVersion()
    except AttributeError:  # pragma: no cover
        warnings.warn("Unable to detect VTK version. Defaulting to v4.0.0")
        major, minor, micro = (4, 0, 0)

    return version_info(major, minor, micro)


vtk_version_info = VTKVersionInfo()


_cmd = """\
import pyvista; \
plotter = pyvista.Plotter(notebook=False, off_screen=True); \
plotter.add_mesh(pyvista.Sphere()); \
plotter.show(auto_close=False); \
gpu_info = plotter.render_window.ReportCapabilities(); \
print(gpu_info); \
plotter.close()\
"""


def get_gpu_info():  # numpydoc ignore=RT01
    """Get all information about the GPU."""
    # an OpenGL context MUST be opened before trying to do this.
    proc = subprocess.run([sys.executable, '-c', _cmd], check=False, capture_output=True)
    gpu_info = '' if proc.returncode else proc.stdout.decode()
    return gpu_info


class GPUInfo:
    """A class to hold GPU details."""

    def __init__(self):
        """Instantiate a container for the GPU information."""
        self._gpu_info = get_gpu_info()

    @property
    def renderer(self):  # numpydoc ignore=RT01
        """GPU renderer name."""
        regex = re.compile("OpenGL renderer string:(.+)\n")
        try:
            renderer = regex.findall(self._gpu_info)[0]
        except IndexError:
            raise RuntimeError("Unable to parse GPU information for the renderer.") from None
        return renderer.strip()

    @property
    def version(self):  # numpydoc ignore=RT01
        """GPU renderer version."""
        regex = re.compile("OpenGL version string:(.+)\n")
        try:
            version = regex.findall(self._gpu_info)[0]
        except IndexError:
            raise RuntimeError("Unable to parse GPU information for the version.") from None
        return version.strip()

    @property
    def vendor(self):  # numpydoc ignore=RT01
        """GPU renderer vendor."""
        regex = re.compile("OpenGL vendor string:(.+)\n")
        try:
            vendor = regex.findall(self._gpu_info)[0]
        except IndexError:
            raise RuntimeError("Unable to parse GPU information for the vendor.") from None
        return vendor.strip()

    def get_info(self):
        """All GPU information as tuple pairs.

        Returns
        -------
        tuple
            Tuples of ``(key, info)``.

        """
        return [
            ("GPU Vendor", self.vendor),
            ("GPU Renderer", self.renderer),
            ("GPU Version", self.version),
        ]

    def _repr_html_(self):
        """HTML table representation."""
        fmt = "<table>"
        row = "<tr><th>{}</th><td>{}</td></tr>\n"
        for meta in self.get_info():
            fmt += row.format(*meta)
        fmt += "</table>"
        return fmt

    def __repr__(self):
        """Representation method."""
        content = "\n"
        for k, v in self.get_info():
            content += f"{k:>18} : {v}\n"
        content += "\n"
        return content


class Report(scooby.Report):
    """Generate a PyVista software environment report.

    Parameters
    ----------
    additional : sequence[types.ModuleType], sequence[str]
        List of packages or package names to add to output information.

    ncol : int, default: 3
        Number of package-columns in html table; only has effect if
        ``mode='HTML'`` or ``mode='html'``.

    text_width : int, default: 80
        The text width for non-HTML display modes.

    sort : bool, default: False
        Alphabetically sort the packages.

    gpu : bool, default: True
        Gather information about the GPU. Defaults to ``True`` but if
        experiencing rendering issues, pass ``False`` to safely generate a
        report.

    Examples
    --------
    >>> import pyvista as pv
    >>> pv.Report()  # doctest:+SKIP
      Date: Fri Oct 28 15:54:11 2022 MDT
    <BLANKLINE>
                    OS : Linux
                CPU(s) : 6
               Machine : x86_64
          Architecture : 64bit
                   RAM : 62.6 GiB
           Environment : IPython
           File system : ext4
            GPU Vendor : NVIDIA Corporation
          GPU Renderer : Quadro P2000/PCIe/SSE2
           GPU Version : 4.5.0 NVIDIA 470.141.03
    <BLANKLINE>
      Python 3.8.10 (default, Jun 22 2022, 20:18:18)  [GCC 9.4.0]
    <BLANKLINE>
               pyvista : 0.37.dev0
                   vtk : 9.1.0
                 numpy : 1.23.3
               imageio : 2.22.0
                scooby : 0.7.1.dev1+gf097dad
                 pooch : v1.6.0
            matplotlib : 3.6.0
               IPython : 7.31.0
              colorcet : 3.0.1
               cmocean : 2.0
                 scipy : 1.9.1
                  tqdm : 4.64.1
                meshio : 5.3.4
            jupyterlab : 3.4.7

    """

    def __init__(self, additional=None, ncol=3, text_width=80, sort=False, gpu=True):
        """Generate a :class:`scooby.Report` instance."""
        from pyvista.plotting.tools import check_math_text_support

        # Mandatory packages
        core = ['pyvista', 'vtk', 'numpy', 'matplotlib', 'scooby', 'pooch', 'pillow']

        # Optional packages.
        optional = [
            'imageio',
            'pyvistaqt',
            'PyQt5',
            'IPython',
            'colorcet',
            'cmocean',
            'ipywidgets',
            'scipy',
            'tqdm',
            'meshio',
            'jupyterlab',
            'pytest_pyvista',
            'trame',
            'trame_client',
            'trame_server',
            'trame_vtk',
            'trame_vuetify',
            'jupyter_server_proxy',
            'nest_asyncio',
        ]

        # Information about the GPU - bare except in case there is a rendering
        # bug that the user is trying to report.
        if gpu:
            try:
                extra_meta = GPUInfo().get_info()
            except:
                extra_meta = [
                    ("GPU Details", "error"),
                ]
        else:
            extra_meta = [
                ("GPU Details", "None"),
            ]

        extra_meta.append(('MathText Support', check_math_text_support()))

        scooby.Report.__init__(
            self,
            additional=additional,
            core=core,
            optional=optional,
            ncol=ncol,
            text_width=text_width,
            sort=sort,
            extra_meta=extra_meta,
        )


# pyvista/trame/__init__.py

"""Trame interface for PyVista."""
import logging

logging.getLogger('trame.app').disabled = True

from pyvista.trame.jupyter import elegantly_launch, launch_server, show_trame
from pyvista.trame.ui import get_or_create_viewer, plotter_ui
from pyvista.trame.views import PyVistaLocalView, PyVistaRemoteLocalView, PyVistaRemoteView

# __all__ only left for mypy --strict to work when pyvista is a dependency
__all__ = [
    'elegantly_launch',
    'get_or_create_viewer',
    'launch_server',
    'plotter_ui',
    'show_trame',
    'PyVistaLocalView',
    'PyVistaRemoteLocalView',
    'PyVistaRemoteView',
]


# pyvista/trame/jupyter.py

"""Trame utilities for running in Jupyter."""
import asyncio
import logging
import os
import warnings

from trame.ui.vuetify import VAppLayout
from trame.widgets import html as html_widgets, vtk as vtk_widgets, vuetify as vuetify_widgets

try:
    from ipywidgets.widgets import HTML
except ImportError:
    HTML = object


import pyvista
from pyvista.trame.ui import UI_TITLE, get_or_create_viewer
from pyvista.trame.views import CLOSED_PLOTTER_ERROR, get_server

SERVER_DOWN_MESSAGE = """Trame server has not launched.

You must start the trame server before attempting to `show()`
with PyVista.

You can use the following snippet to launch the server:

    from pyvista.trame.jupyter import launch_server
    await launch_server('{name}').ready

"""
JUPYTER_SERVER_DOWN_MESSAGE = """Trame server has not launched.

Prior to plotting, please make sure to run `set_jupyter_backend('trame')` when using the `'trame'`, `'server'`, or `'client'` Jupyter backends.

    import pyvista as pv
    pv.set_jupyter_backend('trame')

If this issue persists, please open an issue in PyVista: https://github.com/pyvista/pyvista/issues

"""

logger = logging.getLogger(__name__)


class TrameServerDownError(RuntimeError):  # numpydoc ignore=PR01
    """Exception when trame server is down for Jupyter."""

    def __init__(self, server_name):
        """Call the base class constructor with the custom message."""
        super().__init__(SERVER_DOWN_MESSAGE.format(name=server_name))


class TrameJupyterServerDownError(RuntimeError):
    """Exception when trame server is down for Jupyter."""

    def __init__(self):
        """Call the base class constructor with the custom message."""
        # Be incredibly verbose on how users should launch trame server
        # Both warn so it appears at top
        warnings.warn(JUPYTER_SERVER_DOWN_MESSAGE)
        # and Error
        super().__init__(JUPYTER_SERVER_DOWN_MESSAGE)


class Widget(HTML):  # numpydoc ignore=PR01
    """Custom HTML iframe widget for trame viewer."""

    def __init__(self, viewer, src, width, height, **kwargs):
        """Initialize."""
        if HTML is object:
            raise ImportError('Please install `ipywidgets`.')
        value = f"<iframe src='{src}' style='width: {width}; height: {height};'></iframe>"
        super().__init__(value, **kwargs)
        self._viewer = viewer
        self._src = src

    @property
    def viewer(self):  # numpydoc ignore=RT01
        """Get the associated viewer instance."""
        return self._viewer

    @property
    def src(self):  # numpydoc ignore=RT01
        """Get the src URL."""
        return self._src


def launch_server(server=None, port=None, host=None):
    """Launch a trame server for use with Jupyter.

    Parameters
    ----------
    server : str, optional
        By default this uses :attr:`pyvista.global_theme.trame.jupyter_server_name
        <pyvista.plotting.themes._TrameConfig.jupyter_server_name>`, which by default is
        set to ``'pyvista-jupyter'``.

        If a server name is given and such server is not available yet, it will
        be created otherwise the previously created instance will be returned.

    port : int, optional
        The port on which to bind the server. Defaults to 0 to automatically
        find an available port.

    host : str, optional
        The host name to bind the server to on launch. Server will bind to
        ``127.0.0.1`` by default unless user sets the environment variable ``TRAME_DEFAULT_HOST``.

    Returns
    -------
    trame_server.core.Server
        The launched Trame server. To ``await`` the launch, use the
        ``.ready`` future attribute on the server.

    """
    if server is None:
        server = pyvista.global_theme.trame.jupyter_server_name
    if isinstance(server, str):
        server = get_server(server)
    if port is None:
        port = pyvista.global_theme.trame.jupyter_server_port
    if host is None:
        # Default to `127.0.0.1` unless user sets TRAME_DEFAULT_HOST
        host = os.environ.get('TRAME_DEFAULT_HOST', '127.0.0.1')

    # Must enable all used modules
    html_widgets.initialize(server)
    vtk_widgets.initialize(server)
    vuetify_widgets.initialize(server)

    def on_ready(**_):  # numpydoc ignore=GL08
        logger.debug(f'Server ready: {server}')

    if server._running_stage == 0:
        server.controller.on_server_ready.add(on_ready)
        server.start(
            exec_mode='task',
            host=host,
            port=port,
            open_browser=False,
            show_connection_info=False,
            disable_logging=True,
            timeout=0,
        )
    # else, server is already running or launching
    return server


def build_url(
    _server,
    ui=None,
    server_proxy_enabled=None,
    server_proxy_prefix=None,
    host='localhost',
    protocol='http',
):  # numpydoc ignore=PR01,RT01
    """Build the URL for the iframe."""
    params = f'?ui={ui}&reconnect=auto' if ui else '?reconnect=auto'
    if server_proxy_enabled is None:
        server_proxy_enabled = pyvista.global_theme.trame.server_proxy_enabled
    if server_proxy_enabled:
        if server_proxy_prefix is None:
            server_proxy_prefix = pyvista.global_theme.trame.server_proxy_prefix
        # server_proxy_prefix assumes trailing slash
        src = (
            f"{server_proxy_prefix if server_proxy_prefix else ''}{_server.port}/index.html{params}"
        )
    else:
        src = f'{protocol}://{host}:{_server.port}/index.html{params}'
    logger.debug(src)
    return src


def initialize(
    server, plotter, mode=None, default_server_rendering=True, collapse_menu=False, **kwargs
):  # numpydoc ignore=PR01,RT01
    """Generate the UI for a given plotter."""
    state = server.state
    state.trame__title = UI_TITLE

    viewer = get_or_create_viewer(plotter, suppress_rendering=mode == 'client')

    with VAppLayout(server, template_name=plotter._id_name):
        viewer.ui(
            mode=mode,
            default_server_rendering=default_server_rendering,
            collapse_menu=collapse_menu,
            **kwargs,
        )

    return viewer


def show_trame(
    plotter,
    mode=None,
    name=None,
    server_proxy_enabled=None,
    server_proxy_prefix=None,
    collapse_menu=False,
    add_menu=True,
    default_server_rendering=True,
    handler=None,
    **kwargs,
):
    """Run and display the trame application in jupyter's event loop.

    Parameters
    ----------
    plotter : pyvista.Plotter
        The PyVista plotter to show.

    mode : str, optional
        The UI view mode. This can be set on the global theme. Options are:

        * ``'trame'``: Uses a view that can switch between client and server
          rendering modes.
        * ``'server'``: Uses a view that is purely server rendering.
        * ``'client'``: Uses a view that is purely client rendering (generally
          safe without a virtual frame buffer)

    name : str, optional
        The name of the trame server on which the UI is defined.

    server_proxy_enabled : bool, default: False
        Build a relative URL for use with ``jupyter-server-proxy``.

    server_proxy_prefix : str, optional
        URL prefix when using ``server_proxy_enabled``. This can be set
        globally in the theme. To ignore, pass ``False``. For use with
        ``jupyter-server-proxy``, often set to ``proxy/``.

    collapse_menu : bool, default: False
        Collapse the UI menu (camera controls, etc.) on start.

    add_menu : bool, default: True
        Add a UI controls VCard to the VContainer.

    default_server_rendering : bool, default: True
        Whether to use server-side or client-side rendering on-start when
        using the ``'trame'`` mode.

    handler : callable, optional
        Pass a callable that accptes the viewer instance, the string URL,
        and ``**kwargs`` to create custom HTML representations of the output.

        .. code:: python

            import pyvista as pv
            from IPython.display import IFrame

            mesh = pv.Wavelet()


            def handler(viewer, src, **kwargs):
                return IFrame(src, '75%', '500px')


            p = pv.Plotter(notebook=True)
            _ = p.add_mesh(mesh)
            iframe = p.show(
                jupyter_backend='trame',
                jupyter_kwargs=dict(handler=handler),
                return_viewer=True,
            )
            iframe

    **kwargs : dict, optional
        Mostly ignored, though ``protocol`` and ``host`` can be use to
        override the iframe src url and ``height`` and ``width`` can be
        used to override the iframe style. Remaining kwargs are passed to
        ``ipywidgets.widgets.HTML``.

    Returns
    -------
    ipywidgets.widgets.HTML or handler result
        Returns a HTML IFrame widget or the result of the passed handler.

    """
    if plotter.render_window is None:
        raise RuntimeError(CLOSED_PLOTTER_ERROR)

    if name is None:
        server = get_server(name=pyvista.global_theme.trame.jupyter_server_name)
    else:
        server = get_server(name=name)
    if name is None and not server.running:
        elegantly_launch(server)
        if not server.running:
            raise TrameJupyterServerDownError()
    elif not server.running:
        raise TrameServerDownError(name)

    # Initialize app
    viewer = initialize(
        server,
        plotter,
        mode=mode,
        default_server_rendering=default_server_rendering,
        collapse_menu=collapse_menu,
        add_menu=add_menu,
    )

    # Show as cell result
    src = build_url(
        server,
        ui=plotter._id_name,
        server_proxy_enabled=server_proxy_enabled,
        server_proxy_prefix=server_proxy_prefix,
        host=kwargs.get('host', 'localhost'),
        protocol=kwargs.get('protocol', 'http'),
    )

    if plotter._window_size_unset:
        dw, dh = '99%', '600px'
    else:
        dw, dh = plotter.window_size
        dw = f'{dw}px'
        dh = f'{dh}px'
    kwargs.setdefault('width', dw)
    kwargs.setdefault('height', dh)

    if callable(handler):
        return handler(viewer, src, **kwargs)
    return Widget(viewer, src, **kwargs)


def elegantly_launch(*args, **kwargs):  # numpydoc ignore=PR01
    """Elegantly launch the Trame server without await.

    This provides a mechanism to launch the Trame Jupyter backend in
    a way that does not require users to await the call.

    This is a thin wrapper of
    :func:`launch_server() <pyvista.trame.jupyter.launch_server>`.

    Returns
    -------
    trame_server.core.Server
        The launched trame server.

    Warnings
    --------
    This uses `nest_asyncio <https://github.com/erdewit/nest_asyncio>`_ which
    patches the standard lib `asyncio` package and may have unintended
    consequences for some uses cases. We advise strongly to make sure PyVista's
    Jupyter backend is not set to use Trame when not in a Jupyter environment.

    """
    try:
        import nest_asyncio
    except ImportError:
        raise ImportError(
            """Please install `nest_asyncio` to automagically launch the trame server without await. Or, to avoid `nest_asynctio` run:

    from pyvista.trame.jupyter import launch_server
    await launch_server().ready
"""
        )

    async def launch_it():  # numpydoc ignore=GL08
        await launch_server(*args, **kwargs).ready

    # Basically monkey patches asyncio to support this
    nest_asyncio.apply()

    return asyncio.run(launch_it())


# pyvista/trame/views.py

"""Trame view interface for PyVista."""
import io
import weakref

from trame.app import get_server as trame_get_server
from trame.widgets.vtk import VtkLocalView, VtkRemoteLocalView, VtkRemoteView
from trame_vtk.tools.vtksz2html import write_html

CLOSED_PLOTTER_ERROR = "The render window for this plotter has been destroyed. Do not call `show()` for the plotter before passing to trame."


def get_server(*args, **kwargs):  # numpydoc ignore=RT01
    """Override trame's get_server.

    Parameters
    ----------
    *args :
        Any extra args are passed as option to the server instance.

    **kwargs :
        Any extra keyword args are passed as option to the server instance.

    Returns
    -------
    trame_server.core.Server
        Trame server.
    """
    server = trame_get_server(*args, **kwargs)
    server.client_type = 'vue2'
    return server


class _BasePyVistaView:
    def __init__(self, plotter):
        """Initialize the base PyVista view."""
        self._plotter = weakref.ref(plotter)
        self.pyvista_initialize()
        self._plotter_render_callback = lambda *args: self.update()

    def pyvista_initialize(self):
        if self._plotter().render_window is None:
            raise RuntimeError(CLOSED_PLOTTER_ERROR)
        for renderer in self._plotter().renderers:
            if not renderer.camera.is_set:
                renderer.camera_position = renderer.get_default_cam_pos()
                renderer.ResetCamera()

    def _post_initialize(self):
        if self._server.running:
            self.update()
        else:
            self._server.controller.on_server_ready.add(self.update)

        # Callback to sync view on PyVista's render call when renders are suppressed
        self._plotter().add_on_render_callback(self._plotter_render_callback, render_event=False)

    def update_camera(self):
        """Update camera or push the image."""
        self.push_camera()
        self.update_image()

    def export_html(self):
        """Export scene to HTML as StringIO buffer."""
        content = io.StringIO()
        if isinstance(self, PyVistaLocalView):
            data = self.export(format="zip")
            write_html(data, content)
            content.seek(0)
        elif isinstance(self, PyVistaRemoteLocalView):
            data = self.export_geometry(format="zip")
            write_html(data, content)
            content.seek(0)
        else:
            content = self._plotter().export_html(filename=None)
        return io.BytesIO(content.read().encode('utf8')).read()


class PyVistaRemoteView(VtkRemoteView, _BasePyVistaView):
    """PyVista wrapping of trame ``VtkRemoteView`` for server rendering.

    This will connect to a PyVista plotter and stream the server-side
    renderings.

    Parameters
    ----------
    plotter : pyvista.Plotter
        The PyVista Plotter to display in the output view.

    interactive_ratio : int, optional
        Image size scale factor while interacting. Increasing this
        value will give higher resulotuion images during interaction
        events at the cost of performance. Use lower values (e.g.,
        ``0.5``) to increase performance while interacting.
        Defaults to 1.

    still_ratio : int, optional
        Image size scale factor while not interacting (still).
        Increasing this value will give higher resulotuion images
        when not interacting with the scene. Defaults to 1.

    namespace : str, optional
        The namespace for this view component. A default value is
        chosen based on the ``_id_name`` of the plotter.

    **kwargs : dict, optional
        Any additional keyword arguments to pass to
        ``trame.widgets.vtk.VtkRemoteView``.

    Notes
    -----
    For optimal rendering results, you may want to have the same
    value for ``interactive_ratio`` and ``still_ratio`` so that
    the entire rendering is not re-scaled between interaction events.

    """

    def __init__(
        self, plotter, interactive_ratio=None, still_ratio=None, namespace=None, **kwargs
    ):  # numpydoc ignore=PR01,RT01
        """Create a trame remote view from a PyVista Plotter."""
        _BasePyVistaView.__init__(self, plotter)
        if namespace is None:
            namespace = f'{plotter._id_name}'
        if interactive_ratio is None:
            interactive_ratio = plotter._theme.trame.interactive_ratio
        if still_ratio is None:
            still_ratio = plotter._theme.trame.still_ratio
        VtkRemoteView.__init__(
            self,
            self._plotter().render_window,
            interactive_ratio=interactive_ratio,
            still_ratio=still_ratio,
            __properties=[('still_ratio', 'stillRatio')],
            ref=f'view_{plotter._id_name}',
            namespace=namespace,
            **kwargs,
        )
        self._post_initialize()

    def push_camera(self, *args, **kwargs):
        """No-op implementation to match local viewers."""
        pass  # pragma: no cover

    def update_image(self, *args, **kwargs):
        """Wrap update call."""
        return self.update(*args, **kwargs)


class PyVistaLocalView(VtkLocalView, _BasePyVistaView):
    """PyVista wrapping of trame VtkLocalView for in-browser rendering.

    This will connect to and synchronize with a PyVista plotter to
    perform client-side rendering with VTK.js in the browser.

    Parameters
    ----------
    plotter : pyvista.Plotter
        The PyVista Plotter to represent in the output view.

    namespace : str, optional
        The namespace for this view component. A default value is
        chosen based on the ``_id_name`` of the plotter.

    **kwargs : dict, optional
        Any additional keyword arguments to pass to
        ``trame.widgets.vtk.VtkLocalView``.

    """

    def __init__(self, plotter, namespace=None, **kwargs):
        """Create a trame local view from a PyVista Plotter."""
        _BasePyVistaView.__init__(self, plotter)
        if namespace is None:
            namespace = f'{plotter._id_name}'
        VtkLocalView.__init__(
            self,
            self._plotter().render_window,
            ref=f'view_{plotter._id_name}',
            namespace=namespace,
            **kwargs,
        )
        self._post_initialize()

    def _post_initialize(self):
        super()._post_initialize()
        self.set_widgets(
            [ren.axes_widget for ren in self._plotter().renderers if hasattr(ren, 'axes_widget')]
        )

    def update_image(self, *args, **kwargs):
        """No-op implementation to match remote viewers."""
        pass  # pragma: no cover


class PyVistaRemoteLocalView(VtkRemoteLocalView, _BasePyVistaView):
    """PyVista wrapping of trame ``VtkRemoteLocalView``.

    Dynamically switch between client and server rendering.

    Parameters
    ----------
    plotter : pyvista.Plotter
        The PyVista Plotter to display in the output view.

    interactive_ratio : int, optional
        Image size scale factor while interacting. Increasing this
        value will give higher resulotuion images during interaction
        events at the cost of performance. Use lower values (e.g.,
        ``0.5``) to increase performance while interacting.
        Defaults to 1. This is only valid in the ``'remote'`` mode.

    still_ratio : int, optional
        Image size scale factor while not interacting (still).
        Increasing this value will give higher resulotuion images
        when not interacting with the scene. Defaults to 1.
        This is only valid in the ``'remote'`` mode.

    namespace : str, optional
        The namespace for this view component. A default value is
        chosen based on the ``_id_name`` of the plotter.

    **kwargs : dict, optional
        Any additional keyword arguments to pass to
        ``trame.widgets.vtk.VtkRemoteLocalView``.

    """

    def __init__(
        self, plotter, interactive_ratio=None, still_ratio=None, namespace=None, **kwargs
    ):  # numpydoc ignore=PR01,RT01
        """Create a trame remote/local view from a PyVista Plotter."""
        _BasePyVistaView.__init__(self, plotter)
        if namespace is None:
            namespace = f'{plotter._id_name}'
        if interactive_ratio is None:
            interactive_ratio = plotter._theme.trame.interactive_ratio
        if still_ratio is None:
            still_ratio = plotter._theme.trame.still_ratio
        VtkRemoteLocalView.__init__(
            self,
            self._plotter().render_window,
            interactive_ratio=interactive_ratio,
            still_ratio=still_ratio,
            __properties=[('still_ratio', 'stillRatio')],
            ref=f'view_{plotter._id_name}',
            namespace=namespace,
            **kwargs,
        )
        # Track namespace for our use since trame attributes are name mangled
        self._namespace = namespace

        self._post_initialize()

    def _post_initialize(self):
        super()._post_initialize()
        self.set_widgets(
            [ren.axes_widget for ren in self._plotter().renderers if hasattr(ren, 'axes_widget')]
        )


# pyvista/trame/ui/base_viewer.py
# flake8: noqa: D102,D103,D107
"""PyVista Trame Base Viewer class.

This base class defines methods to manipulate a PyVista Plotter.
This base class does not define a `ui` method, but its derived classes do.
See `pyvista.trame.ui.vuetify2` and ``pyvista.trame.ui.vuetify3` for its derived classes.
"""
import io

from trame.app import get_server
from trame.widgets import html

import pyvista


class BaseViewer:
    """Internal wrapper to sync trame view with Plotter.

    Parameters
    ----------
    plotter : pyvista.Plotter
        Target Plotter instance to view.
    server : trame.Server, optional
        Current Server for Trame Application.
    suppress_rendering : bool, default=False
        Whether to suppress rendering on the Plotter.
    """

    def __init__(self, plotter, server=None, suppress_rendering=False):
        """Initialize Viewer."""
        self._html_views = set()

        if server is None:
            server = get_server()
        self.server = server
        self.plotter = plotter
        self.plotter.suppress_rendering = suppress_rendering

        # State variable names
        self.SHOW_UI = f'{plotter._id_name}_show_ui'
        self.GRID = f'{plotter._id_name}_grid_visibility'
        self.OUTLINE = f'{plotter._id_name}_outline_visibility'
        self.EDGES = f'{plotter._id_name}_edge_visibility'
        self.AXIS = f'{plotter._id_name}_axis_visiblity'
        self.SERVER_RENDERING = f'{plotter._id_name}_use_server_rendering'
        self.VALID_UI_MODES = [
            'trame',
            'client',
            'server',
        ]

    @property
    def views(self):  # numpydoc ignore=RT01
        """Get a set of all associate trame views for this viewer."""
        return self._html_views

    def update(self, **kwargs):
        """Update all associated views.

        Parameters
        ----------
        **kwargs : dict, optional
            Unused keyword arguments.

        """
        for view in self._html_views:
            view.update()

    def push_camera(self, **kwargs):
        """Push camera to all associated views.

        Parameters
        ----------
        **kwargs : dict, optional
            Unused keyword arguments.

        """
        for view in self._html_views:
            view.push_camera()

    def reset_camera(self, **kwargs):
        """Reset camera for all associated views.

        Parameters
        ----------
        **kwargs : dict, optional
            Unused keyword arguments.

        """
        for view in self._html_views:
            view.reset_camera()

    def update_image(self, **kwargs):
        """Update image for all associated views.

        Parameters
        ----------
        **kwargs : dict, optional
            Unused keyword arguments.

        """
        for view in self._html_views:
            view.update_image()

    def update_camera(self, **kwargs):
        """Update image and camera for all associated views.

        Parameters
        ----------
        **kwargs : dict, optional
            Unused keyword arguments.

        """
        for view in self._html_views:
            view.update_camera()

    def view_isometric(self):
        """View isometric."""
        self.plotter.view_isometric(render=False)
        self.update_camera()

    def view_yz(self):
        """View YZ plane."""
        self.plotter.view_yz(render=False)
        self.update_camera()

    def view_xz(self):
        """View XZ plane."""
        self.plotter.view_xz(render=False)
        self.update_camera()

    def view_xy(self):
        """View XY plane."""
        self.plotter.view_xy(render=False)
        self.update_camera()

    def on_edge_visiblity_change(self, **kwargs):
        """Toggle edge visibility for all actors.

        Parameters
        ----------
        **kwargs : dict, optional
            Unused keyword arguments.

        """
        value = kwargs[self.EDGES]
        for renderer in self.plotter.renderers:
            for _, actor in renderer.actors.items():
                if isinstance(actor, pyvista.Actor):
                    actor.prop.show_edges = value
        self.update()

    def on_grid_visiblity_change(self, **kwargs):
        """Handle axes grid visibility.

        Parameters
        ----------
        **kwargs : dict, optional
            Unused keyword arguments.

        """
        value = kwargs[self.GRID]
        for renderer in self.plotter.renderers:
            if value:
                renderer.show_grid()
            else:
                renderer.remove_bounds_axes()
        self.update()

    def on_outline_visiblity_change(self, **kwargs):
        """Handle outline visibility.

        Parameters
        ----------
        **kwargs : dict, optional
            Unused keyword arguments.

        """
        value = kwargs[self.OUTLINE]
        for renderer in self.plotter.renderers:
            if value:
                renderer.add_bounding_box(reset_camera=False)
            else:
                renderer.remove_bounding_box()
        self.update()

    def on_axis_visiblity_change(self, **kwargs):
        """Handle outline visibility.

        Parameters
        ----------
        **kwargs : dict, optional
            Unused keyword arguments.

        """
        value = kwargs[self.AXIS]
        for renderer in self.plotter.renderers:
            if value:
                renderer.show_axes()
            else:
                renderer.hide_axes()
        for view in self._html_views:
            if view.set_widgets:
                # VtkRemoteView does not have set_widgets function, but VtkRemoteLocalView and VtkLocalView do.
                view.set_widgets(
                    [
                        ren.axes_widget
                        for ren in self.plotter.renderers
                        if hasattr(ren, 'axes_widget')
                    ]
                )
        self.update()

    def on_rendering_mode_change(self, **kwargs):
        """Handle any configurations when the render mode changes between client and server.

        Parameters
        ----------
        **kwargs : dict, optional
            Unused keyword arguments.

        """
        if not kwargs[self.SERVER_RENDERING]:
            self.update_camera()

    @property
    def actors(self):  # numpydoc ignore=RT01
        """Get dataset actors."""
        return {k: v for k, v in self.plotter.actors.items() if isinstance(v, pyvista.Actor)}

    def screenshot(self):
        """Take screenshot and add attachament.

        Returns
        -------
        memoryview
            Screenshot as a ``memoryview``.

        """
        self.plotter.render()
        self.update()  # makes sure the plotter and views are in sync
        buffer = io.BytesIO()
        self.plotter.screenshot(filename=buffer)
        buffer.seek(0)
        return memoryview(buffer.read())

    def export(self):  # numpydoc ignore=RT01
        """Export the scene as a zip file."""
        for view in self._html_views:
            return memoryview(view.export_html())
        raise TypeError('This viewer cannot be exported.')

    def ui(self):
        """Implement in derived classes."""
        raise NotImplementedError()
