m_paths(image_paths):
    """Construct a cubemap from image paths."""
    for image_path in image_paths:
        if not os.path.isfile(image_path):
            file_str = '\n'.join(image_paths)
            raise FileNotFoundError(
                f'Unable to locate {image_path}\n'
                'Expected to find the following files:\n'
                f'{file_str}'
            )

    texture = pyvista.Texture()
    texture.SetMipmap(True)
    texture.SetInterpolate(True)
    texture.cube_map = True  # Must be set prior to setting images

    # add each image to the cubemap
    for i, fn in enumerate(image_paths):
        image = pyvista.read(fn)
        flip = _vtk.vtkImageFlip()
        flip.SetInputDataObject(image)
        flip.SetFilteredAxis(1)  # flip y axis
        flip.Update()
        texture.SetInputDataObject(i, flip.GetOutput())

    return texture


def set_default_active_vectors(mesh: 'pyvista.DataSet') -> None:
    """Set a default vectors array on mesh, if not already set.

    If an active vector already exists, no changes are made.

    If an active vectors does not exist, it checks for possibly cell
    or point arrays with shape ``(n, 3)``.  If only one exists, then
    it is set as the active vectors.  Otherwise, an error is raised.

    Parameters
    ----------
    mesh : pyvista.DataSet
        Dataset to set default active vectors.

    Raises
    ------
    MissingDataError
        If no vector-like arrays exist.

    AmbiguousDataError
        If more than one vector-like arrays exist.

    """
    if mesh.active_vectors_name is not None:
        return

    point_data = mesh.point_data
    cell_data = mesh.cell_data

    possible_vectors_point = [
        name for name, value in point_data.items() if value.ndim == 2 and value.shape[1] == 3
    ]
    possible_vectors_cell = [
        name for name, value in cell_data.items() if value.ndim == 2 and value.shape[1] == 3
    ]

    possible_vectors = possible_vectors_point + possible_vectors_cell
    n_possible_vectors = len(possible_vectors)

    if n_possible_vectors == 1:
        if len(possible_vectors_point) == 1:
            preference = 'point'
        else:
            preference = 'cell'
        mesh.set_active_vectors(possible_vectors[0], preference=preference)
    elif n_possible_vectors < 1:
        raise MissingDataError("No vector-like data available.")
    elif n_possible_vectors > 1:
        raise AmbiguousDataError(
            "Multiple vector-like data available\n"
            f"cell data: {possible_vectors_cell}.\n"
            f"point data: {possible_vectors_point}.\n"
            "Set one as active using DataSet.set_active_vectors(name, preference=type)"
        )


def set_default_active_scalars(mesh: 'pyvista.DataSet') -> None:
    """Set a default scalars array on mesh, if not already set.

    If an active scalars already exists, no changes are made.

    If an active scalars does not exist, it checks for point or cell
    arrays.  If only one exists, then it is set as the active scalars.
    Otherwise, an error is raised.

    Parameters
    ----------
    mesh : pyvista.DataSet
        Dataset to set default active scalars.

    Raises
    ------
    MissingDataError
        If no arrays exist.

    AmbiguousDataError
        If more than one array exists.

    """
    if mesh.active_scalars_name is not None:
        return

    point_data = mesh.point_data
    cell_data = mesh.cell_data

    possible_scalars_point = point_data.keys()
    possible_scalars_cell = cell_data.keys()

    possible_scalars = possible_scalars_point + possible_scalars_cell
    n_possible_scalars = len(possible_scalars)

    if n_possible_scalars == 1:
        if len(possible_scalars_point) == 1:
            preference = 'point'
        else:
            preference = 'cell'
        mesh.set_active_scalars(possible_scalars[0], preference=preference)
    elif n_possible_scalars < 1:
        raise MissingDataError("No data available.")
    elif n_possible_scalars > 1:
        raise AmbiguousDataError(
            "Multiple data available\n"
            f"cell data: {possible_scalars_cell}.\n"
            f"point data: {possible_scalars_point}.\n"
            "Set one as active using DataSet.set_active_scalars(name, preference=type)"
        )


# pyvista/utilities/misc.py

"""Miscellaneous pyvista functions."""
from collections import namedtuple
from functools import lru_cache
import importlib
import os
import warnings

import numpy as np

from pyvista import _vtk


def _set_plot_theme_from_env():
    """Set plot theme from an environment variable."""
    from pyvista.themes import _ALLOWED_THEMES, set_plot_theme

    if 'PYVISTA_PLOT_THEME' in os.environ:
        try:
            theme = os.environ['PYVISTA_PLOT_THEME']
            set_plot_theme(theme.lower())
        except KeyError:
            allowed = ', '.join([item.name for item in _ALLOWED_THEMES])
            warnings.warn(
                f'\n\nInvalid PYVISTA_PLOT_THEME environment variable "{theme}". '
                f'Should be one of the following: {allowed}'
            )


@lru_cache(maxsize=None)
def has_module(module_name):
    """Return if a module can be imported."""
    module_spec = importlib.util.find_spec(module_name)
    return module_spec is not None


def raise_has_duplicates(arr):
    """Raise a ValueError if an array is not unique."""
    if has_duplicates(arr):
        raise ValueError("Array contains duplicate values.")


def has_duplicates(arr):
    """Return if an array has any duplicates."""
    s = np.sort(arr, axis=None)
    return (s[1:] == s[:-1]).any()


def _get_vtk_id_type():
    """Return the numpy datatype responding to ``vtk.vtkIdTypeArray``."""
    VTK_ID_TYPE_SIZE = _vtk.vtkIdTypeArray().GetDataTypeSize()
    if VTK_ID_TYPE_SIZE == 4:
        return np.int32
    elif VTK_ID_TYPE_SIZE == 8:
        return np.int64
    return np.int32


class PyvistaDeprecationWarning(Warning):
    """Non-supressed Depreciation Warning."""

    pass


class PyvistaFutureWarning(Warning):
    """Non-supressed Future Warning."""

    pass


def VTKVersionInfo():
    """Return the vtk version as a namedtuple."""
    version_info = namedtuple('VTKVersionInfo', ['major', 'minor', 'micro'])

    try:
        ver = _vtk.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)


def uses_egl() -> bool:
    """Check if VTK has been compiled with EGL support via OSMesa."""
    ren_win_str = str(type(_vtk.vtkRenderWindow()))
    return 'EGL' in ren_win_str or 'OSOpenGL' in ren_win_str


def copy_vtk_array(array, deep=True):
    """Create a deep or shallow copy of a VTK array.

    Parameters
    ----------
    array : vtk.vtkDataArray or vtk.vtkAbstractArray
        VTK array.

    deep : bool, optional
        When ``True``, create a deep copy of the array. When ``False``, returns
        a shallow copy.

    Returns
    -------
    vtk.vtkDataArray or vtk.vtkAbstractArray
        Copy of the original VTK array.

    Examples
    --------
    Perform a deep copy of a vtk array.

    >>> import vtk
    >>> import pyvista
    >>> arr = vtk.vtkFloatArray()
    >>> _ = arr.SetNumberOfValues(10)
    >>> arr.SetValue(0, 1)
    >>> arr_copy = pyvista.utilities.misc.copy_vtk_array(arr)
    >>> arr_copy.GetValue(0)
    1.0

    """
    if not isinstance(array, (_vtk.vtkDataArray, _vtk.vtkAbstractArray)):
        raise TypeError(f"Invalid type {type(array)}.")

    new_array = type(array)()
    if deep:
        new_array.DeepCopy(array)
    else:
        new_array.ShallowCopy(array)

    return new_array


def can_create_mpl_figure():  # pragma: no cover
    """Return if a figure can be created with matplotlib."""
    try:
        import matplotlib.pyplot as plt

        figure = plt.figure()
        plt.close(figure)
        return True
    except:
        return False


vtk_version_info = VTKVersionInfo()


# pyvista/utilities/parametric_objects.py

"""Module managing parametric objects."""

from math import pi

import numpy as np

import pyvista
from pyvista import _vtk
from pyvista.utilities.errors import check_valid_vector

from .geometric_objects import translate


def Spline(points, n_points=None):
    """Create a spline from points.

    Parameters
    ----------
    points : np.ndarray
        Array of points to build a spline out of.  Array must be 3D
        and directionally ordered.

    n_points : int, optional
        Number of points to interpolate along the points array.

    Returns
    -------
    pyvista.PolyData
        Line mesh of spline.

    Examples
    --------
    Construct a spline.

    >>> import numpy as np
    >>> import pyvista as pv
    >>> theta = np.linspace(-4 * np.pi, 4 * np.pi, 100)
    >>> z = np.linspace(-2, 2, 100)
    >>> r = z**2 + 1
    >>> x = r * np.sin(theta)
    >>> y = r * np.cos(theta)
    >>> points = np.column_stack((x, y, z))
    >>> spline = pv.Spline(points, 1000)
    >>> spline.plot(render_lines_as_tubes=True, line_width=10, show_scalar_bar=False)

    """
    spline_function = _vtk.vtkParametricSpline()
    spline_function.SetPoints(pyvista.vtk_points(points, False))

    # get interpolation density
    u_res = n_points
    if u_res is None:
        u_res = points.shape[0]

    u_res -= 1
    spline = surface_from_para(spline_function, u_res)
    return spline.compute_arc_length()


def KochanekSpline(points, tension=None, bias=None, continuity=None, n_points=None):
    """Create a Kochanek spline from points.

    Parameters
    ----------
    points : sequence
        Array of points to build a Kochanek spline out of.  Array must
        be 3D and directionally ordered.

    tension : sequence, optional
        Changes the length of the tangent vector.  Defaults to ``[0.0,
        0.0, 0.0]``.

    bias : sequence, optional
        Primarily changes the direction of the tangent vector.
        Defaults to ``[0.0, 0.0, 0.0]``.

    continuity : sequence, optional
        Changes the sharpness in change between tangents.  Defaults to
        ``[0.0, 0.0, 0.0]``.

    n_points : int, optional
        Number of points on the spline.  Defaults to the number of
        points in ``points``.

    Returns
    -------
    pyvista.PolyData
        Kochanek spline.

    Examples
    --------
    Construct a Kochanek spline.

    >>> import numpy as np
    >>> import pyvista as pv
    >>> theta = np.linspace(-4 * np.pi, 4 * np.pi, 100)
    >>> z = np.linspace(-2, 2, 100)
    >>> r = z ** 2 + 1
    >>> x = r * np.sin(theta)
    >>> y = r * np.cos(theta)
    >>> points = np.column_stack((x, y, z))
    >>> kochanek_spline = pv.KochanekSpline(points, n_points=6)
    >>> kochanek_spline.plot(line_width=4, color="k")

    See :ref:`create_kochanek_spline_example` for an additional example.

    """
    if tension is None:
        tension = np.array([0.0, 0.0, 0.0])
    check_valid_vector(tension, "tension")
    if not np.all(np.abs(tension) <= 1.0):
        raise ValueError(
            "The absolute value of all values of the tension array elements must be <= 1.0 "
        )

    if bias is None:
        bias = np.array([0.0, 0.0, 0.0])
    check_valid_vector(bias, "bias")
    if not np.all(np.abs(bias) <= 1.0):
        raise ValueError(
            "The absolute value of all values of the bias array elements must be <= 1.0 "
        )

    if continuity is None:
        continuity = np.array([0.0, 0.0, 0.0])
    check_valid_vector(continuity, "continuity")
    if not np.all(np.abs(continuity) <= 1.0):
        raise ValueError(
            "The absolute value of all values continuity array elements must be <= 1.0 "
        )

    spline_function = _vtk.vtkParametricSpline()
    spline_function.SetPoints(pyvista.vtk_points(points, False))

    # set Kochanek spline for each direction
    xspline = _vtk.vtkKochanekSpline()
    yspline = _vtk.vtkKochanekSpline()
    zspline = _vtk.vtkKochanekSpline()
    xspline.SetDefaultBias(bias[0])
    yspline.SetDefaultBias(bias[1])
    zspline.SetDefaultBias(bias[2])
    xspline.SetDefaultTension(tension[0])
    yspline.SetDefaultTension(tension[1])
    zspline.SetDefaultTension(tension[2])
    xspline.SetDefaultContinuity(continuity[0])
    yspline.SetDefaultContinuity(continuity[1])
    zspline.SetDefaultContinuity(continuity[2])
    spline_function.SetXSpline(xspline)
    spline_function.SetYSpline(yspline)
    spline_function.SetZSpline(zspline)

    # get interpolation density
    u_res = n_points
    if u_res is None:
        u_res = points.shape[0]

    u_res -= 1
    spline = surface_from_para(spline_function, u_res)
    return spline.compute_arc_length()


def ParametricBohemianDome(a=None, **kwargs):
    """Generate a Bohemian dome surface.

    Parameters
    ----------
    a : float, optional
        Bohemian dome surface parameter.

    **kwargs : dict, optional
        See :func:`surface_from_para` for additional keyword arguments.

    Returns
    -------
    pyvista.PolyData
        ParametricBohemianDome surface.

    Examples
    --------
    Create a ParametricBohemianDome mesh.

    >>> import pyvista
    >>> mesh = pyvista.ParametricBohemianDome()
    >>> mesh.plot(color='w', smooth_shading=True)

    """
    parametric_function = _vtk.vtkParametricBohemianDome()
    if a is not None:
        parametric_function.SetA(a)

    center = kwargs.pop('center', [0.0, 0.0, 0.0])
    direction = kwargs.pop('direction', [1.0, 0.0, 0.0])
    kwargs.setdefault('clean', True)
    surf = surface_from_para(parametric_function, **kwargs)
    translate(surf, center, direction)
    return surf


def ParametricBour(**kwargs):
    """Generate Bour's minimal surface.

    Parameters
    ----------
    **kwargs : dict, optional
        See :func:`surface_from_para` for additional keyword arguments.

    Returns
    -------
    pyvista.PolyData
        ParametricBour surface.

    Examples
    --------
    Create a ParametricBour mesh.

    >>> import pyvista
    >>> mesh = pyvista.ParametricBour()
    >>> mesh.plot(color='w', smooth_shading=True)

    """
    parametric_function = _vtk.vtkParametricBour()

    center = kwargs.pop('center', [0.0, 0.0, 0.0])
    direction = kwargs.pop('direction', [1.0, 0.0, 0.0])
    surf = surface_from_para(parametric_function, **kwargs)

    translate(surf, center, direction)

    return surf


def ParametricBoy(zscale=None, **kwargs):
    """Generate Boy's surface.

    This is a model of the projective plane without singularities.  It
    was found by Werner Boy on assignment from David Hilbert.

    For further information about this surface, please consult the
    technical description "Parametric surfaces" in the
    "VTK Technical Documents" section in the VTK.org web pages.

    Parameters
    ----------
    zscale : float, optional
        The scale factor for the z-coordinate.

    **kwargs : dict, optional
        See :func:`surface_from_para` for additional keyword arguments.

    Returns
    -------
    pyvista.PolyData
        ParametricBoy surface.

    Examples
    --------
    Create a ParametricBoy mesh.

    >>> import pyvista
    >>> mesh = pyvista.ParametricBoy()
    >>> mesh.plot(color='w', smooth_shading=True)

    """
    parametric_function = _vtk.vtkParametricBoy()
    if zscale is not None:
        parametric_function.SetZScale(zscale)

    center = kwargs.pop('center', [0.0, 0.0, 0.0])
    direction = kwargs.pop('direction', [1.0, 0.0, 0.0])
    kwargs.setdefault('clean', True)
    surf = surface_from_para(parametric_function, **kwargs)
    translate(surf, center, direction)
    return surf


def ParametricCatalanMinimal(**kwargs):
    """Generate Catalan's minimal surface.

    ParametricCatalanMinimal generates Catalan's minimal surface
    parametrically. This minimal surface contains the cycloid as a
    geodesic.

    Parameters
    ----------
    **kwargs : dict, optional
        See :func:`surface_from_para` for additional keyword arguments.

    Returns
    -------
    pyvista.PolyData
        ParametricCatalanMinimal surface.

    Examples
    --------
    Create a ParametricCatalanMinimal mesh.

    >>> import pyvista
    >>> mesh = pyvista.ParametricCatalanMinimal()
    >>> mesh.plot(color='w', smooth_shading=True)

    """
    parametric_function = _vtk.vtkParametricCatalanMinimal()

    center = kwargs.pop('center', [0.0, 0.0, 0.0])
    direction = kwargs.pop('direction', [1.0, 0.0, 0.0])
    surf = surface_from_para(parametric_function, **kwargs)

    translate(surf, center, direction)

    return surf


def ParametricConicSpiral(a=None, b=None, c=None, n=None, **kwargs):
    """Generate conic spiral surfaces that resemble sea-shells.

    ParametricConicSpiral generates conic spiral surfaces. These can
    resemble sea shells, or may look like a torus "eating" its own
    tail.

    Parameters
    ----------
    a : float, optional
        The scale factor.
        Default is 0.2.

    b : float, optional
        The A function coefficient.
        See the definition in Parametric surfaces referred to above.
        Default is 1.

    c : float, optional
        The B function coefficient.
        See the definition in Parametric surfaces referred to above.
        Default is 0.1.

    n : float, optional
        The C function coefficient.
        See the definition in Parametric surfaces referred to above.
        Default is 2.

    **kwargs : dict, optional
        See :func:`surface_from_para` for additional keyword arguments.

    Returns
    -------
    pyvista.PolyData
        ParametricConicSpiral surface.

    Examples
    --------
    Create a ParametricConicSpiral mesh.

    >>> import pyvista
    >>> mesh = pyvista.ParametricConicSpiral()
    >>> mesh.plot(color='w', smooth_shading=True)

    """
    parametric_function = _vtk.vtkParametricConicSpiral()
    if a is not None:
        parametric_function.SetA(a)

    if b is not None:
        parametric_function.SetB(b)

    if c is not None:
        parametric_function.SetC(c)

    if n is not None:
        parametric_function.SetN(n)

    center = kwargs.pop('center', [0.0, 0.0, 0.0])
    direction = kwargs.pop('direction', [1.0, 0.0, 0.0])
    surf = surface_from_para(parametric_function, **kwargs)

    translate(surf, center, direction)

    return surf


def ParametricCrossCap(**kwargs):
    """Generate a cross-cap.

    ParametricCrossCap generates a cross-cap which is a non-orientable
    self-intersecting single-sided surface.  This is one possible
    image of a projective plane in three-space.

    Parameters
    ----------
    **kwargs : dict, optional
        See :func:`surface_from_para` for additional keyword arguments.

    Returns
    -------
    pyvista.PolyData
        ParametricCrossCap surface.

    Examples
    --------
    Create a ParametricCrossCap mesh.

    >>> import pyvista
    >>> mesh = pyvista.ParametricCrossCap()
    >>> mesh.plot(color='w', smooth_shading=True)

    """
    parametric_function = _vtk.vtkParametricCrossCap()

    center = kwargs.pop('center', [0.0, 0.0, 0.0])
    direction = kwargs.pop('direction', [1.0, 0.0, 0.0])
    surf = surface_from_para(parametric_function, **kwargs)

    translate(surf, center, direction)

    return surf


def ParametricDini(a=None, b=None, **kwargs):
    """Generate Dini's surface.

    ParametricDini generates Dini's surface.  Dini's surface is a
    surface that possesses constant negative Gaussian curvature

    Parameters
    ----------
    a : float, optional
        The scale factor.  See the definition in Parametric surfaces
        referred to above.  Default is 1.

    b : float, optional
        The scale factor.  See the definition in Parametric surfaces
        referred to above.  Default is 0.2.

    **kwargs : dict, optional
        See :func:`surface_from_para` for additional keyword arguments.

    Returns
    -------
    pyvista.PolyData
        ParametricDini surface.

    Examples
    --------
    Create a ParametricDini mesh.

    >>> import pyvista
    >>> mesh = pyvista.ParametricDini()
    >>> mesh.plot(color='w', smooth_shading=True)

    """
    parametric_function = _vtk.vtkParametricDini()
    if a is not None:
        parametric_function.SetA(a)

    if b is not None:
        parametric_function.SetB(b)

    center = kwargs.pop('center', [0.0, 0.0, 0.0])
    direction = kwargs.pop('direction', [1.0, 0.0, 0.0])
    surf = surface_from_para(parametric_function, **kwargs)

    translate(surf, center, direction)

    return surf


def ParametricEllipsoid(xradius=None, yradius=None, zradius=None, **kwargs):
    """Generate an ellipsoid.

    ParametricEllipsoid generates an ellipsoid.  If all the radii are
    the same, we have a sphere.  An oblate spheroid occurs if RadiusX
    = RadiusY > RadiusZ.  Here the Z-axis forms the symmetry axis. To
    a first approximation, this is the shape of the earth.  A prolate
    spheroid occurs if RadiusX = RadiusY < RadiusZ.

    Parameters
    ----------
    xradius : float, optional
        The scaling factor for the x-axis. Default is 1.

    yradius : float, optional
        The scaling factor for the y-axis. Default is 1.

    zradius : float, optional
        The scaling factor for the z-axis. Default is 1.

    **kwargs : dict, optional
        See :func:`surface_from_para` and :func:`parametric_keywords`
        for additional keyword arguments.

    Returns
    -------
    pyvista.PolyData
        ParametricEllipsoid surface.

    Examples
    --------
    Create a ParametricEllipsoid mesh.

    >>> import pyvista
    >>> mesh = pyvista.ParametricEllipsoid()
    >>> mesh.plot(color='w', smooth_shading=True)

    """
    parametric_function = _vtk.vtkParametricEllipsoid()
    parametric_keywords(
        parametric_function,
        min_u=kwargs.pop("min_u", 0),
        max_u=kwargs.pop("max_u", 2 * pi),
        min_v=kwargs.pop("min_v", 0.0),
        max_v=kwargs.pop("max_v", pi),
        join_u=kwargs.pop("join_u", False),
        join_v=kwargs.pop("join_v", False),
        twist_u=kwargs.pop("twist_u", False),
        twist_v=kwargs.pop("twist_v", False),
        clockwise=kwargs.pop("clockwise", True),
    )

    if xradius is not None:
        parametric_function.SetXRadius(xradius)

    if yradius is not None:
        parametric_function.SetYRadius(yradius)

    if zradius is not None:
        parametric_function.SetZRadius(zradius)

    center = kwargs.pop('center', [0.0, 0.0, 0.0])
    direction = kwargs.pop('direction', [1.0, 0.0, 0.0])
    kwargs.setdefault('clean', True)
    surf = surface_from_para(parametric_function, **kwargs)
    translate(surf, center, direction)
    return surf


def ParametricEnneper(**kwargs):
    """Generate Enneper's surface.

    ParametricEnneper generates Enneper's surface.  Enneper's surface
    is a self-intersecting minimal surface possessing constant
    negative Gaussian curvature.

    Parameters
    ----------
    **kwargs : dict, optional
        See :func:`surface_from_para` for additional keyword arguments.

    Returns
    -------
    pyvista.PolyData
        ParametricEnneper surface.

    Examples
    --------
    Create a ParametricEnneper mesh.

    >>> import pyvista
    >>> mesh = pyvista.ParametricEnneper()
    >>> mesh.plot(color='w', smooth_shading=True)

    """
    parametric_function = _vtk.vtkParametricEnneper()

    center = kwargs.pop('center', [0.0, 0.0, 0.0])
    direction = kwargs.pop('direction', [1.0, 0.0, 0.0])
    surf = surface_from_para(parametric_function, **kwargs)

    translate(surf, center, direction)

    return surf


def ParametricFigure8Klein(radius=None, **kwargs):
    """Generate a figure-8 Klein bottle.

    ParametricFigure8Klein generates a figure-8 Klein bottle.  A Klein
    bottle is a closed surface with no interior and only one surface.
    It is unrealisable in 3 dimensions without intersecting surfaces.

    Parameters
    ----------
    radius : float, optional
        The radius of the bottle. Default is 1.
    **kwargs : dict, optional
        See :func:`surface_from_para` for additional keyword arguments.

    Returns
    -------
    pyvista.PolyData
        ParametricFigure8Klein surface.

    Examples
    --------
    Create a ParametricFigure8Klein mesh.

    >>> import pyvista
    >>> mesh = pyvista.ParametricFigure8Klein()
    >>> mesh.plot(color='w', smooth_shading=True)

    """
    parametric_function = _vtk.vtkParametricFigure8Klein()
    if radius is not None:
        parametric_function.SetRadius(radius)

    center = kwargs.pop('center', [0.0, 0.0, 0.0])
    direction = kwargs.pop('direction', [1.0, 0.0, 0.0])
    kwargs.setdefault('clean', True)
    surf = surface_from_para(parametric_function, **kwargs)
    translate(surf, center, direction)
    return surf


def ParametricHenneberg(**kwargs):
    """Generate Henneberg's minimal surface.

    Parameters
    ----------
    **kwargs : dict, optional
        See :func:`surface_from_para` for additional keyword arguments.

    Returns
    -------
    pyvista.PolyData
        ParametricHenneberg surface.

    Examples
    --------
    Create a ParametricHenneberg mesh.

    >>> import pyvista
    >>> mesh = pyvista.ParametricHenneberg()
    >>> mesh.plot(color='w', smooth_shading=True)

    """
    parametric_function = _vtk.vtkParametricHenneberg()

    center = kwargs.pop('center', [0.0, 0.0, 0.0])
    direction = kwargs.pop('direction', [1.0, 0.0, 0.0])
    surf = surface_from_para(parametric_function, **kwargs)

    translate(surf, center, direction)

    return surf


def ParametricKlein(**kwargs):
    """Generate a "classical" representation of a Klein bottle.

    ParametricKlein generates a "classical" representation of a Klein
    bottle.  A Klein bottle is a closed surface with no interior and only one
    surface.  It is unrealisable in 3 dimensions without intersecting
    surfaces.

    Parameters
    ----------
    **kwargs : dict, optional
        See :func:`surface_from_para` for additional keyword arguments.

    Returns
    -------
    pyvista.PolyData
        ParametricKlein surface.

    Examples
    --------
    Create a ParametricKlein mesh.

    >>> import pyvista
    >>> mesh = pyvista.ParametricKlein()
    >>> mesh.plot(color='w', smooth_shading=True)

    """
    parametric_function = _vtk.vtkParametricKlein()

    center = kwargs.pop('center', [0.0, 0.0, 0.0])
    direction = kwargs.pop('direction', [1.0, 0.0, 0.0])
    kwargs.setdefault('clean', True)
    surf = surface_from_para(parametric_function, **kwargs)
    translate(surf, center, direction)
    return surf


def ParametricKuen(deltav0=None, **kwargs):
    """Generate Kuens' surface.

    ParametricKuen generates Kuens' surface. This surface has a constant
    negative gaussian curvature.

    Parameters
    ----------
    deltav0 : float, optional
        The value to use when ``V == 0``.
        Default is 0.05, giving the best appearance with the default settings.
        Setting it to a value less than 0.05 extrapolates the surface
        towards a pole in the -z direction.
        Setting it to 0 retains the pole whose z-value is -inf.

    **kwargs : dict, optional
        See :func:`surface_from_para` for additional keyword arguments.

    Returns
    -------
    pyvista.PolyData
        ParametricKuen surface.

    Examples
    --------
    Create a ParametricKuen mesh.

    >>> import pyvista
    >>> mesh = pyvista.ParametricKuen()
    >>> mesh.plot(color='w', smooth_shading=True)

    """
    parametric_function = _vtk.vtkParametricKuen()
    if deltav0 is not None:
        parametric_function.SetDeltaV0(deltav0)

    center = kwargs.pop('center', [0.0, 0.0, 0.0])
    direction = kwargs.pop('direction', [1.0, 0.0, 0.0])
    kwargs.setdefault('clean', True)
    surf = surface_from_para(parametric_function, **kwargs)
    translate(surf, center, direction)
    return surf


def ParametricMobius(radius=None, **kwargs):
    """Generate a Mobius strip.

    Parameters
    ----------
    radius : float, optional
        The radius of the Mobius strip. Default is 1.

    **kwargs : dict, optional
        See :func:`surface_from_para` for additional keyword arguments.

    Returns
    -------
    pyvista.PolyData
        ParametricMobius surface.

    Examples
    --------
    Create a ParametricMobius mesh.

    >>> import pyvista
    >>> mesh = pyvista.ParametricMobius()
    >>> mesh.plot(color='w', smooth_shading=True)

    """
    parametric_function = _vtk.vtkParametricMobius()
    if radius is not None:
        parametric_function.SetRadius(radius)

    center = kwargs.pop('center', [0.0, 0.0, 0.0])
    direction = kwargs.pop('direction', [1.0, 0.0, 0.0])
    surf = surface_from_para(parametric_function, **kwargs)
    translate(surf, center, direction)
    return surf


def ParametricPluckerConoid(n=None, **kwargs):
    """Generate Plucker's conoid surface.

    ParametricPluckerConoid generates Plucker's conoid surface
    parametrically.  Plucker's conoid is a ruled surface, named after
    Julius Plucker. It is possible to set the number of folds in this
    class via the parameter 'n'.

    Parameters
    ----------
    n : int, optional
        This is the number of folds in the conoid.

    **kwargs : dict, optional
        See :func:`surface_from_para` for additional keyword arguments.

    Returns
    -------
    pyvista.PolyData
        ParametricPluckerConoid surface.

    Examples
    --------
    Create a ParametricPluckerConoid mesh.

    >>> import pyvista
    >>> mesh = pyvista.ParametricPluckerConoid()
    >>> mesh.plot(color='w', smooth_shading=True)

    """
    parametric_function = _vtk.vtkParametricPluckerConoid()
    if n is not None:
        parametric_function.SetN(n)

    center = kwargs.pop('center', [0.0, 0.0, 0.0])
    direction = kwargs.pop('direction', [1.0, 0.0, 0.0])
    surf = surface_from_para(parametric_function, **kwargs)

    translate(surf, center, direction)

    return surf


def ParametricPseudosphere(**kwargs):
    """Generate a pseudosphere.

    ParametricPseudosphere generates a parametric pseudosphere. The
    pseudosphere is generated as a surface of revolution of the
    tractrix about it's asymptote, and is a surface of constant
    negative Gaussian curvature.

    Parameters
    ----------
    **kwargs : dict, optional
        See :func:`surface_from_para` for additional keyword arguments.

    Returns
    -------
    pyvista.PolyData
        ParametricPseudosphere surface.

    Examples
    --------
    Create a ParametricPseudosphere mesh.

    >>> import pyvista
    >>> mesh = pyvista.ParametricPseudosphere()
    >>> mesh.plot(color='w', smooth_shading=True)

    """
    parametric_function = _vtk.vtkParametricPseudosphere()

    center = kwargs.pop('center', [0.0, 0.0, 0.0])
    direction = kwargs.pop('direction', [1.0, 0.0, 0.0])
    kwargs.setdefault('clean', True)
    surf = surface_from_para(parametric_function, **kwargs)
    translate(surf, center, direction)
    return surf


def ParametricRandomHills(
    numberofhills=None,
    hillxvariance=None,
    hillyvariance=None,
    hillamplitude=None,
    randomseed=None,
    xvariancescalefactor=None,
    yvariancescalefactor=None,
    amplitudescalefactor=None,
    **kwargs,
):
    """Generate a surface covered with randomly placed hills.

    ParametricRandomHills generates a surface covered with randomly
    placed hills. Hills will vary in shape and height since the
    presence of nearby hills will contribute to the shape and height
    of a given hill.  An option is provided for placing hills on a
    regular grid on the surface.  In this case the hills will all have
    the same shape and height.

    Parameters
    ----------
    numberofhills : int, optional
        The number of hills.
        Default is 30.

    hillxvariance : float, optional
        The hill variance in the x-direction.
        Default is 2.5.

    hillyvariance : float, optional
        The hill variance in the y-direction.
        Default is 2.5.

    hillamplitude : float, optional
        The hill amplitude (height).
        Default is 2.

    randomseed : int, optional
        The Seed for the random number generator,
        a value of 1 will initialize the random number generator,
        a negative value will initialize it with the system time.
        Default is 1.

    xvariancescalefactor : float, optional
        The scaling factor for the variance in the x-direction.
        Default is 13.

    yvariancescalefactor : float, optional
        The scaling factor for the variance in the y-direction.
        Default is 13.

    amplitudescalefactor : float, optional
        The scaling factor for the amplitude.
        Default is 13.

    **kwargs : dict, optional
        See :func:`surface_from_para` for additional keyword arguments.

    Returns
    -------
    pyvista.PolyData
        ParametricRandomHills surface.

    Examples
    --------
    Create a ParametricRandomHills mesh.

    >>> import pyvista
    >>> mesh = pyvista.ParametricRandomHills()
    >>> mesh.plot(color='w', smooth_shading=True)

    """
    parametric_function = _vtk.vtkParametricRandomHills()
    if numberofhills is not None:
        parametric_function.SetNumberOfHills(numberofhills)

    if hillxvariance is not None:
        parametric_function.SetHillXVariance(hillxvariance)

    if hillyvariance is not None:
        parametric_function.SetHillYVariance(hillyvariance)

    if hillamplitude is not None:
        parametric_function.SetHillAmplitude(hillamplitude)

    if randomseed is not None:
        parametric_function.SetRandomSeed(randomseed)

    if xvariancescalefactor is not None:
        parametric_function.SetXVarianceScaleFactor(xvariancescalefactor)

    if yvariancescalefactor is not None:
        parametric_function.SetYVarianceScaleFactor(yvariancescalefactor)

    if amplitudescalefactor is not None:
        parametric_function.SetAmplitudeScaleFactor(amplitudescalefactor)

    center = kwargs.pop('center', [0.0, 0.0, 0.0])
    direction = kwargs.pop('direction', [1.0, 0.0, 0.0])
    surf = surface_from_para(parametric_function, **kwargs)

    translate(surf, center, direction)

    return surf


def ParametricRoman(radius=None, **kwargs):
    """Generate Steiner's Roman Surface.

    Parameters
    ----------
    radius : float, optional
        The radius. Default is 1.

    **kwargs : dict, optional
        See :func:`surface_from_para` for additional keyword arguments.

    Returns
    -------
    pyvista.PolyData
        ParametricRoman surface.

    Examples
    --------
    Create a ParametricRoman mesh.

    >>> import pyvista
    >>> mesh = pyvista.ParametricRoman()
    >>> mesh.plot(color='w', smooth_shading=True)

    """
    parametric_function = _vtk.vtkParametricRoman()
    if radius is not None:
        parametric_function.SetRadius(radius)

    center = kwargs.pop('center', [0.0, 0.0, 0.0])
    direction = kwargs.pop('direction', [1.0, 0.0, 0.0])
    surf = surface_from_para(parametric_function, **kwargs)

    translate(surf, center, direction)

    return surf


def ParametricSuperEllipsoid(xradius=None, yradius=None, zradius=None, n1=None, n2=None, **kwargs):
    """Generate a superellipsoid.

    ParametricSuperEllipsoid generates a superellipsoid.  A superellipsoid
    is a versatile primitive that is controlled by two parameters n1 and
    n2. As special cases it can represent a sphere, square box, and closed
    cylindrical can.

    Parameters
    ----------
    xradius : float, optional
        The scaling factor for the x-axis. Default is 1.

    yradius : float, optional
        The scaling factor for the y-axis. Default is 1.

    zradius : float, optional
        The scaling factor for the z-axis. Default is 1.

    n1 : float, optional
        The "squareness" parameter in the z axis.  Default is 1.

    n2 : float, optional
        The "squareness" parameter in the x-y plane. Default is 1.

    **kwargs : dict, optional
        See :func:`surface_from_para` for additional keyword arguments.

    Returns
    -------
    pyvista.PolyData
        ParametricSuperEllipsoid surface.

    See Also
    --------
    pyvista.ParametricSuperToroid :
        Toroidal equivalent of ParametricSuperEllipsoid.
    pyvista.Superquadric :
        Geometric object with additional parameters.

    Examples
    --------
    Create a ParametricSuperEllipsoid surface that looks like a box
    with smooth edges.

    >>> import pyvista
    >>> mesh = pyvista.ParametricSuperEllipsoid(n1=0.02, n2=0.02)
    >>> mesh.plot(color='w', smooth_shading=True)

    Create one that looks like a spinning top.

    >>> mesh = pyvista.ParametricSuperEllipsoid(n1=4, n2=0.5)
    >>> mesh.plot(color='w', smooth_shading=True, cpos='xz')

    """
    parametric_function = _vtk.vtkParametricSuperEllipsoid()
    if xradius is not None:
        parametric_function.SetXRadius(xradius)

    if yradius is not None:
        parametric_function.SetYRadius(yradius)

    if zradius is not None:
        parametric_function.SetZRadius(zradius)

    if n1 is not None:
        parametric_function.SetN1(n1)

    if n2 is not None:
        parametric_function.SetN2(n2)

    center = kwargs.pop('center', [0.0, 0.0, 0.0])
    direction = kwargs.pop('direction', [1.0, 0.0, 0.0])
    surf = surface_from_para(parametric_function, **kwargs)

    translate(surf, center, direction)

    return surf


def ParametricSuperToroid(
    ringradius=None,
    crosssectionradius=None,
    xradius=None,
    yradius=None,
    zradius=None,
    n1=None,
    n2=None,
    **kwargs,
):
    """Generate a supertoroid.

    ParametricSuperToroid generates a supertoroid.  Essentially a
    supertoroid is a torus with the sine and cosine terms raised to a power.
    A supertoroid is a versatile primitive that is controlled by four
    parameters r0, r1, n1 and n2. r0, r1 determine the type of torus whilst
    the value of n1 determines the shape of the torus ring and n2 determines
    the shape of the cross section of the ring. It is the different values of
    these powers which give rise to a family of 3D shapes that are all
    basically toroidal in shape.

    Parameters
    ----------
    ringradius : float, optional
        The radius from the center to the middle of the ring of the
        supertoroid. Default is 1.

    crosssectionradius : float, optional
        The radius of the cross section of ring of the supertoroid.
        Default = 0.5.

    xradius : float, optional
        The scaling factor for the x-axis. Default is 1.

    yradius : float, optional
        The scaling factor for the y-axis. Default is 1.

    zradius : float, optional
        The scaling factor for the z-axis. Default is 1.

    n1 : float, optional
        The shape of the torus ring.  Default is 1.

    n2 : float, optional
        The shape of the cross section of the ring. Default is 1.

    **kwargs : dict, optional
        See :func:`surface_from_para` for additional keyword arguments.

    Returns
    -------
    pyvista.PolyData
        ParametricSuperToroid surface.

    See Also
    --------
    pyvista.ParametricSuperEllipsoid :
        Ellipsoidal equivalent of ParametricSuperToroid.
    pyvista.Superquadric :
        Geometric object with additional parameters.

    Examples
    --------
    Create a ParametricSuperToroid mesh.

    >>> import pyvista
    >>> mesh = pyvista.ParametricSuperToroid(n1=2, n2=0.3)
    >>> mesh.plot(color='w', smooth_shading=True)

    """
    parametric_function = _vtk.vtkParametricSuperToroid()
    if ringradius is not None:
        parametric_function.SetRingRadius(ringradius)

    if crosssectionradius is not None:
        parametric_function.SetCrossSectionRadius(crosssectionradius)

    if xradius is not None:
        parametric_function.SetXRadius(xradius)

    if yradius is not None:
        parametric_function.SetYRadius(yradius)

    if zradius is not None:
        parametric_function.SetZRadius(zradius)

    if n1 is not None:
        parametric_function.SetN1(n1)

    if n2 is not None:
        parametric_function.SetN2(n2)

    center = kwargs.pop('center', [0.0, 0.0, 0.0])
    direction = kwargs.pop('direction', [1.0, 0.0, 0.0])
    kwargs.setdefault('clean', True)
    surf = surface_from_para(parametric_function, **kwargs)
    translate(surf, center, direction)
    return surf


def ParametricTorus(ringradius=None, crosssectionradius=None, **kwargs):
    """Generate a torus.

    Parameters
    ----------
    ringradius : float, optional
        The radius from the center to the middle of the ring of the
        torus. Default is 1.0.

    crosssectionradius : float, optional
        The radius of the cross section of ring of the torus. Default is 0.5.

    **kwargs : dict, optional
        See :func:`surface_from_para` for additional keyword arguments.

    Returns
    -------
    pyvista.PolyData
        ParametricTorus surface.

    Examples
    --------
    Create a ParametricTorus mesh.

    >>> import pyvista
    >>> mesh = pyvista.ParametricTorus()
    >>> mesh.plot(color='w', smooth_shading=True)

    """
    parametric_function = _vtk.vtkParametricTorus()
    if ringradius is not None:
        parametric_function.SetRingRadius(ringradius)

    if crosssectionradius is not None:
        parametric_function.SetCrossSectionRadius(crosssectionradius)

    center = kwargs.pop('center', [0.0, 0.0, 0.0])
    direction = kwargs.pop('direction', [1.0, 0.0, 0.0])
    kwargs.setdefault('clean', True)
    surf = surface_from_para(parametric_function, **kwargs)
    translate(surf, center, direction)
    return surf


def parametric_keywords(
    parametric_function,
    min_u=0,
    max_u=2 * pi,
    min_v=0.0,
    max_v=2 * pi,
    join_u=False,
    join_v=False,
    twist_u=False,
    twist_v=False,
    clockwise=True,
):
    """Apply keyword arguments to a parametric function.

    Parameters
    ----------
    parametric_function : vtk.vtkParametricFunction
        Parametric function to generate mesh from.

    min_u : float, optional
        The minimum u-value.

    max_u : float, optional
        The maximum u-value.

    min_v : float, optional
        The minimum v-value.

    max_v : float, optional
        The maximum v-value.

    join_u : bool, optional
        Joins the first triangle strip to the last one with a twist in
        the u direction.

    join_v : bool, optional
        Joins the first triangle strip to the last one with a twist in
        the v direction.

    twist_u : bool, optional
        Joins the first triangle strip to the last one with a twist in
        the u direction.

    twist_v : bool, optional
        Joins the first triangle strip to the last one with a twist in
        the v direction.

    clockwise : bool, optional
        Determines the ordering of the vertices forming the triangle
        strips.

    """
    parametric_function.SetMinimumU(min_u)
    parametric_function.SetMaximumU(max_u)
    parametric_function.SetMinimumV(min_v)
    parametric_function.SetMaximumV(max_v)
    parametric_function.SetJoinU(join_u)
    parametric_function.SetJoinV(join_v)
    parametric_function.SetTwistU(twist_u)
    parametric_function.SetTwistV(twist_v)
    parametric_function.SetClockwiseOrdering(clockwise)


def surface_from_para(parametric_function, u_res=100, v_res=100, w_res=100, clean=False):
    """Construct a mesh from a parametric function.

    Parameters
    ----------
    parametric_function : vtk.vtkParametricFunction
        Parametric function to generate mesh from.

    u_res : int, optional
        Resolution in the u direction.

    v_res : int, optional
        Resolution in the v direction.

    w_res : int, optional
        Resolution in the w direction.

    clean : bool, optional
        Clean and merge duplicate points to avoid "creases" when
        plotting with smooth shading.

    Returns
    -------
    pyvista.PolyData
        Surface from the parametric function.

    """
    # convert to a mesh
    para_source = _vtk.vtkParametricFunctionSource()
    para_source.SetParametricFunction(parametric_function)
    para_source.SetUResolution(u_res)
    para_source.SetVResolution(v_res)
    para_source.SetWResolution(w_res)
    para_source.Update()
    surf = pyvista.wrap(para_source.GetOutput())
    if clean:
        surf = surf.clean(
            tolerance=1e-7,  # determined experimentally
            absolute=False,
            lines_to_points=False,
            polys_to_lines=False,
            strips_to_polys=False,
        )
    return surf


# pyvista/utilities/reader.py

"""Fine-grained control of reading data files."""
from abc import ABC, abstractmethod
from dataclasses import dataclass
from functools import wraps
import os
import pathlib
from typing import Any, Callable, List, Union
from xml.etree import ElementTree

import numpy as np

import pyvista
from pyvista import _vtk
from pyvista.utilities import abstract_class, wrap

from .fileio import _get_ext_force, _process_filename

HDF_HELP = 'https://kitware.github.io/vtk-examples/site/VTKFileFormats/#hdf-file-formats'


def get_reader(filename, force_ext=None):
    """Get a reader for fine-grained control of reading data files.

    Supported file types and Readers:

    +----------------+---------------------------------------------+
    | File Extension | Class                                       |
    +================+=============================================+
    | ``.bmp``       | :class:`pyvista.BMPReader`                  |
    +----------------+---------------------------------------------+
    | ``.cas``       | :class:`pyvista.FluentReader`               |
    +----------------+---------------------------------------------+
    | ``.case``      | :class:`pyvista.EnSightReader`              |
    +----------------+---------------------------------------------+
    | ``.cgns``      | :class:`pyvista.CGNSReader`                 |
    +----------------+---------------------------------------------+
    | ``.dat``       | :class:`pyvista.TecplotReader`              |
    +----------------+---------------------------------------------+
    | ``.dcm``       | :class:`pyvista.DICOMReader`                |
    +----------------+---------------------------------------------+
    | ``.dem``       | :class:`pyvista.DEMReader`                  |
    +----------------+---------------------------------------------+
    | ``.facet``     | :class:`pyvista.FacetReader`                |
    +----------------+---------------------------------------------+
    | ``.foam``      | :class:`pyvista.POpenFOAMReader`            |
    +----------------+---------------------------------------------+
    | ``.g``         | :class:`pyvista.BYUReader`                  |
    +----------------+---------------------------------------------+
    | ``.gif``       | :class:`pyvista.GIFReader`                  |
    +----------------+---------------------------------------------+
    | ``.glb``       | :class:`pyvista.GLTFReader`                 |
    +----------------+---------------------------------------------+
    | ``.gltf``      | :class:`pyvista.GLTFReader`                 |
    +----------------+---------------------------------------------+
    | ``.hdf``       | :class:`pyvista.HDFReader`                  |
    +----------------+---------------------------------------------+
    | ``.img``       | :class:`pyvista.DICOMReader`                |
    +----------------+---------------------------------------------+
    | ``.inp``       | :class:`pyvista.AVSucdReader`               |
    +----------------+---------------------------------------------+
    | ``.jpg``       | :class:`pyvista.JPEGReader`                 |
    +----------------+---------------------------------------------+
    | ``.jpeg``      | :class:`pyvista.JPEGReader`                 |
    +----------------+---------------------------------------------+
    | ``.hdr``       | :class:`pyvista.HDRReader`                  |
    +----------------+---------------------------------------------+
    | ``.mha``       | :class:`pyvista.MetaImageReader`            |
    +----------------+---------------------------------------------+
    | ``.mhd``       | :class:`pyvista.MetaImageReader`            |
    +----------------+---------------------------------------------+
    | ``.nhdr``      | :class:`pyvista.NRRDReader`                 |
    +----------------+---------------------------------------------+
    | ``.nrrd``      | :class:`pyvista.NRRDReader`                 |
    +----------------+---------------------------------------------+
    | ``.obj``       | :class:`pyvista.OBJReader`                  |
    +----------------+---------------------------------------------+
    | ``.p3d``       | :class:`pyvista.Plot3DMetaReader`           |
    +----------------+---------------------------------------------+
    | ``.ply``       | :class:`pyvista.PLYReader`                  |
    +----------------+---------------------------------------------+
    | ``.png``       | :class:`pyvista.PNGReader`                  |
    +----------------+---------------------------------------------+
    | ``.pnm``       | :class:`pyvista.PNMReader`                  |
    +----------------+---------------------------------------------+
    | ``.pts``       | :class:`pyvista.PTSReader`                  |
    +----------------+---------------------------------------------+
    | ``.pvd``       | :class:`pyvista.PVDReader`                  |
    +----------------+---------------------------------------------+
    | ``.pvti``      | :class:`pyvista.XMLPImageDataReader`        |
    +----------------+---------------------------------------------+
    | ``.pvtk``      | :class:`pyvista.VTKPDataSetReader`          |
    +----------------+---------------------------------------------+
    | ``.pvtr``      | :class:`pyvista.XMLPRectilinearGridReader`  |
    +----------------+---------------------------------------------+
    | ``.pvtu``      | :class:`pyvista.XMLPUnstructuredGridReader` |
    +----------------+---------------------------------------------+
    | ``.res``       | :class:`pyvista.MFIXReader`                 |
    +----------------+---------------------------------------------+
    | ``.segy``      | :class:`pyvista.SegYReader`                 |
    +----------------+---------------------------------------------+
    | ``.sgy``       | :class:`pyvista.SegYReader`                 |
    +----------------+---------------------------------------------+
    | ``.slc``       | :class:`pyvista.SLCReader`                  |
    +----------------+---------------------------------------------+
    | ``.stl``       | :class:`pyvista.STLReader`                  |
    +----------------+---------------------------------------------+
    | ``.tif``       | :class:`pyvista.TIFFReader`                 |
    +----------------+---------------------------------------------+
    | ``.tiff``      | :class:`pyvista.TIFFReader`                 |
    +----------------+---------------------------------------------+
    | ``.tri``       | :class:`pyvista.BinaryMarchingCubesReader`  |
    +----------------+---------------------------------------------+
    | ``.vti``       | :class:`pyvista.XMLImageDataReader`         |
    +----------------+---------------------------------------------+
    | ``.vtk``       | :class:`pyvista.VTKDataSetReader`           |
    +----------------+---------------------------------------------+
    | ``.vtm``       | :class:`pyvista.XMLMultiBlockDataReader`    |
    +----------------+---------------------------------------------+
    | ``.vtmb``      | :class:`pyvista.XMLMultiBlockDataReader`    |
    +----------------+---------------------------------------------+
    | ``.vtp``       | :class:`pyvista.XMLPolyDataReader`          |
    +----------------+---------------------------------------------+
    | ``.vtr``       | :class:`pyvista.XMLRectilinearGridReader`   |
    +----------------+---------------------------------------------+
    | ``.vts``       | :class:`pyvista.XMLStructuredGridReader`    |
    +----------------+---------------------------------------------+
    | ``.vtu``       | :class:`pyvista.XMLUnstructuredGridReader`  |
    +----------------+---------------------------------------------+

    Parameters
    ----------
    filename : str
        The string path to the file to read.

    force_ext : str, optional
        An extension to force a specific reader to be chosen.

    Returns
    -------
    pyvista.BaseReader
        A subclass of :class:`pyvista.BaseReader` is returned based on file type.

    Examples
    --------
    >>> import pyvista
    >>> from pyvista import examples
    >>> filename = examples.download_human(load=False)
    >>> filename.split("/")[-1]  # omit the path
    'Human.vtp'
    >>> reader = pyvista.get_reader(filename)
    >>> reader  # doctest: +ELLIPSIS
    XMLPolyDataReader('.../Human.vtp')
    >>> mesh = reader.read()
    >>> mesh # doctest: +ELLIPSIS
    PolyData ...
    >>> mesh.plot(color='tan')

    """
    ext = _get_ext_force(filename, force_ext)

    try:
        Reader = CLASS_READERS[ext]
    except KeyError:
        raise ValueError(f"`pyvista.get_reader` does not support a file with the {ext} extension")

    return Reader(filename)


@abstract_class
class BaseReader:
    """The Base Reader class.

    The base functionality includes reading data from a file,
    and allowing access to the underlying vtk reader. See
    :func:`pyvista.get_reader` for an example using
    a built-in subclass.

    Parameters
    ----------
    path : str
        Path of the file to read.
    """

    _class_reader: Any = None

    def __init__(self, path):
        """Initialize Reader by setting path."""
        self._reader = self._class_reader()
        self._filename = None
        self._progress_bar = False
        self._progress_msg = None
        self.__directory = None
        self._set_defaults()
        self.path = path
        self._set_defaults_post()

    def __repr__(self):
        """Representation of a Reader object."""
        return f"{self.__class__.__name__}('{self.path}')"

    def show_progress(self, msg=None):
        """Show a progress bar when loading the file.

        Parameters
        ----------
        msg : str, optional
            Progress bar message. Defaults to ``"Reading <file base name>"``.

        Examples
        --------
        >>> import pyvista
        >>> from pyvista import examples
        >>> filename = examples.download_cavity(load=False)
        >>> reader = pyvista.OpenFOAMReader(filename)
        >>> reader.show_progress()

        """
        self._progress_bar = True
        if msg is None:
            msg = f"Reading {os.path.basename(self.path)}"
        self._progress_msg = msg

    def hide_progress(self):
        """Hide the progress bar when loading the file.

        Examples
        --------
        >>> import pyvista
        >>> from pyvista import examples
        >>> filename = examples.download_cavity(load=False)
        >>> reader = pyvista.OpenFOAMReader(filename)
        >>> reader.hide_progress()

        """
        self._progress_bar = False

    @property
    def reader(self):
        """Return the vtk Reader object.

        Returns
        -------
        pyvista.BaseReader
            An instance of the Reader object.

        """
        if self._reader is None:  # pragma: no cover
            raise NotImplementedError
        return self._reader

    @property
    def path(self) -> str:
        """Return or set the filename or directory of the reader.

        Examples
        --------
        >>> import pyvista
        >>> from pyvista import examples
        >>> filename = examples.download_human(load=False)
        >>> reader = pyvista.XMLPolyDataReader(filename)
        >>> reader.path  # doctest:+SKIP
        '/home/user/.local/share/pyvista/examples/Human.vtp'

        """
        if self._filename is not None:
            return self._filename
        return self.__directory

    @path.setter
    def path(self, path: str):
        if os.path.isdir(path):
            self._set_directory(path)
        elif os.path.isfile(path):
            self._set_filename(path)
        else:
            raise FileNotFoundError(f"Path '{path}' is invalid or does not exist.")

    def _set_directory(self, directory):
        """Set directory and update reader."""
        self._filename = None
        self.__directory = directory
        self.reader.SetDirectoryName(directory)
        self._update_information()

    def _set_filename(self, filename):
        """Set filename and update reader."""
        # Private method since changing file type requires a
        # different subclass.
        self.__directory = None
        self._filename = filename
        self.reader.SetFileName(filename)
        self._update_information()

    def read(self):
        """Read data in file.

        Returns
        -------
        pyvista.DataSet
            PyVista Dataset.
        """
        from pyvista.core.filters import _update_alg  # avoid circular import

        _update_alg(self.reader, progress_bar=self._progress_bar, message=self._progress_msg)
        data = wrap(self.reader.GetOutputDataObject(0))
        if data is None:  # pragma: no cover
            raise RuntimeError("Failed to read file.")
        data._post_file_load_processing()

        # check for any pyvista metadata
        data._restore_metadata()
        return data

    def _update_information(self):
        self.reader.UpdateInformation()

    def _set_defaults(self):
        """Set defaults on reader, if needed."""
        pass

    def _set_defaults_post(self):
        """Set defaults on reader post setting file, if needed."""
        pass


class PointCellDataSelection:
    """Mixin for readers that support data array selections.

    Examples
    --------
    >>> import pyvista
    >>> from pyvista import examples
    >>> filename = examples.download_backward_facing_step(load=False)
    >>> filename.split("/")[-1]  # omit the path
    'foam_case_0_0_0_0.case'
    >>> reader = pyvista.get_reader(filename)
    >>> reader  # doctest: +ELLIPSIS
    EnSightReader('.../foam_case_0_0_0_0.case')
    >>> reader.cell_array_names
    ['v2', 'nut', 'k', 'nuTilda', 'p', 'omega', 'f', 'epsilon', 'U']
    >>> reader.point_array_names
    []
    >>> reader.all_cell_arrays_status  # doctest: +NORMALIZE_WHITESPACE
    {'v2': True, 'nut': True, 'k': True, 'nuTilda': True, 'p': True, 'omega': True, 'f': True, 'epsilon': True, 'U': True}
    >>> reader.disable_all_cell_arrays()
    >>> reader.enable_cell_array('U')
    >>> mesh = reader.read()  # MultiBlock mesh
    >>> mesh[0].array_names
    ['U']

    """

    @property
    def number_point_arrays(self):
        """Return the number of point arrays.

        Returns
        -------
        int

        """
        return self.reader.GetNumberOfPointArrays()

    @property
    def point_array_names(self):
        """Return the list of all point array names.

        Returns
        -------
        list[str]

        """
        return [self.reader.GetPointArrayName(i) for i in range(self.number_point_arrays)]

    def enable_point_array(self, name):
        """Enable point array with name.

        Parameters
        ----------
        name : str
            Point array name.

        """
        self.reader.SetPointArrayStatus(name, 1)

    def disable_point_array(self, name):
        """Disable point array with name.

        Parameters
        ----------
        name : str
            Point array name.

        """
        self.reader.SetPointArrayStatus(name, 0)

    def point_array_status(self, name):
        """Get status of point array with name.

        Parameters
        ----------
        name : str
            Point array name.

        Returns
        -------
        bool
            Whether reading the cell array is enabled.

        """
        if self.reader.GetPointArrayStatus(name):
            return True
        return False

    def enable_all_point_arrays(self):
        """Enable all point arrays."""
        for name in self.point_array_names:
            self.enable_point_array(name)

    def disable_all_point_arrays(self):
        """Disable all point arrays."""
        for name in self.point_array_names:
            self.disable_point_array(name)

    @property
    def all_point_arrays_status(self):
        """Return the status of all point arrays.

        Returns
        -------
        dict[str, bool]

        """
        return {name: self.point_array_status(name) for name in self.point_array_names}

    @property
    def number_cell_arrays(self):
        """Return the number of cell arrays.

        Returns
        -------
        int

        """
        return self.reader.GetNumberOfCellArrays()

    @property
    def cell_array_names(self):
        """Return the list of all cell array names.

        Returns
        -------
        list[str]

        """
        return [self.reader.GetCellArrayName(i) for i in range(self.number_cell_arrays)]

    def enable_cell_array(self, name):
        """Enable cell array with name.

        Parameters
        ----------
        name : str
            Cell array name.

        """
        self.reader.SetCellArrayStatus(name, 1)

    def disable_cell_array(self, name):
        """Disable cell array with name.

        Parameters
        ----------
        name : str
            Cell array name.

        """
        self.reader.SetCellArrayStatus(name, 0)

    def cell_array_status(self, name):
        """Get status of cell array with name.

        Parameters
        ----------
        name : str
            Cell array name.

        Returns
        -------
        bool
            Whether reading the cell array is enabled.

        """
        return bool(self.reader.GetCellArrayStatus(name))

    def enable_all_cell_arrays(self):
        """Enable all cell arrays."""
        for name in self.cell_array_names:
            self.enable_cell_array(name)

    def disable_all_cell_arrays(self):
        """Disable all cell arrays."""
        for name in self.cell_array_names:
            self.disable_cell_array(name)

    @property
    def all_cell_arrays_status(self):
        """Return the status of all cell arrays.

        Returns
        -------
        dict[str, bool]
        """
        return {name: self.cell_array_status(name) for name in self.cell_array_names}


class TimeReader(ABC):
    """Abstract class for readers supporting time."""

    @property
    @abstractmethod
    def number_time_points(self):
        """Return number of time points or iterations available to read.

        Returns
        -------
        int

        """

    @abstractmethod
    def time_point_value(self, time_point):
        """Value of time point or iteration by index.

        Parameters
        ----------
        time_point: int
            Time point index.

        Returns
        -------
        float

        """

    @property
    def time_values(self):
        """All time or iteration values.

        Returns
        -------
        list[float]

        """
        return [self.time_point_value(idx) for idx in range(self.number_time_points)]

    @property
    @abstractmethod
    def active_time_value(self):
        """Active time or iteration value.

        Returns
        -------
        float

        """

    @abstractmethod
    def set_active_time_value(self, time_value):
        """Set active time or iteration value.

        Parameters
        ----------
        time_value: float
            Time or iteration value to set as active.

        """

    @abstractmethod
    def set_active_time_point(self, time_point):
        """Set active time or iteration by index.

        Parameters
        ----------
        time_point: int
            Time or iteration point index for setting active time.

        """


class XMLImageDataReader(BaseReader, PointCellDataSelection):
    """XML Image Data Reader for .vti files."""

    _class_reader = _vtk.vtkXMLImageDataReader


class XMLPImageDataReader(BaseReader, PointCellDataSelection):
    """Parallel XML Image Data Reader for .pvti files."""

    _class_reader = _vtk.vtkXMLPImageDataReader


class XMLRectilinearGridReader(BaseReader, PointCellDataSelection):
    """XML RectilinearGrid Reader for .vtr files.

    Examples
    --------
    >>> import pyvista
    >>> from pyvista import examples
    >>> filename = examples.download_rectilinear_grid(load=False)
    >>> filename.split("/")[-1]  # omit the path
    'RectilinearGrid.vtr'
    >>> reader = pyvista.get_reader(filename)
    >>> mesh = reader.read()
    >>> sliced_mesh = mesh.slice('y')
    >>> sliced_mesh.plot(scalars='Void Volume Fraction', cpos='xz',
    ...                  show_scalar_bar=False)

    """

    _class_reader = _vtk.vtkXMLRectilinearGridReader


class XMLPRectilinearGridReader(BaseReader, PointCellDataSelection):
    """Parallel XML RectilinearGrid Reader for .pvtr files."""

    _class_reader = _vtk.vtkXMLPRectilinearGridReader


class XMLUnstructuredGridReader(BaseReader, PointCellDataSelection):
    """XML UnstructuredGrid Reader for .vtu files.

    Examples
    --------
    >>> import pyvista
    >>> from pyvista import examples
    >>> filename = examples.download_notch_displacement(load=False)
    >>> filename.split("/")[-1]  # omit the path
    'notch_disp.vtu'
    >>> reader = pyvista.get_reader(filename)
    >>> mesh = reader.read()
    >>> mesh.plot(scalars="Nodal Displacement", component=0,
    ...           cpos='xy', show_scalar_bar=False)

    """

    _class_reader = _vtk.vtkXMLUnstructuredGridReader


class XMLPUnstructuredGridReader(BaseReader, PointCellDataSelection):
    """Parallel XML UnstructuredGrid Reader for .pvtu files."""

    _class_reader = _vtk.vtkXMLPUnstructuredGridReader


class XMLPolyDataReader(BaseReader, PointCellDataSelection):
    """XML PolyData Reader for .vtp files.

    Examples
    --------
    >>> import pyvista
    >>> from pyvista import examples
    >>> filename = examples.download_cow_head(load=False)
    >>> filename.split("/")[-1]  # omit the path
    'cowHead.vtp'
    >>> reader = pyvista.get_reader(filename)
    >>> mesh = reader.read()
    >>> mesh.plot(
    ...    cpos=((12, 3.5, -4.5), (4.5, 1.6, 0), (0, 1, 0.3)),
    ...    clim=[0, 100], show_scalar_bar=False
    ... )

    """

    _class_reader = _vtk.vtkXMLPolyDataReader


class XMLStructuredGridReader(BaseReader, PointCellDataSelection):
    """XML StructuredGrid Reader for .vts files.

    Examples
    --------
    >>> import pyvista
    >>> from pyvista import examples
    >>> filename = examples.download_structured_grid(load=False)
    >>> filename.split("/")[-1]  # omit the path
    'StructuredGrid.vts'
    >>> reader = pyvista.get_reader(filename)
    >>> mesh = reader.read()
    >>> mesh.plot(style='wireframe', line_width=4, show_scalar_bar=False)

    """

    _class_reader = _vtk.vtkXMLStructuredGridReader


class XMLMultiBlockDataReader(BaseReader, PointCellDataSelection):
    """XML MultiBlock Data Reader for .vtm or .vtmb files."""

    _class_reader = _vtk.vtkXMLMultiBlockDataReader


# skip pydocstyle D102 check since docstring is taken from TimeReader


class EnSightReader(BaseReader, PointCellDataSelection, TimeReader):
    """EnSight Reader for .case files.

    Examples
    --------
    >>> import pyvista
    >>> from pyvista import examples
    >>> filename = examples.download_cylinder_crossflow(load=False)
    >>> filename.split("/")[-1]  # omit the path
    'cylinder_Re35.case'
    >>> reader = pyvista.get_reader(filename)
    >>> mesh = reader.read()
    >>> mesh.plot(scalars="velocity", component=1, clim=[-20, 20],
    ...           cpos='xy', cmap='RdBu', show_scalar_bar=False)

    """

    _class_reader = _vtk.vtkGenericEnSightReader

    def _set_filename(self, filename):
        """Set filename and update reader."""
        # Private method since changing file type requires a
        # different subclass.
        self._filename = filename
        self.reader.SetCaseFileName(filename)
        self._update_information()

    @property
    def number_time_points(self):  # noqa: D102
        return self.reader.GetTimeSets().GetItem(0).GetSize()

    def time_point_value(self, time_point):  # noqa: D102
        return self.reader.GetTimeSets().GetItem(0).GetValue(time_point)

    @property
    def active_time_value(self):  # noqa: D102
        return self.reader.GetTimeValue()

    def set_active_time_value(self, time_value):  # noqa: D102
        if time_value not in self.time_values:
            raise ValueError(
                f"Not a valid time {time_value} from available time values: {self.reader_time_values}"
            )
        self.reader.SetTimeValue(time_value)

    def set_active_time_point(self, time_point):  # noqa: D102
        self.reader.SetTimeValue(self.time_point_value(time_point))


# skip pydocstyle D102 check since docstring is taken from TimeReader
class OpenFOAMReader(BaseReader, PointCellDataSelection, TimeReader):
    """OpenFOAM Reader for .foam files.

    By default, pyvista enables all patch arrays.  This is a deviation
    from the vtk default.

    """

    _class_reader = _vtk.vtkOpenFOAMReader

    def _set_defaults_post(self):
        self.enable_all_patch_arrays()

    @property
    def number_time_points(self):  # noqa: D102
        return self.reader.GetTimeValues().GetNumberOfValues()

    def time_point_value(self, time_point):  # noqa: D102
        return self.reader.GetTimeValues().GetValue(time_point)

    @property
    def active_time_value(self):  # noqa: D102
        try:
            value = self.reader.GetTimeValue()
        except AttributeError as err:  # pragma: no cover
            raise AttributeError(
                "Inspecting active time value only supported for vtk versions >9.1.0"
            ) from err
        return value

    def set_active_time_value(self, time_value):  # noqa: D102
        if time_value not in self.time_values:
            raise ValueError(
                f"Not a valid time {time_value} from available time values: {self.time_values}"
            )
        self.reader.UpdateTimeStep(time_value)

    def set_active_time_point(self, time_point):  # noqa: D102
        self.reader.UpdateTimeStep(self.time_point_value(time_point))

    @property
    def decompose_polyhedra(self):
        """Whether polyhedra are to be decomposed when read.

        Returns
        -------
        bool
            If ``True``, decompose polyhedra into tetrahedra and pyramids.

        Examples
        --------
        >>> import pyvista
        >>> from pyvista import examples
        >>> filename = examples.download_cavity(load=False)
        >>> reader = pyvista.OpenFOAMReader(filename)
        >>> reader.decompose_polyhedra = False
        >>> reader.decompose_polyhedra
        False

        """
        return bool(self.reader.GetDecomposePolyhedra())

    @decompose_polyhedra.setter
    def decompose_polyhedra(self, value):
        self.reader.SetDecomposePolyhedra(value)

    @property
    def skip_zero_time(self):
        """Indicate whether or not to ignore the '/0' time directory.

        Returns
        -------
        bool
            If ``True``, ignore the '/0' time directory.

        Examples
        --------
        >>> import pyvista
        >>> from pyvista import examples
        >>> filename = examples.download_cavity(load=False)
        >>> reader = pyvista.OpenFOAMReader(filename)
        >>> reader.skip_zero_time = False
        >>> reader.skip_zero_time
        False

        """
        return bool(self.reader.GetSkipZeroTime())

    @skip_zero_time.setter
    def skip_zero_time(self, value):
        self.reader.SetSkipZeroTime(value)
        self._update_information()
        self.reader.SetRefresh()

    @property
    def cell_to_point_creation(self):
        """Whether cell data is translated to point data when read.

        Returns
        -------
        bool
            If ``True``, translate cell data to point data.

        Warnings
        --------
        When ``True``, cell and point data arrays will have
        duplicate names.

        Examples
        --------
        >>> import pyvista
        >>> from pyvista import examples
        >>> filename = examples.download_cavity(load=False)
        >>> reader = pyvista.OpenFOAMReader(filename)
        >>> reader.cell_to_point_creation = False
        >>> reader.cell_to_point_creation
        False

        """
        return bool(self.reader.GetCreateCellToPoint())

    @cell_to_point_creation.setter
    def cell_to_point_creation(self, value):
        self.reader.SetCreateCellToPoint(value)

    @property
    def number_patch_arrays(self):
        """Return number of patch arrays in dataset.

        Returns
        -------
        int

        Examples
        --------
        >>> import pyvista
        >>> from pyvista import examples
        >>> filename = examples.download_cavity(load=False)
        >>> reader = pyvista.OpenFOAMReader(filename)
        >>> reader.number_patch_arrays
        4

        """
        return self.reader.GetNumberOfPatchArrays()

    @property
    def patch_array_names(self):
        """Names of patch arrays in a list.

        Returns
        -------
        list[str]

        Examples
        --------
        >>> import pyvista
        >>> from pyvista import examples
        >>> filename = examples.download_cavity(load=False)
        >>> reader = pyvista.OpenFOAMReader(filename)
        >>> reader.patch_array_names
        ['internalMesh', 'patch/movingWall', 'patch/fixedWalls', 'patch/frontAndBack']

        """
        return [self.reader.GetPatchArrayName(i) for i in range(self.number_patch_arrays)]

    def enable_patch_array(self, name):
        """Enable reading of patch array.

        Parameters
        ----------
        name : str
            Which patch array to enable.

        Examples
        --------
        >>> import pyvista
        >>> from pyvista import examples
        >>> filename = examples.download_cavity(load=False)
        >>> reader = pyvista.OpenFOAMReader(filename)
        >>> reader.enable_patch_array("patch/movingWall")
        >>> reader.patch_array_status("patch/movingWall")
        True

        """
        self.reader.SetPatchArrayStatus(name, 1)

    def disable_patch_array(self, name):
        """Disable reading of patch array.

        Parameters
        ----------
        name : str
            Which patch array to disable.

        Examples
        --------
        >>> import pyvista
        >>> from pyvista import examples
        >>> filename = examples.download_cavity(load=False)
        >>> reader = pyvista.OpenFOAMReader(filename)
        >>> reader.disable_patch_array("internalMesh")
        >>> reader.patch_array_status("internalMesh")
        False

        """
        self.reader.SetPatchArrayStatus(name, 0)

    def patch_array_status(self, name):
        """Return status of reading patch array.

        Parameters
        ----------
        name : str
            Which patch array to report status.
        Returns
        -------
        bool
                Whether the patch with the given name is to be read.

        Examples
        --------
        >>> import pyvista
        >>> from pyvista import examples
        >>> filename = examples.download_cavity(load=False)
        >>> reader = pyvista.OpenFOAMReader(filename)
        >>> reader.enable_patch_array("patch/movingWall")
        >>> reader.patch_array_status("patch/movingWall")
        True

        """
        return bool(self.reader.GetPatchArrayStatus(name))

    def enable_all_patch_arrays(self):
        """Enable reading of all patch arrays.

        Examples
        --------
        >>> import pyvista
        >>> from pyvista import examples
        >>> filename = examples.download_cavity(load=False)
        >>> reader = pyvista.OpenFOAMReader(filename)
        >>> reader.enable_all_patch_arrays()
        >>> assert reader.patch_array_status("patch/movingWall")
        >>> assert reader.patch_array_status("patch/fixedWalls")

        """
        self.reader.EnableAllPatchArrays()

    def disable_all_patch_arrays(self):
        """Disable reading of all patch arrays.

        Examples
        --------
        >>> import pyvista
        >>> from pyvista import examples
        >>> filename = examples.download_cavity(load=False)
        >>> reader = pyvista.OpenFOAMReader(filename)
        >>> reader.disable_all_patch_arrays()
        >>> assert not reader.patch_array_status("patch.movingWall")
        >>> assert not reader.patch_array_status("internalMesh")

        """
        self.reader.DisableAllPatchArrays()

    @property
    def all_patch_arrays_status(self):
        """Status of reading all patch arrays.

        Returns
        -------
        dict[str, bool]
            dict key is the patch name and the value is whether it will be read.

        Examples
        --------
        >>> import pyvista
        >>> from pyvista import examples
        >>> filename = examples.download_cavity(load=False)
        >>> reader = pyvista.OpenFOAMReader(filename)
        >>> reader.all_patch_arrays_status  #doctest: +NORMALIZE_WHITESPACE
        {'internalMesh': True, 'patch/movingWall': True, 'patch/fixedWalls': True,
         'patch/frontAndBack': True}

        """
        return {name: self.patch_array_status(name) for name in self.patch_array_names}


class POpenFOAMReader(OpenFOAMReader):
    """Parallel OpenFOAM Reader for .foam files.

    Can read parallel-decomposed mesh information and time dependent data.
    This reader can be used for serial generated data,
    parallel reconstructed data, and decomposed data.
    """

    _class_reader = staticmethod(_vtk.lazy_vtkPOpenFOAMReader)

    @property
    def case_type(self):
        """Indicate whether decomposed mesh or reconstructed mesh should be read.

        Returns
        -------
        str
            If ``'reconstructed'``, reconstructed mesh should be read.
            If ``'decomposed'``, decomposed mesh should be read.

        Raises
        ------
        ValueError
            If the value is not in ['reconstructed', 'decomposed']

        Examples
        --------
        >>> import pyvista
        >>> from pyvista import examples
        >>> filename = examples.download_cavity(load=False)
        >>> reader = pyvista.POpenFOAMReader(filename)
        >>> reader.case_type = 'reconstructed'
        >>> reader.case_type
        'reconstructed'
        """
        return 'reconstructed' if self.reader.GetCaseType() else 'decomposed'

    @case_type.setter
    def case_type(self, value):
        if value == 'reconstructed':
            self.reader.SetCaseType(1)
        elif value == 'decomposed':
            self.reader.SetCaseType(0)
        else:
            raise ValueError(f"Unknown case type '{value}'.")

        self._update_information()


class PLYReader(BaseReader):
    """PLY Reader for reading .ply files.

    Examples
    --------
    >>> import pyvista
    >>> from pyvista import examples
    >>> filename = examples.download_lobster(load=False)
    >>> filename.split("/")[-1]  # omit the path
    'lobster.ply'
    >>> reader = pyvista.get_reader(filename)
    >>> mesh = reader.read()
    >>> mesh.plot()

    """

    _class_reader = _vtk.vtkPLYReader


class OBJReader(BaseReader):
    """OBJ Reader for reading .obj files.

    Examples
    --------
    >>> import pyvista
    >>> from pyvista import examples
    >>> filename = examples.download_trumpet(load=False)
    >>> filename.split("/")[-1]  # omit the path
    'trumpet.obj'
    >>> reader = pyvista.get_reader(filename)
    >>> mesh = reader.read()
    >>> mesh.plot(cpos='yz', show_scalar_bar=False)

    """

    _class_reader = _vtk.vtkOBJReader


class STLReader(BaseReader):
    """STL Reader for .stl files.

    Examples
    --------
    >>> import pyvista
    >>> from pyvista import examples
    >>> filename = examples.download_cad_model(load=False)
    >>> filename.split("/")[-1]  # omit the path
    '42400-IDGH.stl'
    >>> reader = pyvista.get_reader(filename)
    >>> mesh = reader.read()
    >>> mesh.plot()

    """

    _class_reader = _vtk.vtkSTLReader


class TecplotReader(BaseReader):
    """Tecplot Reader for ascii .dat files.

    Examples
    --------
    >>> import pyvista
    >>> from pyvista import examples
    >>> filename = examples.download_tecplot_ascii(load=False)
    >>> reader = pyvista.get_reader(filename)
    >>> mesh = reader.read()
    >>> mesh[0].plot()

    """

    _class_reader = _vtk.vtkTecplotReader


class VTKDataSetReader(BaseReader):
    """VTK Data Set Reader for .vtk files.

    Notes
    -----
    This reader calls ``ReadAllScalarsOn``, ``ReadAllColorScalarsOn``,
    ``ReadAllNormalsOn``, ``ReadAllTCoordsOn``, ``ReadAllVectorsOn``,
    and ``ReadAllFieldsOn`` on the underlying ``vtkDataSetReader``.

    Examples
    --------
    >>> import pyvista
    >>> from pyvista import examples
    >>> filename = examples.download_brain(load=False)
    >>> filename.split("/")[-1]  # omit the path
    'brain.vtk'
    >>> reader = pyvista.get_reader(filename)
    >>> mesh = reader.read()
    >>> sliced_mesh = mesh.slice('x')
    >>> sliced_mesh.plot(cpos='yz', show_scalar_bar=False)

    """

    _class_reader = _vtk.vtkDataSetReader

    def _set_defaults_post(self):
        self.reader.ReadAllScalarsOn()
        self.reader.ReadAllColorScalarsOn()
        self.reader.ReadAllNormalsOn()
        self.reader.ReadAllTCoordsOn()
        self.reader.ReadAllVectorsOn()
        self.reader.ReadAllFieldsOn()
        self.reader.ReadAllTensorsOn()


class VTKPDataSetReader(BaseReader):
    """Parallel VTK Data Set Reader for .pvtk files."""

    _class_reader = staticmethod(_vtk.lazy_vtkPDataSetReader)


class BYUReader(BaseReader):
    """BYU Reader for .g files.

    Examples
    --------
    >>> import pyvista
    >>> from pyvista import examples
    >>> filename = examples.download_teapot(load=False)
    >>> filename.split("/")[-1]  # omit the path
    'teapot.g'
    >>> reader = pyvista.get_reader(filename)
    >>> mesh = reader.read()
    >>> mesh.plot(cpos='xy', show_scalar_bar=False)

    """

    _class_reader = _vtk.vtkBYUReader


class FacetReader(BaseReader):
    """Facet Reader for .facet files.

    Examples
    --------
    >>> import pyvista
    >>> from pyvista import examples
    >>> filename = examples.download_clown(load=False)
    >>> filename.split("/")[-1]  # omit the path
    'clown.facet'
    >>> reader = pyvista.get_reader(filename)
    >>> mesh = reader.read()
    >>> mesh.plot(color="red")

    """

    _class_reader = staticmethod(_vtk.lazy_vtkFacetReader)


class Plot3DMetaReader(BaseReader):
    """Plot3DMeta Reader for .p3d files."""

    _class_reader = staticmethod(_vtk.lazy_vtkPlot3DMetaReader)


class MultiBlockPlot3DReader(BaseReader):
    """MultiBlock Plot3D Reader."""

    _class_reader = staticmethod(_vtk.lazy_vtkMultiBlockPLOT3DReader)

    def _set_defaults(self):
        self.auto_detect_format = True

    def add_q_files(self, files):
        """Add q file(s).

        Parameters
        ----------
        files : str or Iterable(str)
            Solution file or files to add.

        """
        # files may be a list or a single filename
        if files:
            if isinstance(files, (str, pathlib.Path)):
                files = [files]
        files = [_process_filename(f) for f in files]

        if hasattr(self.reader, 'AddFileName'):
            # AddFileName was added to vtkMultiBlockPLOT3DReader sometime around
            # VTK 8.2. This method supports reading multiple q files.
            for q_filename in files:
                self.reader.AddFileName(q_filename)
        else:
            # SetQFileName is used to add a single q file to be read, and is still
            # supported in VTK9.
            if len(files) > 0:
                if len(files) > 1:
                    raise RuntimeError(
                        'Reading of multiple q files is not supported with this version of VTK.'
                    )
                self.reader.SetQFileName(files[0])

    @property
    def auto_detect_format(self):
        """Whether to try to automatically detect format such as byte order, etc."""
        return bool(self.reader.GetAutoDetectFormat())

    @auto_detect_format.setter
    def auto_detect_format(self, value):
        self.reader.SetAutoDetectFormat(value)


class CGNSReader(BaseReader, PointCellDataSelection):
    """CGNS Reader for .cgns files.

    Creates a multi-block dataset and reads unstructured grids and structured
    meshes from binary files stored in CGNS file format, with data stored at
    the nodes, cells or faces.

    By default, all point and cell arrays are loaded as well as the boundary
    patch. This varies from VTK's defaults. For more details, see
    `vtkCGNSReader <https://vtk.org/doc/nightly/html/classvtkCGNSReader.html>`_

    Examples
    --------
    Load a CGNS file.  All arrays are loaded by default.

    >>> import pyvista
    >>> from pyvista import examples
    >>> filename = examples.download_cgns_multi(load=False)
    >>> reader = pyvista.CGNSReader(filename)
    >>> reader.load_boundary_patch = False
    >>> ds = reader.read()
    >>> ds[0][0].cell_data
    pyvista DataSetAttributes
    Association     : CELL
    Active Scalars  : None
    Active Vectors  : Momentum
    Active Texture  : None
    Active Normals  : None
    Contains arrays :
        Density                 float64    (2928,)
        Momentum                float64    (2928, 3)            VECTORS
        EnergyStagnationDensity float64    (2928,)
        ViscosityEddy           float64    (2928,)
        TurbulentDistance       float64    (2928,)
        TurbulentSANuTilde      float64    (2928,)

    """

    _class_reader = staticmethod(_vtk.lazy_vtkCGNSReader)

    def _set_defaults_post(self):
        self.enable_all_point_arrays()
        self.enable_all_cell_arrays()
        self.load_boundary_patch = True

    @property
    def distribute_blocks(self) -> bool:
        """Distribute each block in each zone across ranks.

        To make the reader disregard the piece request and read all blocks in the
        zone, set this to ``False``. The default is ``True``.

        Returns
        -------
        bool
            If ``True``, distribute each block in each zone across ranks.

        Examples
        --------
        Disable distributing blocks.

        >>> import pyvista
        >>> from pyvista import examples
        >>> filename = examples.download_cgns_multi(load=False)
        >>> reader = pyvista.CGNSReader(filename)
        >>> reader.distribute_blocks = False
        >>> reader.distribute_blocks
        False

        """
        return bool(self._reader.GetDistributeBlocks())

    @distribute_blocks.setter
    def distribute_blocks(self, value: str):
        self._reader.SetDistributeBlocks(value)

    def base_array_status(self, name: str) -> bool:
        """Get status of base array with name.

        Parameters
        ----------
        name : str
            Base array name.

        Returns
        -------
        bool
            Whether reading the base array is enabled.

        """
        return bool(self.reader.GetBaseArrayStatus(name))

    @property
    def base_array_names(self):
        """Return the list of all base array names.

        Returns
        -------
        list[int]

        """
        return [self.reader.GetBaseArrayName(i) for i in range(self.number_base_arrays)]

    @property
    def number_base_arrays(self) -> int:
        """Return the number of base arrays.

        Returns
        -------
        int

        """
        return self.reader.GetNumberOfBaseArrays()

    def enable_all_bases(self):
        """Enable reading all bases.

        By default only the 0th base is read.

        Examples
        --------
        Read all bases.

        >>> import pyvista
        >>> from pyvista import examples
        >>> filename = examples.download_cgns_multi(load=False)
        >>> reader = pyvista.CGNSReader(filename)
        >>> reader.enable_all_bases()
        """
        self._reader.EnableAllBases()

    def disable_all_bases(self):
        """Disable reading all bases.

        By default only the 0th base is read.

        Examples
        --------
        Disable reading all bases.

        >>> import pyvista
        >>> from pyvista import examples
        >>> filename = examples.download_cgns_multi(load=False)
        >>> reader = pyvista.CGNSReader(filename)
        >>> reader.disable_all_bases()
        """
        self._reader.DisableAllBases()

    def family_array_status(self, name) -> bool:
        """Get status of family array with name.

        Parameters
        ----------
        name : str
            Family array name.

        Returns
        -------
        bool
            Whether reading the family array is enabled.

        """
        return bool(self.reader.GetFamilyArrayStatus(name))

    @property
    def family_array_names(self) -> List[str]:
        """Return the list of all family array names.

        Returns
        -------
        list[str]

        """
        return [self.reader.GetFamilyArrayName(i) for i in range(self.number_family_arrays)]

    @property
    def number_family_arrays(self) -> int:
        """Return the number of face arrays.

        Returns
        -------
        int

        """
        return self.reader.GetNumberOfFamilyArrays()

    def enable_all_families(self):
        """Enable reading all families.

        By default only the 0th family is read.

        Examples
        --------
        Read all bases.

        >>> import pyvista
        >>> from pyvista import examples
        >>> filename = examples.download_cgns_multi(load=False)
        >>> reader = pyvista.CGNSReader(filename)
        >>> reader.enable_all_families()
        """
        self._reader.EnableAllFamilies()

    def disable_all_families(self):
        """Disable reading all families.

        Examples
        --------
        Disable reading all bases.

        >>> import pyvista
        >>> from pyvista import examples
        >>> filename = examples.download_cgns_multi(load=False)
        >>> reader = pyvista.CGNSReader(filename)
        >>> reader.disable_all_families()
        """
        self._reader.DisableAllFamilies()

    @property
    def unsteady_pattern(self) -> bool:
        """Return or set using an unsteady pattern.

        When set to ``True`` (default is ``False``), the reader will try to
        determine FlowSolution_t nodes to read with a pattern
        matching This can be useful for unsteady solutions when
        FlowSolutionPointers are not reliable.

        Examples
        --------
        Set reading the unsteady pattern to ``True``.

        >>> import pyvista
        >>> from pyvista import examples
        >>> filename = examples.download_cgns_multi(load=False)
        >>> reader = pyvista.CGNSReader(filename)
        >>> reader.unsteady_pattern = True
        >>> reader.unsteady_pattern
        True

        """
        return self._reader.GetUseUnsteadyPattern()

    @unsteady_pattern.setter
    def unsteady_pattern(self, enabled: bool):
        self._reader.SetUseUnsteadyPattern(bool(enabled))

    @property
    def vector_3d(self) -> bool:
        """Return or set adding an empty dimension to vectors in case of 2D solutions.

        Examples
        --------
        Set adding an empty physical dimension to vectors to ``True``.

        >>> import pyvista
        >>> from pyvista import examples
        >>> filename = examples.download_cgns_multi(load=False)
        >>> reader = pyvista.CGNSReader(filename)
        >>> reader.vector_3d = True
        >>> reader.vector_3d
        True

        """
        return self._reader.GetUse3DVector()

    @vector_3d.setter
    def vector_3d(self, enabled: bool):
        self._reader.SetUse3DVector(bool(enabled))

    @property
    def load_boundary_patch(self) -> bool:
        """Return or set loading boundary patches.

        Notes
        -----
        VTK default is ``False``, but PyVista uses ``True``.

        Examples
        --------
        Enable loading boundary patches .

        >>> import pyvista
        >>> from pyvista import examples
        >>> filename = examples.download_cgns_multi(load=False)
        >>> reader = pyvista.CGNSReader(filename)
        >>> reader.load_boundary_patch = True
        >>> reader.load_boundary_patch
        True

        """
        return self._reader.GetLoadBndPatch()

    @load_boundary_patch.setter
    def load_boundary_patch(self, enabled: bool):
        self._reader.SetLoadBndPatch(bool(enabled))


class BinaryMarchingCubesReader(BaseReader):
    """BinaryMarchingCubes Reader for .tri files.

    Examples
    --------
    >>> import pyvista
    >>> from pyvista import examples
    >>> filename = examples.download_pine_roots(load=False)
    >>> filename.split("/")[-1]  # omit the path
    'pine_root.tri'
    >>> reader = pyvista.get_reader(filename)
    >>> mesh = reader.read()
    >>> mesh.plot(color="brown")

    """

    _class_reader = _vtk.vtkMCubesReader


@dataclass(order=True)
class PVDDataSet:
    """Class for storing dataset info from PVD file."""

    time: float
    part: int
    path: str
    group: str


# skip pydocstyle D102 check since docstring is taken from TimeReader
class PVDReader(BaseReader, TimeReader):
    """PVD Reader for .pvd files.

    Examples
    --------
    >>> import pyvista
    >>> from pyvista import examples
    >>> filename = examples.download_wavy(load=False)
    >>> filename.split("/")[-1]  # omit the path
    'wavy.pvd'
    >>> reader = pyvista.get_reader(filename)
    >>> reader.time_values  # doctest: +ELLIPSIS
    [0.0, 1.0, 2.0, 3.0, ... 12.0, 13.0, 14.0]
    >>> reader.set_active_time_point(5)
    >>> reader.active_time_value
    5.0
    >>> mesh = reader.read()[0]  # MultiBlock mesh with only 1 block
    >>> mesh.plot(scalars='z')

    """

    def __init__(self, filename):
        """Initialize PVD file reader."""
        self._reader = None
        self.__directory = None
        self._datasets = []
        self._active_datasets = []
        self._active_readers = []
        self._time_values = []

        self._set_filename(filename)

    @property
    def reader(self):
        """Return the PVDReader.

        .. note::
            This Reader does not have an underlying vtk Reader.

        """
        return self

    @property
    def active_readers(self):
        """Return the active readers.

        Returns
        -------
        list[pyvista.BaseReader]

        """
        return self._active_readers

    @property
    def datasets(self):
        """Return all datasets.

        Returns
        -------
        list[pyvista.PVDDataSet]

        """
        return self._datasets

    @property
    def active_datasets(self):
        """Return all active datasets.

        Returns
        -------
        list[pyvista.PVDDataSet]

        """
        return self._active_datasets

    def _set_filename(self, filename):
        """Set filename and update reader."""
        self._filename = filename
        self.__directory = os.path.join(os.path.dirname(filename))
        self._datasets = None
        self._active_datasets = None
        self._update_information()

    def read(self):
        """Read data from PVD timepoint.

        Overrides :func:`pyvista.BaseReader.read`.

        Returns
        -------
        pyvista.MultiBlock

        """
        return pyvista.MultiBlock([reader.read() for reader in self.active_readers])

    def _update_information(self):
        """If dataset information is unavailable, parse file."""
        if self.datasets is None:
            self._parse_file()

    def _parse_file(self):
        """Parse PVD file."""
        if self.path is None:
            raise ValueError("Filename must be set")
        tree = ElementTree.parse(self.path)
        root = tree.getroot()
        dataset_elements = root[0].findall("DataSet")
        datasets = []
        for element in dataset_elements:
            element_attrib = element.attrib
            datasets.append(
                PVDDataSet(
                    float(element_attrib.get('timestep', 0)),
                    int(element_attrib['part']),
                    element_attrib['file'],
                    element_attrib.get('group'),
                )
            )
        self._datasets = sorted(datasets)
        self._time_values = sorted(list(set([dataset.time for dataset in self.datasets])))

        self.set_active_time_value(self.time_values[0])

    @property
    def time_values(self):  # noqa: D102
        return self._time_values

    @property
    def number_time_points(self):  # noqa: D102
        return len(self.time_values)

    def time_point_value(self, time_point):  # noqa: D102
        return self.time_values[time_point]

    @property
    def active_time_value(self):  # noqa: D102
        # all active datasets have the same time
        return self.active_datasets[0].time

    def set_active_time_value(self, time_value):  # noqa: D102
        self._active_datasets = [dataset for dataset in self.datasets if dataset.time == time_value]
        self._active_readers = [
            get_reader(os.path.join(self.__directory, dataset.path))
            for dataset in self.active_datasets
        ]

    def set_active_time_point(self, time_point):  # noqa: D102
        self.set_active_time_value(self.time_values[time_point])


class DICOMReader(BaseReader):
    """DICOM Reader for reading ``.dcm`` files.

    This reader reads a single file or a path containing a several ``.dcm``
    files (DICOM stack).

    Parameters
    ----------
    path : str
        Path to the single DICOM (``.dcm``) file to be opened or the directory
        containing a stack of DICOM files.

    Examples
    --------
    Read a DICOM stack.

    >>> import pyvista
    >>> from pyvista import examples
    >>> path = examples.download_dicom_stack(load=False)
    >>> reader = pyvista.DICOMReader(path)
    >>> dataset = reader.read()
    >>> dataset.plot(volume=True, zoom=3, show_scalar_bar=False)

    """

    _class_reader = _vtk.vtkDICOMImageReader


class BMPReader(BaseReader):
    """BMP Reader for .bmp files.

    Examples
    --------
    >>> import pyvista
    >>> from pyvista import examples
    >>> filename = examples.download_masonry_texture(load=False)
    >>> filename.split("/")[-1]  # omit the path
    'masonry.bmp'
    >>> reader = pyvista.get_reader(filename)
    >>> mesh = reader.read()
    >>> mesh.plot()

    """

    _class_reader = _vtk.vtkBMPReader


class DEMReader(BaseReader):
    """DEM Reader for .dem files.

    Examples
    --------
    >>> import pyvista
    >>> from pyvista import examples
    >>> filename = examples.download_st_helens(load=False)
    >>> filename.split("/")[-1]  # omit the path
    'SainteHelens.dem'
    >>> reader = pyvista.get_reader(filename)
    >>> mesh = reader.read()
    >>> mesh.plot()

    """

    _class_reader = _vtk.vtkDEMReader


class JPEGReader(BaseReader):
    """JPEG Reader for .jpeg and .jpg files.

    Examples
    --------
    >>> import pyvista
    >>> from pyvista import examples
    >>> filename = examples.download_mars_jpg()
    >>> filename.split("/")[-1]  # omit the path
    'mars.jpg'
    >>> reader = pyvista.get_reader(filename)
    >>> mesh = reader.read()
    >>> mesh.plot()

    """

    _class_reader = _vtk.vtkJPEGReader


class MetaImageReader(BaseReader):
    """Meta Image Reader for .mha and .mhd files.

    Examples
    --------
    >>> import pyvista
    >>> from pyvista import examples
    >>> filename = examples.download_chest(load=False)
    >>> filename.split("/")[-1]  # omit the path
    'ChestCT-SHORT.mha'
    >>> reader = pyvista.get_reader(filename)
    >>> mesh = reader.read()
    >>> mesh.plot()

    """

    _class_reader = _vtk.vtkMetaImageReader


class NRRDReader(BaseReader):
    """NRRDReader for .nrrd and .nhdr files.

    Examples
    --------
    >>> import pyvista
    >>> from pyvista import examples
    >>> filename = examples.download_beach(load=False)
    >>> filename.split("/")[-1]  # omit the path
    'beach.nrrd'
    >>> reader = pyvista.get_reader(filename)
    >>> mesh = reader.read()
    >>> mesh.plot()

    """

    _class_reader = _vtk.vtkNrrdReader


class PNGReader(BaseReader):
    """PNGReader for .png files.

    Examples
    --------
    >>> import pyvista
    >>> from pyvista import examples
    >>> filename = examples.download_vtk_logo(load=False)
    >>> filename.split("/")[-1]  # omit the path
    'vtk.png'
    >>> reader = pyvista.get_reader(filename)
    >>> mesh = reader.read()
    >>> mesh.plot()

    """

    _class_reader = _vtk.vtkPNGReader


class PNMReader(BaseReader):
    """PNMReader for .pnm files.

    Examples
    --------
    >>> import pyvista
    >>> from pyvista import examples
    >>> filename = examples.download_gourds_pnm(load=False)
    >>> filename.split("/")[-1]  # omit the path
    'Gourds.pnm'
    >>> reader = pyvista.get_reader(filename)
    >>> mesh = reader.read()
    >>> mesh.plot()

    """

    _class_reader = _vtk.vtkPNMReader


class SLCReader(BaseReader):
    """SLCReader for .slc files.

    Examples
    --------
    >>> import pyvista
    >>> from pyvista import examples
    >>> filename = examples.download_knee_full(load=False)
    >>> filename.split("/")[-1]  # omit the path
    'vw_knee.slc'
    >>> reader = pyvista.get_reader(filename)
    >>> mesh = reader.read()
    >>> mesh.plot()

    """

    _class_reader = _vtk.vtkSLCReader


class TIFFReader(BaseReader):
    """TIFFReader for .tif and .tiff files.

    Examples
    --------
    >>> import pyvista
    >>> from pyvista import examples
    >>> filename = examples.download_crater_imagery(load=False)
    >>> filename.split("/")[-1]  # omit the path
    'BJ34_GeoTifv1-04_crater_clip.tif'
    >>> reader = pyvista.get_reader(filename)
    >>> mesh = reader.read()
    >>> mesh.plot()

    """

    _class_reader = _vtk.vtkTIFFReader


class HDRReader(BaseReader):
    """HDRReader for .hdr files.

    Examples
    --------
    >>> import pyvista
    >>> from pyvista import examples
    >>> filename = examples.download_parched_canal_4k(load=False)
    >>> filename.split("/")[-1]  # omit the path
    'parched_canal_4k.hdr'
    >>> reader = pyvista.get_reader(filename)
    >>> mesh = reader.read()
    >>> mesh.plot()

    """

    _class_reader = _vtk.vtkHDRReader


class PTSReader(BaseReader):
    """PTSReader for .pts files."""

    _class_reader = _vtk.vtkPTSReader


class AVSucdReader(BaseReader):
    """AVSucdReader for .inp files.

    Examples
    --------
    >>> import pyvista
    >>> from pyvista import examples
    >>> filename = examples.download_cells_nd(load=False)
    >>> filename.split("/")[-1]  # omit the path
    'cellsnd.ascii.inp'
    >>> reader = pyvista.get_reader(filename)
    >>> mesh = reader.read()
    >>> mesh.plot(cpos="xy")

    """

    _class_reader = _vtk.vtkAVSucdReader


class HDFReader(BaseReader):
    """HDFReader for .hdf files.

    Examples
    --------
    >>> import pyvista
    >>> from pyvista import examples
    >>> filename = examples.download_can_crushed_hdf(load=False)
    >>> filename.split("/")[-1]  # omit the path
    'can-vtu.hdf'
    >>> reader = pyvista.get_reader(filename)
    >>> mesh = reader.read()
    >>> mesh.plot()

    """

    _class_reader = staticmethod(_vtk.lazy_vtkHDFReader)

    @wraps(BaseReader.read)
    def read(self):
        """Wrap the base reader to handle the vtk 9.1 --> 9.2 change."""
        try:
            with pyvista.VtkErrorCatcher(raise_errors=True):
                return super().read()
        except RuntimeError as err:  # pragma: no cover
            if "Can't find the `Type` attribute." in str(err):
                raise RuntimeError(
                    f'{self.path} is missing the Type attribute. '
                    'The VTKHDF format has changed as of 9.2.0, '
                    f'see {HDF_HELP} for more details.'
                )
            else:
                raise err


class GLTFReader(BaseReader):
    """GLTFeader for .gltf and .glb files."""

    _class_reader = _vtk.vtkGLTFReader


class FluentReader(BaseReader):
    """FluentReader for .cas files."""

    _class_reader = _vtk.vtkFLUENTReader


class MFIXReader(BaseReader):
    """MFIXReader for .res files."""

    _class_reader = _vtk.vtkMFIXReader


class SegYReader(BaseReader):
    """SegYReader for .sgy and .segy files."""

    _class_reader = staticmethod(_vtk.lazy_vtkSegYReader)


class _GIFReader:
    """Simulate a VTK reader for GIF files."""

    _data_object = None
    _observers: List[Union[int, Callable]] = []
    _n_frames = 0
    _current_frame = 0

    def SetFileName(self, filename):
        """Needed for VTK-like compatibility with BaseReader."""
        self._filename = filename

    def UpdateInformation(self):
        """Needed for VTK-like compatibility with BaseReader."""
        pass

    def AddObserver(self, event_type, callback):
        """Needed for VTK-like compatibility with BaseReader."""
        self._observers.append([event_type, callback])

    def RemoveObservers(self, *args):
        """Needed for VTK-like compatibility with BaseReader."""
        self._observers = []

    def GetProgress(self):
        return self._current_frame / self._n_frames

    def UpdateObservers(self, event_type):
        for event_type_allowed, observer in self._observers:
            if event_type_allowed == event_type:
                observer(self, event_type)

    def Update(self):
        """Read the GIF and store internally to `_data_object`."""
        from PIL import Image, ImageSequence

        img = Image.open(self._filename)
        self._data_object = pyvista.UniformGrid(dims=(img.size[0], img.size[1], 1))

        # load each frame to the grid (RGB since gifs do not support transparency
        self._n_frames = img.n_frames
        for i, frame in enumerate(ImageSequence.Iterator(img)):
            self._current_frame = i
            data = np.array(frame.convert('RGB').getdata(), dtype=np.uint8)
            self._data_object.point_data.set_array(data, f'frame{i}')
            self.UpdateObservers(6)

        if 'frame0' in self._data_object.point_data:
            self._data_object.point_data.active_scalars_name = 'frame0'

    def GetOutputDataObject(self, *args):
        """Needed for VTK-like compatibility with BaseReader."""
        return self._data_object


class GIFReader(BaseReader):
    """GIFReader for .gif files.

    Parameters
    ----------
    path : str
        Path of the GIF to read.

    Examples
    --------
    >>> import pyvista
    >>> from pyvista import examples
    >>> filename = examples.download_gif_simple(load=False)
    >>> filename.split("/")[-1]  # omit the path
    'sample.gif'
    >>> reader = pyvista.get_reader(filename)
    >>> mesh = reader.read()
    >>> mesh.plot(rgba=True, zoom='tight', border=True, border_width=2)

    """

    _class_reader = _GIFReader


CLASS_READERS = {
    # Standard dataset readers:
    '.bmp': BMPReader,
    '.cas': FluentReader,
    '.case': EnSightReader,
    '.cgns': CGNSReader,
    '.dat': TecplotReader,
    '.dcm': DICOMReader,
    '.dem': DEMReader,
    '.facet': FacetReader,
    '.foam': POpenFOAMReader,
    '.g': BYUReader,
    '.gif': GIFReader,
    '.glb': GLTFReader,
    '.gltf': GLTFReader,
    '.img': DICOMReader,
    '.inp': AVSucdReader,
    '.jpg': JPEGReader,
    '.jpeg': JPEGReader,
    '.hdf': HDFReader,
    '.hdr': HDRReader,
    '.mha': MetaImageReader,
    '.mhd': MetaImageReader,
    '.nhdr': NRRDReader,
    '.nrrd': NRRDReader,
    '.obj': OBJReader,
    '.p3d': Plot3DMetaReader,
    '.ply': PLYReader,
    '.png': PNGReader,
    '.pnm': PNMReader,
    '.pts': PTSReader,
    '.pvd': PVDReader,
    '.pvti': XMLPImageDataReader,
    '.pvtk': VTKPDataSetReader,
    '.pvtr': XMLPRectilinearGridReader,
    '.pvtu': XMLPUnstructuredGridReader,
    '.res': MFIXReader,
    '.segy': SegYReader,
    '.sgy': SegYReader,
    '.slc': SLCReader,
    '.stl': STLReader,
    '.tif': TIFFReader,
    '.tiff': TIFFReader,
    '.tri': BinaryMarchingCubesReader,
    '.vti': XMLImageDataReader,
    '.vtk': VTKDataSetReader,
    '.vtm': XMLMultiBlockDataReader,
    '.vtmb': XMLMultiBlockDataReader,
    '.vtp': XMLPolyDataReader,
    '.vtr': XMLRectilinearGridReader,
    '.vts': XMLStructuredGridReader,
    '.vtu': XMLUnstructuredGridReader,
}


# pyvista/utilities/regression.py

"""Image regression module."""
import numpy as np

import pyvista
from pyvista import _vtk


def remove_alpha(img):
    """Remove the alpha channel from ``vtk.vtkImageData``."""
    ec = _vtk.vtkImageExtractComponents()
    ec.SetComponents(0, 1, 2)
    ec.SetInputData(img)
    ec.Update()
    return pyvista.wrap(ec.GetOutput())


def wrap_image_array(arr):
    """Wrap a numpy array as a pyvista.UniformGrid.

    Parameters
    ----------
    arr : np.ndarray
        A ``np.uint8`` ``(X, Y, (3 or 4)`` array.  For example
        ``(768, 1024, 3)``.

    """
    if arr.ndim != 3:
        raise ValueError('Expecting a X by Y by (3 or 4) array')
    if arr.shape[2] not in [3, 4]:
        raise ValueError('Expecting a X by Y by (3 or 4) array')
    if arr.dtype != np.uint8:
        raise ValueError('Expecting a np.uint8 array')

    img = _vtk.vtkImageData()
    img.SetDimensions(arr.shape[1], arr.shape[0], 1)
    wrap_img = pyvista.wrap(img)
    wrap_img.point_data['PNGImage'] = arr[::-1].reshape(-1, arr.shape[2])
    return wrap_img


def image_from_window(ren_win, as_vtk=False, ignore_alpha=False):
    """Extract the image from the render window as an array."""
    width, height = ren_win.GetSize()
    arr = _vtk.vtkUnsignedCharArray()
    ren_win.GetRGBACharPixelData(0, 0, width - 1, height - 1, 0, arr)
    data = _vtk.vtk_to_numpy(arr).reshape(height, width, -1)[::-1]
    if ignore_alpha:
        data = data[:, :, :-1]
    if as_vtk:
        return wrap_image_array(data)
    return data


def compare_images(im1, im2, threshold=1, use_vtk=True):
    """Compare two different images of the same size.

    Parameters
    ----------
    im1 : filename, numpy.ndarray, vtkRenderWindow, or vtkImageData
        Render window, numpy array representing the output of a render
        window, or ``vtkImageData``.

    im2 : filename, numpy.ndarray, vtkRenderWindow, or vtkImageData
        Render window, numpy array representing the output of a render
        window, or ``vtkImageData``.

    threshold : int, optional
        Threshold tolerance for pixel differences.  This should be
        greater than 0, otherwise it will always return an error, even
        on identical images.

    use_vtk : bool, optional
        When disabled, computes the mean pixel error over the entire
        image using numpy.  The difference between pixel is calculated
        for each RGB channel, summed, and then divided by the number
        of pixels.  This is faster than using
        ``vtk.vtkImageDifference`` but potentially less accurate.

    Returns
    -------
    float
        Total error between the images if using ``use_vtk=True``, and
        the mean pixel error when ``use_vtk=False``.

    Examples
    --------
    Compare two active plotters.

    >>> import pyvista
    >>> pl1 = pyvista.Plotter()
    >>> _ = pl1.add_mesh(pyvista.Sphere(), smooth_shading=True)
    >>> pl2 = pyvista.Plotter()
    >>> _ = pl2.add_mesh(pyvista.Sphere(), smooth_shading=False)
    >>> error = pyvista.compare_images(pl1, pl2)

    Compare images from file.

    >>> import pyvista
    >>> img1 = pyvista.read('img1.png')  # doctest:+SKIP
    >>> img2 = pyvista.read('img2.png')  # doctest:+SKIP
    >>> pyvista.compare_images(img1, img2)  # doctest:+SKIP

    """
    from pyvista import Plotter, UniformGrid, read, wrap

    def to_img(img):
        if isinstance(img, UniformGrid):  # pragma: no cover
            return img
        elif isinstance(img, _vtk.vtkImageData):
            return wrap(img)
        elif isinstance(img, str):
            return read(img)
        elif isinstance(img, np.ndarray):
            return wrap_image_array(img)
        elif isinstance(img, Plotter):
            if img._first_time:  # must be rendered first else segfault
                img._on_first_render_request()
                img.render()
            if not hasattr(img, 'ren_win'):
                raise RuntimeError(
                    'Unable to extract image from Plotter as it has already been closed.'
                )
            return image_from_window(img.ren_win, True, ignore_alpha=True)
        else:
            raise TypeError(
                f'Unsupported data type {type(img)}.  Should be '
                'Either a np.ndarray, vtkRenderWindow, or vtkImageData'
            )

    im1 = remove_alpha(to_img(im1))
    im2 = remove_alpha(to_img(im2))

    if im1.GetDimensions() != im2.GetDimensions():
        raise RuntimeError('Input images are not the same size.')

    if use_vtk:
        img_diff = _vtk.vtkImageDifference()
        img_diff.SetThreshold(threshold)
        img_diff.SetInputData(im1)
        img_diff.SetImageData(im2)
        img_diff.AllowShiftOff()  # vastly increases compute time when enabled
        # img_diff.AveragingOff()  # increases compute time
        img_diff.Update()
        return img_diff.GetThresholdedError()

    # otherwise, simply compute the mean pixel difference
    diff = np.abs(im1.point_data[0] - im2.point_data[0])
    return np.sum(diff) / im1.point_data[0].shape[0]


# pyvista/utilities/sphinx_gallery.py

"""Utilities for using pyvista with sphinx-gallery."""

import shutil

import pyvista


def _get_sg_image_scraper():
    """Return the callable scraper to be used by Sphinx-Gallery.

    It allows PyVista users to just use strings as they already can for
    'matplotlib' and 'mayavi'. Details on this implementation can be found in
    `sphinx-gallery/sphinx-gallery/494`_

    .. _sphinx-gallery/sphinx-gallery/494: https://github.com/sphinx-gallery/sphinx-gallery/pull/494
    """
    return Scraper()


class Scraper:
    """
    Save ``pyvista.Plotter`` objects.

    Used by sphinx-gallery to generate the plots from the code in the examples.

    Pass an instance of this class to ``sphinx_gallery_conf`` in your
    ``conf.py`` as the ``"image_scrapers"`` argument.
    """

    def __call__(self, block, block_vars, gallery_conf):
        """Save the figures generated after running example code.

        Called by sphinx-gallery.

        """
        try:
            from sphinx_gallery.scrapers import figure_rst
        except ImportError:
            raise ImportError('You must install `sphinx_gallery`')
        image_names = list()
        image_path_iterator = block_vars["image_path_iterator"]
        figures = pyvista.plotting._ALL_PLOTTERS
        for _, plotter in figures.items():
            fname = next(image_path_iterator)
            if hasattr(plotter, '_gif_filename'):
                # move gif to fname
                shutil.move(plotter._gif_filename, fname)
            else:
                plotter.screenshot(fname)
            image_names.append(fname)
        pyvista.close_all()  # close and clear all plotters
        return figure_rst(image_names, gallery_conf["src_dir"])


# pyvista/utilities/transformations.py

"""Module implementing point transformations and their matrices."""
import numpy as np


def axis_angle_rotation(axis, angle, point=None, deg=True):
    r"""Return a 4x4 matrix for rotation about any axis by given angle.

    Rotations around an axis that contains the origin can easily be
    computed using Rodrigues' rotation formula. The key quantity is
    the ``K`` cross product matrix for the unit vector ``n`` defining
    the axis of the rotation:

             /   0  -nz   ny \
        K =  |  nz    0  -nx |
             \ -ny   nx    0 /

    For a rotation angle ``phi`` around the vector ``n`` the rotation
    matrix is given by

        R = I + sin(phi) K  + (1 - cos(phi)) K^2

    where ``I`` is the 3-by-3 unit matrix and ``K^2`` denotes the matrix
    square of ``K``.

    If the rotation axis doesn't contain the origin, we have to first
    shift real space to transform the axis' ``p0`` reference point into
    the origin, then shift the points back after rotation:

        p' = R @ (p - p0) + p0 = R @ p + (p0 - R @ p0)

    This means that the rotation in general consists of a 3-by-3
    rotation matrix ``R``, and a translation given by
    ``b = p0 - R @ p0``. These can be encoded in a 4-by-4 transformation
    matrix by filling the 3-by-3 leading principal submatrix with ``R``,
    and filling the top 3 values in the last column with ``b``.

    Parameters
    ----------
    axis : 3-length sequence
        The direction vector of the rotation axis. It need not be a
        unit vector, but it must not be a zero vector.

    angle : float
        Angle of rotation around the axis. The angle is defined as a
        counterclockwise rotation when facing the normal vector of the
        rotation axis. Passed either in degrees or radians depending on
        the value of ``deg``.

    point : 3-length sequence, optional
        The origin of the rotation (a reference point through which the
        rotation axis passes). By default the rotation axis contains the
        origin.

    deg : bool, optional
        Whether the angle is specified in degrees. ``False`` implies
        radians.

    Examples
    --------
    Generate a transformation matrix for rotation around a cube's body
    diagonal by 120 degrees.

    >>> import numpy as np
    >>> from pyvista import transformations
    >>> trans = transformations.axis_angle_rotation([1, 1, 1], 120)

    Check that the transformation cycles the cube's three corners.

    >>> corners = np.array([
    ...     [1, 0, 0],
    ...     [0, 1, 0],
    ...     [0, 0, 1],
    ... ])
    >>> rotated = transformations.apply_transformation_to_points(trans, corners)
    >>> np.allclose(rotated, corners[[1, 2, 0], :])
    True

    """
    if deg:
        # convert to radians
        angle *= np.pi / 180

    # return early for no rotation; play it safe and check only exact equality
    if angle % (2 * np.pi) == 0:
        return np.eye(4)

    axis = np.asarray(axis, dtype='float64')
    if axis.shape != (3,):
        raise ValueError('Axis must be a 3-length array-like.')
    if point is not None:
        point = np.asarray(point)
        if point.shape != (3,):
            raise ValueError('Rotation center must be a 3-length array-like.')

    # check and normalize
    axis_norm = np.linalg.norm(axis)
    if np.isclose(axis_norm, 0):
        raise ValueError('Cannot rotate around zero vector axis.')
    if not np.isclose(axis_norm, 1):
        axis = axis / axis_norm

    # build Rodrigues' rotation matrix
    K = np.zeros((3, 3))
    K[[2, 0, 1], [1, 2, 0]] = axis
    K += -K.T
    R = np.eye(3) + np.sin(angle) * K + (1 - np.cos(angle)) * K @ K
    augmented = np.eye(4)
    augmented[:-1, :-1] = R

    if point is not None:
        # rotation of point p would be R @ (p - point) + point
        # which is R @ p + (point - R @ point)
        augmented[:-1, -1] = point - R @ point

    return augmented


def reflection(normal, point=None):
    """Return a 4x4 matrix for reflection across a normal about a point.

    Projection to a unit vector ``n`` can be computed using the dyadic
    product (or outer product) ``P`` of ``n`` with itself, which is a
    3-by-3 symmetric matrix.

    Reflection across a plane that contains the origin amounts to
    reversing the components of real space points that are perpendicular
    to the reflection plane. This gives us the transformation ``R``
    acting on a point ``p`` as

        p' = R @ p = p - 2 P @ p = (I - 2 P) @ p

    so the reflection's transformation matrix is the unit matrix minus
    twice the dyadic product ``P``.

    If additionally we want to compute a reflection to a plane that does
    not contain the origin, we can we can first shift every point in
    real space by ``-p0`` (if ``p0`` is a point that lies on the plane)

        p' = R @ (p - p0) + p0 = R @ p + (p0 - R @ p0)

    This means that the reflection in general consists of a 3-by-3
    reflection matrix ``R``, and a translation given by
    ``b = p0 - R @ p0``. These can be encoded in a 4-by-4 transformation
    matrix by filling the 3-by-3 leading principal submatrix with ``R``,
    and filling the top 3 values in the last column with ``b``.

    Parameters
    ----------
    normal : 3-length sequence
        The normal vector of the reflection plane. It need not be a unit
        vector, but it must not be a zero vector.

    point : 3-length sequence, optional
        The origin of the reflection (a reference point through which
        the reflection plane passes). By default the reflection plane
        contains the origin.

    Examples
    --------
    Generate a transformation matrix for reflection over the XZ plane.

    >>> import numpy as np
    >>> from pyvista import transformations
    >>> trans = transformations.reflection([0, 1, 0])

    Check that the reflection transforms corners of a cube among one
    another.

    >>> verts = np.array([
    ...     [ 1, -1,  1],
    ...     [-1, -1,  1],
    ...     [-1, -1, -1],
    ...     [-1, -1,  1],
    ...     [ 1,  1,  1],
    ...     [-1,  1,  1],
    ...     [-1,  1, -1],
    ...     [-1,  1,  1],
    ... ])
    >>> mirrored = transformations.apply_transformation_to_points(trans, verts)
    >>> np.allclose(mirrored, verts[[np.r_[4:8, 0:4]], :])
    True

    """
    normal = np.asarray(normal, dtype='float64')
    if normal.shape != (3,):
        raise ValueError('Normal must be a 3-length array-like.')
    if point is not None:
        point = np.asarray(point)
        if point.shape != (3,):
            raise ValueError('Plane reference point must be a 3-length array-like.')

    # check and normalize
    normal_norm = np.linalg.norm(normal)
    if np.isclose(normal_norm, 0):
        raise ValueError('Plane normal cannot be zero.')
    if not np.isclose(normal_norm, 1):
        normal = normal / normal_norm

    # build reflection matrix
    projection = np.outer(normal, normal)
    R = np.eye(3) - 2 * projection
    augmented = np.eye(4)
    augmented[:-1, :-1] = R

    if point is not None:
        # reflection of point p would be R @ (p - point) + point
        # which is R @ p + (point - R @ point)
        augmented[:-1, -1] = point - R @ point

    return augmented


def apply_transformation_to_points(transformation, points, inplace=False):
    """Apply a given transformation matrix (3x3 or 4x4) to a set of points.

    Parameters
    ----------
    transformation : np.ndarray
        Transformation matrix of shape (3, 3) or (4, 4).

    points : np.ndarray
        Array of points to be transformed of shape (N, 3).

    inplace : bool, optional
        Updates points in-place while returning nothing.

    Returns
    -------
    numpy.ndarray
        Transformed points.

    Examples
    --------
    Scale a set of points in-place.

    >>> import numpy as np
    >>> import pyvista
    >>> from pyvista import examples
    >>> points = examples.load_airplane().points
    >>> points_orig = points.copy()
    >>> scale_factor = 2
    >>> tf = scale_factor * np.eye(4)
    >>> tf[3, 3,] = 1
    >>> pyvista.transformations.apply_transformation_to_points(tf, points, inplace=True)
    >>> assert np.all(np.isclose(points, scale_factor * points_orig))

    """
    transformation_shape = transformation.shape
    if transformation_shape not in ((3, 3), (4, 4)):
        raise ValueError('`transformation` must be of shape (3, 3) or (4, 4).')

    if points.shape[1] != 3:
        raise ValueError('`points` must be of shape (N, 3).')

    if transformation_shape[0] == 4:
        # Divide by scale factor when homogeneous
        transformation /= transformation[3, 3]

        # Add the homogeneous coordinate
        # `points_2` is a copy of the data, not a view
        points_2 = np.empty((len(points), 4))
        points_2[:, :-1] = points
        points_2[:, -1] = 1
    else:
        points_2 = points

    # Paged matrix multiplication. For arrays with ndim > 2, matmul assumes
    # that the matrices to be multiplied lie in the last two dimensions.
    points_2 = (transformation[np.newaxis, :, :] @ points_2.T)[0, :3, :].T

    # If inplace, set the points
    if inplace:
        points[:] = points_2
    else:
        # otherwise return the new points
        return points_2


# pyvista/utilities/wrappers.py

"""Wrapper mapping.

Setting ``pyvista._wrappers`` allows for developers to override the default class used
to coerce a ``vtkDataSet`` into a pyvista object.  This is useful when creating a
subclass of a :class:`pyvista.DataSet` class.

Examples
--------
A user-defined Foo class is defined that extends the functionality of
:class:`pyvista.PolyData`.  This class is set as the default wrapper for
``vtkPolyData`` objects.

>>> import pyvista
>>> class Foo(pyvista.PolyData):
...     pass  # Extend PolyData here
>>> pyvista._wrappers['vtkPolyData'] = Foo
>>> uniform_grid = pyvista.UniformGrid()
>>> surface = uniform_grid.extract_surface()
>>> assert isinstance(surface, Foo)

"""

import pyvista

_wrappers = {
    'vtkExplicitStructuredGrid': pyvista.ExplicitStructuredGrid,
    'vtkUnstructuredGrid': pyvista.UnstructuredGrid,
    'vtkRectilinearGrid': pyvista.RectilinearGrid,
    'vtkStructuredGrid': pyvista.StructuredGrid,
    'vtkPolyData': pyvista.PolyData,
    'vtkImageData': pyvista.UniformGrid,
    'vtkStructuredPoints': pyvista.UniformGrid,
    'vtkMultiBlockDataSet': pyvista.MultiBlock,
    'vtkTable': pyvista.Table,
    # 'vtkParametricSpline': pyvista.Spline,
}


# pyvista/utilities/xvfb.py

"""Start xvfb from Python."""
import os
import time

XVFB_INSTALL_NOTES = """Please install Xvfb with:

Debian
$ sudo apt install libgl1-mesa-glx xvfb

CentOS / RHL
$ sudo yum install libgl1-mesa-glx xvfb

"""


def start_xvfb(wait=3, window_size=None):
    """Start the virtual framebuffer Xvfb.

    Parameters
    ----------
    wait : float, optional
        Time to wait for the virtual framebuffer to start.  Set to 0
        to disable wait.

    window_size : list, optional
        Window size of the virtual frame buffer.  Defaults to
        :attr:`pyvista.global_theme.window_size
        <pyvista.themes.DefaultTheme.window_size>`.

    Notes
    -----
    Only available on Linux.  Be sure to install ``libgl1-mesa-glx
    xvfb`` in your package manager.

    Examples
    --------
    >>> import pyvista
    >>> pyvista.start_xvfb()  # doctest:+SKIP

    """
    from pyvista import global_theme

    if os.name != 'posix':
        raise OSError('`start_xvfb` is only supported on Linux')

    if os.system('which Xvfb > /dev/null'):
        raise OSError(XVFB_INSTALL_NOTES)

    # use current default window size
    if window_size is None:
        window_size = global_theme.window_size
    window_size_parm = f'{window_size[0]:d}x{window_size[1]:d}x24'
    display_num = ':99'
    os.system(f'Xvfb {display_num} -screen 0 {window_size_parm} > /dev/null 2>&1 &')
    os.environ['DISPLAY'] = display_num
    if wait:
        time.sleep(wait)


# setup.py

"""Installation file for python pyvista module."""
from io import open as io_open
import os

from setuptools import setup

package_name = 'pyvista'

__version__ = None
filepath = os.path.dirname(__file__)
version_file = os.path.join(filepath, package_name, '_version.py')
with io_open(version_file, mode='r') as fd:
    exec(fd.read())

install_requires = [
    'numpy',
    'imageio',
    'pillow',
    'appdirs',
    'scooby>=0.5.1',
    'vtk',
    "typing-extensions; python_version < '3.8'",
]

readme_file = os.path.join(filepath, 'README.rst')

setup(
    name=package_name,
    packages=[
        'pyvista',
        'pyvista.examples',
        'pyvista.core',
        'pyvista.core.filters',
        'pyvista.demos',
        'pyvista.jupyter',
        'pyvista.plotting',
        'pyvista.utilities',
        'pyvista.ext',
    ],
    version=__version__,
    description='Easier Pythonic interface to VTK',
    long_description=io_open(readme_file, encoding="utf-8").read(),
    long_description_content_type='text/x-rst',
    author='PyVista Developers',
    author_email='info@pyvista.org',
    license='MIT',
    classifiers=[
        'Development Status :: 4 - Beta',
        'Intended Audience :: Science/Research',
        'Topic :: Scientific/Engineering :: Information Analysis',
        'License :: OSI Approved :: MIT License',
        'Operating System :: Microsoft :: Windows',
        'Operating System :: POSIX',
        'Operating System :: MacOS',
        'Programming Language :: Python :: 3.7',
        'Programming Language :: Python :: 3.8',
        'Programming Language :: Python :: 3.9',
        'Programming Language :: Python :: 3.10',
    ],
    url='https://github.com/pyvista/pyvista',
    keywords='vtk numpy plotting mesh',
    package_data={
        'pyvista': [
            'py.typed',
        ],
        'pyvista.examples': [
            'airplane.ply',
            'ant.ply',
            'channels.vti',
            'hexbeam.vtk',
            'sphere.ply',
            'nut.ply',
            'uniform.vtk',
            'rectilinear.vtk',
            'globe.vtk',
            '2k_earth_daymap.jpg',
        ],
    },
    project_urls={
        "Documentation": "https://docs.pyvista.org/",
        "Bug Tracker": "https://github.com/pyvista/pyvista/issues",
        "Source Code": "https://github.com/pyvista/pyvista",
    },
    python_requires='>=3.7.*',
    install_requires=install_requires,
    extras_require={
        'all': [
            'matplotlib',
            'colorcet',
            'cmocean',
            'meshio>=5.2',
            'ipywidgets<8.0',
            'ipyvtklink',
            'panel',
            'pythreejs',
        ],
        'colormaps': ['matplotlib', 'colorcet', 'cmocean'],
        'io': ['meshio>=5.2'],
        'jupyter': ['ipyvtklink', 'ipywidgets<8.0', 'panel', 'pythreejs'],
    },
    zip_safe=False,
)


# pyvista/__init__.py

"""PyVista package for 3D plotting and mesh analysis."""

MAX_N_COLOR_BARS = 10

from typing import Optional
import warnings
import os
import appdirs

# Load default theme.  Must be loaded first.
from pyvista._version import __version__
from pyvista.plotting import *
from pyvista.utilities import *
from pyvista.core import *
from pyvista.utilities.misc import _get_vtk_id_type, vtk_version_info, _set_plot_theme_from_env
from pyvista import _vtk
from pyvista.jupyter import set_jupyter_backend, PlotterITK
from pyvista.themes import set_plot_theme, load_theme, _rcParams
from pyvista.themes import DefaultTheme as _GlobalTheme  # hide this

# Per contract with Sphinx-Gallery, this method must be available at top level
from pyvista.utilities.sphinx_gallery import _get_sg_image_scraper

from pyvista.utilities.wrappers import _wrappers

global_theme = _GlobalTheme()
rcParams = _rcParams()  # raises DeprecationError when used

# Set preferred plot theme
_set_plot_theme_from_env()

# get the int type from vtk
ID_TYPE = _get_vtk_id_type()

# determine if using at least vtk 5.0.0
if vtk_version_info.major < 5:  # pragma: no cover
    from pyvista.core.errors import VTKVersionError

    raise VTKVersionError('VTK version must be 5.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"

# If available, a local vtk-data instance will be used for examples
VTK_DATA_PATH: Optional[str] = None
if 'PYVISTA_VTK_DATA' in os.environ:
    VTK_DATA_PATH = os.environ['PYVISTA_VTK_DATA']
    if not os.path.isdir(VTK_DATA_PATH):
        warnings.warn(f"VTK_DATA_PATH: {VTK_DATA_PATH} is an invalid path")
    if not os.path.isdir(os.path.join(VTK_DATA_PATH, 'Data')):
        warnings.warn(f"VTK_DATA_PATH: {os.path.join(VTK_DATA_PATH, 'Data')} does not exist")

# 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


# allow user to override the examples path
if 'PYVISTA_USERDATA_PATH' in os.environ:
    USER_DATA_PATH = os.environ['PYVISTA_USERDATA_PATH']
    if not os.path.isdir(USER_DATA_PATH):
        raise FileNotFoundError(f'Invalid PYVISTA_USERDATA_PATH at {USER_DATA_PATH}')

else:
    USER_DATA_PATH = appdirs.user_data_dir('pyvista')
    try:
        # Set up data directory
        os.makedirs(USER_DATA_PATH, exist_ok=True)
    except Exception as e:
        warnings.warn(
            f'Unable to create `PYVISTA_USERDATA_PATH` at "{USER_DATA_PATH}"\n'
            f'Error: {e}\n\n'
            'Override the default path by setting the environmental variable '
            '`PYVISTA_USERDATA_PATH` to a writable path.'
        )
        USER_DATA_PATH = ''

EXAMPLES_PATH = os.path.join(USER_DATA_PATH, 'examples')
try:
    os.makedirs(EXAMPLES_PATH, exist_ok=True)
except Exception as e:
    warnings.warn(
        f'Unable to create `EXAMPLES_PATH` at "{EXAMPLES_PATH}"\n'
        f'Error: {e}\n\n'
        'Override the default path by setting the environmental variable '
        '`PYVISTA_USERDATA_PATH` to a writable path.'
    )
    EXAMPLES_PATH = ''

# 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}"


# pyvista/_typing.py

"""Type aliases for type hints."""

from __future__ import annotations

from typing import TYPE_CHECKING, Dict, List, Sequence, Tuple, Union

import numpy as np

from . import _vtk

if TYPE_CHECKING:  # pragma: no cover
    from .plotting.colors import Color

Vector = Union[List[float], Tuple[float, float, float], np.ndarray]
VectorArray = Union[np.ndarray, Sequence[Vector]]
Number = Union[float, int, np.number]
NumericArray = Union[Sequence[Number], np.ndarray]
color_like = Union[
    Tuple[int, int, int],
    Tuple[int, int, int, int],
    Tuple[float, float, float],
    Tuple[float, float, float, float],
    Sequence[int],
    Sequence[float],
    np.ndarray,
    Dict[str, Union[int, float, str]],
    str,
    "Color",
    _vtk.vtkColor3ub,
]
# Overwrite default docstring, as sphinx is not able to capture the docstring
# when it is put beneath the definition somehow?
color_like.__doc__ = """Any object convertible to a :class:`Color`."""


# 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, 37, 'dev0'

# Nice string for the version
__version__ = '.'.join(map(str, version_info))


# pyvista/_vtk.py

"""
Import from vtk.

These are the modules within vtk that must be loaded across pyvista.
Here, we attempt to import modules using the VTK9 ``vtkmodules``
package, which lets us only have to import from select modules and not
the entire library.

"""
# flake8: noqa: F401

# Checking for VTK9 here even though 8.2 contains vtkmodules.  There
# are enough idiosyncrasies to VTK 8.2, and supporting it would lead
# to obscure code.

try:
    from vtkmodules.vtkCommonCore import vtkVersion

    VTK9 = vtkVersion().GetVTKMajorVersion() >= 9
except ImportError:  # pragma: no cover
    VTK9 = False

# for charts
_has_vtkRenderingContextOpenGL2 = False

if VTK9:
    # vtkExtractEdges moved from vtkFiltersExtraction to vtkFiltersCore in
    # VTK commit d9981b9aeb93b42d1371c6e295d76bfdc18430bd
    try:
        from vtkmodules.vtkFiltersCore import vtkExtractEdges
    except ImportError:
        from vtkmodules.vtkFiltersExtraction import vtkExtractEdges

    # vtkCellTreeLocator moved from vtkFiltersGeneral to vtkCommonDataModel in
    # VTK commit 4a29e6f7dd9acb460644fe487d2e80aac65f7be9
    try:
        from vtkmodules.vtkCommonDataModel import vtkCellTreeLocator
    except ImportError:
        from vtkmodules.vtkFiltersGeneral import vtkCellTreeLocator

    from vtkmodules.numpy_interface.dataset_adapter import (
        VTKArray,
        VTKObjectWrapper,
        numpyTovtkDataArray,
    )
    from vtkmodules.util.numpy_support import (
        get_vtk_array_type,
        numpy_to_vtk,
        numpy_to_vtkIdTypeArray,
        vtk_to_numpy,
    )
    from vtkmodules.vtkChartsCore import (
        vtkAxis,
        vtkChart,
        vtkChartBox,
        vtkChartPie,
        vtkChartXY,
        vtkChartXYZ,
        vtkPlotArea,
        vtkPlotBar,
        vtkPlotBox,
        vtkPlotLine,
        vtkPlotLine3D,
        vtkPlotPie,
        vtkPlotPoints,
        vtkPlotPoints3D,
        vtkPlotStacked,
        vtkPlotSurface,
    )
    from vtkmodules.vtkCommonColor import vtkColorSeries
    from vtkmodules.vtkCommonComputationalGeometry import (
        vtkKochanekSpline,
        vtkParametricBohemianDome,
        vtkParametricBour,
        vtkParametricBoy,
        vtkParametricCatalanMinimal,
        vtkParametricConicSpiral,
        vtkParametricCrossCap,
        vtkParametricDini,
        vtkParametricEllipsoid,
        vtkParametricEnneper,
        vtkParametricFigure8Klein,
        vtkParametricFunction,
        vtkParametricHenneberg,
        vtkParametricKlein,
        vtkParametricKuen,
        vtkParametricMobius,
        vtkParametricPluckerConoid,
        vtkParametricPseudosphere,
        vtkParametricRandomHills,
        vtkParametricRoman,
        vtkParametricSpline,
        vtkParametricSuperEllipsoid,
        vtkParametricSuperToroid,
        vtkParametricTorus,
    )
    from vtkmodules.vtkCommonCore import (
        VTK_ARIAL,
        VTK_COURIER,
        VTK_TIMES,
        VTK_UNSIGNED_CHAR,
        buffer_shared,
        mutable,
        vtkAbstractArray,
        vtkBitArray,
        vtkCharArray,
        vtkCommand,
        vtkDataArray,
        vtkDoubleArray,
        vtkFileOutputWindow,
        vtkFloatArray,
        vtkIdList,
        vtkIdTypeArray,
        vtkLookupTable,
        vtkOutputWindow,
        vtkPoints,
        vtkSignedCharArray,
        vtkStringArray,
        vtkStringOutputWindow,
        vtkTypeInt32Array,
        vtkTypeInt64Array,
        vtkTypeUInt32Array,
        vtkUnsignedCharArray,
        vtkWeakReference,
    )
    from vtkmodules.vtkCommonDataModel import (
        VTK_HEXAHEDRON,
        VTK_PYRAMID,
        VTK_QUAD,
        VTK_QUADRATIC_HEXAHEDRON,
        VTK_QUADRATIC_PYRAMID,
        VTK_QUADRATIC_QUAD,
        VTK_QUADRATIC_TETRA,
        VTK_QUADRATIC_TRIANGLE,
        VTK_QUADRATIC_WEDGE,
        VTK_TETRA,
        VTK_TRIANGLE,
        VTK_WEDGE,
        vtkCellArray,
        vtkCellLocator,
        vtkColor3ub,
        vtkCompositeDataSet,
        vtkDataObject,
        vtkDataSet,
        vtkDataSetAttributes,
        vtkExplicitStructuredGrid,
        vtkFieldData,
        vtkGenericCell,
        vtkImageData,
        vtkImplicitFunction,
        vtkMultiBlockDataSet,
        vtkNonMergingPointLocator,
        vtkPerlinNoise,
        vtkPiecewiseFunction,
        vtkPlane,
        vtkPlaneCollection,
        vtkPlanes,
        vtkPointLocator,
        vtkPointSet,
        vtkPolyData,
        vtkPolyLine,
        vtkPolyPlane,
        vtkPyramid,
        vtkRectf,
        vtkRectilinearGrid,
        vtkSelection,
        vtkSelectionNode,
        vtkStaticCellLocator,
        vtkStaticPointLocator,
        vtkStructuredGrid,
        vtkTable,
        vtkUnstructuredGrid,
    )
    from vtkmodules.vtkCommonExecutionModel import vtkImageToStructuredGrid
    from vtkmodules.vtkCommonMath import vtkMatrix3x3, vtkMatrix4x4
    from vtkmodules.vtkCommonTransforms import vtkTransform
    from vtkmodules.vtkFiltersCore import (
        VTK_BEST_FITTING_PLANE,
        vtkAppendArcLength,
        vtkAppendFilter,
        vtkAppendPolyData,
        vtkCellCenters,
        vtkCellDataToPointData,
        vtkCenterOfMass,
        vtkCleanPolyData,
        vtkClipPolyData,
        vtkConnectivityFilter,
        vtkContourFilter,
        vtkCutter,
        vtkDecimatePro,
        vtkDelaunay2D,
        vtkDelaunay3D,
        vtkElevationFilter,
        vtkExplicitStructuredGridToUnstructuredGrid,
        vtkFeatureEdges,
        vtkFlyingEdges3D,
        vtkGlyph3D,
        vtkImplicitPolyDataDistance,
        vtkMarchingCubes,
        vtkMassProperties,
        vtkPointDataToCellData,
        vtkPolyDataNormals,
        vtkProbeFilter,
        vtkQuadricDecimation,
        vtkResampleWithDataSet,
        vtkSmoothPolyDataFilter,
        vtkStripper,
        vtkThreshold,
        vtkTriangleFilter,
        vtkTubeFilter,
        vtkUnstructuredGridToExplicitStructuredGrid,
        vtkWindowedSincPolyDataFilter,
    )
    from vtkmodules.vtkFiltersExtraction import (
        vtkExtractGeometry,
        vtkExtractGrid,
        vtkExtractSelection,
    )
    from vtkmodules.vtkFiltersFlowPaths import vtkEvenlySpacedStreamlines2D, vtkStreamTracer
    from vtkmodules.vtkFiltersGeneral import (
        vtkAxes,
        vtkBooleanOperationPolyDataFilter,
        vtkBoxClipDataSet,
        vtkClipClosedSurface,
        vtkCursor3D,
        vtkCurvatures,
        vtkDataSetTriangleFilter,
        vtkGradientFilter,
        vtkIntersectionPolyDataFilter,
        vtkOBBTree,
        vtkRectilinearGridToPointSet,
        vtkRectilinearGridToTetrahedra,
        vtkShrinkFilter,
        vtkTableBasedClipDataSet,
        vtkTableToPolyData,
        vtkTessellatorFilter,
        vtkTransformFilter,
        vtkWarpScalar,
        vtkWarpVector,
    )
    from vtkmodules.vtkFiltersGeometry import (
        vtkCompositeDataGeometryFilter,
        vtkDataSetSurfaceFilter,
        vtkGeometryFilter,
        vtkStructuredGridGeometryFilter,
    )
    from vtkmodules.vtkFiltersHybrid import vtkPolyDataSilhouette
    from vtkmodules.vtkFiltersModeling import (
        vtkAdaptiveSubdivisionFilter,
        vtkButterflySubdivisionFilter,
        vtkCollisionDetectionFilter,
        vtkDijkstraGraphGeodesicPath,
        vtkFillHolesFilter,
        vtkLinearExtrusionFilter,
        vtkLinearSubdivisionFilter,
        vtkLoopSubdivisionFilter,
        vtkOutlineFilter,
        vtkRibbonFilter,
        vtkRotationalExtrusionFilter,
        vtkSelectEnclosedPoints,
        vtkSubdivideTetra,
        vtkTrimmedExtrusionFilter,
    )
    from vtkmodules.vtkFiltersParallel import vtkIntegrateAttributes
    from vtkmodules.vtkFiltersParallelDIY2 import vtkRedistributeDataSetFilter
    from vtkmodules.vtkFiltersPoints import vtkGaussianKernel, vtkPointInterpolator
    from vtkmodules.vtkFiltersSources import (
        vtkArcSource,
        vtkArrowSource,
        vtkConeSource,
        vtkCubeSource,
        vtkCylinderSource,
        vtkDiskSource,
        vtkFrustumSource,
        vtkLineSource,
        vtkOutlineCornerFilter,
        vtkOutlineCornerSource,
        vtkParametricFunctionSource,
        vtkPlaneSource,
        vtkPlatonicSolidSource,
        vtkPointSource,
        vtkRegularPolygonSource,
        vtkSphereSource,
        vtkSuperquadricSource,
        vtkTessellatedBoxSource,
    )
    from vtkmodules.vtkFiltersStatistics import vtkComputeQuartiles
    from vtkmodules.vtkFiltersTexture import vtkTextureMapToPlane, vtkTextureMapToSphere
    from vtkmodules.vtkFiltersVerdict import vtkCellQuality, vtkCellSizeFilter
    from vtkmodules.vtkIOEnSight import vtkGenericEnSightReader
    from vtkmodules.vtkIOGeometry import (
        vtkAVSucdReader,
        vtkBYUReader,
        vtkFLUENTReader,
        vtkGLTFReader,
        vtkMCubesReader,
        vtkMFIXReader,
        vtkOBJReader,
        vtkOpenFOAMReader,
        vtkPTSReader,
        vtkSTLReader,
        vtkSTLWriter,
        vtkTecplotReader,
    )
    from vtkmodules.vtkIOImage import (
        vtkBMPReader,
        vtkDEMReader,
        vtkDICOMImageReader,
        vtkHDRReader,
        vtkJPEGReader,
        vtkMetaImageReader,
        vtkNrrdReader,
        vtkPNGReader,
        vtkPNMReader,
        vtkSLCReader,
        vtkTIFFReader,
    )
    from vtkmodules.vtkIOInfovis import vtkDelimitedTextReader
    from vtkmodules.vtkIOLegacy import (
        vtkDataReader,
        vtkDataSetReader,
        vtkDataSetWriter,
        vtkDataWriter,
        vtkPolyDataReader,
        vtkPolyDataWriter,
        vtkRectilinearGridReader,
        vtkRectilinearGridWriter,
        vtkSimplePointsWriter,
        vtkStructuredGridReader,
        vtkStructuredGridWriter,
        vtkUnstructuredGridReader,
        vtkUnstructuredGridWriter,
    )
    from vtkmodules.vtkIOPLY import vtkPLYReader, vtkPLYWriter
    from vtkmodules.vtkIOXML import (
        vtkXMLImageDataReader,
        vtkXMLImageDataWriter,
        vtkXMLMultiBlockDataReader,
        vtkXMLMultiBlockDataWriter,
        vtkXMLPImageDataReader,
        vtkXMLPolyDataReader,
        vtkXMLPolyDataWriter,
        vtkXMLPRectilinearGridReader,
        vtkXMLPUnstructuredGridReader,
        vtkXMLReader,
        vtkXMLRectilinearGridReader,
        vtkXMLRectilinearGridWriter,
        vtkXMLStructuredGridReader,
        vtkXMLStructuredGridWriter,
        vtkXMLUnstructuredGridReader,
        vtkXMLUnstructuredGridWriter,
        vtkXMLWriter,
    )
    from vtkmodules.vtkImagingCore import (
        vtkExtractVOI,
        vtkImageDifference,
        vtkImageExtractComponents,
        vtkImageFlip,
        vtkImageThreshold,
        vtkRTAnalyticSource,
    )
    from vtkmodules.vtkImagingGeneral import vtkImageGaussianSmooth, vtkImageMedian3D
    from vtkmodules.vtkImagingHybrid import vtkSampleFunction, vtkSurfaceReconstructionFilter
    from vtkmodules.vtkImagingMorphological import vtkImageDilateErode3D
    from vtkmodules.vtkInteractionWidgets import (
        vtkBoxWidget,
        vtkButtonWidget,
        vtkImplicitPlaneWidget,
        vtkLineWidget,
        vtkOrientationMarkerWidget,
        vtkPlaneWidget,
        vtkScalarBarWidget,
        vtkSliderRepresentation2D,
        vtkSliderWidget,
        vtkSphereWidget,
        vtkSplineWidget,
        vtkTexturedButtonRepresentation2D,
    )
    from vtkmodules.vtkPythonContext2D import vtkPythonItem
    from vtkmodules.vtkRenderingAnnotation import (
        vtkAnnotatedCubeActor,
        vtkAxesActor,
        vtkAxisActor2D,
        vtkCornerAnnotation,
        vtkCubeAxesActor,
        vtkLegendBoxActor,
        vtkScalarBarActor,
    )
    from vtkmodules.vtkRenderingContext2D import (
        vtkBlockItem,
        vtkBrush,
        vtkContext2D,
        vtkContextActor,
        vtkContextScene,
        vtkImageItem,
        vtkPen,
    )

    try:
        # Necessary for displaying charts, otherwise crashes on rendering
        import vtkmodules.vtkRenderingContextOpenGL2

        _has_vtkRenderingContextOpenGL2 = True
    except ImportError:  # pragma: no cover
        pass

    from vtkmodules.vtkImagingFourier import (
        vtkImageButterworthHighPass,
        vtkImageButterworthLowPass,
        vtkImageFFT,
        vtkImageRFFT,
    )
    from vtkmodules.vtkRenderingCore import (
        vtkActor,
        vtkActor2D,
        vtkCamera,
        vtkCellPicker,
        vtkColorTransferFunction,
        vtkCoordinate,
        vtkDataSetMapper,
        vtkImageActor,
        vtkLight,
        vtkLightActor,
        vtkLightKit,
        vtkMapper,
        vtkPointPicker,
        vtkPolyDataMapper,
        vtkPolyDataMapper2D,
        vtkPropAssembly,
        vtkProperty,
        vtkPropPicker,
        vtkRenderedAreaPicker,
        vtkRenderer,
        vtkRenderWindow,
        vtkRenderWindowInteractor,
        vtkSelectVisiblePoints,
        vtkSkybox,
        vtkTextActor,
        vtkTexture,
        vtkVolume,
        vtkVolumeProperty,
        vtkWindowToImageFilter,
        vtkWorldPointPicker,
    )
    from vtkmodules.vtkRenderingFreeType import vtkVectorText
    from vtkmodules.vtkRenderingLabel import vtkLabelPlacementMapper, vtkPointSetToLabelHierarchy
    from vtkmodules.vtkRenderingOpenGL2 import (
        vtkCameraPass,
        vtkEDLShading,
        vtkOpenGLHardwareSelector,
        vtkOpenGLRenderer,
        vtkOpenGLTexture,
        vtkRenderPassCollection,
        vtkRenderStepsPass,
        vtkSequencePass,
        vtkShadowMapPass,
    )
    from vtkmodules.vtkRenderingUI import vtkGenericRenderWindowInteractor
    from vtkmodules.vtkRenderingVolume import (
        vtkFixedPointVolumeRayCastMapper,
        vtkGPUVolumeRayCastMapper,
    )
    from vtkmodules.vtkRenderingVolumeOpenGL2 import (
        vtkOpenGLGPUVolumeRayCastMapper,
        vtkSmartVolumeMapper,
    )
    from vtkmodules.vtkViewsContext2D import vtkContextInteractorStyle

    # lazy import for some of the less used readers
    def lazy_vtkOBJExporter():
        """Lazy import of the vtkOBJExporter."""
        from vtkmodules.vtkIOExport import vtkOBJExporter

        return vtkOBJExporter()

    def lazy_vtkVRMLImporter():
        """Lazy import of the vtkVRMLImporter."""
        from vtkmodules.vtkIOImport import vtkVRMLImporter

        return vtkVRMLImporter()

    def lazy_vtkVRMLExporter():
        """Lazy import of the vtkVRMLExporter."""
        from vtkmodules.vtkIOExport import vtkVRMLExporter

        return vtkVRMLExporter()

    def lazy_vtkGL2PSExporter():
        """Lazy import of the vtkGL2PSExporter."""
        from vtkmodules.vtkIOExportGL2PS import vtkGL2PSExporter

        return vtkGL2PSExporter()

    def lazy_vtkFacetReader():
        """Lazy import of the vtkFacetReader."""
        from vtkmodules.vtkFiltersHybrid import vtkFacetReader

        return vtkFacetReader()

    def lazy_vtkPDataSetReader():
        """Lazy import of the vtkPDataSetReader."""
        from vtkmodules.vtkIOParallel import vtkPDataSetReader

        return vtkPDataSetReader()

    def lazy_vtkMultiBlockPLOT3DReader():
        """Lazy import of the vtkMultiBlockPLOT3DReader."""
        from vtkmodules.vtkIOParallel import vtkMultiBlockPLOT3DReader

        return vtkMultiBlockPLOT3DReader()

    def lazy_vtkPlot3DMetaReader():
        """Lazy import of the vtkPlot3DMetaReader."""
        from vtkmodules.vtkIOParallel import vtkPlot3DMetaReader

        return vtkPlot3DMetaReader()

    def lazy_vtkSegYReader():
        """Lazy import of the vtkSegYReader."""
        from vtkmodules.vtkIOSegY import vtkSegYReader

        return vtkSegYReader()

    def lazy_vtkHDFReader():
        """Lazy import of the vtkHDFReader."""
        from vtkmodules.vtkIOHDF import vtkHDFReader

        return vtkHDFReader()

    def lazy_vtkCGNSReader():
        """Lazy import of the vtkCGNSReader."""
        from vtkmodules.vtkIOCGNSReader import vtkCGNSReader

        return vtkCGNSReader()

    def lazy_vtkPOpenFOAMReader():
        """Lazy import of the vtkPOpenFOAMReader."""
        from vtkmodules.vtkIOParallel import vtkPOpenFOAMReader
        from vtkmodules.vtkParallelCore import vtkDummyController

        # Workaround waiting for the fix to be upstream (MR 9195 gitlab.kitware.com/vtk/vtk)
        reader = vtkPOpenFOAMReader()
        reader.SetController(vtkDummyController())
        return reader

else:  # pragma: no cover

    # maintain VTK 8.2 compatibility
    try:
        from vtk.vtkCommonKitPython import buffer_shared, vtkAbstractArray, vtkWeakReference
    except ImportError:
        from vtk.vtkCommonCore import buffer_shared, vtkAbstractArray, vtkWeakReference

    import vtk

    # vtk8 already has an import all, so we can just mirror it here at
    # no cost
    from vtk import *
    from vtk.numpy_interface.dataset_adapter import VTKArray, VTKObjectWrapper, numpyTovtkDataArray
    from vtk.util.numpy_support import (
        get_vtk_array_type,
        numpy_to_vtk,
        numpy_to_vtkIdTypeArray,
        vtk_to_numpy,
    )

    # match the imports for VTK9
    def lazy_vtkOBJExporter():
        """Lazy import of the vtkOBJExporter."""
        return vtk.vtkOBJExporter()

    def lazy_vtkVRMLImporter():
        """Lazy import of the vtkVRMLImporter."""
        return vtk.vtkVRMLImporter()

    def lazy_vtkVRMLExporter():
        """Lazy import of the vtkVRMLExporter."""
        return vtk.vtkVRMLExporter()

    def lazy_vtkGL2PSExporter():
        """Lazy import of the vtkGL2PSExporter."""
        return vtk.vtkGL2PSExporter()

    def lazy_vtkFacetReader():
        """Lazy import of the vtkFacetReader."""
        return vtk.vtkFacetReader()

    def lazy_vtkPDataSetReader():
        """Lazy import of the vtkPDataSetReader."""
        return vtk.vtkPDataSetReader()

    def lazy_vtkMultiBlockPLOT3DReader():
        """Lazy import of the vtkMultiBlockPLOT3DReader."""
        return vtk.vtkMultiBlockPLOT3DReader()

    def lazy_vtkPlot3DMetaReader():
        """Lazy import of the vtkPlot3DMetaReader."""
        return vtk.vtkPlot3DMetaReader()

    def lazy_vtkCGNSReader():
        """Lazy import of the vtkCGNSReader."""
        raise VTKVersionError('vtk.CGNSReader requires VTK v9.1.0 or newer')

    def lazy_vtkPOpenFOAMReader():
        """Lazy import of the vtkPOpenFOAMReader."""
        # Workaround to fix the following issue: https://gitlab.kitware.com/vtk/vtk/-/issues/18143
        # Fixed in vtk > 9.1.0
        reader = vtk.vtkPOpenFOAMReader()
        reader.SetController(vtk.vtkDummyController())
        return reader

    def lazy_vtkHDFReader():
        """Lazy import of the vtkHDFReader."""
        raise VTKVersionError('vtk.HDFReader requires VTK v9.1.0 or newer')

    def lazy_vtkSegYReader():
        """Lazy import of the vtkSegYReader."""
        return vtk.vtkSegYReader()

    class vtkExplicitStructuredGrid:  # type: ignore
        """Empty placeholder for VTK9 compatibility."""

        def __init__(self):  # pragma: no cover
            """Raise version error on init."""
            from pyvista.core.errors import VTKVersionError

            raise VTKVersionError('vtkHDRReader requires VTK v9 or newer')

    class vtkHDRReader:  # type: ignore
        """Empty placeholder for VTK9 compatibility."""

        def __init__(self):  # pragma: no cover
            """Raise version error on init."""
            from pyvista.core.errors import VTKVersionError

            raise VTKVersionError('vtkHDRReader requires VTK v9 or newer')

    class vtkGLTFReader:  # type: ignore
        """Empty placeholder for VTK9 compatibility."""

        def __init__(self):  # pragma: no cover
            """Raise version error on init."""
            from pyvista.core.errors import VTKVersionError

            raise VTKVersionError('vtkGLTFReader requires VTK v9 or newer')

    class vtkPythonItem:  # type: ignore
        """Empty placeholder for VTK9 compatibility."""

        def __init__(self):  # pragma: no cover
            """Raise version error on init."""
            from pyvista.core.errors import VTKVersionError

            raise VTKVersionError('Charts requires VTK v9 or newer')

    class vtkHDFReader:  # type: ignore
        """Empty placeholder for VTK9 compatibility."""

        def __init__(self):  # pragma: no cover
            """Raise version error on init."""
            from pyvista.core.errors import VTKVersionError

            raise VTKVersionError('vtkHDFReader requires VTK v9 or newer')


# lazy import as this was added in 9.1.0
def lazy_vtkCameraOrientationWidget():
    """Lazy import of the vtkCameraOrientationWidget."""
    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')
    return vtkCameraOrientationWidget()


# 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

"""Pyvista specific errors."""


class MissingDataError(ValueError):
    """Exception when data is missing, e.g. no active scalars can be set."""

    def __init__(self, message='No data available.'):
        """Call the base class constructor with the custom message."""
        super().__init__(message)


class AmbiguousDataError(ValueError):
    """Exception when data is ambiguous, e.g. multiple active scalars can be set."""

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


# pyvista/themes.py

"""API description for managing plotting theme parameters in pyvista.

Examples
--------
Apply a built-in theme

>>> import pyvista
>>> pyvista.set_plot_theme('default')
>>> pyvista.set_plot_theme('document')
>>> pyvista.set_plot_theme('dark')
>>> pyvista.set_plot_theme('paraview')

Load a theme into pyvista

>>> theme = pyvista.themes.DefaultTheme()
>>> theme.save('my_theme.json')  # doctest:+SKIP
>>> loaded_theme = pyvista.load_theme('my_theme.json')  # doctest:+SKIP

Create a custom theme from the default theme and load it into
pyvista.

>>> my_theme = pyvista.themes.DefaultTheme()
>>> my_theme.font.size = 20
>>> my_theme.font.title_size = 40
>>> my_theme.cmap = 'jet'
...
>>> pyvista.global_theme.load_theme(my_theme)
>>> pyvista.global_theme.font.size
20

"""

from enum import Enum
import json
import os
from typing import List, Union
import warnings

from ._typing import color_like
from .plotting.colors import Color, get_cmap_safe
from .plotting.tools import parse_font_family
from .utilities.misc import PyvistaDeprecationWarning


class _rcParams(dict):  # pragma: no cover
    """Reference to the deprecated rcParams dictionary."""

    def __getitem__(self, key):
        import pyvista  # avoids circular import

        warnings.warn(
            'rcParams is deprecated.  Please use ``pyvista.global_theme``.', DeprecationWarning
        )
        return getattr(pyvista.global_theme, key)

    def __setitem__(self, key, value):
        import pyvista  # avoids circular import

        warnings.warn(
            'rcParams is deprecated.  Please use ``pyvista.global_theme``.', DeprecationWarning
        )
        setattr(pyvista.global_theme, key, value)

    def __repr__(self):
        """Use the repr of global_theme."""
        import pyvista  # avoids circular import

        warnings.warn(
            'rcParams is deprecated.  Please use ``pyvista.global_theme``', DeprecationWarning
        )
        return repr(pyvista.global_theme)


def _check_between_zero_and_one(value: float, value_name: str = 'value'):
    """Check if a value is between zero and one."""
    if value < 0 or value > 1:
        raise ValueError('{value_name} must be between 0 and 1.')


def load_theme(filename):
    """Load a theme from a file.

    Examples
    --------
    >>> import pyvista
    >>> theme = pyvista.themes.DefaultTheme()
    >>> theme.save('my_theme.json')  # doctest:+SKIP
    >>> loaded_theme = pyvista.load_theme('my_theme.json')  # doctest:+SKIP

    """
    with open(filename) as f:
        theme_dict = json.load(f)
    return DefaultTheme.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
    >>> pyvista.set_plot_theme('default')

    Set to the document theme.

    >>> pyvista.set_plot_theme('document')

    Set to the dark theme.

    >>> pyvista.set_plot_theme('dark')

    Set to the ParaView theme.

    >>> pyvista.set_plot_theme('paraview')

    """
    import pyvista

    if isinstance(theme, str):
        theme = theme.lower()
        if theme == 'night':  # pragma: no cover
            warnings.warn('use "dark" instead of "night" theme', PyvistaDeprecationWarning)
            theme = 'dark'
        new_theme_type = _ALLOWED_THEMES[theme].value
        pyvista.global_theme.load_theme(new_theme_type())
    elif isinstance(theme, DefaultTheme):
        pyvista.global_theme.load_theme(theme)
    else:
        raise TypeError(
            f'Expected a ``pyvista.themes.DefaultTheme`` or ``str``, not '
            f'a {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(self, type(other)):
            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 _DepthPeelingConfig(_ThemeConfig):
    """PyVista depth peeling configuration.

    Examples
    --------
    Set global depth peeling parameters.

    >>> import pyvista
    >>> pyvista.global_theme.depth_peeling.number_of_peels = 1
    >>> pyvista.global_theme.depth_peeling.occlusion_ratio = 0.0
    >>> pyvista.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:
        """Return or set the number of peels in depth peeling.

        Examples
        --------
        >>> import pyvista
        >>> pyvista.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):
        self._number_of_peels = int(number_of_peels)

    @property
    def occlusion_ratio(self) -> float:
        """Return or set the occlusion ratio in depth peeling.

        Examples
        --------
        >>> import pyvista
        >>> pyvista.global_theme.depth_peeling.occlusion_ratio = 0.0

        """
        return self._occlusion_ratio

    @occlusion_ratio.setter
    def occlusion_ratio(self, occlusion_ratio: float):
        self._occlusion_ratio = float(occlusion_ratio)

    @property
    def enabled(self) -> bool:
        """Return or set if depth peeling is enabled.

        Examples
        --------
        >>> import pyvista
        >>> pyvista.global_theme.depth_peeling.enabled = True

        """
        return self._enabled

    @enabled.setter
    def enabled(self, enabled: bool):
        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
    >>> pyvista.global_theme.silhouette.color = 'grey'
    >>> pyvista.global_theme.silhouette.line_width = 2
    >>> pyvista.global_theme.silhouette.feature_angle = 20

    """

    __slots__ = ['_color', '_line_width', '_opacity', '_feature_angle', '_decimate']

    def __init__(self):
        self._color = Color('black')
        self._line_width = 2
        self._opacity = 1.0
        self._feature_angle = None
        self._decimate = 0.9

    @property
    def color(self) -> Color:
        """Return or set the silhouette color.

        Examples
        --------
        >>> import pyvista
        >>> pyvista.global_theme.silhouette.color = 'red'

        """
        return self._color

    @color.setter
    def color(self, color: color_like):
        self._color = Color(color)

    @property
    def line_width(self) -> float:
        """Return or set the silhouette line width.

        Examples
        --------
        >>> import pyvista
        >>> pyvista.global_theme.silhouette.line_width = 2.0

        """
        return self._line_width

    @line_width.setter
    def line_width(self, line_width: float):
        self._line_width = float(line_width)

    @property
    def opacity(self) -> float:
        """Return or set the silhouette opacity.

        Examples
        --------
        >>> import pyvista
        >>> pyvista.global_theme.silhouette.opacity = 1.0

        """
        return self._opacity

    @opacity.setter
    def opacity(self, opacity: float):
        _check_between_zero_and_one(opacity, 'opacity')
        self._opacity = float(opacity)

    @property
    def feature_angle(self) -> Union[float, None]:
        """Return or set the silhouette feature angle.

        Examples
        --------
        >>> import pyvista
        >>> pyvista.global_theme.silhouette.feature_angle = 20.0

        """
        return self._feature_angle

    @feature_angle.setter
    def feature_angle(self, feature_angle: Union[float, None]):
        self._feature_angle = feature_angle

    @property
    def decimate(self) -> float:
        """Return or set the amount to decimate the silhouette.

        Parameter must be between 0 and 1.

        Examples
        --------
        >>> import pyvista
        >>> pyvista.global_theme.silhouette.decimate = 0.9

        """
        return self._decimate

    @decimate.setter
    def decimate(self, decimate: float):
        _check_between_zero_and_one(decimate, '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
    >>> pyvista.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:
        """Return or set colorbar width.

        Examples
        --------
        >>> import pyvista
        >>> pyvista.global_theme.colorbar_horizontal.width = 0.2

        """
        return self._width

    @width.setter
    def width(self, width: float):
        self._width = float(width)

    @property
    def height(self) -> float:
        """Return or set colorbar height.

        Examples
        --------
        >>> import pyvista
        >>> pyvista.global_theme.colorbar_horizontal.height = 0.2

        """
        return self._height

    @height.setter
    def height(self, height: float):
        self._height = float(height)

    @property
    def position_x(self) -> float:
        """Return or set colorbar x position.

        Examples
        --------
        >>> import pyvista
        >>> pyvista.global_theme.colorbar_horizontal.position_x = 0.2

        """
        return self._position_x

    @position_x.setter
    def position_x(self, position_x: float):
        self._position_x = float(position_x)

    @property
    def position_y(self) -> float:
        """Return or set colorbar y position.

        Examples
        --------
        >>> import pyvista
        >>> pyvista.global_theme.colorbar_horizontal.position_y = 0.2

        """
        return self._position_y

    @position_y.setter
    def position_y(self, position_y: float):
        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
    >>> pyvista.global_theme.axes.x_color = 'black'

    Show axes by default.

    >>> pyvista.global_theme.axes.show = True

    Use the ``vtk.vtkCubeAxesActor``.

    >>> pyvista.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:
        """Return or set x axis color.

        Examples
        --------
        >>> import pyvista
        >>> pyvista.global_theme.axes.x_color = 'red'
        """
        return self._x_color

    @x_color.setter
    def x_color(self, color: color_like):
        self._x_color = Color(color)

    @property
    def y_color(self) -> Color:
        """Return or set y axis color.

        Examples
        --------
        >>> import pyvista
        >>> pyvista.global_theme.axes.y_color = 'red'
        """
        return self._y_color

    @y_color.setter
    def y_color(self, color: color_like):
        self._y_color = Color(color)

    @property
    def z_color(self) -> Color:
        """Return or set z axis color.

        Examples
        --------
        >>> import pyvista
        >>> pyvista.global_theme.axes.z_color = 'red'
        """
        return self._z_color

    @z_color.setter
    def z_color(self, color: color_like):
        self._z_color = Color(color)

    @property
    def box(self) -> bool:
        """Use the ``vtk.vtkCubeAxesActor`` instead of the default ``vtk.vtkAxesActor``.

        Examples
        --------
        >>> import pyvista
        >>> pyvista.global_theme.axes.box = True

        """
        return self._box

    @box.setter
    def box(self, box: bool):
        self._box = bool(box)

    @property
    def show(self) -> bool:
        """Show or hide the axes actor.

        Examples
        --------
        Hide the axes by default.

        >>> import pyvista
        >>> pyvista.global_theme.axes.show = False

        """
        return self._show

    @show.setter
    def show(self, show: bool):
        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
    >>> pyvista.global_theme.font.family = 'arial'

    Set the default font size to 20.

    >>> pyvista.global_theme.font.size = 20

    Set the default title size to 40

    >>> pyvista.global_theme.font.title_size = 40

    Set the default label size to 10

    >>> pyvista.global_theme.font.label_size = 10

    Set the default text color to 'grey'

    >>> pyvista.global_theme.font.color = 'grey'

    Set the string formatter used to format numerical data to '%.6e'

    >>> pyvista.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:
        """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
        >>> pyvista.global_theme.font.family = 'courier'

        """
        return self._family

    @family.setter
    def family(self, family: str):
        parse_font_family(family)  # check valid font
        self._family = family

    @property
    def size(self) -> int:
        """Return or set the font size.

        Examples
        --------
        >>> import pyvista
        >>> pyvista.global_theme.font.size = 20

        """
        return self._size

    @size.setter
    def size(self, size: int):
        self._size = int(size)

    @property
    def title_size(self) -> int:
        """Return or set the title size.

        If ``None``, then VTK uses ``UnconstrainedFontSizeOn`` for titles.

        Examples
        --------
        >>> import pyvista
        >>> pyvista.global_theme.font.title_size = 20
        """
        return self._title_size

    @title_size.setter
    def title_size(self, title_size: int):
        if title_size is None:
            self._title_size = None
        else:
            self._title_size = int(title_size)

    @property
    def label_size(self) -> int:
        """Return or set the label size.

        If ``None``, then VTK uses ``UnconstrainedFontSizeOn`` for labels.

        Examples
        --------
        >>> import pyvista
        >>> pyvista.global_theme.font.label_size = 20
        """
        return self._label_size

    @label_size.setter
    def label_size(self, label_size: int):
        if label_size is None:
            self._label_size = None
        else:
            self._label_size = int(label_size)

    @property
    def color(self) -> Color:
        """Return or set the font color.

        Examples
        --------
        >>> import pyvista
        >>> pyvista.global_theme.font.color = 'black'
        """
        return self._color

    @color.setter
    def color(self, color: color_like):
        self._color = Color(color)

    @property
    def fmt(self) -> str:
        """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
        >>> pyvista.global_theme.font.fmt = '%.6e'

        """
        return self._fmt

    @fmt.setter
    def fmt(self, fmt: str):
        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:
        """Return the name of the slider style configuration."""
        return self._name

    @name.setter
    def name(self, name: str):
        self._name = name

    @property
    def cap_width(self) -> float:
        """Return or set the cap width.

        Examples
        --------
        >>> import pyvista
        >>> pyvista.global_theme.slider_styles.modern.cap_width = 0.02

        """
        return self._cap_width

    @cap_width.setter
    def cap_width(self, cap_width: float):
        self._cap_width = float(cap_width)

    @property
    def cap_length(self) -> float:
        """Return or set the cap length.

        Examples
        --------
        >>> import pyvista
        >>> pyvista.global_theme.slider_styles.modern.cap_length = 0.01

        """
        return self._cap_length

    @cap_length.setter
    def cap_length(self, cap_length: float):
        self._cap_length = float(cap_length)

    @property
    def cap_opacity(self) -> float:
        """Return or set the cap opacity.

        Examples
        --------
        >>> import pyvista
        >>> pyvista.global_theme.slider_styles.modern.cap_opacity = 1.0

        """
        return self._cap_opacity

    @cap_opacity.setter
    def cap_opacity(self, cap_opacity: float):
        self._cap_opacity = float(cap_opacity)

    @property
    def tube_color(self) -> Color:
        """Return or set the tube color.

        Examples
        --------
        >>> import pyvista
        >>> pyvista.global_theme.slider_styles.modern.tube_color = 'black'
        """
        return self._tube_color

    @tube_color.setter
    def tube_color(self, tube_color: color_like):
        self._tube_color = Color(tube_color)

    @property
    def tube_width(self) -> float:
        """Return or set the tube_width.

        Examples
        --------
        >>> import pyvista
        >>> pyvista.global_theme.slider_styles.modern.tube_width = 0.005

        """
        return self._tube_width

    @tube_width.setter
    def tube_width(self, tube_width: float):
        self._tube_width = float(tube_width)

    @property
    def slider_color(self) -> Color:
        """Return or set the slider color.

        Examples
        --------
        >>> import pyvista
        >>> pyvista.global_theme.slider_styles.modern.slider_color = 'grey'

        """
        return self._slider_color

    @slider_color.setter
    def slider_color(self, slider_color: color_like):
        self._slider_color = Color(slider_color)

    @property
    def slider_width(self) -> float:
        """Return or set the slider width.

        Examples
        --------
        >>> import pyvista
        >>> pyvista.global_theme.slider_styles.modern.slider_width = 0.04

        """
        return self._slider_width

    @slider_width.setter
    def slider_width(self, slider_width: float):
        self._slider_width = float(slider_width)

    @property
    def slider_length(self) -> float:
        """Return or set the slider_length.

        Examples
        --------
        >>> import pyvista
        >>> pyvista.global_theme.slider_styles.modern.slider_length = 0.02

        """
        return self._slider_length

    @slider_length.setter
    def slider_length(self, slider_length: float):
        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
    >>> pyvista.global_theme.slider_styles.classic.slider_length = 0.02
    >>> pyvista.global_theme.slider_styles.classic.slider_width = 0.04
    >>> pyvista.global_theme.slider_styles.classic.slider_color = (0.5, 0.5, 0.5)
    >>> pyvista.global_theme.slider_styles.classic.tube_width = 0.005
    >>> pyvista.global_theme.slider_styles.classic.tube_color = (1.0, 1.0, 1.0)
    >>> pyvista.global_theme.slider_styles.classic.cap_opacity = 1
    >>> pyvista.global_theme.slider_styles.classic.cap_length = 0.01
    >>> pyvista.global_theme.slider_styles.classic.cap_width = 0.02

    Set the modern slider configuration.

    >>> pyvista.global_theme.slider_styles.modern.slider_length = 0.02
    >>> pyvista.global_theme.slider_styles.modern.slider_width = 0.04
    >>> pyvista.global_theme.slider_styles.modern.slider_color = (0.43, 0.44, 0.45)
    >>> pyvista.global_theme.slider_styles.modern.tube_width = 0.04
    >>> pyvista.global_theme.slider_styles.modern.tube_color = (0.69, 0.70, 0.709)
    >>> pyvista.global_theme.slider_styles.modern.cap_opacity = 0
    >>> pyvista.global_theme.slider_styles.modern.cap_length = 0.01
    >>> pyvista.global_theme.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:
        """Return the Classic slider configuration."""
        return self._classic

    @classic.setter
    def classic(self, config: _SliderStyleConfig):
        if not isinstance(config, _SliderStyleConfig):
            raise TypeError('Configuration type must be `_SliderStyleConfig`')
        self._classic = config

    @property
    def modern(self) -> _SliderStyleConfig:
        """Return the Modern slider configuration."""
        return self._modern

    @modern.setter
    def modern(self, config: _SliderStyleConfig):
        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 DefaultTheme(_ThemeConfig):
    """PyVista default theme.

    Examples
    --------
    Change the global default background color to white.

    >>> import pyvista
    >>> pyvista.global_theme.color = 'white'

    Show edges by default.

    >>> pyvista.global_theme.show_edges = True

    Create a new theme from the default theme and apply it globally.

    >>> my_theme = pyvista.themes.DefaultTheme()
    >>> my_theme.color = 'red'
    >>> my_theme.background = 'white'
    >>> pyvista.global_theme.load_theme(my_theme)

    """

    __slots__ = [
        '_name',
        '_background',
        '_jupyter_backend',
        '_full_screen',
        '_window_size',
        '_camera',
        '_notebook',
        '_font',
        '_auto_close',
        '_cmap',
        '_color',
        '_nan_color',
        '_edge_color',
        '_outline_color',
        '_floor_color',
        '_colorbar_orientation',
        '_colorbar_horizontal',
        '_colorbar_vertical',
        '_show_scalar_bar',
        '_show_edges',
        '_lighting',
        '_interactive',
        '_render_points_as_spheres',
        '_transparent_background',
        '_title',
        '_axes',
        '_multi_samples',
        '_multi_rendering_splitting_position',
        '_volume_mapper',
        '_smooth_shading',
        '_depth_peeling',
        '_silhouette',
        '_slider_styles',
        '_return_cpos',
        '_hidden_line_removal',
        '_antialiasing',
        '_enable_camera_orientation_widget',
        '_split_sharp_edges',
        '_sharp_edges_feature_angle',
    ]

    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._font = _Font()
        self._cmap = 'viridis'
        self._color = Color('white')
        self._nan_color = Color('darkgray')
        self._edge_color = Color('black')
        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._lighting = True
        self._interactive = False
        self._render_points_as_spheres = False
        self._transparent_background = False
        self._title = 'PyVista'
        self._axes = _AxesConfig()
        self._split_sharp_edges = False
        self._sharp_edges_feature_angle = 30.0

        # Grab system flag for anti-aliasing
        try:
            self._multi_samples = int(os.environ.get('PYVISTA_MULTI_SAMPLES', 4))
        except ValueError:  # pragma: no cover
            self._multi_samples = 4

        # 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', 'ipyvtklink')

        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._antialiasing = False
        self._enable_camera_orientation_widget = False

    @property
    def hidden_line_removal(self) -> bool:
        """Return or set hidden line removal.

        Wireframe geometry will be drawn using hidden line removal if
        the rendering engine supports it.

        See Also
        --------
        pyvista.BasePlotter.enable_hidden_line_removal

        Examples
        --------
        Enable hidden line removal.

        >>> import pyvista
        >>> pyvista.global_theme.hidden_line_removal = True
        >>> pyvista.global_theme.hidden_line_removal
        True

        """
        return self._hidden_line_removal

    @hidden_line_removal.setter
    def hidden_line_removal(self, value: bool):
        self._hidden_line_removal = value

    @property
    def return_cpos(self) -> bool:
        """Return or set the default behavior of returning the camera position.

        Examples
        --------
        Disable returning camera position by ``show`` and ``plot`` methods.

        >>> import pyvista
        >>> pyvista.global_theme.return_cpos = False
        """

    @return_cpos.setter
    def return_cpos(self, value: bool):
        self._return_cpos = value

    @property
    def background(self) -> Color:
        """Return or set the default background color of pyvista plots.

        Examples
        --------
        Set the default global background of all plots to white.

        >>> import pyvista
        >>> pyvista.global_theme.background = 'white'
        """
        return self._background

    @background.setter
    def background(self, new_background: color_like):
        self._background = Color(new_background)

    @property
    def jupyter_backend(self) -> str:
        """Return or set the jupyter notebook plotting backend.

        Jupyter backend to use when plotting.  Must be one of the
        following:

        * ``'ipyvtklink'`` : Render remotely and stream the
          resulting VTK images back to the client.  Supports all VTK
          methods, but suffers from lag due to remote rendering.
          Requires that a virtual framebuffer be set up when displaying
          on a headless server.  Must have ``ipyvtklink`` installed.

        * ``'panel'`` : Convert the VTK render window to a vtkjs
          object and then visualize that within jupyterlab. Supports
          most VTK objects.  Requires that a virtual framebuffer be
          set up when displaying on a headless server.  Must have
          ``panel`` installed.

        * ``'ipygany'`` : Convert all the meshes into ``ipygany``
          meshes and streams those to be rendered on the client side.
          Supports VTK meshes, but few others.  Aside from ``none``,
          this is the only method that does not require a virtual
          framebuffer.  Must have ``ipygany`` installed.

        * ``'pythreejs'`` : Convert all the meshes into ``pythreejs``
          meshes and streams those to be rendered on the client side.
          Aside from ``ipygany``, this is the only method that does
          not require a virtual framebuffer.  Must have ``pythreejs``
          installed.

        * ``'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.

        * ``'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
        --------
        Enable the pythreejs backend.

        >>> import pyvista as pv
        >>> pv.set_jupyter_backend('pythreejs')

        Enable the ipygany backend.

        >>> import pyvista as pv
        >>> pv.set_jupyter_backend('ipygany')

        Enable the panel backend.

        >>> pv.set_jupyter_backend('panel')

        Enable the ipyvtklink backend.

        >>> pv.set_jupyter_backend('ipyvtklink')

        Just show static images.

        >>> pv.set_jupyter_backend('static')

        Disable all plotting within JupyterLab and display using a
        standard desktop VTK render window.

        >>> pv.set_jupyter_backend(None)  # or 'none'

        """
        return self._jupyter_backend

    @jupyter_backend.setter
    def jupyter_backend(self, backend: 'str'):
        from pyvista.jupyter import _validate_jupyter_backend

        self._jupyter_backend = _validate_jupyter_backend(backend)

    @property
    def auto_close(self) -> bool:
        """Automatically close the figures when finished plotting.

        .. DANGER::
           Set to ``False`` with extreme caution.

        Examples
        --------
        >>> import pyvista
        >>> pyvista.global_theme.auto_close = False

        """
        return self._auto_close

    @auto_close.setter
    def auto_close(self, value: bool):
        self._auto_close = value

    @property
    def full_screen(self) -> bool:
        """Return if figures are shown in full screen.

        Examples
        --------
        Set windows to be full screen by default.

        >>> import pyvista
        >>> pyvista.global_theme.full_screen = True
        """
        return self._full_screen

    @full_screen.setter
    def full_screen(self, value: bool):
        self._full_screen = value

    @property
    def enable_camera_orientation_widget(self) -> bool:
        """Enable the camera orientation widget in all plotters.

        Examples
        --------
        >>> import pyvista
        >>> pyvista.global_theme.enable_camera_orientation_widget = True
        >>> pyvista.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):
        self._enable_camera_orientation_widget = value

    @property
    def camera(self):
        """Return or set the default camera position.

        Examples
        --------
        Set both the position and view of the camera.

        >>> import pyvista
        >>> pyvista.global_theme.camera = {'position': [1, 1, 1],
        ...                                'viewup': [0, 0, 1]}

        Set the default position of the camera.

        >>> pyvista.global_theme.camera['position'] = [1, 1, 1]

        Set the default view of the camera.

        >>> pyvista.global_theme.camera['viewup'] = [0, 0, 1]

        """
        return self._camera

    @camera.setter
    def camera(self, camera):
        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]:
        """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
        >>> pyvista.global_theme.notebook = False

        """
        return self._notebook

    @notebook.setter
    def notebook(self, value: Union[bool, None]):
        self._notebook = value

    @property
    def window_size(self) -> List[int]:
        """Return or set the default render window size.

        Examples
        --------
        Set window size to ``[400, 400]``.

        >>> import pyvista
        >>> pyvista.global_theme.window_size = [400, 400]

        """
        return self._window_size

    @window_size.setter
    def window_size(self, window_size: List[int]):
        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 font(self) -> _Font:
        """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
        >>> pyvista.global_theme.font.family = 'arial'

        Set the default font size to 20.

        >>> pyvista.global_theme.font.size = 20

        Set the default title size to 40.

        >>> pyvista.global_theme.font.title_size = 40

        Set the default label size to 10.

        >>> pyvista.global_theme.font.label_size = 10

        Set the default text color to 'grey'.

        >>> pyvista.global_theme.font.color = 'grey'

        String formatter used to format numerical data to '%.6e'.

        >>> pyvista.global_theme.font.fmt = '%.6e'

        """
        return self._font

    @font.setter
    def font(self, config: _Font):
        if not isinstance(config, _Font):
            raise TypeError('Configuration type must be `_Font`.')
        self._font = config

    @property
    def cmap(self):
        """Return or set the default colormap of pyvista.

        See available Matplotlib colormaps.  Only applicable for when
        displaying ``scalars``. Requires Matplotlib to be installed.
        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
        >>> pyvista.global_theme.cmap = 'jet'

        """
        return self._cmap

    @cmap.setter
    def cmap(self, cmap):
        try:
            get_cmap_safe(cmap)  # for validation
            self._cmap = cmap
        except ImportError:  # pragma: no cover
            warnings.warn(
                'Unable to set a default theme colormap without matplotlib. '
                'The builtin VTK "jet" colormap will be used.'
            )
            self._cmap = None

    @property
    def color(self) -> Color:
        """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
        >>> pyvista.global_theme.color = 'red'

        """
        return self._color

    @color.setter
    def color(self, color: color_like):
        self._color = Color(color)

    @property
    def nan_color(self) -> Color:
        """Return or set the default NaN color.

        This color is used to plot all NaN values.

        Examples
        --------
        >>> import pyvista
        >>> pyvista.global_theme.nan_color = 'darkgray'

        """
        return self._nan_color

    @nan_color.setter
    def nan_color(self, nan_color: color_like):
        self._nan_color = Color(nan_color)

    @property
    def edge_color(self) -> Color:
        """Return or set the default edge color.

        Examples
        --------
        Set the global edge color to 'blue'.

        >>> import pyvista
        >>> pyvista.global_theme.edge_color = 'blue'

        """
        return self._edge_color

    @edge_color.setter
    def edge_color(self, edge_color: color_like):
        self._edge_color = Color(edge_color)

    @property
    def outline_color(self) -> Color:
        """Return or set the default outline color.

        Examples
        --------
        >>> import pyvista
        >>> pyvista.global_theme.outline_color = 'white'

        """
        return self._outline_color

    @outline_color.setter
    def outline_color(self, outline_color: color_like):
        self._outline_color = Color(outline_color)

    @property
    def floor_color(self) -> Color:
        """Return or set the default floor color.

        Examples
        --------
        >>> import pyvista
        >>> pyvista.global_theme.floor_color = 'black'

        """
        return self._floor_color

    @floor_color.setter
    def floor_color(self, floor_color: color_like):
        self._floor_color = Color(floor_color)

    @property
    def colorbar_orientation(self) -> str:
        """Return or set the default colorbar orientation.

        Must be either ``'vertical'`` or ``'horizontal'``.

        Examples
        --------
        >>> import pyvista
        >>> pyvista.global_theme.colorbar_orientation = 'horizontal'

        """
        return self._colorbar_orientation

    @colorbar_orientation.setter
    def colorbar_orientation(self, colorbar_orientation: str):
        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:
        """Return or set the default parameters of a horizontal colorbar.

        Examples
        --------
        Set the default horizontal colorbar width to 0.6.

        >>> import pyvista
        >>> pyvista.global_theme.colorbar_horizontal.width = 0.6

        Set the default horizontal colorbar height to 0.2.

        >>> pyvista.global_theme.colorbar_horizontal.height = 0.2

        """
        return self._colorbar_horizontal

    @colorbar_horizontal.setter
    def colorbar_horizontal(self, config: _ColorbarConfig):
        if not isinstance(config, _ColorbarConfig):
            raise TypeError('Configuration type must be `_ColorbarConfig`.')
        self._colorbar_horizontal = config

    @property
    def colorbar_vertical(self) -> _ColorbarConfig:
        """Return or set the default parameters of a vertical colorbar.

        Examples
        --------
        Set the default colorbar width to 0.45.

        >>> import pyvista
        >>> pyvista.global_theme.colorbar_vertical.width = 0.45

        Set the default colorbar height to 0.8.

        >>> import pyvista
        >>> pyvista.global_theme.colorbar_vertical.height = 0.8

        """
        return self._colorbar_vertical

    @colorbar_vertical.setter
    def colorbar_vertical(self, config: _ColorbarConfig):
        if not isinstance(config, _ColorbarConfig):
            raise TypeError('Configuration type must be `_ColorbarConfig`.')
        self._colorbar_vertical = config

    @property
    def show_scalar_bar(self) -> bool:
        """Return or set the default color bar visibility.

        Examples
        --------
        Show the scalar bar by default when scalars are available.

        >>> import pyvista
        >>> pyvista.global_theme.show_scalar_bar = True

        """
        return self._show_scalar_bar

    @show_scalar_bar.setter
    def show_scalar_bar(self, show_scalar_bar: bool):
        self._show_scalar_bar = bool(show_scalar_bar)

    @property
    def show_edges(self) -> bool:
        """Return or set the default edge visibility.

        Examples
        --------
        Show edges globally by default.

        >>> import pyvista
        >>> pyvista.global_theme.show_edges = True

        """
        return self._show_edges

    @show_edges.setter
    def show_edges(self, show_edges: bool):
        self._show_edges = bool(show_edges)

    @property
    def lighting(self) -> bool:
        """Return or set the default ``lighting``.

        Examples
        --------
        Disable lighting globally.

        >>> import pyvista
        >>> pyvista.global_theme.lighting = False
        """
        return self._lighting

    @lighting.setter
    def lighting(self, lighting: bool):
        self._lighting = lighting

    @property
    def interactive(self) -> bool:
        """Return or set the default ``interactive`` parameter.

        Examples
        --------
        Make all plots non-interactive globally.

        >>> import pyvista
        >>> pyvista.global_theme.interactive = False
        """
        return self._interactive

    @interactive.setter
    def interactive(self, interactive: bool):
        self._interactive = bool(interactive)

    @property
    def render_points_as_spheres(self) -> bool:
        """Return or set the default ``render_points_as_spheres`` parameter.

        Examples
        --------
        Render points as spheres by default globally.

        >>> import pyvista
        >>> pyvista.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):
        self._render_points_as_spheres = bool(render_points_as_spheres)

    @property
    def transparent_background(self) -> bool:
        """Return or set the default ``transparent_background`` parameter.

        Examples
        --------
        Set transparent_background globally to ``True``.

        >>> import pyvista
        >>> pyvista.global_theme.transparent_background = True

        """
        return self._transparent_background

    @transparent_background.setter
    def transparent_background(self, transparent_background: bool):
        self._transparent_background = transparent_background

    @property
    def title(self) -> str:
        """Return or set the default ``title`` parameter.

        This is the VTK render window title.

        Examples
        --------
        Set title globally to 'plot'.

        >>> import pyvista
        >>> pyvista.global_theme.title = 'plot'

        """
        return self._title

    @title.setter
    def title(self, title: str):
        self._title = title

    @property
    def antialiasing(self) -> bool:
        """Enable or disable anti-aliasing.

        Examples
        --------
        Enable anti-aliasing in the global theme.

        >>> import pyvista
        >>> pyvista.global_theme.antialiasing = True
        >>> pyvista.global_theme.antialiasing
        True

        """
        return self._antialiasing

    @antialiasing.setter
    def antialiasing(self, antialiasing: bool):
        self._antialiasing = antialiasing

    @property
    def multi_samples(self) -> int:
        """Return or set the default ``multi_samples`` parameter.

        Set the number of multisamples to used with hardware antialiasing.

        Examples
        --------
        Set the default number of multisamples to 2.

        >>> import pyvista
        >>> pyvista.global_theme.multi_samples = 2

        """
        return self._multi_samples

    @multi_samples.setter
    def multi_samples(self, multi_samples: int):
        self._multi_samples = int(multi_samples)

    @property
    def multi_rendering_splitting_position(self) -> float:
        """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
        >>> pyvista.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):
        self._multi_rendering_splitting_position = multi_rendering_splitting_position

    @property
    def volume_mapper(self) -> str:
        """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
        >>> pyvista.global_theme.volume_mapper = 'gpu'

        """
        return self._volume_mapper

    @volume_mapper.setter
    def volume_mapper(self, mapper: str):
        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:
        """Return or set the default ``smooth_shading`` parameter.

        Examples
        --------
        Set the global smooth_shading parameter default to ``True``.

        >>> import pyvista
        >>> pyvista.global_theme.smooth_shading = True

        """
        return self._smooth_shading

    @smooth_shading.setter
    def smooth_shading(self, smooth_shading: bool):
        self._smooth_shading = bool(smooth_shading)

    @property
    def depth_peeling(self) -> _DepthPeelingConfig:
        """Return or set the default depth peeling parameters.

        Examples
        --------
        Set the global depth_peeling parameter default to be enabled
        with 8 peels.

        >>> import pyvista
        >>> pyvista.global_theme.depth_peeling.number_of_peels = 8
        >>> pyvista.global_theme.depth_peeling.occlusion_ratio = 0.0
        >>> pyvista.global_theme.depth_peeling.enabled = True

        """
        return self._depth_peeling

    @depth_peeling.setter
    def depth_peeling(self, config: _DepthPeelingConfig):
        if not isinstance(config, _DepthPeelingConfig):
            raise TypeError('Configuration type must be `_DepthPeelingConfig`.')
        self._depth_peeling = config

    @property
    def silhouette(self) -> _SilhouetteConfig:
        """Return or set the default ``silhouette`` configuration.

        Examples
        --------
        Set parameters of the silhouette.

        >>> import pyvista
        >>> pyvista.global_theme.silhouette.color = 'grey'
        >>> pyvista.global_theme.silhouette.line_width = 2.0
        >>> pyvista.global_theme.silhouette.feature_angle = 20

        """
        return self._silhouette

    @silhouette.setter
    def silhouette(self, config: _SilhouetteConfig):
        if not isinstance(config, _SilhouetteConfig):
            raise TypeError('Configuration type must be `_SilhouetteConfig`')
        self._silhouette = config

    @property
    def slider_styles(self) -> _SliderConfig:
        """Return the default slider style configurations."""
        return self._slider_styles

    @slider_styles.setter
    def slider_styles(self, config: _SliderConfig):
        if not isinstance(config, _SliderConfig):
            raise TypeError('Configuration type must be `_SliderConfig`.')
        self._slider_styles = config

    @property
    def axes(self) -> _AxesConfig:
        """Return or set the default ``axes`` configuration.

        Examples
        --------
        Set the x axis color to black.

        >>> import pyvista
        >>> pyvista.global_theme.axes.x_color = 'black'

        Show axes by default.

        >>> pyvista.global_theme.axes.show = True

        Use the ``vtk.vtkCubeAxesActor``.

        >>> pyvista.global_theme.axes.box = True

        """
        return self._axes

    @axes.setter
    def axes(self, config: _AxesConfig):
        if not isinstance(config, _AxesConfig):
            raise TypeError('Configuration type must be `_AxesConfig`.')
        self._axes = config

    def restore_defaults(self):
        """Restore the theme defaults.

        Examples
        --------
        >>> import pyvista
        >>> pyvista.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',
            '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': '_antialiasing',
            'Split sharp edges': '_split_sharp_edges',
            'Sharp edges feat. angle': '_sharp_edges_feature_angle',
        }
        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:
        """Return or set the name of the theme."""
        return self._name

    @name.setter
    def name(self, name: str):
        self._name = name

    def load_theme(self, theme):
        """Overwrite the current theme with a theme.

        Parameters
        ----------
        theme : pyvista.DefaultTheme
            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
        >>> from pyvista.themes import DefaultTheme
        >>> my_theme = DefaultTheme()
        >>> my_theme.font.size = 20
        >>> my_theme.font.title_size = 40
        >>> my_theme.cmap = 'jet'
        ...
        >>> pyvista.global_theme.load_theme(my_theme)
        >>> pyvista.global_theme.font.size
        20

        Create a custom theme from the dark theme and load it into
        pyvista.

        >>> from pyvista.themes import DarkTheme
        >>> my_theme = DarkTheme()
        >>> my_theme.show_edges = True
        >>> pyvista.global_theme.load_theme(my_theme)
        >>> pyvista.global_theme.show_edges
        True

        """
        if isinstance(theme, str):
            theme = load_theme(theme)

        if not isinstance(theme, DefaultTheme):
            raise TypeError(
                '``theme`` must be a pyvista theme like ``pyvista.themes.DefaultTheme``.'
            )

        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.

        Parameters
        ----------
        filename : str
            Path to save the theme to.  Should end in ``'.json'``.

        Examples
        --------
        Export and then load back in a theme.

        >>> import pyvista
        >>> theme = pyvista.themes.DefaultTheme()
        >>> theme.background = 'white'
        >>> theme.save('my_theme.json')  # doctest:+SKIP
        >>> loaded_theme = pyvista.load_theme('my_theme.json')  # doctest:+SKIP

        """
        with open(filename, 'w') as f:
            json.dump(self.to_dict(), f)

    @property
    def use_ipyvtk(self):  # pragma: no cover
        """Set or return the usage of "ipyvtk" as a jupyter backend.

        Deprecated in favor of ``jupyter_backend``.
        """
        warnings.warn(
            'use_ipyvtk is deprecated.  Please use ``pyvista.global_theme.jupyter_backend``',
            DeprecationWarning,
        )
        return self.jupyter_backend == 'ipyvtklink'

    @use_ipyvtk.setter
    def use_ipyvtk(self, value):  # pragma: no cover
        warnings.warn(
            'use_ipyvtk is deprecated.  Please use ``pyvista.global_theme.jupyter_backend``',
            DeprecationWarning,
        )

        if value:
            self.jupyter_backend = 'ipyvtklink'
        else:
            self.jupyter_backend = 'static'

    @property
    def split_sharp_edges(self) -> bool:
        """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
        >>> pyvista.global_theme.split_sharp_edges = True
        >>> pyvista.global_theme.split_sharp_edges
        True

        Disable the splitting of sharp edges globally.

        >>> import pyvista
        >>> pyvista.global_theme.split_sharp_edges = False
        >>> pyvista.global_theme.split_sharp_edges
        False

        """
        return self._split_sharp_edges

    @split_sharp_edges.setter
    def split_sharp_edges(self, value: bool):
        self._split_sharp_edges = value

    @property
    def sharp_edges_feature_angle(self) -> float:
        """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
        >>> pyvista.global_theme.sharp_edges_feature_angle = 45.0
        >>> pyvista.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):
        self._sharp_edges_feature_angle = float(value)


class DarkTheme(DefaultTheme):
    """Dark mode theme.

    Black background, "viridis" colormap, tan meshes, white (hidden) edges.

    Examples
    --------
    Make the dark theme the global default.

    >>> import pyvista
    >>> from pyvista import themes
    >>> pyvista.set_plot_theme(themes.DarkTheme())

    Alternatively, set via a string.

    >>> pyvista.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 = 'tan'
        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(DefaultTheme):
    """A paraview-like theme.

    Examples
    --------
    Make the paraview-like theme the global default.

    >>> import pyvista
    >>> from pyvista import themes
    >>> pyvista.set_plot_theme(themes.ParaViewTheme())

    Alternatively, set via a string.

    >>> pyvista.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(DefaultTheme):
    """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
    >>> from pyvista import themes
    >>> pyvista.set_plot_theme(themes.DocumentTheme())

    Alternatively, set via a string.

    >>> pyvista.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 = 'tan'
        self.outline_color = 'black'
        self.edge_color = 'black'
        self.axes.x_color = 'tomato'
        self.axes.y_color = 'seagreen'
        self.axes.z_color = 'blue'


class _TestingTheme(DefaultTheme):
    """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 _ALLOWED_THEMES(Enum):
    """Global built-in themes available to PyVista."""

    paraview = ParaViewTheme
    document = DocumentTheme
    dark = DarkTheme
    default = DefaultTheme
    testing = _TestingTheme


# pyvista/plotting/__init__.py

"""Plotting routines."""

from pyvista import MAX_N_COLOR_BARS
from .charts import Chart2D, ChartMPL, ChartBox, ChartPie
from .colors import (
    Color,
    color_like,
    color_char_to_word,
    get_cmap_safe,
    hex_to_rgb,
    hexcolors,
    string_to_rgb,
    PARAVIEW_BACKGROUND,
)
from .export_vtkjs import export_plotter_vtkjs, get_vtkjs_url
from .helpers import plot, plot_arrows, plot_compare_four, plot_itk
from .plotting import BasePlotter, Plotter, close_all
from .renderer import CameraPosition, Renderer, scale_point
from .tools import (
    create_axes_marker,
    create_axes_orientation_box,
    opacity_transfer_function,
    FONTS,
    system_supports_plotting,
    parse_color,
    parse_font_family,
)
from .widgets import WidgetHelper
from .lights import Light
from .camera import Camera
from .axes import Axes


class QtDeprecationError(Exception):
    """Depreciation Error for features that moved to `pyvistaqt`."""

    message = """`{}` has moved to pyvistaqt.
    You can install this from PyPI with: `pip install pyvistaqt`
    Then import it via: `from pyvistaqt import {}`
    `{}` is no longer accessible by `pyvista.{}`
    See https://github.com/pyvista/pyvistaqt
"""

    def __init__(self, feature_name):
        """Empty init."""
        Exception.__init__(self, self.message.format(*[feature_name] * 4))


class BackgroundPlotter:
    """This class has been moved to pyvistaqt."""

    def __init__(self, *args, **kwargs):
        """Empty init."""
        raise QtDeprecationError('BackgroundPlotter')


class QtInteractor:
    """This class has been moved to pyvistaqt."""

    def __init__(self, *args, **kwargs):
        """Empty init."""
        raise QtDeprecationError('QtInteractor')


# pyvista/plotting/_plotting.py

"""These are private methods we keep out of plotting.py to simplify the module."""
import warnings

import numpy as np

import pyvista
from pyvista.utilities import get_array

from .tools import opacity_transfer_function


def prepare_smooth_shading(mesh, scalars, texture, split_sharp_edges, feature_angle, preference):
    """Prepare a dataset for smooth shading.

    VTK requires datasets with Phong shading to have active normals.
    This requires extracting the external surfaces from non-polydata
    datasets and computing the point normals.

    Parameters
    ----------
    mesh : pyvista.DataSet
        Dataset to prepare smooth shading for.

    scalars : sequence
        Sequence of scalars.

    texture : vtk.vtkTexture or np.ndarray or bool, optional
        A texture to apply to the mesh.

    split_sharp_edges : bool
        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``.  Note that enabling this will create a copy of
        the input mesh within the plotter.  See
        :ref:`shading_example`.

    feature_angle : float
        Angle to consider an edge a sharp edge.

    preference : str
        If the number of points is identical to the number of cells.
        Either ``'point'`` or ``'cell'``.

    Returns
    -------
    pyvista.PolyData
        Always a surface as we need to compute point normals.

    """
    is_polydata = isinstance(mesh, pyvista.PolyData)
    indices_array = None

    has_scalars = scalars is not None
    use_points = False
    if has_scalars:
        if not isinstance(scalars, np.ndarray):
            scalars = np.array(scalars)
        if scalars.shape[0] == mesh.n_points and scalars.shape[0] == mesh.n_cells:
            use_points = preference == 'point'
        else:
            use_points = scalars.shape[0] == mesh.n_points

    # extract surface if not already a surface
    if not is_polydata:
        mesh = mesh.extract_surface(
            pass_pointid=use_points or texture is not None,
            pass_cellid=not use_points,
        )
        if use_points:
            indices_array = 'vtkOriginalPointIds'
        else:
            indices_array = 'vtkOriginalCellIds'

    if split_sharp_edges:
        mesh = mesh.compute_normals(
            cell_normals=False,
            split_vertices=True,
            feature_angle=feature_angle,
        )
        if is_polydata:
            if has_scalars and use_points:
                # we must track the original IDs with our own array from compute_normals
                indices_array = 'pyvistaOriginalPointIds'
    else:
        # consider checking if mesh contains active normals
        # if mesh.point_data.active_normals is None:
        mesh.compute_normals(cell_normals=False, inplace=True)

    if has_scalars and indices_array is not None:
        ind = mesh[indices_array]
        scalars = np.asarray(scalars)[ind]

    return mesh, scalars


def process_opacity(mesh, opacity, preference, n_colors, scalars, use_transparency):
    """Process opacity.

    This function accepts an opacity string or array and always
    returns an array that can be applied to a dataset for plotting.

    Parameters
    ----------
    mesh : pyvista.DataSet
        Dataset to process the opacity for.

    opacity : str, sequence
        String or array.  If string, can be a ``str`` name of a
        predefined mapping such as ``'linear'``, ``'geom'``,
        ``'sigmoid'``, ``'sigmoid3-10'``, or the key of a cell or
        point data array.

    preference : str
        When ``mesh.n_points == mesh.n_cells``, this parameter
        sets how the scalars will be mapped to the mesh. If
        ``'point'``, causes the scalars will be associated with
        the mesh points.  Can be either ``'point'`` or
        ``'cell'``.

    n_colors : int
        Number of colors to use when displaying the opacity.

    scalars : numpy.ndarray
        Dataset scalars.

    use_transparency : bool
        Invert the opacity mappings and make the values correspond
        to transparency.

    Returns
    -------
    _custom_opac : bool
        If using custom opacity.

    opacity : numpy.ndarray
        Array containing the opacity.

    """
    _custom_opac = False
    if isinstance(opacity, str):
        try:
            # Get array from mesh
            opacity = get_array(mesh, opacity, preference=preference, err=True)
            if np.any(opacity > 1):
                warnings.warn("Opacity scalars contain values over 1")
            if np.any(opacity < 0):
                warnings.warn("Opacity scalars contain values less than 0")
            _custom_opac = True
        except KeyError:
            # Or get opacity transfer function (e.g. "linear")
            opacity = opacity_transfer_function(opacity, n_colors)
        else:
            if scalars.shape[0] != opacity.shape[0]:
                raise ValueError(
                    "Opacity array and scalars array must have the same number of elements."
                )
    elif isinstance(opacity, (np.ndarray, list, tuple)):
        opacity = np.asanyarray(opacity)
        if opacity.shape[0] in [mesh.n_cells, mesh.n_points]:
            # User could pass an array of opacities for every point/cell
            _custom_opac = True
        else:
            opacity = opacity_transfer_function(opacity, n_colors)

    if use_transparency:
        if np.max(opacity) <= 1.0:
            opacity = 1 - opacity
        elif isinstance(opacity, np.ndarray):
            opacity = 255 - opacity

    return _custom_opac, opacity


# pyvista/plotting/axes.py

"""Module containing pyvista implementation of vtkAxes."""
from pyvista import _vtk


class Axes(_vtk.vtkAxes):
    """PyVista wrapper for the VTK Axes class.

    Parameters
    ----------
    show_actor : bool, optional
        Hide or show the actor of these axes.  Default ``False``.

    actor_scale : float, optional
        Scale the size of the axes actor.  Default ``1``.

    line_width : float, optional
        Width of the axes lines.  Default ``1``.

    symmetric : bool, optional
        If true, the axis continue to negative values.

    Examples
    --------
    Create an instance of axes at the pyvista module level.

    >>> import pyvista
    >>> axes = pyvista.Axes()

    """

    def __init__(self, show_actor=False, actor_scale=1, line_width=1.0, symmetric=False):
        """Initialize a new axes descriptor."""
        super().__init__()
        self.mapper = None
        self.actor = None
        self.SetSymmetric(symmetric)

        # Add the axes mapper
        self.mapper = _vtk.vtkPolyDataMapper()
        self.mapper.SetInputConnection(self.GetOutputPort())
        # Add the axes actor
        self.actor = _vtk.vtkActor()
        self.actor.SetMapper(self.mapper)
        self.actor.SetVisibility(show_actor)
        self.actor.SetScale(actor_scale)
        prop = self.actor.GetProperty()
        prop.SetLineWidth(line_width)

    @property
    def origin(self):
        """Origin of the axes in world coordinates.

        Examples
        --------
        >>> import pyvista
        >>> axes = pyvista.Axes()
        >>> axes.origin
        (0.0, 0.0, 0.0)

        Set the origin of the camera.

        >>> axes.origin = (2.0, 1.0, 1.0)
        >>> axes.origin
        (2.0, 1.0, 1.0)

        """
        return self.GetOrigin()

    @origin.setter
    def origin(self, value):
        """Set the origin of the camera."""
        self.SetOrigin(value)

    def show_actor(self):
        """Show an actor of axes.

        Examples
        --------
        >>> import pyvista as pv
        >>> axes = pv.Axes()
        >>> axes.show_actor()
        """
        self.actor.VisibilityOn()

    def hide_actor(self):
        """Hide an actor of axes.

        Examples
        --------
        >>> import pyvista as pv
        >>> axes = pv.Axes()
        >>> axes.hide_actor()
        """
        self.actor.VisibilityOff()

    def show_symmetric(self):
        """Show symmetric of axes.

        Examples
        --------
        >>> import pyvista as pv
        >>> axes = pv.Axes()
        >>> axes.show_symmetric()
        """
        self.SymmetricOn()

    def hide_symmetric(self):
        """Hide symmetric of axes.

        Examples
        --------
        >>> import pyvista as pv
        >>> axes = pv.Axes()
        >>> axes.hide_symmetric()
        """
        self.SymmetricOff()


# pyvista/plotting/background_renderer.py

"""Contains the BackgroundRenderer class."""
import numpy as np

import pyvista

from .renderer import Renderer


class BackgroundRenderer(Renderer):
    """BackgroundRenderer for visualizing a background image."""

    def __init__(self, parent, image_path, scale=1, view_port=None):
        """Initialize BackgroundRenderer with an image."""
        # avoiding circular import
        from pyvista import _vtk

        # read the image first as we don't need to create a render if
        # the image path is invalid
        image_data = pyvista.read(image_path)

        super().__init__(parent, border=False)
        self.SetLayer(0)
        self.InteractiveOff()
        self.SetBackground(self.parent.renderer.GetBackground())
        self._scale = scale
        self._modified_observer = None
        self._prior_window_size = None
        if view_port is not None:
            self.SetViewport(view_port)

        # create image actor
        image_actor = _vtk.vtkImageActor()
        image_actor.SetInputData(image_data)
        self.add_actor(image_actor, name='background')
        self.camera.enable_parallel_projection()
        self.reset_camera()  # necessary to get first render
        self.resize()

    def resize(self, *args):
        """Resize a background renderer."""
        if self.parent is None:  # when deleted
            return
        if not hasattr(self.parent, 'ren_win'):  # BasePlotter
            return

        if self._prior_window_size != self.parent.window_size:
            self._prior_window_size = self.parent.window_size

        actor = self._actors['background']
        image_data = actor.GetInput()
        origin = image_data.GetOrigin()
        extent = image_data.GetExtent()
        spacing = image_data.GetSpacing()
        xc = origin[0] + 0.5 * (extent[0] + extent[1]) * spacing[0]
        yc = origin[1] + 0.5 * (extent[2] + extent[3]) * spacing[1]
        yd = (extent[3] - extent[2] + 1) * spacing[1]
        dist = self.camera.distance

        # make the longest dimensions match the plotting window
        img_dim = np.array(image_data.dimensions[:2])
        self.camera.focus = np.array([xc, yc, 0.0])
        self.camera.position = np.array([xc, yc, dist])

        ratio = img_dim / np.array(self.parent.window_size)
        scale_value = 1
        if ratio.max() > 1:
            # images are not scaled if larger than the window
            scale_value = ratio.max()

        if self._scale is not None:
            scale_value /= self._scale

        self.camera.parallel_scale = 0.5 * yd / self._scale


# pyvista/plotting/camera.py

"""Module containing pyvista implementation of vtkCamera."""
import warnings
from weakref import proxy

import numpy as np

import pyvista
from pyvista import _vtk
from pyvista.utilities.misc import PyvistaDeprecationWarning


class Camera(_vtk.vtkCamera):
    """PyVista wrapper for the VTK Camera class.

    Parameters
    ----------
    renderer : pyvista.Renderer, optional
        Renderer to attach the camera to.

    Examples
    --------
    Create a camera at the pyvista module level.

    >>> import pyvista
    >>> camera = pyvista.Camera()

    Access the active camera of a plotter and get the position of the
    camera.

    >>> pl = pyvista.Plotter()
    >>> pl.camera.position
    (1.0, 1.0, 1.0)

    """

    def __init__(self, renderer=None):
        """Initialize a new camera descriptor."""
        self._parallel_projection = False
        self._elevation = 0.0
        self._azimuth = 0.0

        if renderer:
            if not isinstance(renderer, pyvista.Renderer):
                raise TypeError(
                    'Camera only accepts a pyvista.Renderer or None as the ``renderer`` argument'
                )
            self._renderer = proxy(renderer)
        else:
            self._renderer = None

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

    def __eq__(self, other):
        """Compare whether the relevant attributes of two cameras are equal."""
        # attributes which are native python types and thus implement __eq__

        native_attrs = [
            'position',
            'focal_point',
            'parallel_projection',
            'distance',
            'thickness',
            'parallel_scale',
            'clipping_range',
            'view_angle',
            'roll',
        ]
        for attr in native_attrs:
            if getattr(self, attr) != getattr(other, attr):
                return False

        this_trans = self.model_transform_matrix
        that_trans = other.model_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:
            if not np.array_equal(this_trans, that_trans):
                return False

        return True

    def __del__(self):
        """Delete the camera."""
        self.RemoveAllObservers()
        self.parent = None

    @property
    def position(self):
        """Return or set the position of the camera in world coordinates.

        Examples
        --------
        >>> import pyvista
        >>> pl = pyvista.Plotter()
        >>> pl.camera.position
        (1.0, 1.0, 1.0)
        >>> pl.camera.position = (2.0, 1.0, 1.0)
        >>> pl.camera.position
        (2.0, 1.0, 1.0)

        """
        return self.GetPosition()

    @position.setter
    def position(self, value):
        """Set the position of the camera."""
        self.SetPosition(value)
        self._elevation = 0.0
        self._azimuth = 0.0
        if self._renderer:
            self.reset_clipping_range()

    def reset_clipping_range(self):
        """Reset the camera clipping range based on the bounds of the visible actors.

        Examples
        --------
        >>> import pyvista
        >>> pl = pyvista.Plotter()
        >>> _ = pl.add_mesh(pyvista.Sphere())
        >>> pl.camera.clipping_range = (1, 2)
        >>> pl.camera.reset_clipping_range()  # doctest:+SKIP
        (0.0039213485598532955, 3.9213485598532953)

        """
        if self._renderer is None:
            raise AttributeError(
                'Camera is must be associated with a renderer to reset its clipping range.'
            )
        self._renderer.reset_camera_clipping_range()

    @property
    def focal_point(self):
        """Location of the camera's focus in world coordinates.

        Examples
        --------
        >>> import pyvista
        >>> pl = pyvista.Plotter()
        >>> pl.camera.focal_point
        (0.0, 0.0, 0.0)
        >>> pl.camera.focal_point = (2.0, 0.0, 0.0)
        >>> pl.camera.focal_point
        (2.0, 0.0, 0.0)
        """
        return self.GetFocalPoint()

    @focal_point.setter
    def focal_point(self, point):
        """Set the location of the camera's focus in world coordinates."""
        self.SetFocalPoint(point)

    @property
    def model_transform_matrix(self):
        """Return or set the camera's model transformation matrix.

        Examples
        --------
        >>> import pyvista
        >>> import numpy as np
        >>> pl = pyvista.Plotter()
        >>> pl.camera.model_transform_matrix
        array([[1., 0., 0., 0.],
               [0., 1., 0., 0.],
               [0., 0., 1., 0.],
               [0., 0., 0., 1.]])
        >>> pl.camera.model_transform_matrix = np.array([[1., 0., 0., 0.],
        ...                                              [0., 1., 0., 0.],
        ...                                              [0., 0., 1., 0.],
        ...                                              [0., 0., 0., 0.5]])
        >>>
        array([[1., 0., 0., 0.],
               [0., 1., 0., 0.],
               [0., 0., 1., 0.],
               [0., 0., 0., 0.5]])

        """
        vtk_matrix = self.GetModelTransformMatrix()
        matrix = np.empty((4, 4))
        vtk_matrix.DeepCopy(matrix.ravel(), vtk_matrix)
        return matrix

    @model_transform_matrix.setter
    def model_transform_matrix(self, matrix):
        """Set the camera's model transformation matrix."""
        vtk_matrix = _vtk.vtkMatrix4x4()
        vtk_matrix.DeepCopy(matrix.ravel())
        self.SetModelTransformMatrix(vtk_matrix)

    @property
    def is_parallel_projection(self):
        """Return True if parallel projection is set."""
        warnings.warn(
            "Use of `Camera.is_parallel_projection` is deprecated. "
            "Use `Camera.parallel_projection` instead.",
            PyvistaDeprecationWarning,
        )
        return self._parallel_projection

    @property
    def distance(self):
        """Return or set the distance of the focal point from the camera.

        Notes
        -----
        Setting the distance keeps the camera fixed and moves the focal point.

        Examples
        --------
        >>> import pyvista
        >>> pl = pyvista.Plotter()
        >>> pl.camera.distance
        1.73205
        >>> pl.camera.distance = 2.0
        >>> pl.camera.distance
        2.0

        """
        return self.GetDistance()

    @distance.setter
    def distance(self, distance):
        """Set the distance from the camera position to the focal point."""
        self.SetDistance(distance)

    @property
    def thickness(self):
        """Return or set the distance between clipping planes.

        Examples
        --------
        >>> import pyvista
        >>> pl = pyvista.Plotter()
        >>> pl.camera.thickness
        1000.0
        >>> pl.camera.thickness = 100
        >>> pl.camera.thickness
        100.0

        """
        return self.GetThickness()

    @thickness.setter
    def thickness(self, length):
        """Set the distance between clipping planes."""
        self.SetThickness(length)

    @property
    def parallel_scale(self):
        """Return or set the scaling used for a parallel projection.

        Examples
        --------
        >>> import pyvista
        >>> pl = pyvista.Plotter()
        >>> pl.camera.parallel_scale
        1.0
        >>> pl.camera.parallel_scale = 2.0
        >>> pl.camera.parallel_scale
        2.0

        """
        return self.GetParallelScale()

    @parallel_scale.setter
    def parallel_scale(self, scale):
        """Set the scaling used for parallel projection."""
        self.SetParallelScale(scale)

    def zoom(self, value):
        """Set the zoom of the camera.

        In perspective mode, decrease the view angle by the specified
        factor.

        In parallel mode, decrease the parallel scale by the specified
        factor. A value greater than 1 is a zoom-in, a value less than
        1 is a zoom-out.

        Parameters
        ----------
        value : float or str
            Zoom of the camera. If a float, must be greater than 0. Otherwise,
            if a string, must be ``"tight"``. If tight, the plot will be zoomed
            such that the actors fill the entire viewport.

        Examples
        --------
        Show the Default zoom.

        >>> import pyvista as pv
        >>> pl = pv.Plotter()
        >>> _ = pl.add_mesh(pv.Sphere())
        >>> pl.camera.zoom(1.0)
        >>> pl.show()

        Show 2x zoom.

        >>> pl = pv.Plotter()
        >>> _ = pl.add_mesh(pv.Sphere())
        >>> pl.camera.zoom(2.0)
        >>> pl.show()

        Zoom so the actor fills the entire render window.

        >>> pl = pv.Plotter()
        >>> _ = pl.add_mesh(pv.Sphere())
        >>> pl.camera.zoom('tight')
        >>> pl.show()

        """
        if isinstance(value, str):
            if not value == 'tight':
                raise ValueError('If a string, ``zoom`` can only be "tight"')
            self.tight()
            return

        self.Zoom(value)

    @property
    def up(self):
        """Return or set the "up" of the camera.

        Examples
        --------
        >>> import pyvista
        >>> pl = pyvista.Plotter()
        >>> pl.camera.up
        (0.0, 0.0, 1.0)
        >>> pl.camera.up = (0.410018, 0.217989, 0.885644)
        >>> pl.camera.up
        (0.410018, 0.217989, 0.885644)

        """
        return self.GetViewUp()

    @up.setter
    def up(self, vector):
        """Set the "up" of the camera."""
        self.SetViewUp(vector)

    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,
        but will look odd when viewing 3D datasets.

        Examples
        --------
        >>> import pyvista
        >>> from pyvista import demos
        >>> pl = pyvista.demos.orientation_plotter()
        >>> pl.enable_parallel_projection()
        >>> pl.show()

        """
        self._parallel_projection = True
        self.SetParallelProjection(True)

    def disable_parallel_projection(self):
        """Disable the use of parallel projection.

        This is default behavior.

        Examples
        --------
        >>> import pyvista
        >>> from pyvista import demos
        >>> pl = pyvista.demos.orientation_plotter()
        >>> pl.disable_parallel_projection()
        >>> pl.show()
        """
        self._parallel_projection = False
        self.SetParallelProjection(False)

    @property
    def parallel_projection(self):
        """Return the state of the parallel projection.

        Examples
        --------
        >>> import pyvista
        >>> from pyvista import demos
        >>> pl = pyvista.Plotter()
        >>> pl.disable_parallel_projection()
        >>> pl.parallel_projection
        False
        """
        return self._parallel_projection

    @parallel_projection.setter
    def parallel_projection(self, state):
        """Return the state of the parallel projection.

        Examples
        --------
        >>> import pyvista
        >>> from pyvista import demos
        >>> pl = pyvista.Plotter()
        >>> pl.disable_parallel_projection()
        >>> pl.parallel_projection
        False
        """
        if state:
            self.enable_parallel_projection()
        else:
            self.disable_parallel_projection()

    @property
    def clipping_range(self):
        """Return or set the location of the clipping planes.

        Clipping planes are the the near and far clipping planes along
        the direction of projection.

        Examples
        --------
        >>> import pyvista
        >>> pl = pyvista.Plotter()
        >>> pl.camera.clipping_range
        (0.01, 1000.01)
        >>> pl.camera.clipping_range = (1, 10)
        >>> pl.camera.clipping_range
        (1.0, 10.0)

        """
        return self.GetClippingRange()

    @clipping_range.setter
    def clipping_range(self, points):
        """Set the clipping planes."""
        if points[0] > points[1]:
            raise ValueError('Near point must be lower than the far point.')
        self.SetClippingRange(points[0], points[1])

    @property
    def view_angle(self):
        """Return or set the camera view angle.

        Examples
        --------
        >>> import pyvista
        >>> plotter = pyvista.Plotter()
        >>> plotter.camera.view_angle
        30.0
        >>> plotter.camera.view_angle = 60.0
        >>> plotter.camera.view_angle
        60.0

        """
        return self.GetViewAngle()

    @view_angle.setter
    def view_angle(self, value):
        """Set the camera view angle."""
        self.SetViewAngle(value)

    @property
    def direction(self):
        """Vector from the camera position to the focal point.

        Examples
        --------
        >>> import pyvista
        >>> plotter = pyvista.Plotter()
        >>> plotter.camera.direction  # doctest:+SKIP
        (0.0, 0.0, -1.0)

        """
        return self.GetDirectionOfProjection()

    def view_frustum(self, aspect=1.0):
        """Get the view frustum.

        Parameters
        ----------
        aspect : float, optional
            The aspect of the viewport to compute the planes. Defaults
            to 1.0.

        Returns
        -------
        pyvista.PolyData
            View frustum.

        Examples
        --------
        >>> import pyvista
        >>> plotter = pyvista.Plotter()
        >>> frustum = plotter.camera.view_frustum(1.0)
        >>> frustum.n_points
        8
        >>> frustum.n_cells
        6

        """
        frustum_planes = [0] * 24
        self.GetFrustumPlanes(aspect, frustum_planes)
        planes = _vtk.vtkPlanes()
        planes.SetFrustumPlanes(frustum_planes)

        frustum_source = _vtk.vtkFrustumSource()
        frustum_source.ShowLinesOff()
        frustum_source.SetPlanes(planes)
        frustum_source.Update()

        frustum = pyvista.wrap(frustum_source.GetOutput())
        return frustum

    @property
    def roll(self):
        """Rotate the camera about the direction of projection.

        This will spin the camera about its axis.

        Examples
        --------
        >>> import pyvista
        >>> pl = pyvista.Plotter()
        >>> pl.camera.roll
        -120.00000000000001
        >>> pl.camera.roll = 45.0
        >>> pl.camera.roll
        45.0
        """
        return self.GetRoll()

    @roll.setter
    def roll(self, angle):
        """Set the rotate of the camera about the direction of projection."""
        self.SetRoll(angle)

    @property
    def elevation(self):
        """Vertical rotation of the scene.

        Rotate the camera about the cross product of the negative of
        the direction of projection and the view up vector, using the
        focal point as the center of rotation.

        Examples
        --------
        >>> import pyvista
        >>> pl = pyvista.Plotter()
        >>> pl.camera.elevation
        0.0
        >>> pl.camera.elevation = 45.0
        >>> pl.camera.elevation
        45.0

        """
        return self._elevation

    @elevation.setter
    def elevation(self, angle):
        """Set the vertical rotation of the scene."""
        if self._elevation:
            self.Elevation(-self._elevation)
        self._elevation = angle
        self.Elevation(angle)

    @property
    def azimuth(self):
        """Azimuth of the camera.

        Rotate the camera about the view up vector centered at the
        focal point. Note that the view up vector is whatever was set
        via SetViewUp, and is not necessarily perpendicular to the
        direction of projection.

        Examples
        --------
        >>> import pyvista
        >>> pl = pyvista.Plotter()
        >>> pl.camera.azimuth
        0.0
        >>> pl.camera.azimuth = 45.0
        >>> pl.camera.azimuth
        45.0

        """
        return self._azimuth

    @azimuth.setter
    def azimuth(self, angle):
        """Set the azimuth rotation of the camera."""
        if self._azimuth:
            self.Azimuth(-self._azimuth)
        self._azimuth = angle
        self.Azimuth(angle)

    def copy(self):
        """Return a deep copy of the camera.

        Returns
        -------
        pyvista.Camera
            Deep copy of the camera.

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

        >>> import pyvista as pv
        >>> import numpy as np
        >>> camera = pv.Camera()
        >>> camera.model_transform_matrix = np.array([[1., 0., 0., 0.],
        ...                                           [0., 1., 0., 0.],
        ...                                           [0., 0., 1., 0.],
        ...                                           [0., 0., 0., 1.]])
        >>> copied_camera = camera.copy()
        >>> copied_camera == camera
        True
        >>> camera.model_transform_matrix = np.array([[1., 0., 0., 0.],
        ...                                           [0., 1., 0., 0.],
        ...                                           [0., 0., 1., 0.],
        ...                                           [0., 0., 0., 0.5]])
        >>> copied_camera == camera
        False
        """
        immutable_attrs = [
            'position',
            'focal_point',
            'model_transform_matrix',
            'distance',
            'thickness',
            'parallel_scale',
            'up',
            'clipping_range',
            'view_angle',
            'roll',
            'parallel_projection',
        ]
        new_camera = Camera()

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

        return new_camera

    def tight(self, padding=0.0, adjust_render_window=True):
        """Adjust the camera position so that the actors fill the entire renderer.

        Parameters
        ----------
        padding : float, optional
            Additional padding around the actor(s). This is effectively a zoom,
            where a value of 0.01 results in a zoom out of 1%.

        adjust_render_window : bool, optional
            Adjust the size of the render window as to match the dimensions of
            the visible actors.

        Notes
        -----
        This resets the view direction to look at the XY plane.

        Examples
        --------
        Display the puppy image with a tight view.

        >>> import pyvista as pv
        >>> from pyvista import examples
        >>> puppy = examples.download_puppy()
        >>> pl = pv.Plotter(border=True, border_width=5)
        >>> _ = pl.add_mesh(puppy, rgb=True)
        >>> pl.camera.tight()
        >>> pl.show()

        Set the background to blue use a 5% padding around the image.

        >>> pl = pv.Plotter()
        >>> _ = pl.add_mesh(puppy, rgb=True)
        >>> pl.background_color = 'b'
        >>> pl.camera.tight(padding=0.05)
        >>> pl.show()

        """
        # inspired by vedo resetCamera. Thanks @marcomusy!
        x0, x1, y0, y1, z0, z1 = self._renderer.ComputeVisiblePropBounds()

        self.enable_parallel_projection()

        self._renderer.ComputeAspect()
        aspect = self._renderer.GetAspect()
        angle = np.pi * self.view_angle / 180.0
        dx, dy = (x1 - x0), (y1 - y0)
        dist = max(dx / aspect[0], dy) / np.sin(angle / 2) / 2

        self.SetViewUp(0, 1, 0)
        self.SetPosition(x0 + dx / 2, y0 + dy / 2, dist * (1 + padding))
        self.SetFocalPoint(x0 + dx / 2, y0 + dy / 2, 0)

        ps = max(dx / aspect[0], dy) / 2
        self.parallel_scale = ps * (1 + padding)
        self._renderer.ResetCameraClippingRange(x0, x1, y0, y1, z0, z1)

        if adjust_render_window:
            ren_win = self._renderer.GetRenderWindow()
            size = list(ren_win.GetSize())
            size_ratio = size[0] / size[1]
            tight_ratio = dx / dy
            resize_ratio = tight_ratio / size_ratio
            if resize_ratio < 1:
                size[0] = round(size[0] * resize_ratio)
            else:
                size[1] = round(size[1] / resize_ratio)

            ren_win.SetSize(size)

            # simply call tight again to reset the parallel scale due to the
            # resized window
            self.tight(padding=padding, adjust_render_window=False)


# pyvista/plotting/charts.py

"""Module containing pyvista wrappers for the vtk Charts API."""

from functools import wraps
import inspect
import itertools
import re
from typing import Dict, Optional, Sequence
import weakref

import numpy as np

import pyvista
from pyvista import _vtk

from .colors import Color, color_synonyms, hexcolors


# region Some metaclass wrapping magic
# Note: these classes can be removed once VTK 9.2 is released.
class _vtkWrapperMeta(type):
    def __init__(cls, clsname, bases, attrs):
        # Restore the signature of classes inheriting from _vtkWrapper
        # Based on https://stackoverflow.com/questions/49740290/call-from-metaclass-shadows-signature-of-init
        sig = inspect.signature(cls.__init__)
        params = list(sig.parameters.values())
        params.insert(
            len(params) - 1 if params[-1].kind == inspect.Parameter.VAR_KEYWORD else len(params),
            inspect.Parameter("_wrap", inspect.Parameter.KEYWORD_ONLY, default=None),
        )
        cls.__signature__ = sig.replace(parameters=params[1:])
        super().__init__(clsname, bases, attrs)

    def __call__(cls, *args, _wrap=None, **kwargs):
        # if _wrap is None:
        #     obj = cls.__new__(cls, *args, **kwargs)
        # else:
        #     obj = cls.__new__(_wrap.__class__, _wrap.__this__, *args, **kwargs)
        obj = cls.__new__(cls, *args, **kwargs)
        obj._wrapped = _wrap
        obj.__init__(*args, **kwargs)
        return obj


class _vtkWrapper(object, metaclass=_vtkWrapperMeta):
    def __getattribute__(self, item):
        unwrapped_attrs = ["_wrapped", "__class__", "__init__"]
        wrapped = super().__getattribute__("_wrapped")
        if item in unwrapped_attrs or wrapped is None:
            return super().__getattribute__(item)
        else:
            try:
                return wrapped.__getattribute__(item)
            except AttributeError:
                return super().__getattribute__(item)

    def __str__(self):
        if self._wrapped is None:
            return super().__str__()
        else:
            return "Wrapped: " + self._wrapped.__str__()


# endregion

# region Documentation substitution
class DocSubs:
    """Helper class to easily substitute the docstrings of the listed member functions or properties."""

    # The substitutions to use for this (sub)class
    _DOC_SUBS: Optional[Dict[str, str]] = None
    # Internal dictionary to store registered member functions/properties and their (to be substituted) docs.
    _DOC_STORE = {}  # type: ignore
    # Tag used to mark members that require docstring substitutions.
    _DOC_TAG = ":DOC_SUBS:"

    def __init_subclass__(cls, **kwargs):
        """Initialize subclasses."""
        # First substitute all members for this class (marked in a super class)
        if cls._DOC_SUBS is not None:
            subs = {**cls._DOC_SUBS}
            if "cls" not in subs:
                subs["cls"] = cls.__name__
            for member_name, (m, d) in cls._DOC_STORE.items():
                if member_name not in cls.__dict__:
                    # If the member is not part of the subclass' __dict__, we have to generate a wrapping
                    # function or property and add it to the subclass' __dict__. Otherwise, the docstring
                    # of the superclass would be used for the substitutions.
                    mem_sub = cls._wrap_member(m)
                    mem_sub.__doc__ = d
                    setattr(cls, member_name, mem_sub)
                # Get the member function/property and substitute its docstring.
                member = getattr(cls, member_name)
                member.__doc__ = member.__doc__.format(**subs)

        # Secondly, register all members of this class that require substitutions in subclasses
        # Create copy of registered members so far
        # TODO: B010
        setattr(cls, "_DOC_STORE", {**cls._DOC_STORE})  # noqa: B010
        for member_name, member in cls.__dict__.items():
            if member.__doc__ and member.__doc__.startswith(cls._DOC_TAG):
                # New method/property to register in this class (denoting their docstring should be
                # substituted in subsequent child classes).
                cls._DOC_STORE[member_name] = (member, member.__doc__[len(cls._DOC_TAG) :])
                # Overwrite original docstring to prevent doctest issues
                member.__doc__ = """Docstring to be specialized in subclasses."""

    @staticmethod
    def _wrap_member(member):
        if callable(member):

            @wraps(member)
            def mem_sub(*args, **kwargs):
                return member(*args, **kwargs)

        elif isinstance(member, property):
            mem_sub = property(member.fget, member.fset, member.fdel)
        else:
            raise NotImplementedError(
                "Members other than methods and properties are currently not supported."
            )
        return mem_sub


def doc_subs(member):
    """Doc subs wrapper.

    Only common attribute between methods and properties that we can
    modify is __doc__, so use that to mark members that need doc
    substitutions.
    Still, only methods can be marked for doc substitution (as for
    properties the docstring seems to be overwritten when specifying
    setters or deleters), hence this decorator should be applied
    before the property decorator. And 'type: ignore' comments are
    necessary because mypy cannot handle decorated properties (see
    https://github.com/python/mypy/issues/1362)
    """
    # Ensure we are operating on a method
    if not callable(member):  # pragma: no cover
        raise ValueError('`member` must be a callable.')
    member.__doc__ = DocSubs._DOC_TAG + member.__doc__
    return member


# endregion


class Pen(_vtkWrapper, _vtk.vtkPen):
    """Pythonic wrapper for a VTK Pen, used to draw lines.

    Parameters
    ----------
    color : color_like, optional
        Color of the lines drawn using this pen. Any color parsable by
        :class:`pyvista.Color` is allowed. Defaults to ``"k"``.

    width : float, optional
        Width of the lines drawn using this pen. Defaults to ``1``.

    style : str, optional
        Style of the lines drawn using this pen. See
        :ref:`Pen.LINE_STYLES <pen_line_styles>` for a list of allowed
        line styles. Defaults to ``"-"``.

    Other Parameters
    ----------------
    _wrap : vtk.vtkPen, optional
        Wrap an existing VTK Pen instance. Defaults to ``None`` (no wrapping).

    Notes
    -----
    .. _pen_line_styles:

    LINE_STYLES : dict
        Dictionary containing all allowed line styles as its keys.

        .. include:: ../pen_line_styles.rst

    """

    LINE_STYLES = {  # descr is used in the documentation, set to None to hide it from the docs.
        "": {"id": _vtk.vtkPen.NO_PEN, "descr": "Hidden"},
        "-": {"id": _vtk.vtkPen.SOLID_LINE, "descr": "Solid"},
        "--": {"id": _vtk.vtkPen.DASH_LINE, "descr": "Dashed"},
        ":": {"id": _vtk.vtkPen.DOT_LINE, "descr": "Dotted"},
        "-.": {"id": _vtk.vtkPen.DASH_DOT_LINE, "descr": "Dash-dot"},
        "-..": {"id": _vtk.vtkPen.DASH_DOT_DOT_LINE, "descr": "Dash-dot-dot"},
    }

    def __init__(self, color="k", width=1, style="-"):
        """Initialize a new Pen instance."""
        super().__init__()
        self.color = color
        self.width = width
        self.style = style

    @property
    def color(self):
        """Return or set the pen's color.

        Examples
        --------
        Set the pen's color to red.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> plot = chart.line([0, 1, 2], [2, 1, 3])
        >>> plot.pen.color = 'r'
        >>> chart.show()

        """
        return self._color

    @color.setter
    def color(self, val):
        self._color = Color(val, default_color="black")
        self.SetColor(*self._color.int_rgba)

    @property
    def width(self):
        """Return or set the pen's width.

        Examples
        --------
        Set the pen's width to 10

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> plot = chart.line([0, 1, 2], [2, 1, 3])
        >>> plot.pen.width = 10
        >>> chart.show()

        """
        return self.GetWidth()

    @width.setter
    def width(self, val):
        self.SetWidth(float(val))

    @property
    def style(self):
        """Return or set the pen's line style.

        See :ref:`Pen.LINE_STYLES <pen_line_styles>` for a list of allowed line styles.

        Examples
        --------
        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> plot = chart.line([0, 1, 2], [2, 1, 3])
        >>> plot.pen.style = '-.'
        >>> chart.show()

        """
        return self._line_style

    @style.setter
    def style(self, val):
        if val is None:
            val = ""
        try:
            self.SetLineType(self.LINE_STYLES[val]["id"])
            self._line_style = val
        except KeyError:
            formatted_styles = "\", \"".join(self.LINE_STYLES.keys())
            raise ValueError(f"Invalid line style. Allowed line styles: \"{formatted_styles}\"")


class Brush(_vtkWrapper, _vtk.vtkBrush):
    """Pythonic wrapper for a VTK Brush, used to fill shapes.

    Parameters
    ----------
    color : color_like, optional
        Fill color of the shapes drawn using this brush. Any color
        parsable by :class:`pyvista.Color` is allowed.  Defaults to
        ``"k"``.

    texture : Texture, optional
        Texture used to fill shapes drawn using this brush. Any object
        convertible to a :class:`Texture` is allowed. Defaults to
        ``None``.

    Other Parameters
    ----------------
    _wrap : vtk.vtkBrush, optional
        Wrap an existing VTK Brush instance. Defaults to ``None`` (no wrapping).

    """

    def __init__(self, color="k", texture=None):
        """Initialize a new Pen instance."""
        super().__init__()
        self.color = color
        self.texture = texture
        self._interpolate = True  # vtkBrush textureProperties defaults to LINEAR & STRETCH
        self._repeat = False

    @property
    def color(self):
        """Return or set the brush's color.

        Examples
        --------
        Set the brush's color to red.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> plot = chart.area([0, 1, 2], [0, 0, 1], [1, 3, 2])
        >>> plot.brush.color = 'r'
        >>> chart.show()

        """
        return self._color

    @color.setter
    def color(self, val):
        self._color = Color(val, default_color="black")
        self.SetColor(*self._color.int_rgba)

    @property
    def texture(self):
        """Return or set the brush's texture.

        Examples
        --------
        Set the brush's texture to the sample puppy texture.

        >>> import pyvista
        >>> from pyvista import examples
        >>> chart = pyvista.Chart2D()
        >>> plot = chart.area([0, 1, 2], [0, 0, 1], [1, 3, 2])
        >>> plot.brush.texture = examples.download_puppy_texture()
        >>> chart.show()

        """
        return self._texture

    @texture.setter
    def texture(self, val):
        if val is None:
            self._texture = None
            self.SetTexture(None)
        else:
            self._texture = pyvista.Texture(val)
            self.SetTexture(self._texture.to_image())

    @property
    def texture_interpolate(self):
        """Set texture interpolation mode.

        There are two modes:

        * ``False`` - NEAREST
        * ``True`` - LINEAR

        Examples
        --------
        Set up a brush with a texture.

        >>> import pyvista
        >>> from pyvista import examples
        >>> chart = pyvista.Chart2D()
        >>> plot = chart.area([0, 1, 2], [0, 0, 1], [1, 3, 2])
        >>> plot.brush.texture = examples.download_puppy_texture()
        >>> chart.show()

        Disable linear interpolation.

        >>> plot.brush.texture_interpolate = False
        >>> chart.show()

        """
        return self._interpolate

    @texture_interpolate.setter
    def texture_interpolate(self, val):
        self._interpolate = bool(val)
        self._update_textureprops()

    @property
    def texture_repeat(self):
        """Return or set the texture repeat mode.

        There are two modes:

        * ``False`` - STRETCH
        * ``True`` - REPEAT

        Examples
        --------
        Set up a brush with a texture.

        >>> import pyvista
        >>> from pyvista import examples
        >>> chart = pyvista.Chart2D()
        >>> plot = chart.area([0, 1, 2], [0, 0, 1], [1, 3, 2])
        >>> plot.brush.texture = examples.download_puppy_texture()
        >>> chart.show()

        Enable texture repeat.

        >>> plot.brush.texture_repeat = True
        >>> chart.show()

        """
        return self._repeat

    @texture_repeat.setter
    def texture_repeat(self, val):
        self._repeat = bool(val)
        self._update_textureprops()

    def _update_textureprops(self):
        # Interpolation: NEAREST = 0x01, LINEAR = 0x02
        # Stretch/repeat: STRETCH = 0x04, REPEAT = 0x08
        self.SetTextureProperties(1 + int(self._interpolate) + 4 * (1 + int(self._repeat)))


class Axis(_vtkWrapper, _vtk.vtkAxis):
    """Pythonic interface for a VTK Axis, used by 2D charts.

    Parameters
    ----------
    label : str, optional
        Axis label. Defaults to the empty string ``""`` (no visible label).

    range : list or tuple of float, optional
        Axis range, denoting the minimum and maximum values
        displayed on this axis. Setting this to any valid value
        other than ``None`` will change this axis behavior to
        ``'fixed'``. Setting it to ``None`` will change the axis
        behavior to ``'auto'``. Defaults to ``None``
        (automatically scale axis).

    grid : bool, optional
        Flag to toggle grid lines visibility for this axis. Defaults to ``True``.

    Attributes
    ----------
    pen : Pen
        Pen used to draw the axis.

    grid_pen : Pen
        Pen used to draw the grid lines.

    Other Parameters
    ----------------
    _wrap : vtk.vtkAxis, optional
        Wrap an existing VTK Axis instance. Defaults to ``None`` (no wrapping).

    """

    BEHAVIORS = {"auto": _vtk.vtkAxis.AUTO, "fixed": _vtk.vtkAxis.FIXED}

    def __init__(self, label="", range=None, grid=True):
        """Initialize a new Axis instance."""
        super().__init__()
        self._tick_locs = _vtk.vtkDoubleArray()
        self._tick_labels = _vtk.vtkStringArray()
        self.pen = Pen(color=(0, 0, 0), _wrap=self.GetPen())
        self.grid_pen = Pen(color=(0.95, 0.95, 0.95), _wrap=self.GetGridPen())
        self.label = label
        self._behavior = None  # Will be set by specifying the range below
        self.range = range
        self.grid = grid

    @property
    def label(self):
        """Return or set the axis label.

        Examples
        --------
        Set the axis label to ``"Axis Label"``.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> _ = chart.line([0, 1, 2], [2, 1, 3])
        >>> chart.x_axis.label = "Axis Label"
        >>> chart.show()

        """
        return self.GetTitle()

    @label.setter
    def label(self, val):
        self.SetTitle(val)

    @property
    def label_visible(self):
        """Return or set the axis label's visibility.

        Examples
        --------
        Hide the x-axis label of a 2D chart.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> _ = chart.line([0, 1, 2], [2, 1, 3])
        >>> chart.x_axis.label_visible = False
        >>> chart.show()

        """
        return self.GetTitleVisible()

    @label_visible.setter
    def label_visible(self, val):
        self.SetTitleVisible(bool(val))

    @property
    def label_size(self):
        """Return or set the size of the axis label font.

        Examples
        --------
        Set the x-axis label font size of a 2D chart to 20.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> _ = chart.line([0, 1, 2], [2, 1, 3])
        >>> chart.x_axis.label_size = 20
        >>> chart.x_axis.label_size
        20
        >>> chart.show()

        """
        return self.GetTitleProperties().GetFontSize()

    @label_size.setter
    def label_size(self, size):
        self.GetTitleProperties().SetFontSize(size)

    @property
    def range(self):
        """Return or set the axis range.

        This will automatically set the axis behavior to ``"fixed"``
        when a valid range is given. Setting the range to ``None``
        will set the axis behavior to ``"auto"``.

        Examples
        --------
        Manually specify the x-axis range of a 2D chart.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> _ = chart.line([0, 1, 2], [2, 1, 3])
        >>> chart.x_axis.range = [0, 5]
        >>> chart.show()

        Revert to automatic axis scaling.

        >>> chart.x_axis.range = None
        >>> chart.show()

        """
        r = [0.0, 0.0]
        self.GetRange(r)
        return r

    @range.setter
    def range(self, val):
        if val is None:
            self.behavior = "auto"
        else:
            self.behavior = "fixed"
            self.SetRange(*val)

    @property
    def behavior(self):
        """Set the axis' scaling behavior.

        Allowed behaviors are ``'auto'`` to automatically rescale the
        axis to fit all visible datapoints in the plot, or ``'fixed'``
        to use the user defined range.

        Examples
        --------
        Manually specify the x-axis range of a 2D chart.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> _ = chart.line([0, 1, 2], [2, 1, 3])
        >>> chart.x_axis.range = [0, 5]
        >>> chart.show()

        Revert to automatic axis scaling.

        >>> chart.x_axis.behavior = "auto"
        >>> chart.show()
        >>> chart.x_axis.range
        [0.0, 2.0]

        """
        return self._behavior

    @behavior.setter
    def behavior(self, val):
        try:
            self.SetBehavior(self.BEHAVIORS[val])
            self._behavior = val
        except KeyError:
            formatted_behaviors = "\", \"".join(self.BEHAVIORS.keys())
            raise ValueError(f"Invalid behavior. Allowed behaviors: \"{formatted_behaviors}\"")

    @property
    def margin(self):
        """Return or set the axis margin.

        Examples
        --------
        Create a 2D chart.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> chart.background_color = 'c'
        >>> _ = chart.line([0, 1, 2], [2, 1, 3])
        >>> chart.show()

        Manually specify a larger (bottom) margin for the x-axis and a
        larger (left) margin for the y-axis.

        >>> chart.x_axis.margin = 50
        >>> chart.y_axis.margin = 50
        >>> chart.show()

        """
        return self.GetMargins()[0]

    @margin.setter
    def margin(self, val):
        # Second margin doesn't seem to have any effect? So we only expose the first entry as 'the margin'.
        m = self.GetMargins()
        self.SetMargins(val, m[1])

    @property
    def log_scale(self):
        """Flag denoting whether a log scale is used for this axis.

        Note that setting this property to ``True`` will not guarantee
        that the log scale will be enabled.  Verify whether activating
        the log scale succeeded by rereading this property.

        Examples
        --------
        Create a 2D chart.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> _ = chart.line([0, 1, 2, 3, 4], [1e0, 1e1, 1e2, 1e3, 1e4])
        >>> chart.show()

        Try to enable the log scale on the y-axis.

        >>> chart.y_axis.log_scale = True
        >>> chart.show()
        >>> chart.y_axis.log_scale
        True

        """
        return self.GetLogScaleActive()

    @log_scale.setter
    def log_scale(self, val):
        # False: log_scale will be disabled, True: axis will attempt to activate log_scale if possible
        self.SetLogScale(bool(val))

    @property
    def grid(self):
        """Return or set the axis' grid line visibility.

        Examples
        --------
        Create a 2D chart with grid lines disabled for the x-axis.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> _ = chart.line([0, 1, 2], [2, 1, 3])
        >>> chart.x_axis.grid = False
        >>> chart.show()

        """
        return self.GetGridVisible()

    @grid.setter
    def grid(self, val):
        self.SetGridVisible(bool(val))

    @property
    def visible(self):
        """Return or set the axis' visibility.

        Examples
        --------
        Create a 2D chart with no visible y-axis.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> _ = chart.line([0, 1, 2], [2, 1, 3])
        >>> chart.y_axis.visible = False
        >>> chart.show()

        """
        return self.GetAxisVisible()

    @visible.setter
    def visible(self, val):
        self.SetAxisVisible(bool(val))

    def toggle(self):
        """Toggle the axis' visibility.

        Examples
        --------
        Create a 2D chart.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> _ = chart.line([0, 1, 2], [2, 1, 3])
        >>> chart.show()

        Toggle the visibility of the y-axis.

        >>> chart.y_axis.toggle()
        >>> chart.show()

        """
        self.visible = not self.visible

    # --- Ticks ---
    @property
    def tick_count(self):
        """Return or set the number of ticks drawn on this axis.

        Setting this property to a negative value or ``None`` will
        automatically determine the appropriate amount of ticks to
        draw.

        Examples
        --------
        Create a 2D chart with a reduced number of ticks on the x-axis.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> _ = chart.line([0, 1, 2], [2, 1, 3])
        >>> chart.x_axis.tick_count = 5
        >>> chart.show()

        Revert back to automatic tick behavior.

        >>> chart.x_axis.tick_count = None
        >>> chart.show()

        """
        return self.GetNumberOfTicks()

    @tick_count.setter
    def tick_count(self, val):
        if val is None or val < 0:
            val = -1
        self.SetNumberOfTicks(int(val))

    @property
    def tick_locations(self):
        """Return or set the tick locations for this axis.

        Setting this to ``None`` will revert back to the default,
        automatically determined, tick locations.

        Examples
        --------
        Create a 2D chart with custom tick locations and labels on the y-axis.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> _ = chart.line([0, 1, 2], [2, 1, 3])
        >>> chart.y_axis.tick_locations = (0.2, 0.4, 0.6, 1, 1.5, 2, 3)
        >>> chart.y_axis.tick_labels = ["Very small", "Small", "Still small",
        ...                             "Small?", "Not large", "Large?",
        ...                             "Very large"]
        >>> chart.show()

        Revert back to automatic tick placement.

        >>> chart.y_axis.tick_locations = None
        >>> chart.y_axis.tick_labels = None
        >>> chart.show()

        """
        positions = self.GetTickPositions()
        return tuple(positions.GetValue(i) for i in range(positions.GetNumberOfValues()))

    @tick_locations.setter
    def tick_locations(self, val):
        self._tick_locs.Reset()
        if val is not None:
            for loc in val:
                self._tick_locs.InsertNextValue(loc)
        self._update_ticks()

    @property
    def tick_labels(self):
        """Return or set the tick labels for this axis.

        You can specify a sequence, to provide a unique label to every
        tick position; a string, to describe the label format to use
        for each label; or ``None``, which will revert back to the
        default tick labels.  A label format is a string consisting of
        an integer part, denoting the precision to use, and a final
        character, denoting the notation to use.

        Allowed notations:

        * ``"f"`` for fixed notation
        * ``"e"`` for scientific notation.

        Examples
        --------
        Create a 2D chart with custom tick locations and labels on the y-axis.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> _ = chart.line([0, 1, 2], [2, 1, 3])
        >>> chart.y_axis.tick_locations = (0.2, 0.4, 0.6, 1, 1.5, 2, 3)
        >>> chart.y_axis.tick_labels = ["Very small", "Small", "Still small",
        ...                             "Small?", "Not large", "Large?",
        ...                             "Very large"]
        >>> chart.show()

        Revert back to automatic tick placement.

        >>> chart.y_axis.tick_locations = None
        >>> chart.y_axis.tick_labels = None
        >>> chart.show()

        Specify a custom label format to use (fixed notation with precision 2).

        >>> chart.y_axis.tick_labels = "2f"
        >>> chart.show()

        """
        labels = self.GetTickLabels()
        return tuple(labels.GetValue(i) for i in range(labels.GetNumberOfValues()))

    @tick_labels.setter
    def tick_labels(self, val):
        self._tick_labels.Reset()
        self.SetNotation(_vtk.vtkAxis.STANDARD_NOTATION)
        if isinstance(val, str):
            precision = int(val[:-1])
            notation = val[-1].lower()
            if notation == "f":
                self.SetNotation(_vtk.vtkAxis.FIXED_NOTATION)
                self.SetPrecision(precision)
            elif notation == "e":
                self.SetNotation(_vtk.vtkAxis.SCIENTIFIC_NOTATION)
                self.SetPrecision(precision)
        elif isinstance(val, Sequence):
            for label in val:
                self._tick_labels.InsertNextValue(label)
        self._update_ticks()

    @property
    def tick_label_size(self):
        """Return or set the size of the axis tick label font.

        Examples
        --------
        Set the x-axis tick label font size of a 2D chart to 20.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> _ = chart.line([0, 1, 2], [2, 1, 3])
        >>> chart.x_axis.tick_label_size = 20
        >>> chart.x_axis.tick_label_size
        20
        >>> chart.show()

        """
        return self.GetLabelProperties().GetFontSize()

    @tick_label_size.setter
    def tick_label_size(self, size):
        self.GetLabelProperties().SetFontSize(size)

    @property
    def tick_size(self):
        """Return or set the size of this axis' ticks.

        Examples
        --------
        Create a 2D chart with an x-axis with an increased tick size
        and adjusted offset for the tick labels.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> _ = chart.line([0, 1, 2], [2, 1, 3])
        >>> chart.x_axis.tick_size += 10
        >>> chart.x_axis.tick_labels_offset += 12
        >>> chart.show()

        """
        return self.GetTickLength()

    @tick_size.setter
    def tick_size(self, val):
        self.SetTickLength(val)

    @property
    def tick_labels_offset(self):
        """Return or set the offset of the tick labels for this axis.

        Examples
        --------
        Create a 2D chart with an x-axis with an increased tick size
        and adjusted offset for the tick labels.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> _ = chart.line([0, 1, 2], [2, 1, 3])
        >>> chart.x_axis.tick_size += 10
        >>> chart.x_axis.tick_labels_offset += 12
        >>> chart.show()

        """
        return self.GetLabelOffset()

    @tick_labels_offset.setter
    def tick_labels_offset(self, val):
        self.SetLabelOffset(float(val))

    @property
    def tick_labels_visible(self):
        """Return or set the tick label visibility for this axis.

        Examples
        --------
        Create a 2D chart with hidden tick labels on the y-axis.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> _ = chart.line([0, 1, 2], [2, 1, 3])
        >>> chart.y_axis.tick_labels_visible = False
        >>> chart.show()

        """
        return self.GetLabelsVisible()

    @tick_labels_visible.setter
    def tick_labels_visible(self, val):
        self.SetLabelsVisible(bool(val))
        self.SetRangeLabelsVisible(bool(val))

    @property
    def ticks_visible(self):
        """Return or set the tick visibility for this axis.

        Examples
        --------
        Create a 2D chart with hidden ticks on the y-axis.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> _ = chart.line([0, 1, 2], [2, 1, 3])
        >>> chart.y_axis.ticks_visible = False
        >>> chart.show()

        """
        return self.GetTicksVisible()

    @ticks_visible.setter
    def ticks_visible(self, val):
        self.SetTicksVisible(bool(val))

    def _update_ticks(self):
        locs = None if self._tick_locs.GetNumberOfValues() == 0 else self._tick_locs
        labels = None if self._tick_labels.GetNumberOfValues() == 0 else self._tick_labels
        self.SetCustomTickPositions(locs, labels)


class _CustomContextItem(_vtk.vtkPythonItem):
    class ItemWrapper(object):
        def Initialize(self, item):
            # item is the _CustomContextItem subclass instance
            return True

        def Paint(self, item, painter):
            # item is the _CustomContextItem subclass instance
            return item.paint(painter)

    def __init__(self):
        super().__init__()
        self.SetPythonObject(
            _CustomContextItem.ItemWrapper()
        )  # This will also call ItemWrapper.Initialize

    def paint(self, painter):
        return True


class _ChartBackground(_CustomContextItem):
    """Utility class for chart backgrounds (until native VTK support is available)."""

    def __init__(self, chart):
        super().__init__()
        # Note: This SHOULD be a weakref, as otherwise the garbage collector will not clean up unused charts
        # (because of the cyclic references between charts and their background).
        self._chart = weakref.ref(chart)  # Weak reference to the chart to draw the background for
        # Default background is translucent with black border line
        self.BorderPen = Pen(color=(0, 0, 0))
        self.BackgroundBrush = Brush(color=(0, 0, 0, 0))

    def paint(self, painter):
        if self._chart().visible:
            painter.ApplyPen(self.BorderPen)
            painter.ApplyBrush(self.BackgroundBrush)
            l, b, w, h = self._chart()._geometry
            painter.DrawRect(l, b, w, h)
            # TODO: following 'patch' is necessary until vtkPlotPie is fixed. Otherwise Pie plots will use the same
            #  opacity as the chart's background when their legend is hidden. As the default background is transparent,
            #  this will cause Pie charts to completely disappear.
            painter.GetBrush().SetOpacity(255)
            painter.GetBrush().SetTexture(None)
        return True


class _Chart(DocSubs):
    """Common pythonic interface for vtkChart, vtkChartBox, vtkChartPie and ChartMPL instances."""

    # Subclasses should specify following substitutions: 'chart_name', 'chart_args', 'chart_init' and 'chart_set_labels'.
    _DOC_SUBS: Optional[Dict[str, str]] = None

    def __init__(self, size=(1, 1), loc=(0, 0)):
        super().__init__()
        self._background = _ChartBackground(self)
        self._x_axis = Axis()
        self._y_axis = Axis()
        # _x_axis and _y_axis are not actually used for now (see note in Chart2D),
        # but still present for the Charts.toggle_interaction code
        self._z_axis = Axis()
        if size is not None:
            self.size = size
        if loc is not None:
            self.loc = loc

    @property
    def _scene(self):
        """Get a reference to the vtkScene in which this chart is drawn."""
        return self.GetScene()

    @property
    def _renderer(self):
        """Get a reference to the vtkRenderer in which this chart is drawn."""
        return self._scene.GetRenderer() if self._scene is not None else None

    def _render_event(self, *args, **kwargs):
        """Update the chart right before it will be rendered."""
        self._resize()

    def _resize(self):
        """Resize this chart.

        Resize this chart such that it always occupies the specified
        geometry (matching the specified location and size).

        Returns
        -------
        bool
            ``True`` if the chart was resized, ``False`` otherwise.

        """
        r_w, r_h = self._renderer.GetSize()
        # Alternatively: self.scene.GetViewWidth(), self.scene.GetViewHeight()
        _, _, c_w, c_h = self._geometry
        # Target size is calculated from specified normalized width and height and the renderer's current size
        t_w = self._size[0] * r_w
        t_h = self._size[1] * r_h
        resize = c_w != t_w or c_h != t_h
        if resize:
            # Mismatch between current size and target size, so resize chart:
            self._geometry = (self._loc[0] * r_w, self._loc[1] * r_h, t_w, t_h)
        return resize

    @property
    def _geometry(self):
        """Chart geometry (x and y position of bottom left corner and width and height in pixels)."""
        return tuple(self.GetSize())

    @_geometry.setter
    def _geometry(self, val):
        """Set the chart geometry."""
        self.SetSize(_vtk.vtkRectf(*val))

    def _is_within(self, pos):
        """Check whether the specified position (in pixels) lies within this chart's geometry."""
        l, b, w, h = self._geometry
        return l <= pos[0] <= l + w and b <= pos[1] <= b + h

    @property  # type: ignore
    @doc_subs
    def size(self):
        """Return or set the chart size in normalized coordinates.

        A size of ``(1, 1)`` occupies the whole renderer.

        Examples
        --------
        Create a half-sized {chart_name} centered in the middle of the
        renderer.

        >>> import pyvista
        >>> chart = pyvista.{cls}({chart_args}){chart_init}
        >>> chart.size = (0.5, 0.5)
        >>> chart.loc = (0.25, 0.25)
        >>> chart.show()

        """
        return self._size

    @size.setter
    def size(self, val):
        if not (len(val) == 2 and 0 <= val[0] <= 1 and 0 <= val[1] <= 1):
            raise ValueError(f'Invalid size {val}.')
        self._size = val

    @property  # type: ignore
    @doc_subs
    def loc(self):
        """Return or set the chart position in normalized coordinates.

        This denotes the location of the chart's bottom left corner.

        Examples
        --------
        Create a half-sized {chart_name} centered in the middle of the
        renderer.

        >>> import pyvista
        >>> chart = pyvista.{cls}({chart_args}){chart_init}
        >>> chart.size = (0.5, 0.5)
        >>> chart.loc = (0.25, 0.25)
        >>> chart.show()

        """
        return self._loc

    @loc.setter
    def loc(self, val):
        if not (len(val) == 2 and 0 <= val[0] <= 1 and 0 <= val[1] <= 1):
            raise ValueError(f'Invalid loc {val}.')
        self._loc = val

    @property  # type: ignore
    @doc_subs
    def border_color(self):
        """Return or set the chart's border color.

        Examples
        --------
        Create a {chart_name} with a thick, dashed red border.

        >>> import pyvista
        >>> chart = pyvista.{cls}({chart_args}){chart_init}
        >>> chart.border_color = 'r'
        >>> chart.border_width = 5
        >>> chart.border_style = '--'
        >>> chart.show()

        """
        return self._background.BorderPen.color

    @border_color.setter
    def border_color(self, val):
        self._background.BorderPen.color = val

    @property  # type: ignore
    @doc_subs
    def border_width(self):
        """Return or set the chart's border width.

        Examples
        --------
        Create a {chart_name} with a thick, dashed red border.

        >>> import pyvista
        >>> chart = pyvista.{cls}({chart_args}){chart_init}
        >>> chart.border_color = 'r'
        >>> chart.border_width = 5
        >>> chart.border_style = '--'
        >>> chart.show()

        """
        return self._background.BorderPen.width

    @border_width.setter
    def border_width(self, val):
        self._background.BorderPen.width = val

    @property  # type: ignore
    @doc_subs
    def border_style(self):
        """Return or set the chart's border style.

        Examples
        --------
        Create a {chart_name} with a thick, dashed red border.

        >>> import pyvista
        >>> chart = pyvista.{cls}({chart_args}){chart_init}
        >>> chart.border_color = 'r'
        >>> chart.border_width = 5
        >>> chart.border_style = '--'
        >>> chart.show()

        """
        return self._background.BorderPen.style

    @border_style.setter
    def border_style(self, val):
        self._background.BorderPen.style = val

    @property  # type: ignore
    @doc_subs
    def background_color(self):
        """Return or set the chart's background color.

        Examples
        --------
        Create a {chart_name} with a green background.

        >>> import pyvista
        >>> chart = pyvista.{cls}({chart_args}){chart_init}
        >>> chart.background_color = (0.5, 0.9, 0.5)
        >>> chart.show()

        """
        # return self.GetBackgroundBrush().GetColor()
        return self._background.BackgroundBrush.color

    @background_color.setter
    def background_color(self, val):
        # self.GetBackgroundBrush().SetColor(*Color(val).int_rgba)
        self._background.BackgroundBrush.color = val

    @property  # type: ignore
    @doc_subs
    def background_texture(self):
        """Return or set the chart's background texture.

        Examples
        --------
        Create a {chart_name} with an emoji as its background.

        >>> import pyvista
        >>> from pyvista import examples
        >>> chart = pyvista.{cls}({chart_args}){chart_init}
        >>> chart.background_texture = examples.download_emoji_texture()
        >>> chart.show()

        """
        return self._background.BackgroundBrush.texture

    @background_texture.setter
    def background_texture(self, val):
        self._background.BackgroundBrush.texture = val

    @property  # type: ignore
    @doc_subs
    def visible(self):
        """Return or set the chart's visibility.

        Examples
        --------
        Create a {chart_name}.

        >>> import pyvista
        >>> chart = pyvista.{cls}({chart_args}){chart_init}
        >>> chart.show()

        Hide it.

        >>> chart.visible = False
        >>> chart.show()

        """
        return self.GetVisible()

    @visible.setter
    def visible(self, val):
        self.SetVisible(val)

    @doc_subs
    def toggle(self):
        """Toggle the chart's visibility.

        Examples
        --------
        Create a {chart_name}.

        >>> import pyvista
        >>> chart = pyvista.{cls}({chart_args}){chart_init}
        >>> chart.show()

        Hide it.

        >>> chart.toggle()
        >>> chart.show()

        """
        self.visible = not self.visible

    @property  # type: ignore
    @doc_subs
    def title(self):
        """Return or set the chart's title.

        Examples
        --------
        Create a {chart_name} with title 'My Chart'.

        >>> import pyvista
        >>> chart = pyvista.{cls}({chart_args}){chart_init}
        >>> chart.title = 'My Chart'
        >>> chart.show()

        """
        return self.GetTitle()

    @title.setter
    def title(self, val):
        self.SetTitle(val)

    @property  # type: ignore
    @doc_subs
    def legend_visible(self):
        """Return or set the visibility of the chart's legend.

        Examples
        --------
        Create a {chart_name} with custom labels.

        >>> import pyvista
        >>> chart = pyvista.{cls}({chart_args}){chart_init}
        >>> {chart_set_labels}
        >>> chart.show()

        Hide the legend.

        >>> chart.legend_visible = False
        >>> chart.show()

        """
        return self.GetShowLegend()

    @legend_visible.setter
    def legend_visible(self, val):
        self.SetShowLegend(val)

    @doc_subs
    def show(
        self,
        off_screen=None,
        full_screen=None,
        screenshot=None,
        window_size=None,
        notebook=None,
        background='w',
    ):
        """Show this chart in a self contained plotter.

        Parameters
        ----------
        off_screen : bool
            Plots off screen when ``True``.  Helpful for saving screenshots
            without a window popping up.  Defaults to active theme setting in
            :attr:`pyvista.global_theme.full_screen
            <pyvista.themes.DefaultTheme.full_screen>`.

        full_screen : bool, optional
            Opens window in full screen.  When enabled, ignores
            ``window_size``.  Defaults to active theme setting in
            :attr:`pyvista.global_theme.full_screen
            <pyvista.themes.DefaultTheme.full_screen>`.

        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.

        window_size : list, optional
            Window size in pixels.  Defaults to global theme
            :attr:`pyvista.global_theme.window_size
            <pyvista.themes.DefaultTheme.window_size>`.

        notebook : bool, optional
            When ``True``, the resulting plot is placed inline a
            jupyter notebook.  Assumes a jupyter console is active.

        background : color_like, 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'``.  Defaults to ``'w'``.

        Returns
        -------
        np.ndarray
            Numpy array of the last image when ``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``.

        Examples
        --------
        Create a simple {chart_name} and show it.

        >>> import pyvista
        >>> chart = pyvista.{cls}({chart_args}){chart_init}
        >>> chart.show()

        """
        pl = pyvista.Plotter(window_size=window_size, notebook=notebook, off_screen=off_screen)
        pl.background_color = background
        pl.add_chart(self)
        return pl.show(
            screenshot=screenshot,
            full_screen=full_screen,
        )


class _Plot(DocSubs):
    """Common pythonic interface for vtkPlot and vtkPlot3D instances."""

    # Subclasses should specify following substitutions: 'plot_name', 'chart_init' and 'plot_init'.
    _DOC_SUBS: Optional[Dict[str, str]] = None

    def __init__(self):
        super().__init__()
        self._pen = Pen()
        self._brush = Brush()
        self._label = ""
        if hasattr(self, "SetPen"):
            self.SetPen(self._pen)
        if hasattr(self, "SetBrush"):
            self.SetBrush(self._brush)

    @property  # type: ignore
    @doc_subs
    def color(self):
        """Return or set the plot's color.

        This is the color used by the plot's pen and brush to draw lines and shapes.

        Examples
        --------
        Set the {plot_name}'s color to red.

        >>> import pyvista
        >>> chart = {chart_init}
        >>> plot = {plot_init}
        >>> plot.color = 'r'
        >>> chart.show()

        """
        return self.pen.color

    @color.setter
    def color(self, val):
        self.pen.color = val
        self.brush.color = val

    @property  # type: ignore
    @doc_subs
    def pen(self):
        """Pen object controlling how lines in this plot are drawn.

        Returns
        -------
        Pen
            Pen object controlling how lines in this plot are drawn.

        Examples
        --------
        Increase the line width of the {plot_name}'s pen object.

        >>> import pyvista
        >>> chart = {chart_init}
        >>> plot = {plot_init}
        >>> plot.line_style = '-'  # Make sure all lines are visible
        >>> plot.pen.width = 10
        >>> chart.show()

        """
        return self._pen

    @property  # type: ignore
    @doc_subs
    def brush(self):
        """Brush object controlling how shapes in this plot are filled.

        Returns
        -------
        Brush
            Brush object controlling how shapes in this plot are filled.

        Examples
        --------
        Use a custom texture for the {plot_name}'s brush object.

        >>> import pyvista
        >>> from pyvista import examples
        >>> chart = {chart_init}
        >>> plot = {plot_init}
        >>> plot.brush.texture = examples.download_puppy_texture()
        >>> chart.show()

        """
        return self._brush

    @property  # type: ignore
    @doc_subs
    def line_width(self):
        """Return or set the line width of all lines drawn in this plot.

        This is equivalent to accessing/modifying the width of this plot's pen.

        Examples
        --------
        Set the line width to 10

        >>> import pyvista
        >>> chart = {chart_init}
        >>> plot = {plot_init}
        >>> plot.line_style = '-'  # Make sure all lines are visible
        >>> plot.line_width = 10
        >>> chart.show()

        """
        return self.pen.width

    @line_width.setter
    def line_width(self, val):
        self.pen.width = val

    @property  # type: ignore
    @doc_subs
    def line_style(self):
        """Return or set the line style of all lines drawn in this plot.

        This is equivalent to accessing/modifying the style of this plot's pen.

        Examples
        --------
        Set a custom line style.

        >>> import pyvista
        >>> chart = {chart_init}
        >>> plot = {plot_init}
        >>> plot.line_style = '-.'
        >>> chart.show()

        """
        return self.pen.style

    @line_style.setter
    def line_style(self, val):
        self.pen.style = val

    @property  # type: ignore
    @doc_subs
    def label(self):
        """Return or set the this plot's label, as shown in the chart's legend.

        Examples
        --------
        Create a {plot_name} with custom label.

        >>> import pyvista
        >>> chart = {chart_init}
        >>> plot = {plot_init}
        >>> plot.label = "My awesome plot"
        >>> chart.show()

        """
        return self._label

    @label.setter
    def label(self, val):
        self._label = "" if val is None else val
        self.SetLabel(self._label)

    @property  # type: ignore
    @doc_subs
    def visible(self):
        """Return or set the this plot's visibility.

        Examples
        --------
        Create a {plot_name}.

        >>> import pyvista
        >>> chart = {chart_init}
        >>> plot = {plot_init}
        >>> chart.show()

        Hide it.

        >>> plot.visible = False
        >>> chart.show()

        """
        return self.GetVisible()

    @visible.setter
    def visible(self, val):
        self.SetVisible(val)

    @doc_subs
    def toggle(self):
        """Toggle the plot's visibility.

        Examples
        --------
        Create a {plot_name}.

        >>> import pyvista
        >>> chart = {chart_init}
        >>> plot = {plot_init}
        >>> chart.show()

        Hide it.

        >>> plot.toggle()
        >>> chart.show()

        """
        self.visible = not self.visible


class _MultiCompPlot(_Plot):
    """Common pythonic interface for vtkPlot instances with multiple components.

    Example subclasses are BoxPlot, PiePlot, BarPlot and StackPlot.
    """

    COLOR_SCHEMES = {
        "spectrum": {
            "id": _vtk.vtkColorSeries.SPECTRUM,
            "descr": "black, red, blue, green, purple, orange, brown",
        },
        "warm": {"id": _vtk.vtkColorSeries.WARM, "descr": "dark red → yellow"},
        "cool": {"id": _vtk.vtkColorSeries.COOL, "descr": "green → blue → purple"},
        "blues": {"id": _vtk.vtkColorSeries.BLUES, "descr": "Different shades of blue"},
        "wild_flower": {"id": _vtk.vtkColorSeries.WILD_FLOWER, "descr": "blue → purple → pink"},
        "citrus": {"id": _vtk.vtkColorSeries.CITRUS, "descr": "green → yellow → orange"},
        "div_purple_orange11": {
            "id": _vtk.vtkColorSeries.BREWER_DIVERGING_PURPLE_ORANGE_11,
            "descr": "dark brown → white → dark purple",
        },
        "div_purple_orange10": {
            "id": _vtk.vtkColorSeries.BREWER_DIVERGING_PURPLE_ORANGE_10,
            "descr": "dark brown → white → dark purple",
        },
        "div_purple_orange9": {
            "id": _vtk.vtkColorSeries.BREWER_DIVERGING_PURPLE_ORANGE_9,
            "descr": "brown → white → purple",
        },
        "div_purple_orange8": {
            "id": _vtk.vtkColorSeries.BREWER_DIVERGING_PURPLE_ORANGE_8,
            "descr": "brown → white → purple",
        },
        "div_purple_orange7": {
            "id": _vtk.vtkColorSeries.BREWER_DIVERGING_PURPLE_ORANGE_7,
            "descr": "brown → white → purple",
        },
        "div_purple_orange6": {
            "id": _vtk.vtkColorSeries.BREWER_DIVERGING_PURPLE_ORANGE_6,
            "descr": "brown → white → purple",
        },
        "div_purple_orange5": {
            "id": _vtk.vtkColorSeries.BREWER_DIVERGING_PURPLE_ORANGE_5,
            "descr": "orange → white → purple",
        },
        "div_purple_orange4": {
            "id": _vtk.vtkColorSeries.BREWER_DIVERGING_PURPLE_ORANGE_4,
            "descr": "orange → white → purple",
        },
        "div_purple_orange3": {
            "id": _vtk.vtkColorSeries.BREWER_DIVERGING_PURPLE_ORANGE_3,
            "descr": "orange → white → purple",
        },
        "div_spectral11": {
            "id": _vtk.vtkColorSeries.BREWER_DIVERGING_SPECTRAL_11,
            "descr": "dark red → light yellow → dark blue",
        },
        "div_spectral10": {
            "id": _vtk.vtkColorSeries.BREWER_DIVERGING_SPECTRAL_10,
            "descr": "dark red → light yellow → dark blue",
        },
        "div_spectral9": {
            "id": _vtk.vtkColorSeries.BREWER_DIVERGING_SPECTRAL_9,
            "descr": "red → light yellow → blue",
        },
        "div_spectral8": {
            "id": _vtk.vtkColorSeries.BREWER_DIVERGING_SPECTRAL_8,
            "descr": "red → light yellow → blue",
        },
        "div_spectral7": {
            "id": _vtk.vtkColorSeries.BREWER_DIVERGING_SPECTRAL_7,
            "descr": "red → light yellow → blue",
        },
        "div_spectral6": {
            "id": _vtk.vtkColorSeries.BREWER_DIVERGING_SPECTRAL_6,
            "descr": "red → light yellow → blue",
        },
        "div_spectral5": {
            "id": _vtk.vtkColorSeries.BREWER_DIVERGING_SPECTRAL_5,
            "descr": "red → light yellow → blue",
        },
        "div_spectral4": {
            "id": _vtk.vtkColorSeries.BREWER_DIVERGING_SPECTRAL_4,
            "descr": "red → light yellow → blue",
        },
        "div_spectral3": {
            "id": _vtk.vtkColorSeries.BREWER_DIVERGING_SPECTRAL_3,
            "descr": "orange → light yellow → green",
        },
        "div_brown_blue_green11": {
            "id": _vtk.vtkColorSeries.BREWER_DIVERGING_BROWN_BLUE_GREEN_11,
            "descr": "dark brown → white → dark blue-green",
        },
        "div_brown_blue_green10": {
            "id": _vtk.vtkColorSeries.BREWER_DIVERGING_BROWN_BLUE_GREEN_10,
            "descr": "dark brown → white → dark blue-green",
        },
        "div_brown_blue_green9": {
            "id": _vtk.vtkColorSeries.BREWER_DIVERGING_BROWN_BLUE_GREEN_9,
            "descr": "brown → white → blue-green",
        },
        "div_brown_blue_green8": {
            "id": _vtk.vtkColorSeries.BREWER_DIVERGING_BROWN_BLUE_GREEN_8,
            "descr": "brown → white → blue-green",
        },
        "div_brown_blue_green7": {
            "id": _vtk.vtkColorSeries.BREWER_DIVERGING_BROWN_BLUE_GREEN_7,
            "descr": "brown → white → blue-green",
        },
        "div_brown_blue_green6": {
            "id": _vtk.vtkColorSeries.BREWER_DIVERGING_BROWN_BLUE_GREEN_6,
            "descr": "brown → white → blue-green",
        },
        "div_brown_blue_green5": {
            "id": _vtk.vtkColorSeries.BREWER_DIVERGING_BROWN_BLUE_GREEN_5,
            "descr": "brown → white → blue-green",
        },
        "div_brown_blue_green4": {
            "id": _vtk.vtkColorSeries.BREWER_DIVERGING_BROWN_BLUE_GREEN_4,
            "descr": "brown → white → blue-green",
        },
        "div_brown_blue_green3": {
            "id": _vtk.vtkColorSeries.BREWER_DIVERGING_BROWN_BLUE_GREEN_3,
            "descr": "brown → white → blue-green",
        },
        "seq_blue_green9": {
            "id": _vtk.vtkColorSeries.BREWER_SEQUENTIAL_BLUE_GREEN_9,
            "descr": "light blue → dark green",
        },
        "seq_blue_green8": {
            "id": _vtk.vtkColorSeries.BREWER_SEQUENTIAL_BLUE_GREEN_8,
            "descr": "light blue → dark green",
        },
        "seq_blue_green7": {
            "id": _vtk.vtkColorSeries.BREWER_SEQUENTIAL_BLUE_GREEN_7,
            "descr": "light blue → dark green",
        },
        "seq_blue_green6": {
            "id": _vtk.vtkColorSeries.BREWER_SEQUENTIAL_BLUE_GREEN_6,
            "descr": "light blue → green",
        },
        "seq_blue_green5": {
            "id": _vtk.vtkColorSeries.BREWER_SEQUENTIAL_BLUE_GREEN_5,
            "descr": "light blue → green",
        },
        "seq_blue_green4": {
            "id": _vtk.vtkColorSeries.BREWER_SEQUENTIAL_BLUE_GREEN_4,
            "descr": "light blue → green",
        },
        "seq_blue_green3": {
            "id": _vtk.vtkColorSeries.BREWER_SEQUENTIAL_BLUE_GREEN_3,
            "descr": "light blue → green",
        },
        "seq_yellow_orange_brown9": {
            "id": _vtk.vtkColorSeries.BREWER_SEQUENTIAL_YELLOW_ORANGE_BROWN_9,
            "descr": "light yellow → orange → dark brown",
        },
        "seq_yellow_orange_brown8": {
            "id": _vtk.vtkColorSeries.BREWER_SEQUENTIAL_YELLOW_ORANGE_BROWN_8,
            "descr": "light yellow → orange → brown",
        },
        "seq_yellow_orange_brown7": {
            "id": _vtk.vtkColorSeries.BREWER_SEQUENTIAL_YELLOW_ORANGE_BROWN_7,
            "descr": "light yellow → orange → brown",
        },
        "seq_yellow_orange_brown6": {
            "id": _vtk.vtkColorSeries.BREWER_SEQUENTIAL_YELLOW_ORANGE_BROWN_6,
            "descr": "light yellow → orange → brown",
        },
        "seq_yellow_orange_brown5": {
            "id": _vtk.vtkColorSeries.BREWER_SEQUENTIAL_YELLOW_ORANGE_BROWN_5,
            "descr": "light yellow → orange → brown",
        },
        "seq_yellow_orange_brown4": {
            "id": _vtk.vtkColorSeries.BREWER_SEQUENTIAL_YELLOW_ORANGE_BROWN_4,
            "descr": "light yellow → orange",
        },
        "seq_yellow_orange_brown3": {
            "id": _vtk.vtkColorSeries.BREWER_SEQUENTIAL_YELLOW_ORANGE_BROWN_3,
            "descr": "light yellow → orange",
        },
        "seq_blue_purple9": {
            "id": _vtk.vtkColorSeries.BREWER_SEQUENTIAL_BLUE_PURPLE_9,
            "descr": "light blue → dark purple",
        },
        "seq_blue_purple8": {
            "id": _vtk.vtkColorSeries.BREWER_SEQUENTIAL_BLUE_PURPLE_8,
            "descr": "light blue → purple",
        },
        "seq_blue_purple7": {
            "id": _vtk.vtkColorSeries.BREWER_SEQUENTIAL_BLUE_PURPLE_7,
            "descr": "light blue → purple",
        },
        "seq_blue_purple6": {
            "id": _vtk.vtkColorSeries.BREWER_SEQUENTIAL_BLUE_PURPLE_6,
            "descr": "light blue → purple",
        },
        "seq_blue_purple5": {
            "id": _vtk.vtkColorSeries.BREWER_SEQUENTIAL_BLUE_PURPLE_5,
            "descr": "light blue → purple",
        },
        "seq_blue_purple4": {
            "id": _vtk.vtkColorSeries.BREWER_SEQUENTIAL_BLUE_PURPLE_4,
            "descr": "light blue → purple",
        },
        "seq_blue_purple3": {
            "id": _vtk.vtkColorSeries.BREWER_SEQUENTIAL_BLUE_PURPLE_3,
            "descr": "light blue → purple",
        },
        "qual_accent": {
            "id": _vtk.vtkColorSeries.BREWER_QUALITATIVE_ACCENT,
            "descr": "pastel green, pastel purple, pastel orange, pastel yellow, blue, pink, brown, gray",
        },
        "qual_dark2": {
            "id": _vtk.vtkColorSeries.BREWER_QUALITATIVE_DARK2,
            "descr": "darker shade of qual_set2",
        },
        "qual_set3": {
            "id": _vtk.vtkColorSeries.BREWER_QUALITATIVE_SET3,
            "descr": "pastel colors: blue green, light yellow, dark purple, red, blue, orange, green, pink, gray, purple, light green, yellow",
        },
        "qual_set2": {
            "id": _vtk.vtkColorSeries.BREWER_QUALITATIVE_SET2,
            "descr": "blue green, orange, purple, pink, green, yellow, brown, gray",
        },
        "qual_set1": {
            "id": _vtk.vtkColorSeries.BREWER_QUALITATIVE_SET1,
            "descr": "red, blue, green, purple, orange, yellow, brown, pink, gray",
        },
        "qual_pastel2": {
            "id": _vtk.vtkColorSeries.BREWER_QUALITATIVE_PASTEL2,
            "descr": "pastel shade of qual_set2",
        },
        "qual_pastel1": {
            "id": _vtk.vtkColorSeries.BREWER_QUALITATIVE_PASTEL1,
            "descr": "pastel shade of qual_set1",
        },
        "qual_paired": {
            "id": _vtk.vtkColorSeries.BREWER_QUALITATIVE_PAIRED,
            "descr": "light blue, blue, light green, green, light red, red, light orange, orange, light purple, purple, light yellow",
        },
        "custom": {"id": _vtk.vtkColorSeries.CUSTOM, "descr": None},
    }
    _SCHEME_NAMES = {
        scheme_info["id"]: scheme_name for scheme_name, scheme_info in COLOR_SCHEMES.items()
    }
    DEFAULT_COLOR_SCHEME = "qual_accent"

    # Subclasses should specify following substitutions: 'plot_name', 'chart_init', 'plot_init', 'multichart_init' and 'multiplot_init'.
    _DOC_SUBS: Optional[Dict[str, str]] = None

    def __init__(self):
        super().__init__()
        self._color_series = _vtk.vtkColorSeries()
        self._lookup_table = self._color_series.CreateLookupTable(_vtk.vtkColorSeries.CATEGORICAL)
        self._labels = _vtk.vtkStringArray()
        self.SetLabels(self._labels)
        self.color_scheme = self.DEFAULT_COLOR_SCHEME

    @property  # type: ignore
    @doc_subs
    def color_scheme(self):
        """Return or set the plot's color scheme.

        This scheme defines the colors of the different
        components drawn by this plot.
        See the table below for the available color
        schemes.

        Notes
        -----
        .. _plot_color_schemes:

        Overview of all available color schemes.

        .. include:: ../plot_color_schemes.rst

        Examples
        --------
        Set the {plot_name}'s color scheme to warm.

        >>> import pyvista
        >>> chart = {multichart_init}
        >>> plot = {multiplot_init}
        >>> plot.color_scheme = "warm"
        >>> chart.show()

        """
        return self._SCHEME_NAMES.get(self._color_series.GetColorScheme(), "custom")

    @color_scheme.setter
    def color_scheme(self, val):
        self._color_series.SetColorScheme(
            self.COLOR_SCHEMES.get(val, self.COLOR_SCHEMES["custom"])["id"]
        )
        self._color_series.BuildLookupTable(self._lookup_table, _vtk.vtkColorSeries.CATEGORICAL)
        self.brush.color = self.colors[0]

    @property  # type: ignore
    @doc_subs
    def colors(self):
        """Return or set the plot's colors.

        These are the colors used for the different
        components drawn by this plot.

        Examples
        --------
        Set the {plot_name}'s colors manually.

        >>> import pyvista
        >>> chart = {multichart_init}
        >>> plot = {multiplot_init}
        >>> plot.colors = ["b", "g", "r", "c"]
        >>> chart.show()

        """
        return [
            Color(self._color_series.GetColor(i))
            for i in range(self._color_series.GetNumberOfColors())
        ]

    @colors.setter
    def colors(self, val):
        if val is None:
            self.color_scheme = self.DEFAULT_COLOR_SCHEME
            # Setting color_scheme already sets brush.color
        elif isinstance(val, str):
            self.color_scheme = val
            # Setting color_scheme already sets brush.color
        else:
            try:
                self._color_series.SetNumberOfColors(len(val))
                for i, color in enumerate(val):
                    self._color_series.SetColor(i, Color(color).vtk_c3ub)
                self._color_series.BuildLookupTable(
                    self._lookup_table, _vtk.vtkColorSeries.CATEGORICAL
                )
                self.brush.color = self.colors[0]  # Synchronize "color" and "colors" properties
            except ValueError as e:
                self.color_scheme = self.DEFAULT_COLOR_SCHEME
                raise ValueError(
                    "Invalid colors specified, falling back to default color scheme."
                ) from e

    @property  # type: ignore
    @doc_subs
    def color(self):
        """Return or set the plot's color.

        This is the color used by the plot's brush
        to draw the different components.

        Examples
        --------
        Set the {plot_name}'s color to red.

        >>> import pyvista
        >>> chart = {chart_init}
        >>> plot = {plot_init}
        >>> plot.color = 'r'
        >>> chart.show()

        """
        return self.brush.color

    @color.setter
    def color(self, val):
        # Override default _Plot behaviour. This makes sure the plot's "color_scheme", "colors" and "color" properties
        # (and their internal representations through color series, lookup tables and brushes) stay synchronized.
        self.colors = [val]

    @property  # type: ignore
    @doc_subs
    def labels(self):
        """Return or set the this plot's labels, as shown in the chart's legend.

        Examples
        --------
        Create a {plot_name}.

        >>> import pyvista
        >>> chart = {multichart_init}
        >>> plot = {multiplot_init}
        >>> chart.show()

        Modify the labels.

        >>> plot.labels = ["A", "B", "C", "D"]
        >>> chart.show()

        """
        return [self._labels.GetValue(i) for i in range(self._labels.GetNumberOfValues())]

    @labels.setter
    def labels(self, val):
        self._labels.Reset()
        if isinstance(val, str):
            val = [val]
        try:
            if val is not None:
                for label in val:
                    self._labels.InsertNextValue(label)
        except TypeError:
            raise ValueError("Invalid labels specified.")

    @property  # type: ignore
    @doc_subs
    def label(self):
        """Return or set the this plot's label, as shown in the chart's legend.

        Examples
        --------
        Create a {plot_name} with custom label.

        >>> import pyvista
        >>> import numpy as np
        >>> chart = {chart_init}
        >>> plot = {plot_init}
        >>> chart.show()

        Modify the label.

        >>> plot.label = "My awesome plot"
        >>> chart.show()

        """
        return self.labels[0] if self._labels.GetNumberOfValues() > 0 else ""

    @label.setter
    def label(self, val):
        # Override default _Plot behaviour. This makes sure the plot's "labels" and "label" properties (and their
        # internal representations) stay synchronized.
        self.labels = None if val is None else [val]


class LinePlot2D(_vtk.vtkPlotLine, _Plot):
    """Class representing a 2D line plot.

    Users should typically not directly create new plot instances, but use the dedicated 2D chart's plotting methods.

    Parameters
    ----------
    x : array_like
        X coordinates of the points through which a line should be drawn.

    y : array_like
        Y coordinates of the points through which a line should be drawn.

    color : color_like, optional
        Color of the line drawn in this plot. Any color parsable by :class:`pyvista.Color` is allowed. Defaults
        to ``"b"``.

    width : float, optional
        Width of the line drawn in this plot. Defaults to ``1``.

    style : str, optional
        Style of the line drawn in this plot. See :ref:`Pen.LINE_STYLES <pen_line_styles>` for a list of allowed line
        styles. Defaults to ``"-"``.

    label : str, optional
        Label of this plot, as shown in the chart's legend. Defaults to ``""``.

    Examples
    --------
    Create a 2D chart plotting an approximate satellite
    trajectory.

    >>> import pyvista
    >>> from pyvista import examples
    >>> import numpy as np
    >>> chart = pyvista.Chart2D()
    >>> x = np.linspace(0, 1, 100)
    >>> y = np.sin(6.5*x-1)
    >>> _ = chart.line(x, y, "y", 4)
    >>> chart.background_texture = examples.load_globe_texture()
    >>> chart.hide_axes()
    >>> chart.show()

    """

    _DOC_SUBS = {
        "plot_name": "2D line plot",
        "chart_init": "pyvista.Chart2D()",
        "plot_init": "chart.line([0, 1, 2], [2, 1, 3])",
    }

    def __init__(self, x, y, color="b", width=1.0, style="-", label=""):
        """Initialize a new 2D line plot instance."""
        super().__init__()
        self._table = pyvista.Table({"x": np.empty(0, np.float32), "y": np.empty(0, np.float32)})
        self.SetInputData(self._table, "x", "y")
        self.update(x, y)
        self.color = color
        self.line_width = width
        self.line_style = style
        self.label = label

    @property
    def x(self):
        """Retrieve the X coordinates of the points through which a line is drawn.

        Examples
        --------
        Create a line plot and display the x coordinates.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> plot = chart.line([0, 1, 2], [2, 1, 3])
        >>> plot.x
        pyvista_ndarray([0, 1, 2])
        >>> chart.show()

        """
        return self._table["x"]

    @property
    def y(self):
        """Retrieve the Y coordinates of the points through which a line is drawn.

        Examples
        --------
        Create a line plot and display the y coordinates.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> plot = chart.line([0, 1, 2], [2, 1, 3])
        >>> plot.y
        pyvista_ndarray([2, 1, 3])
        >>> chart.show()

        """
        return self._table["y"]

    def update(self, x, y):
        """Update this plot's points, through which a line is drawn.

        Parameters
        ----------
        x : array_like
            The new x coordinates of the points through which a line should be drawn.

        y : array_like
            The new y coordinates of the points through which a line should be drawn.

        Examples
        --------
        Create a line plot.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> plot = chart.line([0, 1, 2], [2, 1, 3])
        >>> chart.show()

        Update the line's y coordinates.

        >>> plot.update([0, 1, 2], [3, 1, 2])
        >>> chart.show()

        """
        if len(x) > 1:
            self._table.update({"x": np.array(x, copy=False), "y": np.array(y, copy=False)})
            self.visible = True
        else:
            # Turn off visibility for fewer than 2 points as otherwise an error message is shown
            self.visible = False


class ScatterPlot2D(_vtk.vtkPlotPoints, _Plot):
    """Class representing a 2D scatter plot.

    Users should typically not directly create new plot instances, but use the dedicated 2D chart's plotting methods.

    Parameters
    ----------
    x : array_like
        X coordinates of the points to draw.

    y : array_like
        Y coordinates of the points to draw.

    color : color_like, optional
        Color of the points drawn in this plot. Any color parsable by :class:`pyvista.Color` is allowed. Defaults
        to ``"b"``.

    size : float, optional
        Size of the point markers drawn in this plot. Defaults to ``10``.

    style : str, optional
        Style of the point markers drawn in this plot. See :ref:`ScatterPlot2D.MARKER_STYLES <scatter_marker_styles>`
        for a list of allowed marker styles. Defaults to ``"o"``.

    label : str, optional
        Label of this plot, as shown in the chart's legend. Defaults to ``""``.

    Notes
    -----
    .. _scatter_marker_styles:

    MARKER_STYLES : dict
        Dictionary containing all allowed marker styles as its keys.

        .. include:: ../scatter_marker_styles.rst

    Examples
    --------
    Plot a simple sine wave as a scatter plot.

    >>> import pyvista
    >>> import numpy as np
    >>> x = np.linspace(0, 2*np.pi, 20)
    >>> y = np.sin(x)
    >>> chart = pyvista.Chart2D()
    >>> _ = chart.scatter(x, y)
    >>> chart.show()

    """

    MARKER_STYLES = {  # descr is used in the documentation, set to None to hide it from the docs.
        "": {"id": _vtk.vtkPlotPoints.NONE, "descr": "Hidden"},
        "x": {"id": _vtk.vtkPlotPoints.CROSS, "descr": "Cross"},
        "+": {"id": _vtk.vtkPlotPoints.PLUS, "descr": "Plus"},
        "s": {"id": _vtk.vtkPlotPoints.SQUARE, "descr": "Square"},
        "o": {"id": _vtk.vtkPlotPoints.CIRCLE, "descr": "Circle"},
        "d": {"id": _vtk.vtkPlotPoints.DIAMOND, "descr": "Diamond"},
    }
    _DOC_SUBS = {
        "plot_name": "2D scatter plot",
        "chart_init": "pyvista.Chart2D()",
        "plot_init": "chart.scatter([0, 1, 2, 3, 4], [2, 1, 3, 4, 2])",
    }

    def __init__(self, x, y, color="b", size=10, style="o", label=""):
        """Initialize a new 2D scatter plot instance."""
        super().__init__()
        self._table = pyvista.Table({"x": np.empty(0, np.float32), "y": np.empty(0, np.float32)})
        self.SetInputData(self._table, "x", "y")
        self.update(x, y)
        self.color = color
        self.marker_size = size
        self.marker_style = style
        self.label = label

    @property
    def x(self):
        """Retrieve the X coordinates of this plot's points.

        Examples
        --------
        Create a scatter plot and display the x coordinates.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> plot = chart.scatter([0, 1, 2, 3, 4], [2, 1, 3, 4, 2])
        >>> plot.x
        pyvista_ndarray([0, 1, 2, 3, 4])
        >>> chart.show()

        """
        return self._table["x"]

    @property
    def y(self):
        """Retrieve the Y coordinates of this plot's points.

        Examples
        --------
        Create a scatter plot and display the y coordinates.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> plot = chart.scatter([0, 1, 2, 3, 4], [2, 1, 3, 4, 2])
        >>> plot.y
        pyvista_ndarray([2, 1, 3, 4, 2])
        >>> chart.show()

        """
        return self._table["y"]

    def update(self, x, y):
        """Update this plot's points.

        Parameters
        ----------
        x : array_like
            The new x coordinates of the points to draw.

        y : array_like
            The new y coordinates of the points to draw.

        Examples
        --------
        Create a scatter plot.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> plot = chart.scatter([0, 1, 2, 3, 4], [2, 1, 3, 4, 2])
        >>> chart.show()

        Update the marker locations.

        >>> plot.update([0, 1, 2, 3, 4], [3, 2, 4, 2, 1])
        >>> chart.show()

        """
        if len(x) > 0:
            self._table.update({"x": np.array(x, copy=False), "y": np.array(y, copy=False)})
            self.visible = True
        else:
            self.visible = False

    @property
    def marker_size(self):
        """Return or set the plot's marker size.

        Examples
        --------
        Create a 2D scatter plot.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> plot = chart.scatter([0, 1, 2, 3, 4], [2, 1, 3, 4, 2])
        >>> chart.show()

        Increase the marker size.

        >>> plot.marker_size = 30
        >>> chart.show()

        """
        return self.GetMarkerSize()

    @marker_size.setter
    def marker_size(self, val):
        self.SetMarkerSize(val)

    @property
    def marker_style(self):
        """Return or set the plot's marker style.

        Examples
        --------
        Create a 2D scatter plot.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> plot = chart.scatter([0, 1, 2, 3, 4], [2, 1, 3, 4, 2])
        >>> chart.show()

        Change the marker style.

        >>> plot.marker_style = "d"
        >>> chart.show()

        """
        return self._marker_style

    @marker_style.setter
    def marker_style(self, val):
        if val is None:
            val = ""
        try:
            self.SetMarkerStyle(self.MARKER_STYLES[val]["id"])
            self._marker_style = val
        except KeyError:
            formatted_styles = "\", \"".join(self.MARKER_STYLES.keys())
            raise ValueError(f"Invalid marker style. Allowed marker styles: \"{formatted_styles}\"")


class AreaPlot(_vtk.vtkPlotArea, _Plot):
    """Class representing a 2D area plot.

    Users should typically not directly create new plot instances, but use the dedicated 2D chart's plotting methods.

    Parameters
    ----------
    x : array_like
        X coordinates of the points outlining the area to draw.

    y1 : array_like
        Y coordinates of the points on the first outline of the area to draw.

    y2 : array_like, optional
        Y coordinates of the points on the second outline of the area to draw. Defaults to a sequence of zeros.

    color : color_like, optional
        Color of the area drawn in this plot. Any color parsable by :class:`pyvista.Color` is allowed. Defaults
        to ``"b"``.

    label : str, optional
        Label of this plot, as shown in the chart's legend. Defaults to ``""``.

    Examples
    --------
    Create an area plot showing the minimum and maximum precipitation observed in each month.

    >>> import pyvista
    >>> import numpy as np
    >>> x = np.arange(12)
    >>> p_min = [11, 0, 16, 2, 23, 18, 25, 17, 9, 12, 14, 21]
    >>> p_max = [87, 64, 92, 73, 91, 94, 107, 101, 84, 88, 95, 103]
    >>> chart = pyvista.Chart2D()
    >>> _ = chart.area(x, p_min, p_max)
    >>> chart.x_axis.tick_locations = x
    >>> chart.x_axis.tick_labels = ["Jan", "Feb", "Mar", "Apr", "May",
    ...                             "Jun", "Jul", "Aug", "Sep", "Oct",
    ...                             "Nov", "Dec"]
    >>> chart.x_axis.label = "Month"
    >>> chart.y_axis.label = "Precipitation [mm]"
    >>> chart.show()

    """

    _DOC_SUBS = {
        "plot_name": "area plot",
        "chart_init": "pyvista.Chart2D()",
        "plot_init": "chart.area([0, 1, 2], [0, 0, 1], [1, 3, 2])",
    }

    def __init__(self, x, y1, y2=None, color="b", label=""):
        """Initialize a new 2D area plot instance."""
        super().__init__()
        self._table = pyvista.Table(
            {
                "x": np.empty(0, np.float32),
                "y1": np.empty(0, np.float32),
                "y2": np.empty(0, np.float32),
            }
        )
        self.SetInputData(self._table)
        self.SetInputArray(0, "x")
        self.SetInputArray(1, "y1")
        self.SetInputArray(2, "y2")
        self.update(x, y1, y2)
        self.color = color
        self.label = label

    @property
    def x(self):
        """Retrieve the X coordinates of the points outlining the drawn area.

        Examples
        --------
        Create an area plot and display the x coordinates.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> plot = chart.area([0, 1, 2], [2, 1, 3], [1, 0, 1])
        >>> plot.x
        pyvista_ndarray([0, 1, 2])
        >>> chart.show()

        """
        return self._table["x"]

    @property
    def y1(self):
        """Retrieve the Y coordinates of the points on the first outline of the drawn area.

        Examples
        --------
        Create an area plot and display the y1 coordinates.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> plot = chart.area([0, 1, 2], [2, 1, 3], [1, 0, 1])
        >>> plot.y1
        pyvista_ndarray([2, 1, 3])
        >>> chart.show()

        """
        return self._table["y1"]

    @property
    def y2(self):
        """Retrieve the Y coordinates of the points on the second outline of the drawn area.

        Examples
        --------
        Create an area plot and display the y2 coordinates.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> plot = chart.area([0, 1, 2], [2, 1, 3], [1, 0, 1])
        >>> plot.y2
        pyvista_ndarray([1, 0, 1])
        >>> chart.show()

        """
        return self._table["y2"]

    def update(self, x, y1, y2=None):
        """Update this plot's points, outlining the area to draw.

        Parameters
        ----------
        x : array_like
            The new x coordinates of the points outlining the area.

        y1 : array_like
            The new y coordinates of the points on the first outline of the area.

        y2 : array_like, optional
            The new y coordinates of the points on the second outline of the area. Defaults to a sequence of zeros.

        Examples
        --------
        Create an area plot.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> plot = chart.area([0, 1, 2], [2, 1, 3])
        >>> chart.show()

        Update the points on the second outline of the area.

        >>> plot.update([0, 1, 2], [2, 1, 3], [1, 0, 1])
        >>> chart.show()

        """
        if len(x) > 0:
            if y2 is None:
                y2 = np.zeros_like(x)
            self._table.update(
                {
                    "x": np.array(x, copy=False),
                    "y1": np.array(y1, copy=False),
                    "y2": np.array(y2, copy=False),
                }
            )
            self.visible = True
        else:
            self.visible = False


class BarPlot(_vtk.vtkPlotBar, _MultiCompPlot):
    """Class representing a 2D bar plot.

    Users should typically not directly create new plot instances, but use the dedicated 2D chart's plotting methods.

    Parameters
    ----------
    x : array_like
        Positions (along the x-axis for a vertical orientation, along the y-axis for
        a horizontal orientation) of the bars to draw.

    y : array_like
        Size of the bars to draw. Multiple bars can be stacked by passing a sequence of sequences.

    color : color_like, optional
        Color of the bars drawn in this plot. Any color parsable by :class:`pyvista.Color` is allowed. Defaults
        to ``"b"``.

    orientation : str, optional
        Orientation of the bars drawn in this plot. Either ``"H"`` for an horizontal orientation or ``"V"`` for a
        vertical orientation. Defaults to ``"V"``.

    label : str, optional
        Label of this plot, as shown in the chart's legend. Defaults to ``""``.

    Examples
    --------
    Create a stacked bar chart showing the average time spent on activities
    throughout the week.

    >>> import pyvista
    >>> import numpy as np
    >>> x = np.arange(1, 8)
    >>> y_s = [7, 8, 7.5, 8, 7.5, 9, 10]
    >>> y_h = [2, 3, 2, 2.5, 1.5, 4, 6.5]
    >>> y_w = [8, 8, 7, 8, 7, 0, 0]
    >>> y_r = [5, 2.5, 4.5, 3.5, 6, 9, 6.5]
    >>> y_t = [2, 2.5, 3, 2, 2, 2, 1]
    >>> labels = ["Sleep", "Household", "Work", "Relax", "Transport"]
    >>> chart = pyvista.Chart2D()
    >>> _ = chart.bar(x, [y_s, y_h, y_w, y_r, y_t], label=labels)
    >>> chart.x_axis.tick_locations = x
    >>> chart.x_axis.tick_labels = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
    >>> chart.x_label = "Day of week"
    >>> chart.y_label = "Average time spent"
    >>> chart.grid = False  # Disable the grid lines
    >>> chart.show()

    """

    ORIENTATIONS = {"H": _vtk.vtkPlotBar.HORIZONTAL, "V": _vtk.vtkPlotBar.VERTICAL}
    _DOC_SUBS = {
        "plot_name": "bar plot",
        "chart_init": "pyvista.Chart2D()",
        "plot_init": "chart.bar([1, 2, 3], [2, 1, 3])",
        "multichart_init": "pyvista.Chart2D()",
        "multiplot_init": "chart.bar([1, 2, 3], [[2, 1, 3], [1, 0, 2], [0, 3, 1], [3, 2, 0]])",
    }

    def __init__(self, x, y, color=None, orientation="V", label=None):
        """Initialize a new 2D bar plot instance."""
        super().__init__()
        if not isinstance(y[0], (Sequence, np.ndarray)):
            y = (y,)
        y_data = {f"y{i}": np.empty(0, np.float32) for i in range(len(y))}
        self._table = pyvista.Table({"x": np.empty(0, np.float32), **y_data})
        self.SetInputData(self._table, "x", "y0")
        for i in range(1, len(y)):
            self.SetInputArray(i + 1, f"y{i}")
        self.update(x, y)

        if len(y) > 1:
            self.SetColorSeries(self._color_series)
            self.colors = color  # None will use default scheme
            self.labels = label
        else:
            # Use blue bars by default in single component mode
            self.color = "b" if color is None else color
            self.label = label
        self.orientation = orientation

    @property
    def x(self):
        """Retrieve the positions of the drawn bars.

        Examples
        --------
        Create a bar plot and display the positions.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> plot = chart.bar([1, 2, 3], [[2, 1, 3], [1, 2, 0]])
        >>> plot.x
        pyvista_ndarray([1, 2, 3])
        >>> chart.show()

        """
        return self._table["x"]

    @property
    def y(self):
        """Retrieve the sizes of the drawn bars.

        Examples
        --------
        Create a bar plot and display the sizes.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> plot = chart.bar([1, 2, 3], [[2, 1, 3], [1, 2, 0]])
        >>> plot.y
        (pyvista_ndarray([2, 1, 3]), pyvista_ndarray([1, 2, 0]))
        >>> chart.show()

        """
        return tuple(self._table[f"y{i}"] for i in range(self._table.n_arrays - 1))

    def update(self, x, y):
        """Update the positions and/or size of the bars in this plot.

        Parameters
        ----------
        x : array_like
            The new positions of the bars to draw.

        y : array_like
            The new sizes of the bars to draw.

        Examples
        --------
        Create a bar plot.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> plot = chart.bar([1, 2, 3], [2, 1, 3])
        >>> chart.show()

        Update the bar sizes.

        >>> plot.update([1, 2, 3], [3, 1, 2])
        >>> chart.show()

        """
        if len(x) > 0:
            if not isinstance(y[0], (Sequence, np.ndarray)):
                y = (y,)
            y_data = {f"y{i}": np.array(y[i], copy=False) for i in range(len(y))}
            self._table.update({"x": np.array(x, copy=False), **y_data})
            self.visible = True
        else:
            self.visible = False

    @property
    def orientation(self):
        """Return or set the orientation of the bars in this plot.

        Examples
        --------
        Create a bar plot.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> plot = chart.bar([1, 2, 3], [[2, 1, 3], [1, 3, 2]])
        >>> chart.show()

        Change the orientation to horizontal.

        >>> plot.orientation = "H"
        >>> chart.show()

        """
        return self._orientation

    @orientation.setter
    def orientation(self, val):
        try:
            self.SetOrientation(self.ORIENTATIONS[val])
            self._orientation = val
        except KeyError:
            formatted_orientations = "\", \"".join(self.ORIENTATIONS.keys())
            raise ValueError(
                f"Invalid orientation. Allowed orientations: \"{formatted_orientations}\""
            )


class StackPlot(_vtk.vtkPlotStacked, _MultiCompPlot):
    """Class representing a 2D stack plot.

    Users should typically not directly create new plot instances, but use the dedicated 2D chart's plotting methods.

    Parameters
    ----------
    x : array_like
        X coordinates of the points outlining the stacks (areas) to draw.

    ys : list or tuple of array_like
        Size of the stacks (areas) to draw at the corresponding X
        coordinates. Each sequence defines the sizes of one stack
        (area), which are stacked on top of each other.

    colors : list or tuple of color_like, optional
        Color of the stacks (areas) drawn in this plot. Any color
        parsable by :class:`pyvista.Color` is allowed.  Defaults to
        ``None``.

    labels : list or tuple of str, optional
        Label for each stack (area) drawn in this plot, as shown in
        the chart's legend. Defaults to ``[]``.

    Examples
    --------
    Create a stack plot showing the amount of vehicles sold per type.

    >>> import pyvista
    >>> import numpy as np
    >>> year = [f"{y}" for y in np.arange(2011, 2021)]
    >>> x = np.arange(len(year))
    >>> n_e = [1739, 4925, 9515, 21727, 31452, 29926, 40648,
    ...        57761, 76370, 93702]
    >>> n_h = [5563, 7642, 11937, 13905, 22807, 46700, 60875,
    ...        53689, 46650, 50321]
    >>> n_f = [166556, 157249, 151552, 138183, 129669,
    ...        113985, 92965, 73683, 57097, 29499]
    >>> chart = pyvista.Chart2D()
    >>> plot = chart.stack(x, [n_e, n_h, n_f])
    >>> plot.labels = ["Electric", "Hybrid", "Fossil"]
    >>> chart.x_axis.label = "Year"
    >>> chart.x_axis.tick_locations = x
    >>> chart.x_axis.tick_labels = year
    >>> chart.y_axis.label = "New car sales"
    >>> chart.show()

    """

    _DOC_SUBS = {
        "plot_name": "stack plot",
        "chart_init": "pyvista.Chart2D()",
        "plot_init": "chart.stack([0, 1, 2], [2, 1, 3])",
        "multichart_init": "pyvista.Chart2D()",
        "multiplot_init": "chart.stack([0, 1, 2], [[2, 1, 3], [1, 0, 2], [0, 3, 1], [3, 2, 0]])",
    }

    def __init__(self, x, ys, colors=None, labels=None):
        """Initialize a new 2D stack plot instance."""
        super().__init__()
        if not isinstance(ys[0], (Sequence, np.ndarray)):
            ys = (ys,)
        y_data = {f"y{i}": np.empty(0, np.float32) for i in range(len(ys))}
        self._table = pyvista.Table({"x": np.empty(0, np.float32), **y_data})
        self.SetInputData(self._table, "x", "y0")
        for i in range(1, len(ys)):
            self.SetInputArray(i + 1, f"y{i}")
        self.update(x, ys)

        if len(ys) > 1:
            self.SetColorSeries(self._color_series)
            self.colors = colors  # None will use default scheme
            self.labels = labels
        else:
            self.color = "b" if colors is None else colors
            self.label = labels
        self.pen.style = None  # Hide lines by default

    @property
    def x(self):
        """Retrieve the X coordinates of the drawn stacks.

        Examples
        --------
        Create a stack plot and display the x coordinates.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> plot = chart.stack([0, 1, 2], [[2, 1, 3], [1, 2, 0]])
        >>> plot.x
        pyvista_ndarray([0, 1, 2])
        >>> chart.show()

        """
        return self._table["x"]

    @property
    def ys(self):
        """Retrieve the sizes of the drawn stacks.

        Examples
        --------
        Create a stack plot and display the sizes.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> plot = chart.stack([0, 1, 2], [[2, 1, 3], [1, 2, 0]])
        >>> plot.ys
        (pyvista_ndarray([2, 1, 3]), pyvista_ndarray([1, 2, 0]))
        >>> chart.show()

        """
        return tuple(self._table[f"y{i}"] for i in range(self._table.n_arrays - 1))

    def update(self, x, ys):
        """Update the locations and/or size of the stacks (areas) in this plot.

        Parameters
        ----------
        x : array_like
            The new x coordinates of the stacks (areas) to draw.

        ys : list or tuple of array_like
            The new sizes of the stacks (areas) to draw.

        Examples
        --------
        Create a stack plot.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> plot = chart.stack([0, 1, 2], [[2, 1, 3],[1, 2, 1]])
        >>> chart.show()

        Update the stack sizes.

        >>> plot.update([0, 1, 2], [[3, 1, 2], [0, 3, 1]])
        >>> chart.show()

        """
        if len(x) > 0:
            if not isinstance(ys[0], (Sequence, np.ndarray)):
                ys = (ys,)
            y_data = {f"y{i}": np.array(ys[i], copy=False) for i in range(len(ys))}
            self._table.update({"x": np.array(x, copy=False), **y_data})
            self.visible = True
        else:
            self.visible = False


class Chart2D(_vtk.vtkChartXY, _Chart):
    """2D chart class similar to a ``matplotlib`` figure.

    Parameters
    ----------
    size : list or tuple, optional
        Size of the chart in normalized coordinates. A size of ``(0,
        0)`` is invisible, a size of ``(1, 1)`` occupies the whole
        renderer's width and height.

    loc : list or tuple, optional
        Location of the chart (its bottom left corner) in normalized
        coordinates. A location of ``(0, 0)`` corresponds to the
        renderer's bottom left corner, a location of ``(1, 1)``
        corresponds to the renderer's top right corner.

    x_label : str, optional
        Label along the x-axis.  Defaults to ``'x'``.

    y_label : str, optional
        Label along the y-axis.  Defaults to ``'y'``.

    grid : bool, optional
        Show the background grid in the plot.  Default ``True``.

    Examples
    --------
    Plot a simple sine wave as a scatter and line plot.

    >>> import pyvista
    >>> import numpy as np
    >>> x = np.linspace(0, 2*np.pi, 20)
    >>> y = np.sin(x)
    >>> chart = pyvista.Chart2D()
    >>> _ = chart.scatter(x, y)
    >>> _ = chart.line(x, y, 'r')
    >>> chart.show()

    Combine multiple types of plots in the same chart.

    >>> rng = np.random.default_rng(1)
    >>> x = np.arange(1, 8)
    >>> y = rng.integers(5, 15, 7)
    >>> e = np.abs(rng.normal(scale=2, size=7))
    >>> z = rng.integers(0, 5, 7)
    >>> chart = pyvista.Chart2D()
    >>> _ = chart.area(x, y-e, y+e, color=(0.12, 0.46, 0.71, 0.2))
    >>> _ = chart.line(x, y, color="tab:blue", style="--", label="Scores")
    >>> _ = chart.scatter(x, y, color="tab:blue", style="d")
    >>> _ = chart.bar(x, z, color="tab:orange", label="Violations")
    >>> chart.x_axis.tick_locations = x
    >>> chart.x_axis.tick_labels = ["Mon", "Tue", "Wed", "Thu", "Fri",
    ...                             "Sat", "Sun"]
    >>> chart.x_label = "Day of week"
    >>> chart.show()

    """

    PLOT_TYPES = {
        "scatter": ScatterPlot2D,
        "line": LinePlot2D,
        "area": AreaPlot,
        "bar": BarPlot,
        "stack": StackPlot,
    }
    _PLOT_CLASSES = {plot_class: plot_type for (plot_type, plot_class) in PLOT_TYPES.items()}
    _DOC_SUBS = {
        "chart_name": "2D chart",
        "chart_args": "",
        "chart_init": """
        >>> plot = chart.line([0, 1, 2], [2, 1, 3])""",
        "chart_set_labels": 'plot.label = "My awesome plot"',
    }

    def __init__(self, size=(1, 1), loc=(0, 0), x_label="x", y_label="y", grid=True):
        """Initialize the chart."""
        super().__init__(size, loc)
        self._plots = {plot_type: [] for plot_type in self.PLOT_TYPES.keys()}
        self.SetAutoSize(False)  # We manually set the appropriate size
        # self.SetAxis(_vtk.vtkAxis.BOTTOM, self._x_axis)  # Disabled for now and replaced by a wrapper object, as for
        # self.SetAxis(_vtk.vtkAxis.LEFT, self._y_axis)  # some reason vtkChartXY.SetAxis(...) causes a crash at the end
        # TODO: fix for above issue, once the VTK PR (!8618) is merged:
        #  self.Register(self._x_axis)
        #  self.Register(self._y_axis)
        self._x_axis = Axis(
            _wrap=self.GetAxis(_vtk.vtkAxis.BOTTOM)
        )  # of the script's execution (nonzero exit code)
        self._y_axis = Axis(_wrap=self.GetAxis(_vtk.vtkAxis.LEFT))
        self.x_label = x_label
        self.y_label = y_label
        self.grid = grid
        self.legend_visible = True

    def _render_event(self, *args, **kwargs):
        self.RecalculateBounds()
        super()._render_event(*args, **kwargs)

    def _add_plot(self, plot_type, *args, **kwargs):
        """Add a plot of the given type to this chart."""
        plot = self.PLOT_TYPES[plot_type](*args, **kwargs)
        self.AddPlot(plot)
        self._plots[plot_type].append(plot)
        return plot

    @classmethod
    def _parse_format(cls, fmt):
        """Parse a format string and separate it into a marker style, line style and color.

        Parameters
        ----------
        fmt : str
            Format string to parse. A format string consists of any
            combination of a valid marker style, a valid line style
            and parsable color. The specific order does not
            matter. See :attr:`pyvista.ScatterPlot2D.MARKER_STYLES`
            for a list of valid marker styles,
            :attr:`pyvista.Pen.LINE_STYLES` for a list of valid line
            styles and :class:`pyvista.Color` for an overview of
            parsable colors.

        Returns
        -------
        marker_style : str
            Extracted marker style (empty string if no marker style
            was present in the format string).

        line_style : str
            Extracted line style (empty string if no line style was
            present in the format string).

        color : str
            Extracted color string (defaults to ``"b"`` if no color
            was present in the format string).

        Examples
        --------
        >>> import pyvista
        >>> m, l, c = pyvista.Chart2D._parse_format("x--b")

        """
        marker_style = ""
        line_style = ""
        color = None
        # Note: All colors, marker styles and line styles are sorted in decreasing order of length to be able to find
        # the largest match first (e.g. find 'darkred' and '--' first instead of 'red' and '-')
        colors = sorted(
            itertools.chain(hexcolors.keys(), color_synonyms.keys()),
            key=len,
            reverse=True,
        )
        marker_styles = sorted(ScatterPlot2D.MARKER_STYLES.keys(), key=len, reverse=True)
        line_styles = sorted(Pen.LINE_STYLES.keys(), key=len, reverse=True)
        hex_pattern = "(#|0x)[A-Fa-f0-9]{6}([A-Fa-f0-9]{2})?"  # Match RGB(A) hex string
        # Extract color from format string
        match = re.search(hex_pattern, fmt)  # Start with matching hex strings
        if match is not None:
            color = match.group()
        else:  # Proceed with matching color strings
            for c in colors:
                if c in fmt:
                    color = c
                    break
        if color is not None:
            fmt = fmt.replace(color, "", 1)  # Remove found color from format string
        else:
            color = "b"
        # Extract marker style from format string
        for style in marker_styles[:-1]:  # Last style is empty string
            if style in fmt:
                marker_style = style
                fmt = fmt.replace(
                    marker_style, "", 1
                )  # Remove found marker_style from format string
                break
        # Extract line style from format string
        for style in line_styles[:-1]:  # Last style is empty string
            if style in fmt:
                line_style = style
                fmt = fmt.replace(line_style, "", 1)  # Remove found line_style from format string
                break
        return marker_style, line_style, color

    def plot(self, x, y=None, fmt='-'):
        """Matplotlib like plot method.

        Parameters
        ----------
        x : array_like
            Values to plot on the X-axis. In case ``y`` is ``None``,
            these are the values to plot on the Y-axis instead.

        y : array_like, optional
            Values to plot on the Y-axis.

        fmt : str, optional
            A format string, e.g. ``'ro'`` for red circles. See the Notes
            section for a full description of the format strings.

        Returns
        -------
        scatter_plot : plotting.charts.ScatterPlot2D, optional
            The created scatter plot when a valid marker style
            was present in the format string, ``None`` otherwise.

        line_plot : plotting.charts.LinePlot2D, optional
            The created line plot when a valid line style was
            present in the format string, ``None`` otherwise.

        Notes
        -----
        This plot method shares many of the same plotting features as
        the `matplotlib.pyplot.plot
        <https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.plot.html>`_.
        Please reference the documentation there for a full
        description of the allowable format strings.

        Examples
        --------
        Generate a line plot.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> _, line_plot = chart.plot(range(10), range(10))
        >>> chart.show()

        Generate a line and scatter plot.

        >>> chart = pyvista.Chart2D()
        >>> scatter_plot, line_plot = chart.plot(range(10), fmt='o-')
        >>> chart.show()

        """
        if y is None:
            y = x
            x = np.arange(len(y))
        elif isinstance(y, str):
            fmt = y
            y = x
            x = np.arange(len(y))
        marker_style, line_style, color = self._parse_format(fmt)
        scatter_plot, line_plot = None, None
        if marker_style != "":
            scatter_plot = self.scatter(x, y, color, style=marker_style)
        if line_style != "":
            line_plot = self.line(x, y, color, style=line_style)
        return scatter_plot, line_plot

    def scatter(self, x, y, color="b", size=10, style="o", label=""):
        """Add a scatter plot to this chart.

        Parameters
        ----------
        x : array_like
            X coordinates of the points to draw.

        y : array_like
            Y coordinates of the points to draw.

        color : color_like, optional
            Color of the points drawn in this plot. Any color parsable
            by :class:`pyvista.Color` is allowed. Defaults to
            ``"b"``.

        size : float, optional
            Size of the point markers drawn in this plot. Defaults to ``10``.

        style : str, optional
            Style of the point markers drawn in this plot. See
            :ref:`ScatterPlot2D.MARKER_STYLES <scatter_marker_styles>`
            for a list of allowed marker styles. Defaults to ``"o"``.

        label : str, optional
            Label of this plot, as shown in the chart's legend. Defaults to ``""``.

        Returns
        -------
        plotting.charts.ScatterPlot2D
            The created scatter plot.

        Examples
        --------
        Generate a scatter plot.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> plot = chart.scatter([0, 1, 2], [2, 1, 3])
        >>> chart.show()

        """
        return self._add_plot("scatter", x, y, color=color, size=size, style=style, label=label)

    def line(self, x, y, color="b", width=1.0, style="-", label=""):
        """Add a line plot to this chart.

        Parameters
        ----------
        x : array_like
            X coordinates of the points through which a line should be drawn.

        y : array_like
            Y coordinates of the points through which a line should be drawn.

        color : color_like, optional
            Color of the line drawn in this plot. Any color parsable
            by :class:`pyvista.Color` is allowed. Defaults to
            ``"b"``.

        width : float, optional
            Width of the line drawn in this plot. Defaults to ``1``.

        style : str, optional
            Style of the line drawn in this plot. See
            :ref:`Pen.LINE_STYLES <pen_line_styles>` for a list of
            allowed line styles. Defaults to ``"-"``.

        label : str, optional
            Label of this plot, as shown in the chart's legend. Defaults to ``""``.

        Returns
        -------
        plotting.charts.LinePlot2D
            The created line plot.

        Examples
        --------
        Generate a line plot.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> plot = chart.line([0, 1, 2], [2, 1, 3])
        >>> chart.show()

        """
        return self._add_plot("line", x, y, color=color, width=width, style=style, label=label)

    def area(self, x, y1, y2=None, color="b", label=""):
        """Add an area plot to this chart.

        Parameters
        ----------
        x : array_like
            X coordinates of the points outlining the area to draw.

        y1 : array_like
            Y coordinates of the points on the first outline of the area to draw.

        y2 : array_like, optional
            Y coordinates of the points on the second outline of the
            area to draw. Defaults to a sequence of zeros.

        color : color_like, optional
            Color of the area drawn in this plot. Any color parsable
            by :class:`pyvista.Color` is allowed. Defaults to
            ``"b"``.

        label : str, optional
            Label of this plot, as shown in the chart's legend. Defaults to ``""``.

        Returns
        -------
        plotting.charts.AreaPlot
            The created area plot.

        Examples
        --------
        Generate an area plot.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> plot = chart.area([0, 1, 2], [2, 1, 3])
        >>> chart.show()

        """
        return self._add_plot("area", x, y1, y2, color=color, label=label)

    def bar(self, x, y, color=None, orientation="V", label=None):
        """Add a bar plot to this chart.

        Parameters
        ----------
        x : array_like
            Positions (along the x-axis for a vertical orientation,
            along the y-axis for a horizontal orientation) of the bars
            to draw.

        y : array_like
            Size of the bars to draw. Multiple bars can be stacked by
            passing a sequence of sequences.

        color : color_like, optional
            Color of the bars drawn in this plot. Any color parsable
            by :class:`pyvista.Color` is allowed. Defaults to
            ``"b"``.

        orientation : str, optional
            Orientation of the bars drawn in this plot. Either ``"H"``
            for an horizontal orientation or ``"V"`` for a vertical
            orientation. Defaults to ``"V"``.

        label : str, optional
            Label of this plot, as shown in the chart's legend. Defaults to ``""``.

        Returns
        -------
        plotting.charts.BarPlot
            The created bar plot.

        Examples
        --------
        Generate a bar plot.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> plot = chart.bar([0, 1, 2], [2, 1, 3])
        >>> chart.show()

        """
        return self._add_plot("bar", x, y, color=color, orientation=orientation, label=label)

    def stack(self, x, ys, colors=None, labels=None):
        """Add a stack plot to this chart.

        Parameters
        ----------
        x : array_like
            X coordinates of the points outlining the stacks (areas) to draw.

        ys : list or tuple of array_like
            Size of the stacks (areas) to draw at the corresponding X
            coordinates. Each sequence defines the sizes of one stack
            (area), which are stacked on top of each other.

        colors : list or tuple of color_like, optional
            Color of the stacks (areas) drawn in this plot. Any color
            parsable by :class:`pyvista.Color` is allowed.  Defaults
            to ``None``.

        labels : list or tuple of str, optional
            Label for each stack (area) drawn in this plot, as shown
            in the chart's legend. Defaults to ``[]``.

        Returns
        -------
        plotting.charts.StackPlot
            The created stack plot.

        Examples
        --------
        Generate a stack plot.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> plot = chart.stack([0, 1, 2], [[2, 1, 3],[1, 2, 1]])
        >>> chart.show()

        """
        return self._add_plot("stack", x, ys, colors=colors, labels=labels)

    def plots(self, plot_type=None):
        """Return all plots of the specified type in this chart.

        Parameters
        ----------
        plot_type : str, optional
            The type of plots to return. Allowed types are
            ``"scatter"``, ``"line"``, ``"area"``, ``"bar"``
            and ``"stack"``.
            Defaults to ``None``, which will return all plots,
            regardless of their type.

        Yields
        ------
        plot : plotting.charts.ScatterPlot2D, plotting.charts.LinePlot2D, plotting.charts.AreaPlot, plotting.charts.BarPlot or plotting.charts.StackPlot
            One of the plots (of the specified type) in this chart.

        Examples
        --------
        Create a 2D chart with a line and scatter plot.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> scatter_plot, line_plot = chart.plot([0, 1, 2], [2, 1, 3], "o-")
        >>> chart.show()

        Retrieve all plots in the chart.

        >>> plots = [*chart.plots()]
        >>> scatter_plot in plots and line_plot in plots
        True

        Retrieve all line plots in the chart.

        >>> line_plots = [*chart.plots("line")]
        >>> line_plot == line_plots[0]
        True

        """
        plot_types = self.PLOT_TYPES.keys() if plot_type is None else [plot_type]
        for plot_type in plot_types:
            for plot in self._plots[plot_type]:
                yield plot

    def remove_plot(self, plot):
        """Remove the given plot from this chart.

        Parameters
        ----------
        plot : plotting.charts.ScatterPlot2D, plotting.charts.LinePlot2D, plotting.charts.AreaPlot, plotting.charts.BarPlot or plotting.charts.StackPlot
            The plot to remove.

        Examples
        --------
        Create a 2D chart with a line and scatter plot.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> scatter_plot, line_plot = chart.plot([0, 1, 2], [2, 1, 3], "o-")
        >>> chart.show()

        Remove the scatter plot from the chart.

        >>> chart.remove_plot(scatter_plot)
        >>> chart.show()

        """
        try:
            plot_type = self._PLOT_CLASSES[type(plot)]
            self._plots[plot_type].remove(plot)
            self.RemovePlotInstance(plot)
        except (KeyError, ValueError):
            raise ValueError("The given plot is not part of this chart.")

    def clear(self, plot_type=None):
        """Remove all plots of the specified type from this chart.

        Parameters
        ----------
        plot_type : str, optional
            The type of the plots to remove. Allowed types are
            ``"scatter"``, ``"line"``, ``"area"``, ``"bar"``
            and ``"stack"``.
            Defaults to ``None``, which will remove all plots,
            regardless of their type.

        Examples
        --------
        Create a 2D chart with multiple line and scatter plot.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> _ = chart.plot([0, 1, 2], [2, 1, 3], "o-b")
        >>> _ = chart.plot([-2, -1, 0], [3, 1, 2], "d-r")
        >>> chart.show()

        Remove all scatter plots from the chart.

        >>> chart.clear("scatter")
        >>> chart.show()

        """
        plot_types = self.PLOT_TYPES.keys() if plot_type is None else [plot_type]
        for plot_type in plot_types:
            plots = [
                *self._plots[plot_type]
            ]  # Make a copy, as this list will be modified by remove_plot
            for plot in plots:
                self.remove_plot(plot)

    @property
    def x_axis(self):
        """Return this chart's horizontal (x) :class:`Axis <plotting.charts.Axis>`.

        Examples
        --------
        Create a 2D plot and hide the x axis.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> _ = chart.line([0, 1, 2], [2, 1, 3])
        >>> chart.x_axis.toggle()
        >>> chart.show()

        """
        return self._x_axis

    @property
    def y_axis(self):
        """Return this chart's vertical (y) :class:`Axis <plotting.charts.Axis>`.

        Examples
        --------
        Create a 2D plot and hide the y axis.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> _ = chart.line([0, 1, 2], [2, 1, 3])
        >>> chart.y_axis.toggle()
        >>> chart.show()

        """
        return self._y_axis

    @property
    def x_label(self):
        """Return or set the label of this chart's x axis.

        Examples
        --------
        Create a 2D plot and set custom axis labels.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> _ = chart.line([0, 1, 2], [2, 1, 3])
        >>> chart.x_label = "Horizontal axis"
        >>> chart.y_label = "Vertical axis"
        >>> chart.show()

        """
        return self.x_axis.label

    @x_label.setter
    def x_label(self, val):
        self.x_axis.label = val

    @property
    def y_label(self):
        """Return or set the label of this chart's y axis.

        Examples
        --------
        Create a 2D plot and set custom axis labels.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> _ = chart.line([0, 1, 2], [2, 1, 3])
        >>> chart.x_label = "Horizontal axis"
        >>> chart.y_label = "Vertical axis"
        >>> chart.show()

        """
        return self.y_axis.label

    @y_label.setter
    def y_label(self, val):
        self.y_axis.label = val

    @property
    def x_range(self):
        """Return or set the range of this chart's x axis.

        Examples
        --------
        Create a 2D plot and set custom axis ranges.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> _ = chart.line([0, 1, 2], [2, 1, 3])
        >>> chart.x_range = [-2, 2]
        >>> chart.y_range = [0, 5]
        >>> chart.show()

        """
        return self.x_axis.range

    @x_range.setter
    def x_range(self, val):
        self.x_axis.range = val

    @property
    def y_range(self):
        """Return or set the range of this chart's y axis.

        Examples
        --------
        Create a 2D plot and set custom axis ranges.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> _ = chart.line([0, 1, 2], [2, 1, 3])
        >>> chart.x_range = [-2, 2]
        >>> chart.y_range = [0, 5]
        >>> chart.show()

        """
        return self.y_axis.range

    @y_range.setter
    def y_range(self, val):
        self.y_axis.range = val

    @property
    def grid(self):
        """Enable or disable the chart grid.

        Examples
        --------
        Create a 2D chart with the grid disabled.

        >>> import pyvista
        >>> import numpy as np
        >>> x = np.linspace(0, 2*np.pi, 20)
        >>> y = np.sin(x)
        >>> chart = pyvista.Chart2D()
        >>> _ = chart.line(x, y, 'r')
        >>> chart.grid = False
        >>> chart.show()

        Enable the grid

        >>> chart.grid = True
        >>> chart.show()

        """
        return self.x_axis.grid and self.y_axis.grid

    @grid.setter
    def grid(self, val):
        self.x_axis.grid = val
        self.y_axis.grid = val

    def hide_axes(self):
        """Hide the x- and y-axis of this chart.

        This includes all labels, ticks and the grid.

        Examples
        --------
        Create a 2D plot and hide the axes.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> _ = chart.line([0, 1, 2], [2, 1, 3])
        >>> chart.hide_axes()
        >>> chart.show()

        """
        for axis in (self.x_axis, self.y_axis):
            axis.visible = False
            axis.label_visible = False
            axis.ticks_visible = False
            axis.tick_labels_visible = False
            axis.grid = False


class BoxPlot(_vtk.vtkPlotBox, _MultiCompPlot):
    """Class representing a box plot.

    Users should typically not directly create new plot instances, but
    use the dedicated ``ChartBox`` class.

    Parameters
    ----------
    data : list or tuple of array_like
        Dataset(s) from which the relevant statistics will be
        calculated used to draw the box plot.

    colors : list or tuple of color_like, optional
        Color of the boxes drawn in this plot. Any color parsable by
        :class:`pyvista.Color` is allowed.  Defaults to ``None``.

    labels : list or tuple of str, optional
        Label for each box drawn in this plot, as shown in the chart's
        legend. Defaults to ``[]``.

    Examples
    --------
    Create boxplots for datasets sampled from shifted normal distributions.

    >>> import pyvista
    >>> import numpy as np
    >>> rng = np.random.default_rng(1)  # Seeded random number generator used for data generation
    >>> normal_data = [rng.normal(i, size=50) for i in range(5)]
    >>> chart = pyvista.ChartBox(normal_data, labels=[f"x ~ N({i},1)" for i in range(5)])
    >>> chart.show()

    """

    _DOC_SUBS = {
        "plot_name": "box plot",
        "chart_init": "pyvista.ChartBox([[0, 1, 1, 2, 3, 3, 4]])",
        "plot_init": "chart.plot",
        "multichart_init": "pyvista.ChartBox([[0, 1, 1, 2, 3, 4, 5], [0, 1, 2, 2, 3, 4, 5], [0, 1, 2, 3, 3, 4, 5], [0, 1, 2, 3, 4, 4, 5]])",
        "multiplot_init": "chart.plot",
    }

    def __init__(self, data, colors=None, labels=None):
        """Initialize a new box plot instance."""
        super().__init__()
        self._table = pyvista.Table(
            {f"data_{i}": np.array(d, copy=False) for i, d in enumerate(data)}
        )
        self._quartiles = _vtk.vtkComputeQuartiles()
        self._quartiles.SetInputData(self._table)
        self.SetInputData(self._quartiles.GetOutput())
        self.update(data)
        self.SetLookupTable(self._lookup_table)
        self.colors = colors
        self.labels = labels

    @property
    def data(self):
        """Retrieve the datasets of which the boxplots are drawn.

        Examples
        --------
        Create a box plot and display the datasets.

        >>> import pyvista
        >>> chart = pyvista.ChartBox([[0, 1, 1, 2, 3, 3, 4]])
        >>> chart.plot.data
        (pyvista_ndarray([0, 1, 1, 2, 3, 3, 4]),)
        >>> chart.show()

        """
        return tuple(self._table[f"data_{i}"] for i in range(self._table.n_arrays))

    @property
    def stats(self):
        """Retrieve the statistics (quartiles and extremum values) of the datasets of which the boxplots are drawn.

        Examples
        --------
        Create a box plot and display the statistics.

        >>> import pyvista
        >>> chart = pyvista.ChartBox([[0, 1, 1, 2, 3, 3, 4]])
        >>> chart.plot.stats
        (pyvista_ndarray([0., 1., 2., 3., 4.]),)
        >>> chart.show()

        """
        stats_table = pyvista.Table(self._quartiles.GetOutput())
        return tuple(stats_table[f"data_{i}"] for i in range(stats_table.n_arrays))

    def update(self, data):
        """Update the plot's underlying dataset(s).

        Parameters
        ----------
        data : list or tuple of array_like
            The new dataset(s) used in this box plot.

        Examples
        --------
        Create a box plot from a standard Gaussian dataset.

        >>> import pyvista
        >>> import numpy as np
        >>> rng = np.random.default_rng(1)  # Seeded random number generator for data generation
        >>> chart = pyvista.ChartBox([rng.normal(size=100)])
        >>> chart.show()

        Update the box plot (shift the standard Gaussian distribution).

        >>> chart.plot.update([rng.normal(loc=2, size=100)])
        >>> chart.show()

        """
        self._table.update({f"data_{i}": np.array(d, copy=False) for i, d in enumerate(data)})
        self._quartiles.Update()


class ChartBox(_vtk.vtkChartBox, _Chart):
    """Dedicated chart for drawing box plots.

    Parameters
    ----------
    data : list or tuple of array_like
        Dataset(s) from which the relevant statistics will be
        calculated used to draw the box plot.

    colors : list or tuple of color_like, optional
        Color used for each drawn boxplot. Defaults to ``None``, which
        uses the default color scheme.

    labels : list or tuple of str, optional
        Label for each drawn boxplot, as shown in the chart's
        legend. Defaults to ``[]``.

    Examples
    --------
    Create boxplots for datasets sampled from shifted normal distributions.

    >>> import pyvista
    >>> import numpy as np
    >>> rng = np.random.default_rng(1)  # Seeded random number generator used for data generation
    >>> normal_data = [rng.normal(i, size=50) for i in range(5)]
    >>> chart = pyvista.ChartBox(normal_data, labels=[f"x ~ N({i},1)" for i in range(5)])
    >>> chart.show()

    """

    _DOC_SUBS = {
        "chart_name": "boxplot chart",
        "chart_args": "[[0, 1, 1, 2, 3, 3, 4]]",
        "chart_init": "",
        "chart_set_labels": 'chart.plot.label = "Data label"',
    }

    def __init__(self, data, colors=None, labels=None):
        """Initialize a new chart containing box plots."""
        super().__init__(None, None)
        self._plot = BoxPlot(data, colors, labels)
        self.SetPlot(self._plot)
        self.SetColumnVisibilityAll(True)
        self.legend_visible = True

    def _render_event(self, *args, **kwargs):
        # ChartBox fills entire scene by default, so no resizing is
        # needed (nor possible at this moment)
        pass

    @property
    def _geometry(self):
        # Needed for background (remove once resizing is possible)
        return (0, 0, *self._renderer.GetSize())

    @_geometry.setter
    def _geometry(self, value):
        raise AttributeError(f'Cannot set the geometry of {type(self).__class__}')

    @property
    def plot(self):
        """Return the :class:`BoxPlot <plotting.charts.BoxPlot>` instance associated with this chart.

        Examples
        --------
        Create a box plot from a standard Gaussian dataset.

        >>> import pyvista
        >>> import numpy as np
        >>> rng = np.random.default_rng(1)  # Seeded random number generator for data generation
        >>> chart = pyvista.ChartBox([rng.normal(size=100)])
        >>> chart.show()

        Update the box plot (shift the standard Gaussian distribution).

        >>> chart.plot.update([rng.normal(loc=2, size=100)])
        >>> chart.show()

        """
        return self._plot

    @property
    def size(self):
        """Return or set the chart size in normalized coordinates.

        A size of ``(1, 1)`` occupies the whole renderer.

        Notes
        -----
        The size of a ChartBox instance cannot be modified, it fills
        up the entire viewport by default.
        """
        return (1, 1)

    @size.setter
    def size(self, val):
        raise ValueError(
            "Cannot set ChartBox geometry, it fills up the entire viewport by default."
        )

    @property
    def loc(self):
        """Return or set the chart position in normalized coordinates.

        This denotes the location of the chart's bottom left corner.

        Notes
        -----
        The location of a ChartBox instance cannot be modified, it
        fills up the entire viewport by default.
        """
        return (0, 0)

    @loc.setter
    def loc(self, val):
        raise ValueError(
            "Cannot set ChartBox geometry, it fills up the entire viewport by default."
        )


class PiePlot(_vtkWrapper, _vtk.vtkPlotPie, _MultiCompPlot):
    """Class representing a pie plot.

    Users should typically not directly create new plot instances, but
    use the dedicated :class:`ChartPie` class.

    Parameters
    ----------
    data : array_like
        Relative size of each pie segment.

    colors : list or tuple of color_like, optional
        Color of the segments drawn in this plot. Any color parsable
        by :class:`pyvista.Color` is allowed.  Defaults to ``None``.

    labels : list or tuple of str, optional
        Label for each pie segment drawn in this plot, as shown in the
        chart's legend. Defaults to ``[]``.

    Other Parameters
    ----------------
    _wrap : vtk.vtkPlotPie, optional
        Wrap an existing VTK PlotPie instance. Defaults to ``None`` (no wrapping).

    Examples
    --------
    Create a pie plot showing the usage of tax money.

    >>> import pyvista
    >>> x = [128.3, 32.9, 31.8, 29.3, 21.2]
    >>> l = ["Social benefits", "Governance", "Economic policy", "Education", "Other"]
    >>> chart = pyvista.ChartPie(x, labels=l)
    >>> chart.show()

    """

    _DOC_SUBS = {
        "plot_name": "pie plot",
        "chart_init": "pyvista.ChartPie([4, 3, 2, 1])",
        "plot_init": "chart.plot",
        "multichart_init": "pyvista.ChartPie([4, 3, 2, 1])",
        "multiplot_init": "chart.plot",
    }

    def __init__(self, data, colors=None, labels=None):
        """Initialize a new pie plot instance."""
        super().__init__()
        self._table = pyvista.Table(data)
        self.SetInputData(self._table)
        self.SetInputArray(0, self._table.keys()[0])
        self.update(data)

        self.labels = labels

        self.SetColorSeries(self._color_series)
        self.colors = colors

    @property
    def data(self):
        """Retrieve the sizes of the drawn segments.

        Examples
        --------
        Create a pie plot and display the sizes.

        >>> import pyvista
        >>> chart = pyvista.ChartPie([1, 2, 3])
        >>> chart.plot.data
        pyvista_ndarray([1, 2, 3])
        >>> chart.show()

        """
        return self._table[0]

    def update(self, data):
        """Update the size of the pie segments.

        Parameters
        ----------
        data : array_like
            The new relative size of each pie segment.

        Examples
        --------
        Create a pie plot with segments of increasing size.

        >>> import pyvista
        >>> chart = pyvista.ChartPie([1, 2, 3, 4, 5])
        >>> chart.show()

        Update the pie plot (segments of equal size).

        >>> chart.plot.update([1, 1, 1, 1, 1])
        >>> chart.show()

        """
        self._table.update(data)


class ChartPie(_vtk.vtkChartPie, _Chart):
    """Dedicated chart for drawing pie plots.

    Parameters
    ----------
    data : array_like
        Relative size of each pie segment.

    colors : list or tuple of color_like, optional
        Color used for each pie segment drawn in this plot. Defaults
        to ``None``, which uses the default color scheme.

    labels : list or tuple of str, optional
        Label for each pie segment drawn in this plot, as shown in the
        chart's legend. Defaults to ``[]``.

    Examples
    --------
    Create a pie plot showing the usage of tax money.

    >>> import pyvista
    >>> x = [128.3, 32.9, 31.8, 29.3, 21.2]
    >>> l = ["Social benefits", "Governance", "Economic policy", "Education", "Other"]
    >>> chart = pyvista.ChartPie(x, labels=l)
    >>> chart.show()

    """

    _DOC_SUBS = {
        "chart_name": "pie chart",
        "chart_args": "[5, 4, 3, 2, 1]",
        "chart_init": "",
        "chart_set_labels": 'chart.plot.labels = ["A", "B", "C", "D", "E"]',
    }

    def __init__(self, data, colors=None, labels=None):
        """Initialize a new chart containing a pie plot."""
        super().__init__(None, None)
        # We can't manually set a wrapped vtkPlotPie instance (for now), so we
        # have to wrap the existing one.
        self.AddPlot(0)
        self._plot = PiePlot(data, colors, labels, _wrap=self.GetPlot(0))
        self.legend_visible = True

    def _render_event(self, *args, **kwargs):
        pass  # ChartPie fills entire scene by default, so no resizing is needed (nor possible at this moment)

    @property
    def _geometry(self):
        # Needed for background (remove once resizing is possible)
        return (0, 0, *self._renderer.GetSize())

    @_geometry.setter
    def _geometry(self, value):
        raise AttributeError(f'Cannot set the geometry of {type(self).__class__}')

    @property
    def plot(self):
        """Return the :class:`PiePlot <plotting.charts.PiePlot>` instance associated with this chart.

        Examples
        --------
        Create a pie plot with segments of increasing size.

        >>> import pyvista
        >>> chart = pyvista.ChartPie([1, 2, 3, 4, 5])
        >>> chart.show()

        Update the pie plot (segments of equal size).

        >>> chart.plot.update([1, 1, 1, 1, 1])
        >>> chart.show()

        """
        return self._plot

    @property
    def size(self):
        """Return or set the chart size in normalized coordinates.

        A size of ``(1, 1)`` occupies the whole renderer.

        Notes
        -----
        The size of a ChartPie instance cannot be modified, it fills
        up the entire viewport by default.
        """
        return (1, 1)

    @size.setter
    def size(self, val):
        raise ValueError(
            "Cannot set ChartPie geometry, it fills up the entire viewport by default."
        )

    @property
    def loc(self):
        """Return or set the chart position in normalized coordinates.

        This denotes the location of the chart's bottom left corner.

        Notes
        -----
        The location of a ChartPie instance cannot be modified, it
        fills up the entire viewport by default.
        """
        return (0, 0)

    @loc.setter
    def loc(self, val):
        raise ValueError(
            "Cannot set ChartPie geometry, it fills up the entire viewport by default."
        )


# region 3D charts
# A basic implementation of 3D line, scatter and volume plots, to be used in a 3D chart was provided in this section
# but removed in commit 8ef8daea5d105e85f256d4e9af584aeea3c85040 of PR #1432. Unfortunately, these charts are much less
# customisable than their 2D counterparts and they do not respect the enforced size/geometry constraints once you start
# interacting with them.
# endregion


class ChartMPL(_vtk.vtkImageItem, _Chart):
    """Create new chart from an existing matplotlib figure.

    Parameters
    ----------
    figure : matplotlib.figure.Figure
        The matplotlib figure to draw.

    size : list or tuple, optional
        Size of the chart in normalized coordinates. A size of ``(0,
        0)`` is invisible, a size of ``(1, 1)`` occupies the whole
        renderer's width and height.

    loc : list or tuple, optional
        Location of the chart (its bottom left corner) in normalized
        coordinates. A location of ``(0, 0)`` corresponds to the
        renderer's bottom left corner, a location of ``(1, 1)``
        corresponds to the renderer's top right corner.

    Examples
    --------
    Plot streamlines of a vector field with varying colors (based on `this example <https://matplotlib.org/stable/gallery/images_contours_and_fields/plot_streamplot.html>`_).

    .. pyvista-plot::

    >>> import pyvista
    >>> import numpy as np
    >>> import matplotlib.pyplot as plt

    >>> w = 3
    >>> Y, X = np.mgrid[-w:w:100j, -w:w:100j]
    >>> U = -1 - X**2 + Y
    >>> V = 1 + X - Y**2
    >>> speed = np.sqrt(U**2 + V**2)

    >>> f, ax = plt.subplots()
    >>> strm = ax.streamplot(X, Y, U, V, color=U, linewidth=2, cmap='autumn')
    >>> _ = f.colorbar(strm.lines)
    >>> _ = ax.set_title('Streamplot with varying Color')
    >>> plt.tight_layout()

    >>> chart = pyvista.ChartMPL(f)
    >>> chart.show()

    """

    _DOC_SUBS = {
        "chart_name": "matplotlib chart",
        "chart_args": "",
        "chart_init": """
        >>> plots = chart.figure.axes[0].plot([0, 1, 2], [2, 1, 3])""",
        "chart_set_labels": 'plots[0].label = "My awesome plot"',
    }

    def __init__(self, figure=None, size=(1, 1), loc=(0, 0)):
        """Initialize chart."""
        try:
            from matplotlib.backends.backend_agg import FigureCanvasAgg
            import matplotlib.figure  # noqa
            import matplotlib.pyplot as plt
        except ModuleNotFoundError:
            raise ImportError("ChartMPL requires matplotlib")

        super().__init__(size, loc)
        if figure is None:
            figure, _ = plt.subplots()
        self._fig = figure
        self._canvas = FigureCanvasAgg(
            self._fig
        )  # Switch backends and store reference to figure's canvas
        # Make figure and axes fully transparent, as the background is already dealt with by self._background.
        self._fig.patch.set_alpha(0)
        for ax in self._fig.axes:
            ax.patch.set_alpha(0)
        self._canvas.mpl_connect('draw_event', self._redraw)  # Attach 'draw_event' callback

        self._redraw()

        # Close the underlying matplotlib figure when creating the sphinx gallery.
        # This prevents the charts from being drawn twice in example scripts:
        # once as a pyvista plot (fetched by the 'pyvista' scraper) and once as a
        # matplotlib figure (fetched by the 'matplotlib' scraper).
        # See #1999 and #2031.
        if pyvista.BUILDING_GALLERY:  # pragma: no cover
            plt.close(self._fig)

    @property
    def figure(self):
        """Retrieve the matplotlib figure associated with this chart.

        Examples
        --------
        Create a matplotlib chart from an existing figure.

        .. pyvista-plot::

        >>> import pyvista
        >>> import matplotlib.pyplot as plt
        >>> f, ax = plt.subplots()
        >>> _ = ax.plot([0, 1, 2], [2, 1, 3])
        >>> chart = pyvista.ChartMPL(f)
        >>> chart.figure is f
        True
        >>> chart.show()
        """
        return self._fig

    def _resize(self):
        r_w, r_h = self._renderer.GetSize()
        c_w, c_h = self._canvas.get_width_height()
        # Calculate target size from specified normalized width and height and the renderer's current size
        t_w = self._size[0] * r_w
        t_h = self._size[1] * r_h
        resize = c_w != t_w or c_h != t_h
        if resize:
            # Mismatch between canvas size and target size, so resize figure:
            f_w = t_w / self._fig.dpi
            f_h = t_h / self._fig.dpi
            self._fig.set_size_inches(f_w, f_h)
            self.position = (self._loc[0] * r_w, self._loc[1] * r_h)
        return resize

    def _redraw(self, event=None):
        """Redraw the chart."""
        if event is None:
            # Manual call, so make sure canvas is redrawn first (which will callback to _redraw with a proper event defined)
            self._canvas.draw()
        else:
            # Called from draw_event callback
            img = np.frombuffer(
                self._canvas.buffer_rgba(), dtype=np.uint8
            )  # Store figure data in numpy array
            w, h = self._canvas.get_width_height()
            img_arr = img.reshape([h, w, 4])
            img_data = pyvista.Texture(img_arr).to_image()  # Convert to vtkImageData
            self.SetImage(img_data)

    def _render_event(self, *args, **kwargs):
        if self._resize():  # Update figure dimensions if needed
            self._redraw()  # Redraw figure when geometry has changed

    @property
    def _geometry(self):
        r_w, r_h = self._renderer.GetSize()
        t_w = self._size[0] * r_w
        t_h = self._size[1] * r_h
        return (*self.position, t_w, t_h)

    @_geometry.setter
    def _geometry(self, value):
        raise AttributeError(f'Cannot set the geometry of {type(self).__class__}')

    # Below code can be used to customize the chart's background without a _ChartBackground instance
    # @property
    # def background_color(self):
    #     return self._bg_color
    #
    # @background_color.setter
    # def background_color(self, val):
    #     color = parse_color(val) if val is not None else [1.0, 1.0, 1.0, 1.0]
    #     opacity = color[3] if len(color) == 4 else 1
    #     self._bg_color = color
    #     self._fig.patch.set_color(color[:3])
    #     self._fig.patch.set_alpha(opacity)
    #     for ax in self._fig.axes:
    #         ax.patch.set_alpha(0 if opacity < 1 else 1)  # Make axes fully transparent if opacity is lower than 1

    @property
    def position(self):
        """Chart position w.r.t the bottom left corner (in pixels)."""
        return self.GetPosition()

    @position.setter
    def position(self, val):
        if len(val) != 2:
            raise ValueError(f'Invalid position {val}, must be length 2.')
        self.SetPosition(*val)

    @property
    def title(self):
        """Return or set the chart's title.

        Examples
        --------
        Create a matplotlib chart with title 'My Chart'.

        .. pyvista-plot::

        >>> import pyvista
        >>> import matplotlib.pyplot as plt
        >>> f, ax = plt.subplots()
        >>> _ = ax.plot([0, 1, 2], [2, 1, 3])
        >>> chart = pyvista.ChartMPL(f)
        >>> chart.title = 'My Chart'
        >>> chart.show()

        """
        return self._fig._suptitle.get_text()

    @title.setter
    def title(self, val):
        self._fig.suptitle(val)

    @property
    def legend_visible(self):
        """Return or set the visibility of the chart's legend.

        Examples
        --------
        Create a matplotlib chart with custom labels and show the legend.

        .. pyvista-plot::

        >>> import pyvista
        >>> import matplotlib.pyplot as plt
        >>> f, ax = plt.subplots()
        >>> _ = ax.plot([0, 1, 2], [2, 1, 3], label="Line")
        >>> _ = ax.scatter([0, 1, 2], [3, 2, 1], label="Points")
        >>> chart = pyvista.ChartMPL(f)
        >>> chart.legend_visible = True
        >>> chart.show()

        Hide the legend.

        >>> chart.legend_visible = False
        >>> chart.show()

        """
        legend = self._fig.axes[0].get_legend()
        return False if legend is None else legend.get_visible()

    @legend_visible.setter
    def legend_visible(self, val):
        legend = self._fig.axes[0].get_legend()
        if legend is None:
            legend = self._fig.axes[0].legend()
        legend.set_visible(val)


class Charts:
    """Collection of charts for a renderer.

    Users should typically not directly create new instances of this
    class, but use the dedicated ``Plotter.add_chart`` method.

    """

    def __init__(self, renderer):
        """Create a new collection of charts for the given renderer."""
        self._charts = []

        # Postpone creation of scene and actor objects until they are
        # needed.
        self._scene = None
        self._actor = None

        # a weakref.proxy would be nice here, but that doesn't play
        # nicely with SetRenderer, so instead we'll use a weak reference
        # plus a property to call it
        self.__renderer = weakref.ref(renderer)

    @property
    def _renderer(self):
        """Return the weakly dereferenced renderer, maybe None."""
        return self.__renderer()

    def _setup_scene(self):
        """Set up a new context scene and actor for these charts."""
        self._scene = _vtk.vtkContextScene()
        self._actor = _vtk.vtkContextActor()

        self._actor.SetScene(self._scene)
        self._renderer.AddActor(self._actor)
        self._scene.SetRenderer(self._renderer)

    def deep_clean(self):
        """Remove all references to the chart objects and internal objects."""
        if self._scene is not None:
            charts = [*self._charts]  # Make a copy, as this list will be modified by remove_chart
            for chart in charts:
                self.remove_chart(chart)
            self._renderer.RemoveActor(self._actor)
        self._scene = None
        self._actor = None

    def add_chart(self, *charts):
        """Add charts to the collection."""
        if self._scene is None:
            self._setup_scene()
        for chart in charts:
            self._charts.append(chart)
            self._scene.AddItem(chart._background)
            self._scene.AddItem(chart)
            chart.SetInteractive(False)  # Charts are not interactive by default

    def remove_chart(self, chart_or_index):
        """Remove a chart from the collection."""
        chart = self._charts[chart_or_index] if isinstance(chart_or_index, int) else chart_or_index
        if chart not in self._charts:  # pragma: no cover
            raise ValueError('chart_index not present in charts collection.')
        self._charts.remove(chart)
        self._scene.RemoveItem(chart)
        self._scene.RemoveItem(chart._background)

    def toggle_interaction(self, mouse_pos):
        """Toggle interaction of the charts based on the given mouse position.

        Disables interaction with all charts, except the one indicated
        by the mouse position.  In case the indicated chart was
        already interactive, interaction is disabled again.

        Parameters
        ----------
        mouse_pos : tuple of float or bool
            This parameter should be either False, to disable
            interaction with all charts; or a tuple containing the
            mouse position, to disable interaction with all charts,
            except the one indicated by the mouse, if any.

        Returns
        -------
        vtk.vtkContextScene, optional
            Returns the scene if one of the charts got activated, None otherwise.

        """
        enable = False
        for chart in self._charts:
            if chart.visible and (mouse_pos is not False and chart._is_within(mouse_pos)):
                enable = not chart.GetInteractive()
                chart.SetInteractive(enable)
                # Change the chart's axis behaviour to fixed, such that the user can properly interact with the chart.
                if chart._x_axis is not None:
                    chart._x_axis.behavior = "fixed"
                if chart._y_axis is not None:
                    chart._y_axis.behavior = "fixed"
            else:
                chart.SetInteractive(False)

        return self._scene if enable else None

    def __getitem__(self, index):
        """Return a chart based on an index."""
        return self._charts[index]

    def __len__(self):
        """Return number of charts."""
        return len(self._charts)

    def __iter__(self):
        """Return an iterable of charts."""
        for chart in self._charts:
            yield chart

    def __del__(self):
        """Clean up before being destroyed."""
        self.deep_clean()


# pyvista/plotting/export_vtkjs.py

"""Export a rendering window to a VTKjs file.

This module holds a set of tools for exporting a VTK rendering window
to a VTKjs file that can be viewed in a web browser.

PVGeo has a webveiwer_ set up to load these files.

.. _webviewer: http://viewer.pyvista.org


Much of this export script was adopted from the
`VTKjs export script for ParaView`_.

.. VTKjs export script for ParaView: https://github.com/Kitware/vtk-js/blob/master/Utilities/ParaView/export-scene-macro.py

The license for the original export script is as follows:

Copyright (c) 2016, Kitware Inc.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of the <organization> nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT
HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

"""
import errno
import gzip
import hashlib
import json
import os
import shutil
import sys
import time
import zipfile

FILENAME_EXTENSION = '.vtkjs'

arrayTypesMapping = '  bBhHiIlLfdL'  # last one is idtype

jsMapping = {
    'b': 'Int8Array',
    'B': 'Uint8Array',
    'h': 'Int16Array',
    'H': 'Int16Array',
    'i': 'Int32Array',
    'I': 'Uint32Array',
    'l': 'Int32Array',
    'L': 'Uint32Array',
    'f': 'Float32Array',
    'd': 'Float64Array',
}

writer_mapping = {}

# -----------------------------------------------------------------------------


def get_range_info(array, component):
    """Get the data range of the array's component."""
    r = array.GetRange(component)
    comp_range = {}
    comp_range['min'] = r[0]
    comp_range['max'] = r[1]
    comp_range['component'] = array.GetComponentName(component)
    return comp_range


# -----------------------------------------------------------------------------


def get_ref(dest_dir, md5):
    """Get reference."""
    ref = {}
    ref['id'] = md5
    ref['encode'] = 'BigEndian' if sys.byteorder == 'big' else 'LittleEndian'
    ref['basepath'] = dest_dir
    return ref


# -----------------------------------------------------------------------------


objIds = []  # type: ignore


def get_object_id(obj):
    """Get object identifier."""
    try:
        idx = objIds.index(obj)
        return idx + 1
    except ValueError:
        objIds.append(obj)
        return len(objIds)


# -----------------------------------------------------------------------------


def dump_data_array(dataset_dir, data_dir, array, root=None, compress=True):
    """Dump vtkjs data array."""
    # import here to avoid circular imports
    from pyvista import _vtk

    if root is None:
        root = {}
    if not array:
        return None

    if array.GetDataType() == 12:
        # IdType need to be converted to Uint32
        array_size = array.GetNumberOfTuples() * array.GetNumberOfComponents()
        new_array = _vtk.vtkTypeUInt32Array()
        new_array.SetNumberOfTuples(array_size)
        for i in range(array_size):
            new_array.SetValue(i, -1 if array.GetValue(i) < 0 else array.GetValue(i))
        pbuffer = memoryview(new_array)
    else:
        pbuffer = memoryview(array)

    pMd5 = hashlib.md5(pbuffer).hexdigest()
    ppath = os.path.join(data_dir, pMd5)
    with open(ppath, 'wb') as f:
        f.write(pbuffer)

    if compress:
        with open(ppath, 'rb') as f_in, gzip.open(
            os.path.join(data_dir, pMd5 + '.gz'), 'wb'
        ) as f_out:
            shutil.copyfileobj(f_in, f_out)
        # Close then remove.
        os.remove(ppath)

    root['ref'] = get_ref(os.path.relpath(data_dir, dataset_dir), pMd5)
    root['vtkClass'] = 'vtkDataArray'
    root['name'] = array.GetName()
    root['dataType'] = jsMapping[arrayTypesMapping[array.GetDataType()]]
    root['numberOfComponents'] = array.GetNumberOfComponents()
    root['size'] = array.GetNumberOfComponents() * array.GetNumberOfTuples()
    root['ranges'] = []
    if root['numberOfComponents'] > 1:
        for i in range(root['numberOfComponents']):
            root['ranges'].append(get_range_info(array, i))
        root['ranges'].append(get_range_info(array, -1))
    else:
        root['ranges'].append(get_range_info(array, 0))

    return root


# -----------------------------------------------------------------------------


def dump_color_array(dataset_dir, data_dir, color_array_info, root=None, compress=True):
    """Dump vtkjs color array."""
    if root is None:
        root = {}
    root['pointData'] = {
        'vtkClass': 'vtkDataSetAttributes',
        "activeGlobalIds": -1,
        "activeNormals": -1,
        "activePedigreeIds": -1,
        "activeScalars": -1,
        "activeTCoords": -1,
        "activeTensors": -1,
        "activeVectors": -1,
        "arrays": [],
    }
    root['cellData'] = {
        'vtkClass': 'vtkDataSetAttributes',
        "activeGlobalIds": -1,
        "activeNormals": -1,
        "activePedigreeIds": -1,
        "activeScalars": -1,
        "activeTCoords": -1,
        "activeTensors": -1,
        "activeVectors": -1,
        "arrays": [],
    }
    root['fieldData'] = {
        'vtkClass': 'vtkDataSetAttributes',
        "activeGlobalIds": -1,
        "activeNormals": -1,
        "activePedigreeIds": -1,
        "activeScalars": -1,
        "activeTCoords": -1,
        "activeTensors": -1,
        "activeVectors": -1,
        "arrays": [],
    }

    colorArray = color_array_info['colorArray']
    location = color_array_info['location']

    dumped_array = dump_data_array(dataset_dir, data_dir, colorArray, {}, compress)

    if dumped_array:
        root[location]['activeScalars'] = 0
        root[location]['arrays'].append({'data': dumped_array})

    return root


# -----------------------------------------------------------------------------


def dump_t_coords(dataset_dir, data_dir, dataset, root=None, compress=True):
    """Dump vtkjs texture coordinates."""
    if root is None:
        root = {}
    tcoords = dataset.GetPointData().GetTCoords()
    if tcoords:
        dumped_array = dump_data_array(dataset_dir, data_dir, tcoords, {}, compress)
        root['pointData']['activeTCoords'] = len(root['pointData']['arrays'])
        root['pointData']['arrays'].append({'data': dumped_array})


# -----------------------------------------------------------------------------


def dump_normals(dataset_dir, data_dir, dataset, root=None, compress=True):
    """Dump vtkjs normal vectors."""
    if root is None:
        root = {}
    normals = dataset.GetPointData().GetNormals()
    if normals:
        dumped_array = dump_data_array(dataset_dir, data_dir, normals, {}, compress)
        root['pointData']['activeNormals'] = len(root['pointData']['arrays'])
        root['pointData']['arrays'].append({'data': dumped_array})


# -----------------------------------------------------------------------------


def dump_all_arrays(dataset_dir, data_dir, dataset, root=None, compress=True):
    """Dump all data arrays to vtkjs."""
    if root is None:
        root = {}
    root['pointData'] = {
        'vtkClass': 'vtkDataSetAttributes',
        "activeGlobalIds": -1,
        "activeNormals": -1,
        "activePedigreeIds": -1,
        "activeScalars": -1,
        "activeTCoords": -1,
        "activeTensors": -1,
        "activeVectors": -1,
        "arrays": [],
    }
    root['cellData'] = {
        'vtkClass': 'vtkDataSetAttributes',
        "activeGlobalIds": -1,
        "activeNormals": -1,
        "activePedigreeIds": -1,
        "activeScalars": -1,
        "activeTCoords": -1,
        "activeTensors": -1,
        "activeVectors": -1,
        "arrays": [],
    }
    root['fieldData'] = {
        'vtkClass': 'vtkDataSetAttributes',
        "activeGlobalIds": -1,
        "activeNormals": -1,
        "activePedigreeIds": -1,
        "activeScalars": -1,
        "activeTCoords": -1,
        "activeTensors": -1,
        "activeVectors": -1,
        "arrays": [],
    }

    # Point data
    pd = dataset.GetPointData()
    pd_size = pd.GetNumberOfArrays()
    for i in range(pd_size):
        array = pd.GetArray(i)
        if array:
            dumped_array = dump_data_array(dataset_dir, data_dir, array, {}, compress)
            root['pointData']['activeScalars'] = 0
            root['pointData']['arrays'].append({'data': dumped_array})

    # Cell data
    cd = dataset.GetCellData()
    cd_size = pd.GetNumberOfArrays()
    for i in range(cd_size):
        array = cd.GetArray(i)
        if array:
            dumped_array = dump_data_array(dataset_dir, data_dir, array, {}, compress)
            root['cellData']['activeScalars'] = 0
            root['cellData']['arrays'].append({'data': dumped_array})

    return root


# -----------------------------------------------------------------------------


def dump_poly_data(dataset_dir, data_dir, dataset, color_array_info, root=None, compress=True):
    """Dump poly data object to vtkjs."""
    if root is None:
        root = {}
    root['vtkClass'] = 'vtkPolyData'
    container = root

    # Points
    points = dump_data_array(dataset_dir, data_dir, dataset.GetPoints().GetData(), {}, compress)
    points['vtkClass'] = 'vtkPoints'
    container['points'] = points

    # Cells
    _cells = container

    # Verts
    if dataset.GetVerts() and dataset.GetVerts().GetData().GetNumberOfTuples() > 0:
        _verts = dump_data_array(dataset_dir, data_dir, dataset.GetVerts().GetData(), {}, compress)
        _cells['verts'] = _verts
        _cells['verts']['vtkClass'] = 'vtkCellArray'

    # Lines
    if dataset.GetLines() and dataset.GetLines().GetData().GetNumberOfTuples() > 0:
        _lines = dump_data_array(dataset_dir, data_dir, dataset.GetLines().GetData(), {}, compress)
        _cells['lines'] = _lines
        _cells['lines']['vtkClass'] = 'vtkCellArray'

    # Polys
    if dataset.GetPolys() and dataset.GetPolys().GetData().GetNumberOfTuples() > 0:
        _polys = dump_data_array(dataset_dir, data_dir, dataset.GetPolys().GetData(), {}, compress)
        _cells['polys'] = _polys
        _cells['polys']['vtkClass'] = 'vtkCellArray'

    # Strips
    if dataset.GetStrips() and dataset.GetStrips().GetData().GetNumberOfTuples() > 0:
        _strips = dump_data_array(
            dataset_dir, data_dir, dataset.GetStrips().GetData(), {}, compress
        )
        _cells['strips'] = _strips
        _cells['strips']['vtkClass'] = 'vtkCellArray'

    dump_color_array(dataset_dir, data_dir, color_array_info, container, compress)

    # PointData TCoords
    dump_t_coords(dataset_dir, data_dir, dataset, container, compress)
    # dump_normals(dataset_dir, data_dir, dataset, container, compress)

    return root


# -----------------------------------------------------------------------------
writer_mapping['vtkPolyData'] = dump_poly_data
# -----------------------------------------------------------------------------


def dump_image_data(dataset_dir, data_dir, dataset, color_array_info, root=None, compress=True):
    """Dump image data object to vtkjs."""
    if root is None:
        root = {}
    root['vtkClass'] = 'vtkImageData'
    container = root

    container['spacing'] = dataset.GetSpacing()
    container['origin'] = dataset.GetOrigin()
    container['extent'] = dataset.GetExtent()

    dump_all_arrays(dataset_dir, data_dir, dataset, container, compress)

    return root


# -----------------------------------------------------------------------------
writer_mapping['vtkImageData'] = dump_image_data
# -----------------------------------------------------------------------------


def write_data_set(file_path, dataset, output_dir, color_array_info, new_name=None, compress=True):
    """Write dataset to vtkjs."""
    fileName = new_name if new_name else os.path.basename(file_path)
    dataset_dir = os.path.join(output_dir, fileName)
    data_dir = os.path.join(dataset_dir, 'data')

    if not os.path.exists(data_dir):
        os.makedirs(data_dir)

    root = {}
    root['metadata'] = {}
    root['metadata']['name'] = fileName

    writer = writer_mapping[dataset.GetClassName()]
    if writer:
        writer(dataset_dir, data_dir, dataset, color_array_info, root, compress)
    else:
        print(dataset.GetClassName(), 'is not supported')

    with open(os.path.join(dataset_dir, "index.json"), 'w') as f:
        f.write(json.dumps(root, indent=2))

    return dataset_dir


### ----------------------------------------------------------------------- ###
###                          Main script contents                           ###
### ----------------------------------------------------------------------- ###


def mkdir_p(path):
    """Make directory at path."""
    try:
        os.makedirs(path)
    except OSError as exc:  # Python >2.5
        if exc.errno == errno.EEXIST and os.path.isdir(path):
            pass
        else:
            raise


def export_plotter_vtkjs(plotter, filename, compress_arrays=False):
    """Export a plotter's rendering window to the VTKjs format."""
    arrays = []  # assist in cleaning up references

    # import here to avoid circular imports
    from pyvista import _vtk

    sceneName = os.path.split(filename)[1]
    doCompressArrays = compress_arrays

    # Generate timestamp and use it to make subdirectory within the top level output dir
    timeStamp = time.strftime("%a-%d-%b-%Y-%H-%M-%S")
    root_output_directory = os.path.split(filename)[0]
    output_dir = os.path.join(root_output_directory, timeStamp)
    mkdir_p(output_dir)

    renderers = plotter.ren_win.GetRenderers()

    scDirs = []
    sceneComponents = []
    textureToSave = {}

    for rIdx in range(renderers.GetNumberOfItems()):
        renderer = renderers.GetItemAsObject(rIdx)
        renProps = renderer.GetViewProps()
        for rpIdx in range(renProps.GetNumberOfItems()):
            renProp = renProps.GetItemAsObject(rpIdx)
            if not renProp.GetVisibility():
                continue
            if hasattr(renProp, 'GetMapper') and renProp.GetMapper() is not None:
                mapper = renProp.GetMapper()
                dataObject = mapper.GetInputDataObject(0, 0)
                dataset = None
                if dataObject is None:
                    continue
                if dataObject.IsA('vtkCompositeDataSet'):
                    if dataObject.GetNumberOfBlocks() == 1:
                        dataset = dataObject.GetBlock(0)
                    else:
                        gf = _vtk.vtkCompositeDataGeometryFilter()
                        gf.SetInputData(dataObject)
                        gf.Update()
                        dataset = gf.GetOutput()
                else:
                    dataset = mapper.GetInput()

                if dataset and not isinstance(dataset, (_vtk.vtkPolyData, _vtk.vtkImageData)):
                    # All data must be PolyData surfaces
                    gf = _vtk.vtkGeometryFilter()
                    gf.SetInputData(dataset)
                    gf.Update()
                    dataset = gf.GetOutputDataObject(0)

                if dataset:  # and dataset.GetPoints(): # NOTE: vtkImageData does not have points
                    componentName = f'data_{rIdx}_{rpIdx}'  # getComponentName(renProp)
                    scalarVisibility = mapper.GetScalarVisibility()
                    # arrayAccessMode = mapper.GetArrayAccessMode()
                    # colorArrayName = mapper.GetArrayName() #TODO: if arrayAccessMode == 1 else mapper.GetArrayId()
                    colorMode = mapper.GetColorMode()
                    scalarMode = mapper.GetScalarMode()
                    lookupTable = mapper.GetLookupTable()

                    dsAttrs = None
                    arrayLocation = ''

                    if scalarVisibility:
                        if scalarMode == 3 or scalarMode == 1:
                            # VTK_SCALAR_MODE_USE_POINT_FIELD_DATA or VTK_SCALAR_MODE_USE_POINT_DATA
                            dsAttrs = dataset.GetPointData()
                            arrayLocation = 'pointData'
                        # VTK_SCALAR_MODE_USE_CELL_FIELD_DATA or VTK_SCALAR_MODE_USE_CELL_DATA
                        elif scalarMode == 4 or scalarMode == 2:
                            dsAttrs = dataset.GetCellData()
                            arrayLocation = 'cellData'

                    colorArray = None
                    dataArray = None

                    if dsAttrs:
                        dataArray = dsAttrs.GetArray(0)  # Force getting the active array

                    if dataArray:
                        # component = -1 => let specific instance get scalar from vector before mapping
                        colorArray = lookupTable.MapScalars(dataArray, colorMode, -1)
                        colorArrayName = '__CustomRGBColorArray__'
                        colorArray.SetName(colorArrayName)
                        colorMode = 0

                        # track arrays for cleanup
                        arrays.append(colorArray)
                    else:
                        colorArrayName = ''

                    color_array_info = {'colorArray': colorArray, 'location': arrayLocation}

                    scDirs.append(
                        write_data_set(
                            '',
                            dataset,
                            output_dir,
                            color_array_info,
                            new_name=componentName,
                            compress=doCompressArrays,
                        )
                    )

                    # Handle texture if any
                    textureName = None
                    if renProp.GetTexture() and renProp.GetTexture().GetInput():
                        textureData = renProp.GetTexture().GetInput()
                        textureName = f'texture_{get_object_id(textureData)}'
                        textureToSave[textureName] = textureData

                    representation = (
                        renProp.GetProperty().GetRepresentation()
                        if hasattr(renProp, 'GetProperty')
                        else 2
                    )
                    colorToUse = (
                        renProp.GetProperty().GetDiffuseColor()
                        if hasattr(renProp, 'GetProperty')
                        else [1.0, 1.0, 1.0]
                    )
                    if representation == 1:
                        colorToUse = (
                            renProp.GetProperty().GetColor()
                            if hasattr(renProp, 'GetProperty')
                            else [1.0, 1.0, 1.0]
                        )
                    pointSize = (
                        renProp.GetProperty().GetPointSize()
                        if hasattr(renProp, 'GetProperty')
                        else 1.0
                    )
                    opacity = (
                        renProp.GetProperty().GetOpacity()
                        if hasattr(renProp, 'GetProperty')
                        else 1.0
                    )
                    edgeVisibility = (
                        renProp.GetProperty().GetEdgeVisibility()
                        if hasattr(renProp, 'GetProperty')
                        else False
                    )

                    p3dPosition = renProp.GetPosition() if renProp.IsA('vtkProp3D') else [0, 0, 0]
                    p3dScale = renProp.GetScale() if renProp.IsA('vtkProp3D') else [1, 1, 1]
                    p3dOrigin = renProp.GetOrigin() if renProp.IsA('vtkProp3D') else [0, 0, 0]
                    p3dRotateWXYZ = (
                        renProp.GetOrientationWXYZ() if renProp.IsA('vtkProp3D') else [0, 0, 0, 0]
                    )

                    sceneComponents.append(
                        {
                            "name": componentName,
                            "type": "httpDataSetReader",
                            "httpDataSetReader": {"url": componentName},
                            "actor": {
                                "origin": p3dOrigin,
                                "scale": p3dScale,
                                "position": p3dPosition,
                            },
                            "actorRotation": p3dRotateWXYZ,
                            "mapper": {
                                "colorByArrayName": colorArrayName,
                                "colorMode": colorMode,
                                "scalarMode": scalarMode,
                            },
                            "property": {
                                "representation": representation,
                                "edgeVisibility": edgeVisibility,
                                "diffuseColor": colorToUse,
                                "pointSize": pointSize,
                                "opacity": opacity,
                            },
                            "lookupTable": {
                                "tableRange": lookupTable.GetRange(),
                                "hueRange": lookupTable.GetHueRange()
                                if hasattr(lookupTable, 'GetHueRange')
                                else [0.5, 0],
                            },
                        }
                    )

                    if textureName:
                        sceneComponents[-1]['texture'] = textureName

    # Save texture data if any
    for key, val in textureToSave.items():
        write_data_set('', val, output_dir, None, new_name=key, compress=doCompressArrays)

    cameraClippingRange = plotter.camera.clipping_range

    sceneDescription = {
        "fetchGzip": doCompressArrays,
        "background": plotter.background_color.float_rgb,
        "camera": {
            "focalPoint": plotter.camera.focal_point,
            "position": plotter.camera.position,
            "viewUp": plotter.camera.up,
            "clippingRange": [elt for elt in cameraClippingRange],
        },
        "centerOfRotation": plotter.camera.focal_point,
        "scene": sceneComponents,
    }

    indexFilePath = os.path.join(output_dir, 'index.json')
    with open(indexFilePath, 'w') as outfile:
        json.dump(sceneDescription, outfile, indent=4)

    # -----------------------------------------------------------------------------

    # Now zip up the results and get rid of the temp directory
    sceneFileName = os.path.join(root_output_directory, f'{sceneName}{FILENAME_EXTENSION}')

    try:
        import zlib  # noqa

        compression = zipfile.ZIP_DEFLATED
    except:  # noqa: E722
        compression = zipfile.ZIP_STORED

    zf = zipfile.ZipFile(sceneFileName, mode='w')

    try:
        for dirName, _, fileList in os.walk(output_dir):
            for fname in fileList:
                fullPath = os.path.join(dirName, fname)
                relPath = f'{sceneName}/{os.path.relpath(fullPath, output_dir)}'
                zf.write(fullPath, arcname=relPath, compress_type=compression)
    finally:
        zf.close()

    shutil.rmtree(output_dir)

    # this must occur to avoid leaks
    scDirs.clear()
    for array in arrays:
        array.SetReferenceCount(0)


def convert_dropbox_url(url):
    """Convert dropbox url to direct download link."""
    return url.replace("https://www.dropbox.com", "https://dl.dropbox.com")


def generate_viewer_url(dataURL):
    """Generate viewer url with data link."""
    viewerURL = "http://viewer.pyvista.org/"
    return viewerURL + f'?fileURL={dataURL}'


def get_vtkjs_url(*args):
    """Provide shareable link from the vtkjs script.

    After using ``export_vtkjs()`` to create a ``.vtkjs`` file from a
    data scene which is uploaded to an online file hosting service like Dropbox,
    use this method to get a shareable link to that scene on the
    `PVGeo VTKjs viewer`_.

    .. _PVGeo VTKjs viewer: http://viewer.pyvista.org

    **Current file hosts supported:**

    - Dropbox

    Args:
        host (str): the name of the file hosting service.
        inURL (str): the web URL to the ``.vtkjs`` file.

    """
    if len(args) == 1:
        host = 'dropbox'
        inURL = args[0]
    elif len(args) == 2:
        host = args[0]
        inURL = args[1]
    else:
        raise TypeError('Arguments not understood.')
    if host.lower() == "dropbox":
        convertURL = convert_dropbox_url(inURL)
    else:
        print(
            "--> Warning: Web host not specified or supported. URL is simply appended to standalone scene loader link."
        )
        convertURL = inURL
    # print("--> Your link: %s" % generate_viewer_url(convertURL))
    return generate_viewer_url(convertURL)


# pyvista/plotting/helpers.py

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

import numpy as np

import pyvista
from pyvista.utilities import is_pyvista_dataset

from .plotting import Plotter


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,
    use_ipyvtk=None,
    jupyter_backend=None,
    return_viewer=False,
    return_cpos=False,
    jupyter_kwargs=None,
    theme=None,
    hidden_line_removal=None,
    anti_aliasing=None,
    zoom=None,
    border=None,
    border_color='k',
    border_width=2.0,
    **kwargs,
):
    """Plot a PyVista, numpy, or vtk object.

    Parameters
    ----------
    var_item : pyvista.DataSet, vtk, or numpy object
        PyVista, VTK, or ``numpy`` object to be plotted.

    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, optional
        Opens window in full screen.  When enabled, ignores
        ``window_size``.  Defaults to active theme setting in
        :attr:`pyvista.global_theme.full_screen
        <pyvista.themes.DefaultTheme.full_screen>`.

    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, optional
        Allows user to pan and move figure.  Defaults to
        :attr:`pyvista.global_theme.interactive <pyvista.themes.DefaultTheme.interactive>`.

    cpos : list, optional
        List of camera position, focal point, and view up.

    window_size : list, optional
        Window size in pixels.  Defaults to global theme
        :attr:`pyvista.global_theme.window_size <pyvista.themes.DefaultTheme.window_size>`.

    show_bounds : bool, optional
        Shows mesh bounds when ``True``.  Default ``False``.

    show_axes : bool, optional
        Shows a vtk axes widget.  If ``None``, enabled according to
        :attr:`pyvista.global_theme.axes.show <pyvista.themes._AxesConfig.show>`.

    notebook : bool, optional
        When ``True``, the resulting plot is placed inline a jupyter
        notebook.  Assumes a jupyter console is active.

    background : color_like, optional
        Color of the background.

    text : str, optional
        Adds text at the bottom of the plot.

    return_img : bool, optional
        Returns numpy array of the last image rendered.

    eye_dome_lighting : bool, optional
        Enables eye dome lighting.

    volume : bool, optional
        Use the :func:`Plotter.add_volume()
        <pyvista.Plotter.add_volume>` method for volume rendering.

    parallel_projection : bool, optional
        Enable parallel projection.

    use_ipyvtk : bool, optional
        Deprecated.  Instead, set the backend either globally with
        ``pyvista.set_jupyter_backend('ipyvtklink')`` or with
        ``backend='ipyvtklink'``.

    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.
        * ``'ipygany'`` : Show a ``ipygany`` widget
        * ``'panel'`` : Show a ``panel`` widget.

        This can also be set globally with
        :func:`pyvista.set_jupyter_backend`.

    return_viewer : bool, optional
        Return the jupyterlab viewer, scene, or display object
        when plotting with jupyter notebook.

    return_cpos : bool, optional
        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.themes.DefaultTheme, optional
        Plot-specific theme.

    hidden_line_removal : bool, optional
        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>`.  Defaults to the
        theme setting :attr:`pyvista.global_theme.hidden_line_removal
        <pyvista.themes.DefaultTheme.hidden_line_removal>`.

    anti_aliasing : bool, optional
        Enable or disable anti-aliasing.  Defaults to the theme
        setting :attr:`pyvista.global_theme.antialiasing
        <pyvista.themes.DefaultTheme.antialiasing>`.

    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, optional
        Draw a border around each render window.  Default ``False``.

    border_color : color_like, 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'``

    border_width : float, optional
        Width of the border in pixels when enabled.

    **kwargs : optional keyword arguments
        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
        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
    UniformGrid. Note ``volume=True`` is passed.

    >>> import numpy as np
    >>> grid = pv.UniformGrid(dims=(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 = 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:
        pl.enable_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)
        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 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,
        use_ipyvtk=use_ipyvtk,
        jupyter_backend=jupyter_backend,
        before_close_callback=before_close_callback,
        jupyter_kwargs=jupyter_kwargs,
        return_viewer=return_viewer,
        return_cpos=return_cpos,
    )


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

    Parameters
    ----------
    cent : numpy.ndarray
        Accepts a single 3d point or array of 3d points.

    direction : numpy.ndarray
        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
    --------
    :func:`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 plot([cent, direction], **kwargs)


def plot_compare_four(
    data_a,
    data_b,
    data_c,
    data_d,
    disply_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.

    Plotting parameters and camera positions will all be the same.

    """
    datasets = [[data_a, data_b], [data_c, data_d]]
    labels = [labels[0:2], labels[2:4]]

    if plotter_kwargs is None:
        plotter_kwargs = {}
    if disply_kwargs is None:
        disply_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], **disply_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 plot_itk(mesh, color=None, scalars=None, opacity=1.0, smooth_shading=False):
    """Plot a PyVista/VTK mesh or dataset.

    Adds any PyVista/VTK mesh that itkwidgets can wrap to the
    scene.

    Parameters
    ----------
    mesh : pyvista.DataSet or pyvista.MultiBlock
        Any PyVista or VTK mesh is supported. Also, any dataset that
        :func:`pyvista.wrap` can handle including NumPy arrays of XYZ
        points.

    color : color_like, optional, defaults to white
        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.

    scalars : str or 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.

    opacity : float, optional
        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.  Default 1.0

    smooth_shading : bool, optional
        Smooth mesh surface mesh by taking into account surface
        normals.  Surface will appear smoother while sharp edges will
        still look sharp.  Default ``False``.

    Returns
    --------
    itkwidgets.Viewer
        ITKwidgets viewer.
    """
    pl = pyvista.PlotterITK()
    if isinstance(mesh, np.ndarray):
        pl.add_points(mesh, color)
    else:
        pl.add_mesh(mesh, color, scalars, opacity, smooth_shading)
    return pl.show()


# 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 ..utilities.helpers import vtkmatrix_from_array
from .colors import Color, color_like


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 : list or tuple, 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 : list or tuple, 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 : color_like, optional
        The color of the light. The ambient, diffuse and specular
        colors will all be set to this color on creation.

    light_type : str or int, optional
        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, optional
        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):
        """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):
        """Set the shadow intensity."""
        self.SetShadowAttenuation(value)

    @property
    def ambient_color(self):
        """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')

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

    @ambient_color.setter
    def ambient_color(self, color: color_like):
        """Set the ambient color of the light."""
        self.SetAmbientColor(Color(color).float_rgb)

    @property
    def diffuse_color(self):
        """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')

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

    @diffuse_color.setter
    def diffuse_color(self, color: color_like):
        """Set the diffuse color of the light."""
        self.SetDiffuseColor(Color(color).float_rgb)

    @property
    def specular_color(self):
        """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')

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

    @specular_color.setter
    def specular_color(self, color: color_like):
        """Set the specular color of the light."""
        self.SetSpecularColor(Color(color).float_rgb)

    @property
    def position(self):
        """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):
        """Set the position of the light."""
        self.SetPosition(pos)

    @property
    def world_position(self):
        """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):
        """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):
        """Set the focal point of the light."""
        self.SetFocalPoint(pos)

    @property
    def world_focal_point(self):
        """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):
        """Return 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):
        """Set the brightness of the light (between 0 and 1)."""
        self.SetIntensity(intensity)

    @property
    def on(self):
        """Return 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):
        """Set whether the light should be on."""
        self.SetSwitch(state)

    @property
    def positional(self):
        """Return 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):
        """Set whether the light should be positional."""
        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):
        """Return 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):
        """Set the exponent of the cosine used in positional lighting."""
        self.SetExponent(exp)

    @property
    def cone_angle(self):
        """Return 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):
        """Set the cone angle of a positional light."""
        if angle >= 90:
            self.hide_actor()
        self.SetConeAngle(angle)
        self._check_actor()

    @property
    def attenuation_values(self):
        """Return 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):
        """Set the quadratic attenuation constants."""
        self.SetAttenuationValues(values)

    @property
    def transform_matrix(self):
        """Return the transformation matrix of the light (if any).

        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):
        """Set the 4x4 transformation matrix of the light."""
        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):
        """Return 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``

        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):
        """Set the light type.

        Either an integer code or a class constant enum value must be used.

        """
        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):
        """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):
        """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):
        """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, optional
            Whether to return a deep copy rather than a shallow
            one. Default ``True``.

        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.

        """
        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):
        """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/mapper.py

"""An internal module for wrapping the use of mappers."""
import logging
import sys

import numpy as np

from pyvista import _vtk
from pyvista.utilities import convert_array, convert_string_array, raise_not_matching
from pyvista.utilities.misc import has_module

from .colors import Color, get_cmap_safe
from .tools import normalize


def make_mapper(mapper_class):
    """Wrap a mapper.

    This makes a mapper wrapped with a few convenient tools for managing
    mappers with scalar bars in a consistent way since not all mapper classes
    have scalar ranges and lookup tables.
    """

    class MapperHelper(mapper_class):
        """A helper that dynamically inherits the mapper's class."""

        def __init__(self, *args, **kwargs):
            self._scalar_range = None
            self._lut = None

        @property
        def scalar_range(self):
            if hasattr(self, 'GetScalarRange'):
                self._scalar_range = self.GetScalarRange()
            return self._scalar_range

        @scalar_range.setter
        def scalar_range(self, clim):
            if hasattr(self, 'SetScalarRange'):
                self.SetScalarRange(*clim)
            if self.lookup_table is not None:
                self.lookup_table.SetRange(*clim)
            self._scalar_range = clim

        @property
        def lookup_table(self):
            if hasattr(self, 'GetLookupTable'):
                self._lut = self.GetLookupTable()
            return self._lut

        @lookup_table.setter
        def lookup_table(self, lut):
            if hasattr(self, 'SetLookupTable'):
                self.SetLookupTable(lut)
            self._lut = lut

        def set_scalars(
            self,
            mesh,
            scalars,
            scalars_name,
            scalar_bar_args,
            rgb,
            component,
            preference,
            interpolate_before_map,
            _custom_opac,
            annotations,
            log_scale,
            nan_color,
            above_color,
            below_color,
            cmap,
            flip_scalars,
            opacity,
            categories,
            n_colors,
            clim,
            theme,
            show_scalar_bar,
        ):
            """Set the scalars on this mapper."""
            if cmap is None:  # Set default map if matplotlib is available
                if has_module('matplotlib'):
                    cmap = theme.cmap

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

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

            _using_labels = False
            if not np.issubdtype(scalars.dtype, np.number):
                # raise TypeError('Non-numeric scalars are currently not supported for plotting.')
                # TODO: If str array, digitive 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)
                _using_labels = True

            # 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 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 scalars.ndim != 1:
                if rgb:
                    pass
                elif scalars.ndim == 2 and (
                    scalars.shape[0] == mesh.n_points or scalars.shape[0] == mesh.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 = 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_)

            table = self.GetLookupTable()

            if _using_labels:
                table.SetAnnotations(convert_array(values), convert_string_array(cats))

            if isinstance(annotations, dict):
                for val, anno in annotations.items():
                    table.SetAnnotation(float(val), str(anno))

            # 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]]
                table.SetScaleToLog10()

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

            table.SetNanColor(Color(nan_color).float_rgba)
            if above_color:
                table.SetUseAboveRangeColor(True)
                table.SetAboveRangeColor(*Color(above_color).float_rgba)
                scalar_bar_args.setdefault('above_label', 'Above')
            if below_color:
                table.SetUseBelowRangeColor(True)
                table.SetBelowRangeColor(*Color(below_color).float_rgba)
                scalar_bar_args.setdefault('below_label', 'Below')

            if cmap is not None:
                # have to add the attribute to pass it onward to some classes
                if isinstance(cmap, str):
                    self.cmap = cmap
                # ipygany uses different colormaps
                if theme.jupyter_backend == 'ipygany':
                    from ..jupyter.pv_ipygany import check_colormap

                    check_colormap(cmap)
                else:
                    if not has_module('matplotlib'):
                        cmap = None
                        logging.warning('Please install matplotlib for color maps.')

                    cmap = get_cmap_safe(cmap)
                    if categories:
                        if categories is True:
                            n_colors = len(np.unique(scalars))
                        elif isinstance(categories, int):
                            n_colors = categories
                    ctable = cmap(np.linspace(0, 1, n_colors)) * 255
                    ctable = ctable.astype(np.uint8)
                    # Set opactities
                    if isinstance(opacity, np.ndarray) and not _custom_opac:
                        ctable[:, -1] = opacity
                    if flip_scalars:
                        ctable = np.ascontiguousarray(ctable[::-1])
                    table.SetTable(_vtk.numpy_to_vtk(ctable))
                    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 = cmap(scalars) * 255
                        scalars[:, -1] *= opacity
                        scalars = scalars.astype(np.uint8)

            else:  # no cmap specified
                if flip_scalars:
                    table.SetHueRange(0.0, 0.66667)
                else:
                    table.SetHueRange(0.66667, 0.0)

            self.configure_scalars_mode(
                scalars,
                mesh,
                scalars_name,
                n_colors,
                preference,
                interpolate_before_map,
                rgb or _custom_opac,
            )

            return show_scalar_bar, n_colors, clim

        def configure_scalars_mode(
            self,
            scalars,
            mesh,
            scalars_name,
            n_colors,
            preference,
            interpolate_before_map,
            direct_scalars_color_mode,
        ):
            """Configure scalar mode.

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

            mesh : pyvista.Dataset
                Dataset to assign the scalars to.

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

            n_colors : int
                Number of colors.

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

            interpolate_before_map : bool
                When ``True`` scalars will be interpolated within polygons and
                color mapping will happen on a per-pixel basis.  When
                ``False``, Colors are interpolated after being mapped. This
                option avoids color interpolation by using a one dimensional
                texture map for the colors.

            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] == mesh.n_points and scalars.shape[0] == mesh.n_cells:
                use_points = preference == 'point'
                use_cells = not use_points
            else:
                use_points = scalars.shape[0] == mesh.n_points
                use_cells = scalars.shape[0] == mesh.n_cells

            # Scalars interpolation approach
            if use_points:
                if scalars_name not in mesh.point_data:
                    mesh.point_data.set_array(scalars, scalars_name, False)
                mesh.active_scalars_name = scalars_name
                self.SetScalarModeToUsePointData()
            elif use_cells:
                if scalars_name not in mesh.cell_data:
                    mesh.cell_data.set_array(scalars, scalars_name, False)
                mesh.active_scalars_name = scalars_name
                self.SetScalarModeToUseCellData()
            else:
                raise_not_matching(scalars, mesh)

            self.GetLookupTable().SetNumberOfTableValues(n_colors)
            if interpolate_before_map:
                self.InterpolateScalarsBeforeMappingOn()
            if direct_scalars_color_mode:
                self.SetColorModeToDirectScalars()
            else:
                self.SetColorModeToMapScalars()

        def set_custom_opacity(
            self, opacity, color, mesh, n_colors, preference, interpolate_before_map, rgb, theme
        ):
            """Set custom opacity.

            Returns
            -------
            str or None
                If the scalars do not exist within the dataset, this is the
                name of the scalars array.

            str
                Association of the scalars, either ``'point'`` or ``'cell'``.

            """
            # create a custom RGBA array to supply our opacity to
            if opacity.size == mesh.n_points:
                rgba = np.empty((mesh.n_points, 4), np.uint8)
            elif opacity.size == mesh.n_cells:
                rgba = np.empty((mesh.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 ({mesh.n_points}) or the "
                    f"number of cells ({mesh.n_cells})."
                )

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

            self.SetColorModeToDirectScalars()
            return self.configure_scalars_mode(
                rgba, mesh, '', n_colors, preference, interpolate_before_map, True
            )

    return MapperHelper()


# pyvista/plotting/picking.py

"""Module managing picking events."""

from functools import partial
import logging
import weakref

import numpy as np

import pyvista
from pyvista import _vtk
from pyvista.utilities import try_callback


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.renderer
    picker.Pick(click_x, click_y, click_z, renderer)


class PickingHelper:
    """An internal class to hold picking related features."""

    def __init__(self, *args, **kwargs):
        """Initialize the picking helper."""
        super().__init__(*args, **kwargs)
        self.picked_cells = None
        self._picked_point = None
        self._picked_mesh = None
        self.picked_path = None
        self.picked_geodesic = None
        self.picked_horizon = None
        self._picking_left_clicking_observer = None
        self._picking_text = None
        self._picker = None

    def get_pick_position(self):
        """Get the pick position or area.

        Returns
        -------
        sequence
            Picked position or area as ``(x0, y0, x1, y1)``.

        """
        return self.renderer.get_pick_position()

    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,
        **kwargs,
    ):
        """Enable picking of a mesh.

        Parameters
        ----------
        callback : function, optional
            When input, calls this function after a selection is made. The
            ``mesh`` is input as the first parameter to this function.

        show : bool, optional
            Show the selection interactively. Best when combined with
            ``left_clicking``.

        show_message : bool or str, optional
            Show the message about how to use the mesh picking tool. If this
            is a string, that will be the message shown.

        style : str, optional
            Visualization style of the selection.  Defaults to
            ``'wireframe'``. One of the following:

            * ``'surface'``
            * ``'wireframe'``
            * ``'points'``

        line_width : float, optional
            Thickness of selected mesh edges. Default 5.

        color : color_like, optional
            The color of the selected mesh when shown.

        font_size : int, optional
            Sets the font size of the message.

        left_clicking : bool, optional
            When ``True``, meshes can be picked by clicking the left
            mousebutton.  Default to ``False``.

            .. note::
               If enabled, left-clicking will **not** display the bounding box
               around the picked point.

        **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(left_clicking=True)

        See :ref:`mesh_picking_example` for a full example using this method.

        """

        def end_pick_call_back(picked, event):
            is_valid_selection = False
            self_ = weakref.ref(self)

            actor = picked.GetActor()
            if actor:
                mesh = actor.GetMapper().GetInput()
                is_valid_selection = True

            if is_valid_selection:
                self_()._picked_mesh = mesh

            if callback and is_valid_selection:
                try_callback(callback, mesh)

            if show and is_valid_selection:

                # Select the renderer where the mesh is added.
                active_renderer_index = self_().renderers._active_index
                for index in range(len(self.renderers)):
                    renderer = self.renderers[index]
                    for actor in renderer._actors.values():
                        mapper = actor.GetMapper()
                        if isinstance(mapper, _vtk.vtkDataSetMapper) and mapper.GetInput() == mesh:
                            loc = self_().renderers.index_to_loc(index)
                            self_().subplot(*loc)
                            break

                # Use try in case selection is empty or invalid
                try:
                    self_().add_mesh(
                        mesh,
                        name='_mesh_picking_selection',
                        style=style,
                        color=color,
                        line_width=line_width,
                        pickable=False,
                        reset_camera=False,
                        **kwargs,
                    )
                except Exception as e:  # pragma: no cover
                    logging.warning("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()
            elif not is_valid_selection:
                self.remove_actor('_mesh_picking_selection')
                self_()._picked_mesh = None

        # add on-screen message about point-selection
        if show_message:
            if show_message is True:
                show_message = "\nPress P to pick a single dataset under the mouse pointer."
                if left_clicking:
                    show_message += "\nor click to select a dataset under the mouse pointer."

            self._picking_text = self.add_text(
                str(show_message), font_size=font_size, name='_mesh_picking_message'
            )

        if left_clicking:
            self._picking_left_clicking_observer = self.iren.interactor.AddObserver(
                "LeftButtonPressEvent",
                partial(try_callback, _launch_pick_event),
            )

        self._picker = _vtk.vtkPropPicker()
        self._picker.AddObserver(_vtk.vtkCommand.EndPickEvent, end_pick_call_back)
        self.enable_trackball_style()
        self.iren.set_picker(self._picker)
        return self._picker

    def enable_cell_picking(
        self,
        mesh=None,
        callback=None,
        through=True,
        show=True,
        show_message=True,
        style='wireframe',
        line_width=5,
        color='pink',
        font_size=18,
        start=False,
        **kwargs,
    ):
        """Enable picking at cells.

        Press ``"r"`` to enable retangle based selection.  Press
        ``"r"`` again to turn it off. Selection will be saved to
        ``self.picked_cells``. Also press ``"p"`` to pick a single
        cell under the mouse location.

        When using ``through=False``, and multiple cells 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
        ----------
        mesh : pyvista.DataSet, optional
            Mesh to select cells from. When ``through`` is ``True``,
            uses last input mesh by default. When ``through`` is
            ``False``, all meshes in the scene are available for
            picking and this argument is ignored. 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.

        callback : function, optional
            When input, calls this function after a selection is made.
            The picked_cells are input as the first parameter to this
            function.

        through : bool, optional
            When ``True`` (default) the picker will select all cells
            through the mesh. When ``False``, the picker will select
            only visible cells on the mesh's surface.

        show : bool, optional
            Show the selection interactively.

        show_message : bool or str, optional
            Show the message about how to use the cell picking tool. If this
            is a string, that will be the message shown.

        style : str, optional
            Visualization style of the selection.  One of the
            following: ``style='surface'``, ``style='wireframe'``, or
            ``style='points'``.  Defaults to ``'wireframe'``.

        line_width : float, optional
            Thickness of selected mesh edges. Default 5.

        color : color_like, optional
            The color of the selected mesh when shown.

        font_size : int, optional
            Sets the font size of the message.

        start : bool, optional
            Automatically start the cell selection tool.

        **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(left_clicking=True)

        """
        if mesh is None:
            if not hasattr(self, 'mesh') or self.mesh is None:
                raise AttributeError(
                    'Input a mesh into the Plotter class first or or set it in this function'
                )
            mesh = self.mesh
        self_ = weakref.ref(self)

        # make sure to consistently use renderer
        renderer_ = weakref.ref(self.renderer)

        def end_pick_helper(picker, event_id):
            # Merge the selection into a single mesh
            picked = self_().picked_cells
            if isinstance(picked, pyvista.MultiBlock):
                if picked.n_blocks > 0:
                    picked = picked.combine()
                else:
                    picked = pyvista.UnstructuredGrid()
            # Check if valid
            is_valid_selection = picked.n_cells > 0

            if show and is_valid_selection:
                # Select the renderer where the mesh is added.
                active_renderer_index = self_().renderers._active_index
                for index in range(len(self.renderers)):
                    renderer = self.renderers[index]
                    for actor in renderer._actors.values():
                        mapper = actor.GetMapper()
                        if isinstance(mapper, _vtk.vtkDataSetMapper) and mapper.GetInput() == mesh:
                            loc = self_().renderers.index_to_loc(index)
                            self_().subplot(*loc)
                            break

                # Use try in case selection is empty
                self_().add_mesh(
                    picked,
                    name='_cell_picking_selection',
                    style=style,
                    color=color,
                    line_width=line_width,
                    pickable=False,
                    reset_camera=False,
                    **kwargs,
                )

                # 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()
            elif not is_valid_selection:
                self.remove_actor('_cell_picking_selection')
                self_().picked_cells = None

            if callback is not None:
                try_callback(callback, self_().picked_cells)

            # TODO: Deactivate selection tool
            return

        def through_pick_call_back(picker, event_id):
            extract = _vtk.vtkExtractGeometry()
            mesh.cell_data['orig_extract_id'] = np.arange(mesh.n_cells)
            extract.SetInputData(mesh)
            extract.SetImplicitFunction(picker.GetFrustum())
            extract.Update()
            self_().picked_cells = pyvista.wrap(extract.GetOutput())
            return end_pick_helper(picker, event_id)

        def visible_pick_call_back(picker, event_id):
            picked = pyvista.MultiBlock()
            x0, y0, x1, y1 = renderer_().get_pick_position()
            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())

                    # if not a surface
                    if actor.GetProperty().GetRepresentation() != 2:  # pragma: no cover
                        logging.warning(
                            "Display representations other than `surface` will result in incorrect results."
                        )
                    smesh = 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) == 1:
                self_().picked_cells = picked[0]
            else:
                self_().picked_cells = picked
            return end_pick_helper(picker, event_id)

        self._picker = _vtk.vtkRenderedAreaPicker()
        if through:
            self._picker.AddObserver(_vtk.vtkCommand.EndPickEvent, through_pick_call_back)
        else:
            # NOTE: there can be issues with non-triangulated meshes
            # Reference:
            #     https://github.com/pyvista/pyvista/issues/277
            #     https://github.com/pyvista/pyvista/pull/281
            #     https://discourse.vtk.org/t/visible-cell-selection-hardwareselector-py-example-is-not-working-reliably/1262
            self._picker.AddObserver(_vtk.vtkCommand.EndPickEvent, visible_pick_call_back)

        self.enable_rubber_band_style()
        self.iren.set_picker(self._picker)

        # Now add text about cell-selection
        if show_message:
            if show_message is True:
                show_message = "Press R to toggle selection tool"
                if not through:
                    show_message += "\nPress P to pick a single cell under the mouse"
            self._picking_text = self.add_text(
                str(show_message), font_size=font_size, name='_cell_picking_message'
            )

        if start:
            self.iren._style_class.StartSelect()

    @property
    def picked_mesh(self):
        """Return the picked mesh.

        This returns the picked mesh after selecting a mesh with
        :func:`<enable_mesh_picking> pyvista.Plotter.enable_mesh_picking` or
        :func:`<enable_point_picking> pyvista.Plotter.enable_point_picking`.

        Returns
        -------
        pyvista.DataSet or None
            Picked mesh if available.

        """
        return self._picked_mesh

    @property
    def picked_point(self):
        """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 enable_surface_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,
        **kwargs,
    ):
        """Enable picking of a point on the surface of a mesh.

        Parameters
        ----------
        callback : function, optional
            When input, calls this function after a selection is made. The
            ``mesh`` is input as the first parameter to this function.

        show_message : bool or str, optional
            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, optional
            Sets the font size of the message.

        color : color_like, optional
            The color of the selected mesh when shown.

        show_point : bool, optional
            Show the selection interactively. Default ``True``.

        point_size : int, optional
            Size of picked points if ``show_point`` is
            ``True``. Default 10.

        tolerance : float, optional
            Specify tolerance for performing pick operation. Tolerance
            is specified as fraction of rendering window
            size. Rendering window size is measured across diagonal.

        pickable_window : bool, optional
            When ``True``, points in the 3D window are pickable. Default to ``False``.

        left_clicking : bool, optional
            When ``True``, meshes can be picked by clicking the left
            mousebutton.  Default to ``False``.

            .. note::
               If enabled, left-clicking will **not** display the bounding box
               around the picked mesh.

        **kwargs : dict, optional
            All remaining keyword arguments are used to control how
            the picked path is interactively displayed.

        Returns
        -------
        vtk.vtkPropPicker
            Property picker.

        Notes
        -----
        Picked point can be accessed from :attr:`picked_point
        <PickingHelper.picked_point>` attribute.

        Examples
        --------
        Add a cube to a plot and enable cell 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
        >>> cube = pv.Cube()
        >>> pl = pv.Plotter()
        >>> _ = pl.add_mesh(cube)
        >>> _ = pl.enable_surface_picking(left_clicking=True)

        See :ref:`surface_picking_example` for a full example using this method.

        """

        def _end_pick_event(picker, event):

            picked_point_id = picker.GetPointId()
            if not pickable_window and picked_point_id < 0:
                self._picked_point = None
                return

            self._picked_point = np.array(picker.GetPickPosition())
            self._picked_mesh = picker.GetDataSet()
            if show_point:
                self.add_mesh(
                    self.picked_point,
                    color=color,
                    point_size=point_size,
                    name='_picked_point',
                    pickable=False,
                    reset_camera=False,
                    **kwargs,
                )
            if callable(callback):
                try_callback(callback, self.picked_point)

        picker = _vtk.vtkCellPicker()
        picker.SetTolerance(tolerance)
        self._picker = picker
        picker.AddObserver(_vtk.vtkCommand.EndPickEvent, _end_pick_event)

        self.enable_trackball_style()
        self.iren.set_picker(picker)

        if left_clicking:
            self._picking_left_clicking_observer = self.iren.interactor.AddObserver(
                "LeftButtonPressEvent",
                partial(try_callback, _launch_pick_event),
            )

        # add on-screen message about point-selection
        if show_message:
            if show_message is True:
                show_message = "\nPress P to pick a point on the surface under the mouse pointer."
                if left_clicking:
                    show_message += "\nor click to select a point under the mouse pointer."

            self._picking_text = self.add_text(
                str(show_message), font_size=font_size, name='_surf_picking_message'
            )

        return picker

    def enable_point_picking(
        self,
        callback=None,
        show_message=True,
        font_size=18,
        color='pink',
        point_size=10,
        use_mesh=False,
        show_point=True,
        tolerance=0.025,
        pickable_window=False,
        left_clicking=False,
        **kwargs,
    ):
        """Enable picking at points.

        Enable picking a point at the mouse location in the render
        view using the ``P`` key. This point is saved to the
        ``.picked_point`` attribute on the plotter. Pass a callback
        function 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.

        Parameters
        ----------
        callback : callable, optional
            When input, calls this function after a pick is made.  The
            picked point is input as the first parameter to this
            function.  If ``use_mesh`` is ``True``, the callback
            function will be passed a pointer to the picked mesh and
            the point ID of the selected mesh.

        show_message : bool or str, optional
            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, optional
            Sets the size of the message.

        color : color_like, optional
            The color of the selected mesh when shown.

        point_size : int, optional
            Size of picked points if ``show_point`` is
            ``True``. Default 10.

        use_mesh : bool, optional
            If ``True``, the callback function will be passed a
            pointer to the picked mesh and the point ID of the
            selected mesh.

        show_point : bool, optional
            Show the picked point after clicking.

        tolerance : float, optional
            Specify tolerance for performing pick operation. Tolerance
            is specified as fraction of rendering window
            size. Rendering window size is measured across diagonal.

        pickable_window : bool, optional
            When ``True``, points in the 3D window are pickable. Default to ``False``.

        left_clicking : bool, optional
            When ``True``, points can be picked by clicking the left mousebutton.
            Default to ``False``. Note, if enabled, left-clicking will **not**
            display the bounding box around the picked mesh.

        **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="Press P to pick")

        See :ref:`point_picking_example` for a full example using this method.

        """

        def _end_pick_event(picker, event):

            picked_point_id = picker.GetPointId()
            if (not pickable_window) and (picked_point_id < 0):
                return None

            self._picked_point = np.array(picker.GetPickPosition())
            self._picked_mesh = picker.GetDataSet()
            self.picked_point_id = picked_point_id
            if show_point:
                self.add_mesh(
                    self.picked_point,
                    color=color,
                    point_size=point_size,
                    name='_picked_point',
                    pickable=False,
                    reset_camera=False,
                    **kwargs,
                )
            if callable(callback):
                if use_mesh:
                    try_callback(callback, self.picked_mesh, self.picked_point_id)
                else:
                    try_callback(callback, self.picked_point)

        point_picker = _vtk.vtkPointPicker()
        point_picker.SetTolerance(tolerance)
        self._picker = point_picker
        point_picker.AddObserver(_vtk.vtkCommand.EndPickEvent, _end_pick_event)

        self.enable_trackball_style()
        self.iren.set_picker(point_picker)

        if left_clicking:
            self._picking_left_clicking_observer = self.iren.add_observer(
                "LeftButtonPressEvent",
                partial(try_callback, _launch_pick_event),
            )

        # Now add text about cell-selection
        if show_message:
            if show_message is True and left_clicking:
                show_message = "Left-click or press P to pick under the mouse"
            elif show_message is True:
                show_message = "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_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
        <PickingHelper.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 function after a pick is made.  The
            entire picked path is passed as the only parameter to this
            function.

        show_message : bool or str, optional
            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, optional
            Sets the size of the message.

        color : color_like, optional
            The color of the selected mesh when shown.

        point_size : int, optional
            Size of picked points if ``show_path`` is
            ``True``. Default 10.

        line_width : float, optional
            Thickness of path representation if ``show_path`` is
            ``True``.  Default 5.

        show_path : bool, optional
            Show the picked path interactively.

        tolerance : float, optional
            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.

        """
        kwargs.setdefault('pickable', False)

        def make_line_cells(n_points):
            cells = np.arange(0, n_points, dtype=np.int_)
            cells = np.insert(cells, 0, n_points)
            return cells

        the_points = []
        the_ids = []

        def _the_callback(mesh, idx):
            if mesh is None:
                return
            the_ids.append(idx)
            the_points.append(mesh.points[idx])
            self.picked_path = pyvista.PolyData(np.array(the_points))
            self.picked_path.lines = make_line_cells(len(the_points))
            if show_path:
                self.add_mesh(
                    self.picked_path,
                    color=color,
                    name='_picked_path',
                    line_width=line_width,
                    point_size=point_size,
                    reset_camera=False,
                    **kwargs,
                )
            if callable(callback):
                try_callback(callback, self.picked_path)

        def _clear_path_event_watcher():
            del the_points[:]
            del the_ids[:]
            self.remove_actor('_picked_path')

        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_point_picking(
            callback=_the_callback,
            use_mesh=True,
            font_size=font_size,
            show_message=show_message,
            show_point=False,
            tolerance=tolerance,
        )

    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 function after a pick is made.  The
            entire picked, geodesic path is passed as the only
            parameter to this function.

        show_message : bool or str, optional
            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, optional
            Sets the size of the message.

        color : color_like, optional
            The color of the selected mesh when shown.

        point_size : int, optional
            Size of picked points if ``show_path`` is
            ``True``. Default 10.

        line_width : float, optional
            Thickness of path representation if ``show_path`` is
            ``True``.  Default 5.

        tolerance : float, optional
            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, optional
            Show the picked path interactively.

        keep_order : bool, optional
            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.

        """
        kwargs.setdefault('pickable', False)

        self.picked_geodesic = pyvista.PolyData()
        self._last_picked_idx = None

        def _the_callback(mesh, idx):
            if mesh is None:
                return
            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:
                self.add_mesh(
                    self.picked_geodesic,
                    color=color,
                    name='_picked_path',
                    line_width=line_width,
                    point_size=point_size,
                    reset_camera=False,
                    **kwargs,
                )
            if callable(callback):
                try_callback(callback, self.picked_geodesic)

        def _clear_g_path_event_watcher():
            self.picked_geodesic = pyvista.PolyData()
            self.remove_actor('_picked_path')
            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_point_picking(
            callback=_the_callback,
            use_mesh=True,
            font_size=font_size,
            show_message=show_message,
            tolerance=tolerance,
            show_point=False,
        )

    def enable_horizon_picking(
        self,
        callback=None,
        normal=(0, 0, 1),
        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 function after a pick is made.  The
            entire picked path is passed as the only parameter to this
            function.

        normal : tuple(float), optional
            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 or str, optional
            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, optional
            Sets the font size of the message.

        color : color_like, optional
            The color of the horizon surface if shown.

        point_size : int, optional
            Size of picked points if ``show_horizon`` is
            ``True``. Default 10.

        line_width : float, optional
            Thickness of path representation if ``show_horizon`` is
            ``True``.  Default 5.

        show_path : bool, optional
            Show the picked path that the horizon is built from
            interactively.

        opacity : float, optional
            The opacity of the horizon surface if shown.

        show_horizon : bool, optional
            Show the picked horizon surface interactively.

        **kwargs : dict, optional
            All remaining keyword arguments are used to control how
            the picked path is interactively displayed.

        """
        name = '_horizon'
        self.add_key_event('c', lambda: self.remove_actor(name))

        def _the_callback(path):
            if path.n_points < 2:
                self.remove_actor(name)
                return
            self.picked_horizon = path.ribbon(normal=normal, width=width)

            if show_horizon:
                self.add_mesh(
                    self.picked_horizon,
                    name=name,
                    color=color,
                    opacity=opacity,
                    pickable=False,
                    reset_camera=False,
                )

            if callable(callback):
                try_callback(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,
        )

    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()
        picker = _vtk.vtkWorldPointPicker()
        picker.Pick(self.click_position[0], self.click_position[1], 0, self.renderer)
        return 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()
        picker = _vtk.vtkWorldPointPicker()
        picker.Pick(self.mouse_position[0], self.mouse_position[1], 0, self.renderer)
        return picker.GetPickPosition()

    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 function to call immediately after right
            clicking.

        """

        def _the_callback(*args):
            click_point = self.pick_mouse_position()
            self.fly_to(click_point)
            if callable(callback):
                try_callback(callback, click_point)

        self.track_click_position(callback=_the_callback, side="right")

    def disable_picking(self):
        """Disable any active picking.

        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(left_clicking=True)
        >>> pl.disable_picking()

        """
        if getattr(self, '_picker', None):
            self._picker.RemoveObservers(_vtk.vtkCommand.EndPickEvent)

        # remove left clicking observer if available
        if getattr(self, 'iren', None):
            self.iren.remove_observer(self._picking_left_clicking_observer)
        self._picking_left_clicking_observer = None

        # remove any picking text
        if hasattr(self, 'renderers'):
            self.remove_actor(self._picking_text)
        self._picking_text = None


# pyvista/plotting/plotting.py

"""PyVista plotting module."""
import collections.abc
import ctypes
from functools import wraps
import io
import logging
import os
import pathlib
import platform
import textwrap
from threading import Thread
import time
from typing import Dict
import warnings
import weakref

import numpy as np
import scooby

import pyvista
from pyvista import _vtk
from pyvista.utilities import (
    FieldAssociation,
    abstract_class,
    assert_empty_kwargs,
    convert_array,
    get_array,
    get_array_association,
    is_pyvista_dataset,
    numpy_to_texture,
    raise_not_matching,
    wrap,
)

from ..utilities.misc import PyvistaDeprecationWarning, has_module, uses_egl
from ..utilities.regression import image_from_window
from ._plotting import prepare_smooth_shading, process_opacity
from .colors import Color, get_cmap_safe
from .export_vtkjs import export_plotter_vtkjs
from .mapper import make_mapper
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 .tools import FONTS, normalize, opacity_transfer_function, parse_font_family  # noqa
from .widgets import WidgetHelper

SUPPORTED_FORMATS = [".png", ".jpeg", ".jpg", ".bmp", ".tif", ".tiff"]
VERY_FIRST_RENDER = True  # windows plotter helper


# 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 _, p in _ALL_PLOTTERS.items():
        if not p._closed:
            p.close()
        p.deep_clean()
    _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 ['ipygany', 'pythreejs']:
            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'
        )


USE_SCALAR_BAR_ARGS = """
"stitle" is a depreciated keyword and will be removed in a future
release.

Use ``scalar_bar_args`` instead.  For example:

scalar_bar_args={'title': 'Scalar Bar Title'}
"""


@abstract_class
class BasePlotter(PickingHelper, WidgetHelper):
    """To be used by the Plotter and pyvistaqt.QtInteractor classes.

    Parameters
    ----------
    shape : list or tuple, 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 renderer.
        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.  Default ``False``.

    border_color : color_like, 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'``

    border_width : float, optional
        Width of the border in pixels when enabled.

    title : str, optional
        Window title of the scalar bar

    lighting : str, optional
        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.

        The default is a Light Kit (to be precise, 5 separate lights
        that act like a Light Kit).

    theme : pyvista.themes.DefaultTheme, optional
        Plot-specific theme.

    """

    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,
        **kwargs,
    ):
        """Initialize base plotter."""
        super().__init__(**kwargs)  # cooperative multiple inheritance
        log.debug('BasePlotter init start')
        self._initialized = False

        self._theme = pyvista.themes.DefaultTheme()
        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.themes.DefaultTheme):
                raise TypeError(
                    'Expected ``pyvista.themes.DefaultTheme`` 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._store_image = False
        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

        # 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}".')

        # Add self to open plotters
        self._id_name = f"{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._has_background_layer = False

        # set hidden line removal based on theme
        if self.theme.hidden_line_removal:
            self.enable_hidden_line_removal()

        # set antialiasing based on theme
        if self.theme.antialiasing:
            self.enable_anti_aliasing()

        self._initialized = True

    @property
    def theme(self):
        """Return or set the theme used for 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):
        if not isinstance(theme, pyvista.themes.DefaultTheme):
            raise TypeError(
                'Expected a pyvista theme like '
                '``pyvista.themes.DefaultTheme``, '
                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, optional
            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.

        """
        if not _vtk.VTK9:  # pragma: no cover
            from pyvista.core.errors import VTKVersionError

            raise VTKVersionError('Support for glTF requires VTK v9 or newer')

        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.ren_win)
        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.

        """
        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 = _vtk.lazy_vtkVRMLImporter()
        importer.SetFileName(filename)
        importer.SetRenderWindow(self.ren_win)
        importer.Update()

    def export_html(self, filename, backend='pythreejs'):
        """Export this plotter as an interactive scene to a HTML file.

        You have the option of exposing the scene using either vtk.js (using
        ``panel``) or three.js (using ``pythreejs``), both of which are
        excellent JavaScript libraries to visualize small to moderately complex
        scenes for scientific visualization.

        Parameters
        ----------
        filename : str
            Path to export the html file to.

        backend : str, optional
            One of the following:

            - ``'pythreejs'``
            - ``'panel'``

            For more details about the advantages and disadvantages of each
            backend, see :ref:`jupyter_plotting`.

        Notes
        -----
        You will need ``ipywidgets`` and ``pythreejs`` installed if you
        wish to export using the ``'pythreejs'`` backend, or ``'panel'``
        installed to export using ``'panel'``.

        Examples
        --------
        Export as a three.js scene using the pythreejs backend.

        >>> 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

        Export as a vtk.js scene using the panel backend.

        >>> pl.export_html('pyvista_panel.html', backend='panel')  # doctest:+SKIP

        """
        if backend == 'pythreejs':
            widget = self.to_pythreejs()
        elif backend == 'panel':
            self._save_panel(filename)
            return
        else:
            raise ValueError(f"Invalid backend {backend}. Should be either 'panel' or 'pythreejs'")
        widget = self.to_pythreejs()

        # import after converting as we check for pythreejs import first
        try:
            from ipywidgets.embed import dependency_state, embed_minimal_html
        except ImportError:  # pragma: no cover
            raise ImportError('Please install ipywidgets with:\n\n\tpip install ipywidgets')

        # Garbage collection for embedded html output:
        # https://github.com/jupyter-widgets/pythreejs/issues/217
        state = dependency_state(widget)

        # convert and write to file
        embed_minimal_html(filename, None, title=self.title, state=state)

    def _save_panel(self, filename):
        """Save the render window as a ``panel.pane.vtk`` html file.

        See https://panel.holoviz.org/api/panel.pane.vtk.html

        Parameters
        ----------
        filename : str
            Path to export the plotter as a panel scene to.

        """
        from ..jupyter.notebook import handle_plotter

        pane = handle_plotter(self, backend='panel', return_viewer=True, title=self.title)
        pane.save(filename)

    def to_pythreejs(self):
        """Convert this plotting scene to a pythreejs widget.

        Returns
        -------
        ipywidgets.Widget
            Widget containing pythreejs renderer.

        """
        self._on_first_render_request()  # set up camera
        from pyvista.jupyter.pv_pythreejs import convert_plotter

        return convert_plotter(self)

    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, optional
            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, optional
            Rotate scene to be compatible with the glTF specifications.

        save_normals : bool, optional
            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 not _vtk.VTK9:  # pragma: no cover
            from pyvista.core.errors import VTKVersionError

            raise VTKVersionError('Support for glTF requires VTK v9 or newer')

        if not hasattr(self, "ren_win"):
            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.GetInputAsDataSet()
                            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.ren_win)
        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

        """
        if not hasattr(self, "ren_win"):
            raise RuntimeError("This plotter has been closed and cannot be shown.")

        exporter = _vtk.lazy_vtkVRMLExporter()
        exporter.SetFileName(filename)
        exporter.SetRenderWindow(self.ren_win)
        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
        <BasePlotter.disable_hidden_line_removal>`

        Parameters
        ----------
        all_renderers : bool
            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
        <BasePlotter.enable_hidden_line_removal>`

        Parameters
        ----------
        all_renderers : bool
            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):
        """First scalar bar.  Kept for backwards compatibility."""
        return list(self.scalar_bars.values())[0]

    @property
    def scalar_bars(self):
        """Scalar bars.

        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']  # doctest:+SKIP
        (vtkmodules.vtkRenderingAnnotation.vtkScalarBarActor)0x7fcd3567ca00

        """
        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):
        """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):
        """Return the active renderer.

        Examples
        --------
        >>> import pyvista
        >>> pl = pyvista.Plotter()
        >>> pl.renderer  # doctest:+SKIP
        (Renderer)0x7f916129bfa0

        """
        return self.renderers.active_renderer

    @property
    def store_image(self):
        """Store last rendered frame on close.

        This is normally disabled to avoid caching the image, and is
        enabled by default by setting:

        ``pyvista.BUILDING_GALLERY = True``

        Examples
        --------
        >>> import pyvista
        >>> pl = pyvista.Plotter(off_screen=True)
        >>> pl.store_image = True
        >>> _ = pl.add_mesh(pyvista.Cube())
        >>> pl.show()
        >>> image = pl.last_image
        >>> type(image)  # doctest:+SKIP
        <class 'numpy.ndarray'>

        """
        return self._store_image

    @store_image.setter
    def store_image(self, value):
        """Store last rendered frame on close."""
        self._store_image = bool(value)

    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
            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_legend)
    def add_legend(self, *args, **kwargs):
        """Wrap ``Renderer.add_legend``."""
        return self.renderer.add_legend(*args, **kwargs)

    @wraps(Renderer.remove_legend)
    def remove_legend(self, *args, **kwargs):
        """Wrap ``Renderer.remove_legend``."""
        return self.renderer.remove_legend(*args, **kwargs)

    @property
    def legend(self):
        """Legend actor.

        There can only be one legend actor per renderer.  If
        ``legend`` is ``None``, there is no legend actor.

        """
        return self.renderer.legend

    @wraps(Renderer.add_floor)
    def add_floor(self, *args, **kwargs):
        """Wrap ``Renderer.add_floor``."""
        return self.renderer.add_floor(*args, **kwargs)

    @wraps(Renderer.remove_floors)
    def remove_floors(self, *args, **kwargs):
        """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
            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 depreciated."""
        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

        This will replace all pre-existing lights in the renderer.

        Parameters
        ----------
        only_active : bool
            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()

    @wraps(Renderer.enable_anti_aliasing)
    def enable_anti_aliasing(self, *args, **kwargs):
        """Wrap ``Renderer.enable_anti_aliasing``."""
        for renderer in self.renderers:
            renderer.enable_anti_aliasing(*args, **kwargs)

    @wraps(Renderer.disable_anti_aliasing)
    def disable_anti_aliasing(self, *args, **kwargs):
        """Wrap ``Renderer.disable_anti_aliasing``."""
        self.renderer.disable_anti_aliasing(*args, **kwargs)

    @wraps(Renderer.set_focus)
    def set_focus(self, *args, render=True, **kwargs):
        """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):
        """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):
        """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):
        """Wrap ``Renderer.add_orientation_widget``."""
        return self.renderer.add_orientation_widget(*args, **kwargs)

    @wraps(Renderer.add_axes)
    def add_axes(self, *args, **kwargs):
        """Wrap ``Renderer.add_axes``."""
        return self.renderer.add_axes(*args, **kwargs)

    @wraps(Renderer.hide_axes)
    def hide_axes(self, *args, **kwargs):
        """Wrap ``Renderer.hide_axes``."""
        return self.renderer.hide_axes(*args, **kwargs)

    @wraps(Renderer.show_axes)
    def show_axes(self, *args, **kwargs):
        """Wrap ``Renderer.show_axes``."""
        return self.renderer.show_axes(*args, **kwargs)

    @wraps(Renderer.update_bounds_axes)
    def update_bounds_axes(self, *args, **kwargs):
        """Wrap ``Renderer.update_bounds_axes``."""
        return self.renderer.update_bounds_axes(*args, **kwargs)

    @wraps(Renderer.add_chart)
    def add_chart(self, *args, **kwargs):
        """Wrap ``Renderer.add_chart``."""
        return self.renderer.add_chart(*args, **kwargs)

    @wraps(Renderer.remove_chart)
    def remove_chart(self, *args, **kwargs):
        """Wrap ``Renderer.remove_chart``."""
        return self.renderer.remove_chart(*args, **kwargs)

    @wraps(Renderer.add_actor)
    def add_actor(self, *args, **kwargs):
        """Wrap ``Renderer.add_actor``."""
        return self.renderer.add_actor(*args, **kwargs)

    @wraps(Renderer.enable_parallel_projection)
    def enable_parallel_projection(self, *args, **kwargs):
        """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):
        """Wrap ``Renderer.disable_parallel_projection``."""
        return self.renderer.disable_parallel_projection(*args, **kwargs)

    @wraps(Renderer.enable_shadows)
    def enable_shadows(self, *args, **kwargs):
        """Wrap ``Renderer.enable_shadows``."""
        return self.renderer.enable_shadows(*args, **kwargs)

    @wraps(Renderer.disable_shadows)
    def disable_shadows(self, *args, **kwargs):
        """Wrap ``Renderer.disable_shadows``."""
        return self.renderer.disable_shadows(*args, **kwargs)

    @property
    def parallel_projection(self):
        """Return parallel projection state of active render window."""
        return self.renderer.parallel_projection

    @parallel_projection.setter
    def parallel_projection(self, state):
        """Set parallel projection state of all active render windows."""
        self.renderer.parallel_projection = state

    @property
    def parallel_scale(self):
        """Return parallel scale of active render window."""
        return self.renderer.parallel_scale

    @parallel_scale.setter
    def parallel_scale(self, value):
        """Set parallel scale of all active render windows."""
        self.renderer.parallel_scale = value

    @wraps(Renderer.add_axes_at_origin)
    def add_axes_at_origin(self, *args, **kwargs):
        """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):
        """Wrap ``Renderer.show_bounds``."""
        return self.renderer.show_bounds(*args, **kwargs)

    @wraps(Renderer.add_bounding_box)
    def add_bounding_box(self, *args, **kwargs):
        """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):
        """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):
        """Wrap ``Renderer.remove_bounds_axes``."""
        return self.renderer.remove_bounds_axes(*args, **kwargs)

    @wraps(Renderer.show_grid)
    def show_grid(self, *args, **kwargs):
        """Wrap ``Renderer.show_grid``."""
        return self.renderer.show_grid(*args, **kwargs)

    @wraps(Renderer.set_scale)
    def set_scale(self, *args, **kwargs):
        """Wrap ``Renderer.set_scale``."""
        return self.renderer.set_scale(*args, **kwargs)

    @wraps(Renderer.enable_eye_dome_lighting)
    def enable_eye_dome_lighting(self, *args, **kwargs):
        """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):
        """Wrap ``Renderer.disable_eye_dome_lighting``."""
        self.renderer.disable_eye_dome_lighting(*args, **kwargs)

    @wraps(Renderer.reset_camera)
    def reset_camera(self, *args, **kwargs):
        """Wrap ``Renderer.reset_camera``."""
        self.renderer.reset_camera(*args, **kwargs)
        self.render()

    @wraps(Renderer.isometric_view)
    def isometric_view(self, *args, **kwargs):
        """Wrap ``Renderer.isometric_view``."""
        self.renderer.isometric_view(*args, **kwargs)

    @wraps(Renderer.view_isometric)
    def view_isometric(self, *args, **kwarg):
        """Wrap ``Renderer.view_isometric``."""
        self.renderer.view_isometric(*args, **kwarg)

    @wraps(Renderer.view_vector)
    def view_vector(self, *args, **kwarg):
        """Wrap ``Renderer.view_vector``."""
        self.renderer.view_vector(*args, **kwarg)

    @wraps(Renderer.view_xy)
    def view_xy(self, *args, **kwarg):
        """Wrap ``Renderer.view_xy``."""
        self.renderer.view_xy(*args, **kwarg)

    @wraps(Renderer.view_yx)
    def view_yx(self, *args, **kwarg):
        """Wrap ``Renderer.view_yx``."""
        self.renderer.view_yx(*args, **kwarg)

    @wraps(Renderer.view_xz)
    def view_xz(self, *args, **kwarg):
        """Wrap ``Renderer.view_xz``."""
        self.renderer.view_xz(*args, **kwarg)

    @wraps(Renderer.view_zx)
    def view_zx(self, *args, **kwarg):
        """Wrap ``Renderer.view_zx``."""
        self.renderer.view_zx(*args, **kwarg)

    @wraps(Renderer.view_yz)
    def view_yz(self, *args, **kwarg):
        """Wrap ``Renderer.view_yz``."""
        self.renderer.view_yz(*args, **kwarg)

    @wraps(Renderer.view_zy)
    def view_zy(self, *args, **kwarg):
        """Wrap ``Renderer.view_zy``."""
        self.renderer.view_zy(*args, **kwarg)

    @wraps(Renderer.disable)
    def disable(self, *args, **kwarg):
        """Wrap ``Renderer.disable``."""
        self.renderer.disable(*args, **kwarg)

    @wraps(Renderer.enable)
    def enable(self, *args, **kwarg):
        """Wrap ``Renderer.enable``."""
        self.renderer.enable(*args, **kwarg)

    @wraps(Renderer.enable_depth_peeling)
    def enable_depth_peeling(self, *args, **kwargs):
        """Wrap ``Renderer.enable_depth_peeling``."""
        if hasattr(self, 'ren_win'):
            result = self.renderer.enable_depth_peeling(*args, **kwargs)
            if result:
                self.ren_win.AlphaBitPlanesOn()
        return result

    @wraps(Renderer.disable_depth_peeling)
    def disable_depth_peeling(self):
        """Wrap ``Renderer.disable_depth_peeling``."""
        if hasattr(self, 'ren_win'):
            self.ren_win.AlphaBitPlanesOff()
            return self.renderer.disable_depth_peeling()

    @wraps(Renderer.get_default_cam_pos)
    def get_default_cam_pos(self, *args, **kwargs):
        """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):
        """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):
        """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):
        """Wrap ``Renderer.remove_environment_texture``."""
        return self.renderer.remove_environment_texture(*args, **kwargs)

    #### Properties from Renderer ####

    @property
    def camera(self):
        """Return the active camera of the active renderer."""
        if not self.camera_set:
            self.camera_position = self.get_default_cam_pos()
            self.reset_camera()
            self.camera_set = True
        return self.renderer.camera

    @camera.setter
    def camera(self, camera):
        """Set the active camera for the rendering scene."""
        self.renderer.camera = camera

    @property
    def camera_set(self):
        """Return if the camera of the active renderer has been set."""
        return self.renderer.camera_set

    @camera_set.setter
    def camera_set(self, is_set):
        """Set if the camera has been set on the active renderer."""
        self.renderer.camera_set = is_set

    @property
    def bounds(self):
        """Return the bounds of the active renderer.

        Returns
        -------
        list
            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):
        """Return the length of the diagonal of the bounding box of the scene."""
        return self.renderer.length

    @property
    def center(self):
        """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):
        """Set the scalar bar slot lookup of the active renderer."""
        self.renderer._scalar_bar_slot_lookup = value

    @property
    def scale(self):
        """Return the scaling of the active renderer."""
        return self.renderer.scale

    @scale.setter
    def scale(self, scale):
        """Set the scaling of the active renderer."""
        self.renderer.set_scale(*scale)

    @property
    def camera_position(self):
        """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):
        """Set camera position of the active render window."""
        self.renderer.camera_position = camera_location

    @property
    def background_color(self):
        """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')
        >>> pl.show()

        """
        return self.renderers.active_renderer.background_color

    @background_color.setter
    def background_color(self, color):
        """Set the background color of all the render windows."""
        self.set_background(color)

    @property
    def window_size(self):
        """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.ren_win.GetSize())

    @window_size.setter
    def window_size(self, window_size):
        """Set the render window size."""
        self.ren_win.SetSize(window_size[0], window_size[1])

    @property
    def image_depth(self):
        """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 not hasattr(self, 'ren_win'):
            raise AttributeError(
                '\n\nTo retrieve an image after the render window '
                'has been closed, set:\n\n'
                ' ``plotter.store_image = True``\n\n'
                'before closing the plotter.'
            )

    @property
    def image(self):
        """Return an image array of current render window.

        To retrieve an image after the render window has been closed,
        set: ``plotter.store_image = True`` before closing the plotter.
        """
        if not hasattr(self, 'ren_win') and self.last_image is not None:
            return self.last_image

        self._check_rendered()
        self._check_has_ren_win()

        data = image_from_window(self.ren_win)
        if self.image_transparent_background:
            return data

        # ignore alpha channel
        return data[:, :, :-1]

    def render(self):
        """Render the main window.

        Does nothing until ``show`` has been called.
        """
        if hasattr(self, 'ren_win') and not self._first_time:
            log.debug('Rendering')
            self.ren_win.Render()
            self._rendered = True

    @wraps(RenderWindowInteractor.add_key_event)
    def add_key_event(self, *args, **kwargs):
        """Wrap RenderWindowInteractor.add_key_event."""
        if hasattr(self, 'iren'):
            self.iren.add_key_event(*args, **kwargs)

    def clear_events_for_key(self, key):
        """Remove the callbacks associated to the key.

        Parameters
        ----------
        key : str
            Key to clear events for.

        """
        self.iren.clear_events_for_key(key)

    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.BasePlotter.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):
        """Wrap RenderWindowInteractor.track_click_position."""
        self.iren.track_click_position(*args, **kwargs)

    @wraps(RenderWindowInteractor.untrack_click_position)
    def untrack_click_position(self, *args, **kwargs):
        """Stop tracking the click position."""
        self.iren.untrack_click_position(*args, **kwargs)

    @property
    def pickable_actors(self):
        """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 of vtk.vtkActors

        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):
        """Set the pickable actors."""
        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 hasattr(self, 'iren'):
            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):
        """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.ren_win, 'GetOffScreenFramebuffer'):
            if not self.ren_win.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):
        """Wrap RenderWindowInteractor.enable_trackball_style."""
        self.iren.enable_trackball_style()

    @wraps(RenderWindowInteractor.enable_trackball_actor_style)
    def enable_trackball_actor_style(self):
        """Wrap RenderWindowInteractor.enable_trackball_actor_style."""
        self.iren.enable_trackball_actor_style()

    @wraps(RenderWindowInteractor.enable_image_style)
    def enable_image_style(self):
        """Wrap RenderWindowInteractor.enable_image_style."""
        self.iren.enable_image_style()

    @wraps(RenderWindowInteractor.enable_joystick_style)
    def enable_joystick_style(self):
        """Wrap RenderWindowInteractor.enable_joystick_style."""
        self.iren.enable_joystick_style()

    @wraps(RenderWindowInteractor.enable_joystick_actor_style)
    def enable_joystick_actor_style(self):
        """Wrap RenderWindowInteractor.enable_joystick_actor_style."""
        self.iren.enable_joystick_actor_style()

    @wraps(RenderWindowInteractor.enable_zoom_style)
    def enable_zoom_style(self):
        """Wrap RenderWindowInteractor.enable_zoom_style."""
        self.iren.enable_zoom_style()

    @wraps(RenderWindowInteractor.enable_terrain_style)
    def enable_terrain_style(self, *args, **kwargs):
        """Wrap RenderWindowInteractor.enable_terrain_style."""
        self.iren.enable_terrain_style(*args, **kwargs)

    @wraps(RenderWindowInteractor.enable_rubber_band_style)
    def enable_rubber_band_style(self):
        """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):
        """Wrap RenderWindowInteractor.enable_rubber_band_2d_style."""
        self.iren.enable_rubber_band_2d_style()

    def enable_stereo_render(self):
        """Enable stereo rendering.

        Disable this with :func:`disable_stereo_render
        <BasePlotter.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 hasattr(self, 'ren_win'):
            self.ren_win.StereoRenderOn()
            self.ren_win.SetStereoTypeToAnaglyph()

    def disable_stereo_render(self):
        """Disable stereo rendering.

        Enable again with :func:`enable_stereo_render
        <BasePlotter.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 hasattr(self, 'ren_win'):
            self.ren_win.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
        >>>
        >>> # 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(examples.load_globe())
        >>>
        >>> # 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, optional
            Duration of timer that interrupt vtkRenderWindowInteractor
            in milliseconds.

        force_redraw : bool, optional
            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):
                self.right_timer_id = self.iren.create_repeating_timer(stime)
                self.render()
                Plotter.last_update_time = curr_time
                return

        if force_redraw:
            self.render()

    def add_mesh(
        self,
        mesh,
        color=None,
        style=None,
        scalars=None,
        clim=None,
        show_edges=None,
        edge_color=None,
        point_size=5.0,
        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,
        texture=None,
        render_points_as_spheres=None,
        render_lines_as_tubes=False,
        smooth_shading=None,
        split_sharp_edges=None,
        ambient=0.0,
        diffuse=1.0,
        specular=0.0,
        specular_power=100.0,
        nan_color=None,
        nan_opacity=1.0,
        culling=None,
        rgb=None,
        categories=False,
        silhouette=False,
        use_transparency=False,
        below_color=None,
        above_color=None,
        annotations=None,
        pickable=True,
        preference="point",
        log_scale=False,
        pbr=False,
        metallic=0.0,
        roughness=0.5,
        render=True,
        component=None,
        copy_mesh=False,
        **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.BasePlotter.add_volume`.

        Parameters
        ----------
        mesh : pyvista.DataSet or pyvista.MultiBlock
            Any PyVista or VTK mesh is supported. Also, any dataset
            that :func:`pyvista.wrap` can handle including NumPy
            arrays of XYZ points.

        color : color_like, optional, defaults to white
            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.

        style : str, optional
            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 or 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 : 2 item list, optional
            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 : color_like, optional, defaults to black
            The solid color to give the edges when ``show_edges=True``.
            Either a string, RGB list, or hex color string.

        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, optional
            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, optional
            Name of the Matplotlib colormap to use when mapping the
            ``scalars``.  See available Matplotlib colormaps.  Only
            applicable for when displaying ``scalars``. Requires
            Matplotlib to be installed.  ``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']``.

        label : str, optional
            String label to use when adding a legend to the scene with
            :func:`pyvista.BasePlotter.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.BasePlotter.add_scalar_bar`.

        show_scalar_bar : bool
            If ``False``, a scalar bar will not be added to the
            scene. Defaults to ``True``.

        multi_colors : bool, optional
            If a ``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 : vtk.vtkTexture or np.ndarray or bool or str, optional
            A texture to apply if the input mesh has texture
            coordinates.  This will not work with MultiBlock
            datasets. If set to ``True``, the first available texture
            on the object will be used. If a string name is given, it
            will pull a texture with that name associated to the input
            mesh.

        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 : color_like, optional, defaults to gray
            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``: ``color_like``, 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 : color_like, optional
            Solid color for values below the scalars range
            (``clim``). This will automatically set the scalar bar
            ``below_label`` to ``'Below'``.

        above_color : color_like, 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 the string annotations.

        pickable : bool, optional
            Set whether this actor 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'``.

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

        pbr : bool, optional
            Enable physics based rendering (PBR) if the mesh is
            ``PolyData``.  Use the ``color`` argument to set the base
            color. This is only available in VTK>=9.

        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. Default value is 0.0.

        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. Default value is 0.5.

        render : bool, optional
            Force a render when ``True``.  Default ``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.

        copy_mesh : bool, optional
            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.
            Defaults to ``False``.

        **kwargs : dict, optional
            Optional developer keyword arguments.

        Returns
        -------
        vtk.vtkActor
            VTK actor of the mesh.

        Examples
        --------
        Add a sphere to the plotter and show it with a custom scalar
        bar title.

        >>> import pyvista
        >>> sphere = pyvista.Sphere()
        >>> sphere['Data'] = sphere.points[:, 2]
        >>> plotter = pyvista.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
        >>> import numpy as np
        >>> vertices = np.array([[0, 0, 0], [1, 0, 0], [.5, .667, 0], [0.5, .33, 0.667]])
        >>> faces = np.hstack([[3, 0, 1, 2], [3, 0, 3, 2], [3, 0, 1, 3], [3, 1, 2, 3]])
        >>> mesh = pyvista.PolyData(vertices, faces)
        >>> mesh.cell_data['colors'] = [[255, 255, 255],
        ...                               [0, 255, 0],
        ...                               [0, 0, 255],
        ...                               [255, 0, 0]]
        >>> plotter = pyvista.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 = pyvista.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 = pyvista.Plane()
        >>> plane.plot(color='b', opacity=np.linspace(0, 1, plane.n_points),
        ...            show_edges=True)

        """
        self.mapper = make_mapper(_vtk.vtkDataSetMapper)

        # 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.'
                )
        elif isinstance(mesh, pyvista.PointSet):
            # cast to PointSet to PolyData
            mesh = mesh.cast_to_polydata(deep=False)
        elif copy_mesh:
            # A shallow copy of `mesh` is made here so when we set (or add) scalars
            # active, it doesn't modify the original input mesh.
            mesh = mesh.copy(deep=False)

        ##### Parse arguments to be used for all meshes #####

        # Avoid mutating input
        if scalar_bar_args is None:
            scalar_bar_args = {'n_colors': n_colors}
        else:
            scalar_bar_args = scalar_bar_args.copy()

        # theme based parameters
        if show_edges is None:
            show_edges = self._theme.show_edges
        if split_sharp_edges is None:
            split_sharp_edges = self._theme.split_sharp_edges
        if show_scalar_bar is None:
            show_scalar_bar = self._theme.show_scalar_bar
        if lighting is None:
            lighting = self._theme.lighting
        feature_angle = kwargs.pop('feature_angle', self._theme.sharp_edges_feature_angle)

        if smooth_shading is None:
            if pbr:
                smooth_shading = True
            else:
                smooth_shading = self._theme.smooth_shading

        # supported aliases
        clim = kwargs.pop('rng', clim)
        cmap = kwargs.pop('colormap', cmap)
        culling = kwargs.pop("backface_culling", culling)

        if render_points_as_spheres is None:
            render_points_as_spheres = self._theme.render_points_as_spheres

        if name is None:
            name = f'{type(mesh).__name__}({mesh.memory_address})'
            remove_existing_actor = False
        else:
            # check if this actor already exists
            remove_existing_actor = True

        nan_color = Color(
            nan_color, default_opacity=nan_opacity, default_color=self._theme.nan_color
        )

        if color is True:
            color = self._theme.color

        if texture is False:
            texture = None

        if culling is True:
            culling = 'backface'

        rgb = kwargs.pop('rgba', rgb)

        # account for legacy behavior
        if 'stitle' in kwargs:  # pragma: no cover
            warnings.warn(USE_SCALAR_BAR_ARGS, PyvistaDeprecationWarning)
            scalar_bar_args.setdefault('title', kwargs.pop('stitle'))

        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)

        # 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

        ##### Handle composite datasets #####

        if isinstance(mesh, pyvista.MultiBlock):
            # first check the scalars
            if clim is None and scalars is not None:
                # Get the data range across the array for all blocks
                # if scalars specified
                if isinstance(scalars, str):
                    clim = mesh.get_data_range(scalars)
                else:
                    # TODO: an array was given... how do we deal with
                    #       that? Possibly a 2D arrays or list of
                    #       arrays where first index corresponds to
                    #       the block? This could get complicated real
                    #       quick.
                    raise TypeError(
                        'scalars array must be given as a string name for multiblock datasets.'
                    )

            the_arguments = locals()
            the_arguments.pop('self')
            the_arguments.pop('mesh')
            the_arguments.pop('kwargs')
            the_arguments.pop('remove_existing_actor')

            if multi_colors:
                # Compute unique colors for each index of the block
                if has_module('matplotlib'):
                    from itertools import cycle

                    import matplotlib

                    cycler = matplotlib.rcParams['axes.prop_cycle']
                    colors = cycle(cycler)
                else:
                    multi_colors = False
                    logging.warning('Please install matplotlib for color cycles')

            # Now iteratively plot each element of the multiblock dataset
            actors = []
            for idx in range(mesh.GetNumberOfBlocks()):
                if mesh[idx] is None:
                    continue
                # Get a good name to use
                next_name = f'{name}-{idx}'
                # Get the data object
                if not is_pyvista_dataset(mesh[idx]):
                    data = wrap(mesh.GetBlock(idx))
                    if not is_pyvista_dataset(mesh[idx]):
                        continue  # move on if we can't plot it
                else:
                    data = mesh.GetBlock(idx)
                if data is None or (not isinstance(data, pyvista.MultiBlock) and data.n_points < 1):
                    # Note that a block can exist but be None type
                    # or it could have zeros points (be empty) after filtering
                    continue
                # Now check that scalars is available for this dataset
                if isinstance(data, _vtk.vtkMultiBlockDataSet) or get_array(data, scalars) is None:
                    ts = None
                else:
                    ts = scalars
                if multi_colors:
                    color = next(colors)['color']

                ## Add to the scene
                the_arguments['color'] = color
                the_arguments['scalars'] = ts
                the_arguments['name'] = next_name
                the_arguments['texture'] = None
                a = self.add_mesh(data, **the_arguments)
                actors.append(a)

                if reset_camera:
                    cpos = self.get_default_cam_pos()
                    self.camera_position = cpos
                    self.camera_set = False
                    self.reset_camera()
            return actors

        ##### Plot a single PyVista mesh #####

        if silhouette:
            if isinstance(silhouette, dict):
                self.add_silhouette(mesh, silhouette)
            else:
                self.add_silhouette(mesh)

        # Try to plot something if no preference given
        if scalars is None and color is None and texture is None:
            # Prefer texture first
            if len(list(mesh.textures.keys())) > 0:
                texture = True
            # If no texture, plot any active scalar
            else:
                # 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 = 'Data'
        if isinstance(scalars, str):
            self.mapper.SetArrayName(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)
            if field == FieldAssociation.POINT:
                mesh.point_data.active_scalars_name = original_scalar_name
                self.mapper.SetScalarModeToUsePointData()
            elif field == FieldAssociation.CELL:
                mesh.cell_data.active_scalars_name = original_scalar_name
                self.mapper.SetScalarModeToUseCellData()

        # Compute surface normals if using smooth shading
        if smooth_shading:
            mesh, scalars = prepare_smooth_shading(
                mesh, scalars, texture, split_sharp_edges, feature_angle, preference
            )

        if mesh.n_points < 1:
            raise ValueError('Empty meshes cannot be plotted. Input mesh has zero points.')

        # set main values
        self.mesh = mesh
        self.mapper.SetInputData(self.mesh)
        self.mapper.GetLookupTable().SetNumberOfTableValues(n_colors)
        if interpolate_before_map:
            self.mapper.InterpolateScalarsBeforeMappingOn()

        actor = _vtk.vtkActor()
        prop = _vtk.vtkProperty()
        actor.SetMapper(self.mapper)
        actor.SetProperty(prop)

        if texture is True or isinstance(texture, (str, int)):
            texture = mesh._activate_texture(texture)

        if texture:

            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.SetTexture(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.SetScalarModeToUsePointFieldData()

            # 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:
            show_scalar_bar, n_colors, clim = self.mapper.set_scalars(
                mesh,
                scalars,
                scalars_name,
                scalar_bar_args,
                rgb,
                component,
                preference,
                interpolate_before_map,
                custom_opac,
                annotations,
                log_scale,
                nan_color,
                above_color,
                below_color,
                cmap,
                flip_scalars,
                opacity,
                categories,
                n_colors,
                clim,
                self._theme,
                show_scalar_bar,
            )
        elif custom_opac:  # no scalars but custom opacity
            self.mapper.set_custom_opacity(
                opacity,
                color,
                mesh,
                n_colors,
                preference,
                interpolate_before_map,
                rgb,
                self._theme,
            )
        else:
            self.mapper.SetScalarModeToUseFieldData()

        # Set actor properties ================================================

        # select view style
        if not style:
            style = 'surface'
        style = style.lower()
        if style == 'wireframe':
            prop.SetRepresentationToWireframe()
            if color is None:
                color = self._theme.outline_color
        elif style == 'points':
            prop.SetRepresentationToPoints()
        elif style == 'surface':
            prop.SetRepresentationToSurface()
        else:
            raise ValueError(
                'Invalid style.  Must be one of the following:\n'
                '\t"surface"\n'
                '\t"wireframe"\n'
                '\t"points"\n'
            )

        prop.SetPointSize(point_size)
        prop.SetAmbient(ambient)
        prop.SetDiffuse(diffuse)
        prop.SetSpecular(specular)
        prop.SetSpecularPower(specular_power)

        if pbr:
            if not _vtk.VTK9:  # pragma: no cover
                raise RuntimeError('Physically based rendering requires VTK 9 ' 'or newer')
            prop.SetInterpolationToPBR()
            prop.SetMetallic(metallic)
            prop.SetRoughness(roughness)
        elif smooth_shading:
            prop.SetInterpolationToPhong()
        else:
            prop.SetInterpolationToFlat()
        # edge display style
        if show_edges:
            prop.EdgeVisibilityOn()

        rgb_color = Color(color, default_color=self._theme.color)
        prop.SetColor(rgb_color.float_rgb)
        if isinstance(opacity, (float, int)):
            prop.SetOpacity(opacity)
        prop.SetEdgeColor(Color(edge_color, default_color=self._theme.edge_color).float_rgb)

        if render_points_as_spheres:
            prop.SetRenderPointsAsSpheres(render_points_as_spheres)
        if render_lines_as_tubes:
            prop.SetRenderLinesAsTubes(render_lines_as_tubes)

        # legend label
        if label:
            if not isinstance(label, str):
                raise TypeError('Label must be a string')
            geom = pyvista.Triangle()
            if scalars is not None:
                geom = pyvista.Box()
                rgb_color = Color('black')
            geom.points -= geom.center
            addr = actor.GetAddressAsString("")
            self.renderer._labels[addr] = [geom, label, rgb_color]

        # lighting display style
        if not lighting:
            prop.LightingOff()

        # set line thickness
        if line_width:
            prop.SetLineWidth(line_width)

        self.add_actor(
            actor,
            reset_camera=reset_camera,
            name=name,
            culling=culling,
            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_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=0.0,
        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,
        specular=0.2,
        specular_power=10.0,
        render=True,
        **kwargs,
    ):
        """Add a volume, rendered using a smart mapper by default.

        Requires a 3D :class:`numpy.ndarray` or :class:`pyvista.UniformGrid`.

        Parameters
        ----------
        volume : 3D numpy.ndarray or pyvista.UniformGrid
            The input volume to visualize. 3D numpy arrays are accepted.

        scalars : str or 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 ``scalars`` is
            ``None``, then the active scalars are used.

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

        resolution : list, optional
            Block resolution.

        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.

        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, optional
            Name of the Matplotlib colormap to us when mapping the ``scalars``.
            See available Matplotlib colormaps.  Only applicable for when
            displaying ``scalars``. Requires Matplotlib to be installed.
            ``colormap`` is also an accepted alias for this. If ``colorcet`` or
            ``cmocean`` are installed, their colormaps can be specified by name.

        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 'additive'.

        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.

        scalar_bar_args : dict, optional
            Dictionary of keyword arguments to pass when adding the
            scalar bar to the scene. For options, see
            :func:`pyvista.BasePlotter.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 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
            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 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, 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``.

        render : bool, optional
            Force a render when True.  Default ``True``.

        **kwargs : dict, optional
            Optional keyword arguments.

        Returns
        -------
        vtk.vtkActor
            VTK 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()

        """
        # 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)

        # 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
            warnings.warn(USE_SCALAR_BAR_ARGS, PyvistaDeprecationWarning)
            scalar_bar_args.setdefault('title', kwargs.pop('stitle'))

        if show_scalar_bar is None:
            show_scalar_bar = self._theme.show_scalar_bar

        if culling is True:
            culling = 'backface'

        if mapper is None:
            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,
                )

                actors.append(a)
            return actors

        if not isinstance(volume, pyvista.UniformGrid):
            raise TypeError(
                f'Type {type(volume)} not supported for volume rendering at this time. Use `pyvista.UniformGrid`.'
            )

        if opacity_unit_distance is None:
            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.copy()
            # 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 ValueError('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)

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

        if not np.issubdtype(scalars.dtype, np.number):
            raise TypeError('Non-numeric scalars are currently not supported for volume rendering.')
        if scalars.ndim != 1:
            scalars = scalars.ravel()

        # Define mapper, volume, and add the correct properties
        mappers = {
            'fixed_point': _vtk.vtkFixedPointVolumeRayCastMapper,
            'gpu': _vtk.vtkGPUVolumeRayCastMapper,
            'open_gl': _vtk.vtkOpenGLGPUVolumeRayCastMapper,
            'smart': _vtk.vtkSmartVolumeMapper,
        }
        if not isinstance(mapper, str) or mapper not in mappers.keys():
            raise TypeError(
                f"Mapper ({mapper}) unknown. Available volume mappers include: {', '.join(mappers.keys())}"
            )
        self.mapper = make_mapper(mappers[mapper])

        # Scalars interpolation approach
        if scalars.shape[0] == volume.n_points:
            volume.point_data.set_array(scalars, title, True)
            self.mapper.SetScalarModeToUsePointData()
        elif scalars.shape[0] == volume.n_cells:
            volume.cell_data.set_array(scalars, title, True)
            self.mapper.SetScalarModeToUseCellData()
        else:
            raise_not_matching(scalars, volume)

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

        # convert the scalars to np.uint8 and scale between 0 and 255 within clim
        clim = np.asarray(clim, dtype=scalars.dtype)
        scalars.clip(clim[0], clim[1], out=scalars)
        min_ = np.nanmin(scalars)
        max_ = np.nanmax(scalars)
        np.true_divide((scalars - min_), (max_ - min_) / 255, out=scalars, casting='unsafe')
        volume[title] = np.array(scalars, dtype=np.uint8)

        self.mapper.scalar_range = clim

        # Set colormap and build lookup table
        table = _vtk.vtkLookupTable()
        # table.SetNanColor(nan_color) # NaN's are chopped out with current implementation
        # above/below colors not supported with volume rendering

        if isinstance(annotations, dict):
            for val, anno in annotations.items():
                table.SetAnnotation(float(val), str(anno))

        if cmap is None:  # Set default map if matplotlib is available
            if has_module('matplotlib'):
                cmap = self._theme.cmap

        if cmap is not None:
            if not has_module('matplotlib'):
                raise ImportError('Please install matplotlib for volume rendering.')

            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()

        color_tf = _vtk.vtkColorTransferFunction()
        for ii in range(n_colors):
            color_tf.AddRGBPoint(ii, *cmap(ii)[:-1])

        # Set opacities
        if isinstance(opacity, (float, int)):
            opacity_values = [opacity] * n_colors
        elif isinstance(opacity, str):
            opacity_values = pyvista.opacity_transfer_function(opacity, n_colors)
        elif isinstance(opacity, (np.ndarray, list, tuple)):
            opacity = np.array(opacity)
            opacity_values = opacity_transfer_function(opacity, n_colors)

        opacity_tf = _vtk.vtkPiecewiseFunction()
        for ii in range(n_colors):
            opacity_tf.AddPoint(ii, opacity_values[ii] / n_colors)

        # Now put color tf and opacity tf into a lookup table for the scalar bar
        table.SetNumberOfTableValues(n_colors)
        lut = cmap(np.array(range(n_colors))) * 255
        lut[:, 3] = opacity_values
        lut = lut.astype(np.uint8)
        table.SetTable(_vtk.numpy_to_vtk(lut))
        table.SetRange(*clim)
        self.mapper.lookup_table = table

        self.mapper.SetInputData(volume)

        blending = blending.lower()
        if blending in ['additive', 'add', 'sum']:
            self.mapper.SetBlendModeToAdditive()
        elif blending in ['average', 'avg', 'average_intensity']:
            self.mapper.SetBlendModeToAverageIntensity()
        elif blending in ['composite', 'comp']:
            self.mapper.SetBlendModeToComposite()
        elif blending in ['maximum', 'max', 'maximum_intensity']:
            self.mapper.SetBlendModeToMaximumIntensity()
        elif blending in ['minimum', 'min', 'minimum_intensity']:
            self.mapper.SetBlendModeToMinimumIntensity()
        else:
            raise ValueError(
                f'Blending mode {blending!r} invalid. '
                'Please choose one of "additive", '
                '"composite", "minimum" or "maximum".'
            )
        self.mapper.Update()

        self.volume = _vtk.vtkVolume()
        self.volume.SetMapper(self.mapper)

        prop = _vtk.vtkVolumeProperty()
        prop.SetColor(color_tf)
        prop.SetScalarOpacity(opacity_tf)
        prop.SetAmbient(ambient)
        prop.SetScalarOpacityUnitDistance(opacity_unit_distance)
        prop.SetShade(shade)
        prop.SetDiffuse(diffuse)
        prop.SetSpecular(specular)
        prop.SetSpecularPower(specular_power)
        self.volume.SetProperty(prop)

        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, 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.PolyData
            Mesh for generating silhouette to plot.

        params : dict, optional

            * If not supplied, the default theme values will be used.
            * ``color``: ``color_like``, 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

        Returns
        -------
        vtk.vtkActor
            VTK actor of the silhouette.

        Examples
        --------
        >>> import pyvista
        >>> from pyvista import examples
        >>> bunny = examples.download_bunny()
        >>> plotter = pyvista.Plotter()
        >>> _ = plotter.add_mesh(bunny, color='tan')
        >>> _ = plotter.add_silhouette(bunny,
        ...     params={'color': 'red', 'line_width': 8.0})
        >>> plotter.view_xy()
        >>> plotter.show()

        """
        silhouette_params = self._theme.silhouette.to_dict()
        if params:
            silhouette_params.update(params)

        if not is_pyvista_dataset(mesh):
            mesh = wrap(mesh)
        if not isinstance(mesh, pyvista.PolyData):
            raise TypeError(f"Expected type is `PolyData` but {type(mesh)} was given.")

        if isinstance(silhouette_params["decimate"], float):
            silhouette_mesh = mesh.decimate(silhouette_params["decimate"])
        else:
            silhouette_mesh = mesh
        alg = _vtk.vtkPolyDataSilhouette()
        alg.SetInputData(silhouette_mesh)
        alg.SetCamera(self.renderer.camera)
        if silhouette_params["feature_angle"] is not None:
            alg.SetEnableFeatureAngle(True)
            alg.SetFeatureAngle(silhouette_params["feature_angle"])
        else:
            alg.SetEnableFeatureAngle(False)
        mapper = make_mapper(_vtk.vtkDataSetMapper)
        mapper.SetInputConnection(alg.GetOutputPort())
        actor, prop = self.add_actor(mapper)
        prop.SetColor(Color(silhouette_params["color"]).float_rgb)
        prop.SetOpacity(silhouette_params["opacity"])
        prop.SetLineWidth(silhouette_params["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
            The new range of scalar bar. Two item list (e.g. ``[-1, 2]``).

        name : str, optional
            The title of the scalar bar to update.

        """
        if isinstance(clim, float) or isinstance(clim, 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

        # Use the name to find the desired actor
        def update_mapper(mapper_helper):
            mapper_helper.scalar_range = clim
            return

        try:
            for mh in self._scalar_bar_mappers[name]:
                update_mapper(mh)
        except KeyError:
            raise KeyError('Name ({}) not valid/not found in this plotter.')
        return

    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

    def link_views(self, views=0):
        """Link the views' cameras.

        Parameters
        ----------
        views : int | tuple or list
            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)):
            for renderer in self.renderers:
                renderer.camera = self.renderers[views].camera
            return
        views = np.asarray(views)
        if np.issubdtype(views.dtype, np.integer):
            for view_index in views:
                self.renderers[view_index].camera = self.renderers[views[0]].camera
        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 : None, int, tuple or list
            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()
        elif isinstance(views, int):
            self.renderers[views].camera = Camera()
            self.renderers[views].reset_camera()
        elif isinstance(views, collections.abc.Iterable):
            for view_index in views:
                self.renderers[view_index].camera = Camera()
                self.renderers[view_index].reset_camera()
        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):
        """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 : np.ndarray
            Scalars to replace existing scalars.

        mesh : vtk.PolyData or vtk.UnstructuredGrid, optional
            Object that has already been added to the Plotter.  If
            None, uses last added mesh.

        render : bool, optional
            Force a render when True.  Default ``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
        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 or vtk.UnstructuredGrid, optional
            Object that has already been added to the Plotter.  If
            None, uses last added mesh.

        render : bool, optional
            Force a render when True.  Default ``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."""
        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
        if self._store_image:
            self.last_image = self.screenshot(None, return_img=True)
            self.last_image_depth = self.get_image_depth()

        # reset scalar bars
        self.clear()

        # grab the display id before clearing the window
        # this is an experimental feature
        if KILL_DISPLAY:  # pragma: no cover
            disp_id = None
            if hasattr(self, 'ren_win'):
                disp_id = self.ren_win.GetGenericDisplayId()
        self._clear_ren_win()

        if self.iren is not None:
            self.iren.remove_observers()
            self.iren.terminate_app()
            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

        # 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
        if getattr(self, 'mapper', None) is not None:
            self.mapper.lookup_table = 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, tuple(float), optional
            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, optional
            Sets the size of the title font.  Defaults to 18.

        color : color_like, 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.themes._Font.color>`.

        font : str, optional
            Font name may be ``'courier'``, ``'times'``, or ``'arial'``.

        shadow : bool, optional
            Adds a black shadow to the text.  Defaults to ``False``.

        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, optional
            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, optional
            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 0 degrees, which is horizontal.

        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.

        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, optional
            Frames per second.

        quality : int, optional
            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

        """
        from imageio import get_writer

        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.

        Parameters
        ----------
        filename : str
            Filename of the gif to open.  Filename must end in ``"gif"``.

        loop : int, optional
            The number of iterations. Default 0 (meaning loop indefinitely).

        fps : float, optional
            The number of frames per second. If duration is not given, the
            duration for each frame is set to 1/fps. Default 10.

        palettesize : int, optional
            The number of colors to quantize the image to. Is rounded to the
            nearest power of two. Must be between 2 and 256. Default 256.

        subrectangles : bool, optional
            If ``True``, will try and optimize the GIF by storing only the rectangular
            parts of each frame that change with respect to the previous. Default
            ``False``.

            .. 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.

        """
        from imageio import get_writer

        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)
        self.mwriter = get_writer(
            filename,
            mode='I',
            loop=loop,
            fps=fps,
            palettesize=palettesize,
            subrectangles=subrectangles,
            **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 _run_image_filter(self, ifilter):
        # Update filter and grab pixels
        ifilter.Modified()
        ifilter.Update()
        image = pyvista.wrap(ifilter.GetOutput())
        img_size = image.dimensions
        img_array = pyvista.utilities.point_array(image, 'ImageScalars')

        # Reshape and write
        tgt_size = (img_size[1], img_size[0], -1)
        return img_array.reshape(tgt_size)[::-1]

    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, optional
            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, optional
            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.store_image = True
        >>> plotter.show()
        >>> zval = plotter.get_image_depth()

        """
        # allow no render window
        if not hasattr(self, 'ren_win') 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.ren_win)
        ifilter.ReadFrontBufferOff()
        ifilter.SetInputBufferTypeToZBuffer()
        zbuff = self._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):
        """Add lines to the plotting object.

        Parameters
        ----------
        lines : np.ndarray or pyvista.PolyData
            Points representing line segments.  For example, two line
            segments would be represented as ``np.array([[0, 0, 0],
            [1, 0, 0], [1, 0, 0], [1, 1, 0]])``.

        color : color_like, 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'``

        width : float, optional
            Thickness of lines.

        label : str, optional
            String label to use when adding a legend to the scene with
            :func:`pyvista.BasePlotter.add_legend`.

        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.

        Returns
        -------
        vtk.vtkActor
            Lines actor.

        Examples
        --------
        >>> 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='yellow', width=3)
        >>> 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)

        # Create mapper and add lines
        mapper = _vtk.vtkDataSetMapper()
        mapper.SetInputData(lines)

        rgb_color = Color(color)

        # Create actor
        actor = _vtk.vtkActor()
        actor.SetMapper(mapper)
        actor.GetProperty().SetLineWidth(width)
        actor.GetProperty().EdgeVisibilityOn()
        actor.GetProperty().SetEdgeColor(rgb_color.float_rgb)
        actor.GetProperty().SetColor(rgb_color.float_rgb)
        actor.GetProperty().LightingOff()

        # 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, rgb_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):
        """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=5,
        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 or pyvista.DataSet
            An ``n x 3`` sequence points or pyvista dataset with points.

        labels : list or 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, optional
            Italicises title and bar labels.  Default ``False``.

        bold : bool, optional
            Bolds title and bar labels.  Default ``True``.

        font_size : float, optional
            Sets the size of the title font.  Defaults to 16.

        text_color : color_like, 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, optional
            Adds a black shadow to the text.  Defaults to ``False``.

        show_points : bool, optional
            Controls if points are visible.  Default ``True``.

        point_color : color_like, 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 : color_like, optional
            Color of points (if visible).  Either a string, rgb
            sequence, or hex color string.

        shape : str, optional
            The string name of the shape to use. Options are ``'rect'`` or
            ``'rounded_rect'``. If you want no shape, pass ``None``.

        fill_shape : bool, optional
            Fill the shape with the ``shape_color``. Outlines if ``False``.

        margin : int, optional
            The size of the margin on the label background shape. Default is 3.

        shape_opacity : float, optional
            The opacity of the shape in the range of ``[0, 1]``.

        pickable : bool, optional
            Set whether this actor is pickable.

        render_points_as_spheres : bool, optional
            Render points as spheres rather than dots.

        tolerance : float, optional
            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, optional
            Skip adding the visibility filter. Default False.

        render : bool, optional
            Force a render when ``True`` (default).

        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):
            vtkpoints = pyvista.PolyData(points)  # Cast to poly data
        elif is_pyvista_dataset(points):
            vtkpoints = pyvista.PolyData(points.points)
            if isinstance(labels, str):
                labels = points.point_data[labels]
        else:
            raise TypeError(f'Points type not usable: {type(points)}')

        if len(vtkpoints.points) != len(labels):
            raise ValueError('There must be one label for each point')

        if name is None:
            name = f'{type(vtkpoints).__name__}({vtkpoints.memory_address})'

        vtklabels = _vtk.vtkStringArray()
        vtklabels.SetName('labels')
        for item in labels:
            vtklabels.InsertNextValue(str(item))
        vtkpoints.GetPointData().AddArray(vtklabels)

        # Create hierarchy
        hier = _vtk.vtkPointSetToLabelHierarchy()
        hier.SetLabelArrayName('labels')

        if always_visible:
            hier.SetInputData(vtkpoints)
        else:
            # Only show visible points
            vis_points = _vtk.vtkSelectVisiblePoints()
            vis_points.SetInputData(vtkpoints)
            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(
                vtkpoints,
                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.BasePlotter.add_point_labels`.

        Parameters
        ----------
        points : numpy.ndarray or pyvista.DataSet
            An ``n x 3`` numpy.ndarray or pyvista dataset with points.

        labels : str, optional
            String name of the point data array to use.

        fmt : str, optional
            String formatter used to format numerical data.

        preamble : str, optional
            Text before the start of each label.

        **kwargs : dict, optional
            Keyword arguments passed to
            :func:`pyvista.BasePlotter.add_point_labels`.

        Returns
        -------
        vtk.vtkActor2D
            VTK label actor.  Can be used to change properties of the labels.

        """
        if not is_pyvista_dataset(points):
            raise TypeError(f'input points must be a pyvista dataset, not: {type(points)}')
        if not isinstance(labels, str):
            raise TypeError('labels must be a string name of the scalars array to use')
        if fmt is None:
            fmt = self._theme.font.fmt
        if fmt is None:
            fmt = '%.6e'
        scalars = points.point_data[labels]
        phrase = f'{preamble} %.3e'
        labels = [phrase % val for val in scalars]
        return self.add_point_labels(points, labels, **kwargs)

    def add_points(self, points, **kwargs):
        """Add points to a mesh.

        Parameters
        ----------
        points : numpy.ndarray or pyvista.DataSet
            Array of points or the points from a pyvista object.

        **kwargs : dict, optional
            See :func:`pyvista.BasePlotter.add_mesh` for optional
            keyword arguments.

        Returns
        -------
        vtk.vtkActor
            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()

        """
        kwargs['style'] = 'points'
        return self.add_mesh(points, **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.BasePlotter.add_mesh` for optional
            keyword arguments.

        Returns
        -------
        vtk.vtkActor
            VTK 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, optional
            Title to use within the file properties.

        raster : bool, optional
            Attempt to write 3D properties as a raster image.

        painter : bool, optional
            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

        """
        if not hasattr(self, 'ren_win'):
            raise AttributeError('This plotter is closed and unable to save a screenshot.')
        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.fileio.get_ext(filename)

        writer = _vtk.lazy_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.ren_win)
        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
    ):
        """Take screenshot at current camera position.

        Parameters
        ----------
        filename : str, pathlib.Path, 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, optional
            If ``True`` (the default), a NumPy array of the image will
            be returned.

        window_size : 2-length tuple, optional
            Set the plotter's size to this ``(width, height)`` before
            taking the screenshot.

        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

        """
        if window_size is not None:
            self.window_size = 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 not hasattr(self, 'ren_win'):
            # If plotter has been closed...
            # check if last_image exists
            if self.last_image is not None:
                # Save last image
                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()

        return self._save_image(self.image, filename, return_img)

    @wraps(Renderers.set_background)
    def set_background(self, *args, **kwargs):
        """Wrap ``Renderers.set_background``."""
        self.renderers.set_background(*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, optional
            A scaling factor when building the orbital extent.

        n_points : int, optional
            Number of points on the orbital path.

        viewup : list(float), optional
            The normal to the orbital plane.

        shift : float, optional
            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
            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 : list(float) of length 3, optional
            The point of focus the camera.

        step : float, optional
            The timestep between flying to each camera position.

        viewup : list(float), optional
            The normal to the orbital plane.

        write_frames : bool, optional
            Assume a file is open and write a frame on each camera
            view during the orbit.

        threaded : bool, optional
            Run this as a background thread.  Generally used within a
            GUI (i.e. PyQt).

        progress_bar : bool, optional
            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
        >>> filename = os.path.join(mkdtemp(), 'orbit.gif')
        >>> plotter = pyvista.Plotter(window_size=[300, 300])
        >>> _ = plotter.add_mesh(examples.load_globe(), 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:
                    time.sleep(sleep_time)
            if write_frames:
                self.mwriter.close()

        if threaded:
            thread = Thread(target=orbit)
            thread.start()
        else:
            orbit()

    def export_vtkjs(self, filename, compress_arrays=False):
        """Export the current rendering scene as a VTKjs scene.

        It can be used for rendering in a web browser.

        Parameters
        ----------
        filename : str
            Filename to export the scene to.  A filename extension of
            ``'.vtkjs'`` will be added.

        compress_arrays : bool, optional
            Enable array compression.

        Examples
        --------
        >>> import pyvista
        >>> from pyvista import examples
        >>> pl = pyvista.Plotter()
        >>> _ = pl.add_mesh(examples.load_hexbeam())
        >>> pl.export_vtkjs("sample")  # doctest:+SKIP

        """
        if not hasattr(self, 'ren_win'):
            raise RuntimeError('Export must be called before showing/closing the scene.')
        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))

        export_plotter_vtkjs(self, filename, compress_arrays=compress_arrays)

    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

        """
        if pyvista.vtk_version_info <= (8, 1, 2):
            raise pyvista.core.errors.VTKVersionError()

        if not hasattr(self, "ren_win"):
            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 = _vtk.lazy_vtkOBJExporter()
        # remove the extension as VTK always adds it in
        exporter.SetFilePrefix(filename[:-4])
        exporter.SetRenderWindow(self.ren_win)
        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(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, auto_resize=True, as_global=True):
        """Add a background image to a plot.

        Parameters
        ----------
        image_path : str
            Path to an image file.

        scale : float, optional
            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.

        auto_resize : bool, optional
            Resize the background when the render window changes size.

        as_global : bool, optional
            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.ren_win.SetNumberOfLayers(3)
        renderer = self.renderers.add_background_renderer(image_path, scale, as_global)
        self.ren_win.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):
        """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, cpos=None):
        """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:  # and not self.camera_set:
            for renderer in self.renderers:
                if not renderer.camera_set and cpos is None:
                    renderer.camera_position = renderer.get_default_cam_pos()
                    renderer.ResetCamera()
                elif cpos is not None:
                    renderer.camera_position = cpos
            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, optional
            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.plotting.renderer.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
            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

    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,
    ):
        """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
            Starting point for ruler.

        pointb : Sequence
            Ending point for ruler.

        flip_range : bool
            If ``True``, the distance range goes from ``pointb`` to ``pointa``.

        number_labels : int
            Number of labels to place on ruler.

        show_labels : bool, optional
            Whether to show labels.

        font_size_factor : float
            Factor to scale font size overall.

        label_size_factor : float
            Factor to scale label size relative to title size.

        label_format : str, optional
            A printf style format for labels, e.g. '%E'.

        title : str, optional
            The title to display.

        number_minor_ticks : int, optional
            Number of minor ticks between major ticks.

        tick_length : int
            Length of ticks in pixels.

        minor_tick_length : int
            Length of minor ticks in pixels.

        show_ticks : bool, optional
            Whether to show the ticks.

        tick_label_offset : int
            Offset between tick and label in pixels.

        Returns
        -------
        vtk.vtkActor
            VTK actor of the ruler.

        Examples
        --------
        >>> import pyvista
        >>> cone = pyvista.Cone(height=2.0, radius=0.5)
        >>> plotter = pyvista.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()

        """
        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.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


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 : list or tuple, 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.  Default ``False``.

    border_color : color_like, 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'``

    window_size : list, 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, optional
        If ``True``, enable line smoothing.

    polygon_smoothing : bool, optional
        If ``True``, enable polygon smoothing.

    lighting : str, optional
        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.

        The default is a ``'light_kit'`` (to be precise, 5 separate
        lights that act like a Light Kit).

    theme : pyvista.themes.DefaultTheme, optional
        Plot-specific theme.

    Examples
    --------
    >>> import pyvista
    >>> from pyvista import examples
    >>> mesh = examples.load_hexbeam()
    >>> another_mesh = examples.load_uniform()
    >>> plotter = pyvista.Plotter()
    >>> actor = plotter.add_mesh(mesh, color='red')
    >>> actor = plotter.add_mesh(another_mesh, color='blue')
    >>> plotter.show()

    """

    last_update_time = 0.0
    right_timer_id = -1

    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,
    ):
        """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,
        )
        # reset partial initialization flag
        self._initialized = False

        log.debug('Plotter init start')

        # check if a plotting backend is enabled
        _warn_xserver()

        def on_timer(iren, event_id):
            """Exit application if interactive renderer stops."""
            if event_id == 'TimerEvent' and self.iren._style != "Context":
                self.iren.terminate_app()

        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

        self._window_size_unset = False
        if window_size is None:
            self._window_size_unset = True
            window_size = self._theme.window_size
        self.__prior_window_size = window_size

        if multi_samples is None:
            multi_samples = self._theme.multi_samples

        # initialize render window
        self.ren_win = _vtk.vtkRenderWindow()
        self.ren_win.SetMultiSamples(multi_samples)
        self.ren_win.SetBorders(True)
        if line_smoothing:
            self.ren_win.LineSmoothingOn()
        if point_smoothing:
            self.ren_win.PointSmoothingOn()
        if polygon_smoothing:
            self.ren_win.PolygonSmoothingOn()

        for renderer in self.renderers:
            self.ren_win.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.ren_win.GetNumberOfLayers()
        current_layer = self.renderer.GetLayer()
        self.ren_win.SetNumberOfLayers(number_or_layers + 1)
        self.ren_win.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.ren_win.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.ren_win)
        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 = window_size

        # add timer event if interactive render exists
        self.iren.add_observer(_vtk.vtkCommand.TimerEvent, on_timer)

        if self._theme.depth_peeling.enabled:
            if self.enable_depth_peeling():
                for renderer in self.renderers:
                    renderer.enable_depth_peeling()

        # 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,
        use_ipyvtk=None,
        jupyter_backend=None,
        return_viewer=False,
        return_cpos=None,
        **kwargs,
    ):
        """Display the plotting window.

        Parameters
        ----------
        title : str, optional
            Title of plotting window.  Defaults to
            :attr:`pyvista.global_theme.title <pyvista.themes.DefaultTheme.title>`.

        window_size : list, optional
            Window size in pixels.  Defaults to
            :attr:`pyvista.global_theme.window_size <pyvista.themes.DefaultTheme.window_size>`.

        interactive : bool, optional
            Enabled by default.  Allows user to pan and move figure.
            Defaults to
            :attr:`pyvista.global_theme.interactive <pyvista.themes.DefaultTheme.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.themes.DefaultTheme.auto_close>`.

        interactive_update : bool, optional
            Disabled by default.  Allows user to non-blocking draw,
            user should call :func:`BasePlotter.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.themes.DefaultTheme.full_screen>`.

        screenshot : str, pathlib.Path, BytesIO or bool, optional
            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. Defaults to ``False``. 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`.

        return_img : bool
            Returns a numpy array representing the last image along
            with the camera position.

        cpos : list(tuple(floats))
            The camera position.  You can also set this with
            :attr:`Plotter.camera_position`.

        use_ipyvtk : bool, optional
            Deprecated.  Instead, set the backend either globally with
            ``pyvista.set_jupyter_backend('ipyvtklink')`` or with
            ``backend='ipyvtklink'``.

        jupyter_backend : str, optional
            Jupyter notebook plotting backend to use.  One of the
            following:

            * ``'none'`` : Do not display in the notebook.
            * ``'pythreejs'`` : Show a ``pythreejs`` widget
            * ``'static'`` : Display a static figure.
            * ``'ipygany'`` : Show a ``ipygany`` widget
            * ``'panel'`` : Show a ``panel`` widget.

            This can also be set globally with
            :func:`pyvista.set_jupyter_backend`.

        return_viewer : bool, optional
            Return the jupyterlab viewer, scene, or display object
            when plotting with jupyter notebook.

        return_cpos : bool, optional
            Return the last camera position from the render window
            when enabled.  Default based on theme setting.  See
            :attr:`pyvista.themes.DefaultTheme.return_cpos`.

        **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.  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
            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

        Display a ``pythreejs`` scene within a jupyter notebook

        >>> pl.show(jupyter_backend='pythreejs')  # doctest:+SKIP

        Return a ``pythreejs`` scene.

        >>> pl.show(jupyter_backend='pythreejs', return_viewer=True)  # 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)]

        """
        # developer keyword argument: runs a function immediately prior to ``close``
        self._before_close_callback = kwargs.pop('before_close_callback', None)
        jupyter_kwargs = kwargs.pop('jupyter_kwargs', {})
        assert_empty_kwargs(**kwargs)

        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 use_ipyvtk:
            txt = textwrap.dedent(
                """
                use_ipyvtk is deprecated.  Set the backend
                globally with ``pyvista.set_jupyter_backend("ipyvtklink")
                or with ``backend="ipyvtklink"``
                """
            ).strip()
            from pyvista.core.errors import DeprecationError

            raise DeprecationError(txt)

        if not hasattr(self, "ren_win"):
            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.ren_win.SetFullScreen(True)
            self.ren_win.BordersOn()  # super buggy when disabled
        else:
            if window_size is None:
                window_size = self.window_size
            else:
                self._window_size_unset = False
            self.ren_win.SetSize(window_size[0], window_size[1])

        # reset unless camera for the first render unless camera is set
        self._on_first_render_request(cpos)

        # handle plotter notebook
        if jupyter_backend and not self.notebook:
            warnings.warn(
                'Not within a jupyter notebook environment.\nIgnoring ``jupyter_backend``.'
            )

        if self.notebook:
            from ..jupyter.notebook import handle_plotter

            if jupyter_backend is None:
                jupyter_backend = self._theme.jupyter_backend

            if jupyter_backend != 'none':
                if screenshot:
                    warnings.warn(
                        '\nSet `jupyter_backend` backend to `"none"` to take a screenshot'
                        ' within a notebook environment.'
                    )

                disp = handle_plotter(
                    self, backend=jupyter_backend, return_viewer=return_viewer, **jupyter_kwargs
                )
                return disp

        self.render()

        # This has to be after the first render for some reason
        if title is None:
            title = self.title
        if title:
            self.ren_win.SetWindowName(title)
            self.title = title

        # Keep track of image for sphinx-gallery
        if pyvista.BUILDING_GALLERY or screenshot:
            # always save screenshots for sphinx_gallery
            self.last_image = self.screenshot(screenshot, return_img=True)
            self.last_image_depth = self.get_image_depth()

        # 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':
                        if _vtk.VTK9:
                            self.iren.process_events()
                        else:
                            global VERY_FIRST_RENDER
                            if not VERY_FIRST_RENDER:
                                self.iren.start()
                            VERY_FIRST_RENDER = False

                    self.iren.start()
                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.
        if not self.ren_win.IsCurrent():
            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."
                )
                auto_close = True
        # 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 auto_close:
            self.close()

        # If user asked for screenshot, return as numpy array after camera
        # position
        if return_img or screenshot is True:
            if return_cpos:
                return self.camera_position, self.last_image

        if return_cpos:
            return self.camera_position

    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, optional
            Sets the size of the title font.  Defaults to 16 or the
            value of the global theme if set.

        color : color_like, 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, optional
            Adds a black shadow to the text.  Defaults to ``False``.

        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 : length 6 sequence
            Specify the bounds in the format of:

            - ``(xmin, xmax, ymin, ymax, zmin, zmax)``

            Defaults to ``(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0)``.

        focal_point : list or tuple, optional
            The focal point of the cursor.

            Defaults to ``(0.0, 0.0, 0.0)``.

        color : color_like, 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 = make_mapper(_vtk.vtkDataSetMapper)
        mapper.SetInputConnection(alg.GetOutputPort())
        actor, prop = self.add_actor(mapper)
        prop.SetColor(Color(color).float_rgb)

        return actor


# Tracks created plotters.  At the end of the file as we need to
# define ``BasePlotter`` before including it in the type definition.
_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/render_window_interactor.py

"""Wrap vtk.vtkRenderWindowInteractor."""
import collections.abc
from functools import partial
import logging
import time
import weakref

from pyvista import _vtk
from pyvista.utilities import try_callback

log = logging.getLogger(__name__)
log.setLevel('CRITICAL')
log.addHandler(logging.StreamHandler())


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.

    """

    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 = 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_context_style, side="left", double=True, viewport=True
        )

    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 or 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 or 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):
        """Remove the callbacks associated to the key."""
        self._key_press_event_callbacks.pop(key)

    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.BasePlotter.track_click_position` instead.

        """
        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()
        self._click_time = t
        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

        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, optional
            The mouse button to track (either ``'left'`` or ``'right'``).
            Default is ``'right'``. Also accepts ``'r'`` or ``'l'``.

        double : bool, optional
            Track single clicks if ``False``, double clicks if ``True``.
            Defaults to single clicks ``False``.

        viewport : bool, optional
            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_context_style(self, mouse_pos):
        scene = None
        for renderer in self._plotter.renderers:
            if scene is None and renderer.IsInViewport(*mouse_pos):
                scene = renderer._charts.toggle_interaction(mouse_pos)
            else:
                # Not in viewport or already an active chart found (in case they overlap), so disable interaction
                renderer._charts.toggle_interaction(False)

        # Set scene to interact with or reset it to stop interaction (otherwise crash)
        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, optional
            Whether to use the mouse wheel for zooming. By default
            zooming can be performed with right click and drag.

        shift_pans : bool, optional
            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.AddObserver(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.AddObserver(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: no cover
        """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: 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: 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: 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: 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: no cover
        """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_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_repeating_timer(self, stime):
        """Create a repeating timer.

        Returns
        -------
        int
            Timer ID.
        """
        timer_id = self.interactor.CreateRepeatingTimer(stime)
        if hasattr(self.interactor, 'ProcessEvents'):
            self.process_events()
        else:
            self.interactor.Start()
        self.interactor.DestroyTimer(timer_id)
        return timer_id

    def start(self):
        """Start interactions."""
        self.interactor.Start()

    def initialize(self):
        """Initialize the interactor."""
        self.interactor.Initialize()

    def set_render_window(self, ren_win):
        """Set the render window."""
        self.interactor.SetRenderWindow(ren_win)

    def process_events(self):
        """Process events."""
        # Note: This is only available in VTK 9+
        if not self.initialized:
            raise RuntimeError(
                'Render window interactor must be initialized before processing events.'
            )
        self.interactor.ProcessEvents()

    @property
    def initialized(self):
        """Return if the interactor has been initialized."""
        return self.interactor.GetInitialized()

    def get_picker(self):
        """Get the picker.

        Returns
        -------
        vtk.vtkAbstractPicker
            VTK picker.
        """
        return self.interactor.GetPicker()

    def set_picker(self, picker):
        """Set the picker."""
        self.interactor.SetPicker(picker)

    def fly_to(self, renderer, point):
        """Fly to the given point."""
        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 _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

    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.AddObserver("LeftButtonPressEvent", partial(try_callback, self._press))
            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)

    return CustomStyle


# pyvista/plotting/renderer.py

"""Module containing pyvista implementation of vtkRenderer."""

import collections.abc
from functools import partial
from typing import Sequence
import warnings
from weakref import proxy

import numpy as np

import pyvista
from pyvista import MAX_N_COLOR_BARS, _vtk
from pyvista.utilities import check_depth_peeling, try_callback, wrap
from pyvista.utilities.misc import uses_egl

from .camera import Camera
from .charts import Charts
from .colors import Color
from .tools import create_axes_marker, create_axes_orientation_box, parse_font_family

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.

    Attempt to place 2d actor in a sensible position.

    """
    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."""
    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 : tuple(float)
        Length 3 tuple of the point coordinates.

    invert : bool
        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."""

    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):
        """Location of the camera in world coordinates."""
        return self._position

    @position.setter
    def position(self, value):
        self._position = value

    @property
    def focal_point(self):
        """Location of the camera's focus in world coordinates."""
        return self._focal_point

    @focal_point.setter
    def focal_point(self, value):
        self._focal_point = value

    @property
    def viewup(self):
        """Viewup vector of the camera."""
        return self._viewup

    @viewup.setter
    def viewup(self, value):
        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):
        """Initialize the renderer."""
        super().__init__()
        self._actors = {}
        self.parent = parent  # weakref.proxy to the plotter from Renderers
        self._theme = parent.theme
        self.camera_set = False
        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

        # 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)

    @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._render_event))
        return self.__charts

    @property
    def camera_position(self):
        """Return 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):
        """Set camera position of all active render windows."""
        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:
                err = pyvista.core.errors.InvalidCameraError
                raise err(
                    '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 pyvista.core.errors.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 pyvista.core.errors.InvalidCameraError
                elif any([len(item) != 3 for item in camera_location]):
                    raise pyvista.core.errors.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):
        """Return the active camera for the rendering scene."""
        return self._camera

    @camera.setter
    def camera(self, source):
        """Set the active camera for the rendering scene."""
        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):
        """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 the_bounds.tolist()

    @property
    def length(self):
        """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):
        """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):
        """Return the background color of this renderer."""
        return Color(self.GetBackground())

    @background_color.setter
    def background_color(self, color):
        """Set the background color of this renderer."""
        self.set_background(color)
        self.Modified()

    def _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
            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
            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):
        """Enable anti-aliasing using FXAA.

        This tends to make edges appear softer and less pixelated.

        Warnings
        --------
        Enabling this causes screenshots with vtk compiled with OSMesa to be
        all black. This cannot be enabled when compiled with OSMesa (EGL). See
        https://github.com/pyvista/pyvista/issues/2686 for more details.

        Examples
        --------
        >>> import pyvista
        >>> pl = pyvista.Plotter()
        >>> pl.enable_anti_aliasing()
        >>> _ = pl.add_mesh(pyvista.Sphere(), show_edges=True)
        >>> pl.show()

        """
        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 does not properly support anti-aliasing and anti-aliasing will not be enabled."
                )
            return
        self.SetUseFXAA(True)
        self.Modified()

    def disable_anti_aliasing(self):
        """Disable anti-aliasing.

        Examples
        --------
        >>> import pyvista
        >>> pl = pyvista.Plotter()
        >>> pl.disable_anti_aliasing()
        >>> _ = pl.add_mesh(pyvista.Sphere(), show_edges=True)
        >>> pl.show()

        """
        self.SetUseFXAA(False)
        self.Modified()

    def add_border(self, color='white', width=2.0):
        """Add borders around the frame.

        Parameters
        ----------
        color : color_like, optional
            Color of the border.

        width : float, optional
            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):
        """Return if the renderer has a border."""
        return self._border_actor is not None

    @property
    def border_width(self):
        """Return the border width."""
        if self.has_border:
            return self._border_actor.GetProperty().GetLineWidth()
        return 0

    @property
    def border_color(self):
        """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 : Chart2D, ChartBox, ChartPie or ChartMPL
            Chart to add to renderer.

        *charts : Chart2D, ChartBox, ChartPie or ChartMPL
            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 not _vtk._has_vtkRenderingContextOpenGL2:  # 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)

    def remove_chart(self, chart_or_index):
        """Remove a chart from this renderer.

        Parameters
        ----------
        chart_or_index : Chart2D, ChartBox, ChartPie, ChartMPL 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()

        """
        self._charts.remove_chart(chart_or_index)

    @property
    def actors(self):
        """Return a dictionary of actors assigned to this renderer."""
        return self._actors

    def add_actor(
        self,
        uinput,
        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
        ----------
        uinput : vtk.vtkMapper or vtk.vtkActor
            Vtk mapper or vtk actor to be added.

        reset_camera : bool, optional
            Resets the camera when ``True``.

        name : str, optional
            Name to assign to the actor.  Defaults to the memory address.

        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.  Default
            ``False``.

        pickable : bool, optional
            Whether to allow this actor to be pickable within the
            render window.

        render : bool, optional
            If the render window is being shown, trigger a render
            after adding the actor.

        remove_existing_actor : bool, optional
            Removes any existing actor if the named actor ``name`` is already
            present.

        Returns
        -------
        actor : vtk.vtkActor
            The actor.

        actor_properties : vtk.Properties
            Actor properties.
        """
        # Remove actor by that name if present
        if name and remove_existing_actor:
            rv = self.remove_actor(name, reset_camera=False, render=False)

        if isinstance(uinput, _vtk.vtkMapper):
            actor = _vtk.vtkActor()
            actor.SetMapper(uinput)
        else:
            actor = uinput

        self.AddActor(actor)
        actor.renderer = proxy(self)

        if name is None:
            name = actor.GetAddressAsString("")

        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.')

        actor.SetPickable(pickable)
        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 : color_like, optional
            The color of the x axes arrow.

        y_color : color_like, optional
            The color of the y axes arrow.

        z_color : color_like, optional
            The color of the z axes arrow.

        xlabel : str, optional
            The label of the x axes arrow.

        ylabel : str, optional
            The label of the y axes arrow.

        zlabel : str, optional
            The label of the z axes arrow.

        line_width : int, optional
            Width of the arrows.

        labels_off : bool, optional
            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):
        """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 or 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.themes.DefaultTheme.interactive>`.

        color : color_like, optional
            The color of the actor.  This only applies if ``actor`` is
            a :class:`pyvista.DataSet`.

        opacity : int or float, optional
            Opacity of the marker.

        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 = _vtk.vtkActor()
            actor.SetMapper(mapper)
            prop = actor.GetProperty()
            if color is not None:
                prop.SetColor(Color(color).float_rgb)
            prop.SetOpacity(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)
        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,
        marker_args=None,
        box=None,
        box_args=None,
        viewport=(0, 0, 0.2, 0.2),
    ):
        """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, optional
            The width of the marker lines.

        color : color_like, optional
            Color of the labels.

        x_color : color_like, optional
            Color used for the x axis arrow.  Defaults to theme axes parameters.

        y_color : color_like, optional
            Color used for the y axis arrow.  Defaults to theme axes parameters.

        z_color : color_like, optional
            Color used for the z axis arrow.  Defaults to theme axes parameters.

        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.

        labels_off : bool, optional
            Enable or disable the text labels for the axes.

        marker_args : dict, optional
            Parameters for the orientation marker widget. See the parameters of
            :func:`pyvista.create_axes_marker`.

        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 : tuple, optional
            Viewport ``(xstart, ystart, xend, yend)`` of the widget.

        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)
        >>> marker_args = dict(cone_radius=0.6, shaft_length=0.7, tip_length=0.3, ambient=0.5, label_size=(0.4, 0.16))
        >>> _ = pl.add_axes(line_width=5, marker_args=marker_args)
        >>> pl.show()

        """
        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:
            if marker_args is None:
                marker_args = {}
            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,
                **marker_args,
            )
        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):
        """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,
        xlabel='X Axis',
        ylabel='Y Axis',
        zlabel='Z Axis',
        use_2d=False,
        grid=None,
        location='closest',
        ticks=None,
        all_edges=False,
        corner_factor=0.5,
        fmt=None,
        minor_ticks=False,
        padding=0.0,
        render=None,
    ):
        """Add bounds axes.

        Shows the bounds of the most recent input mesh unless mesh is
        specified.

        Parameters
        ----------
        mesh : pyvista.DataSet or pyvista.MultiBlock
            Input mesh to draw bounds axes around.

        bounds : list or tuple, optional
            Bounds to override mesh bounds in the form ``[xmin, xmax,
            ymin, ymax, zmin, zmax]``.

        axes_ranges : list, tuple, or numpy.ndarray, 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, optional
            Makes x axis visible.  Default ``True``.

        show_yaxis : bool, optional
            Makes y axis visible.  Default ``True``.

        show_zaxis : bool, optional
            Makes z axis visible.  Default ``True``.

        show_xlabels : bool, optional
            Shows x labels.  Default ``True``.

        show_ylabels : bool, optional
            Shows y labels.  Default ``True``.

        show_zlabels : bool, optional
            Shows z labels.  Default ``True``.

        bold : bool, optional
            Bolds axis labels and numbers.  Default ``True``.

        font_size : float, optional
            Sets the size of the label font. Defaults to
            :attr:`pyvista.global_theme.font.size
            <pyvista.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.themes._Font.family>`.

        color : color_like, optional
            Color of all labels and axis titles.  Defaults to
            :attr:`pyvista.global_theme.font.color
            <pyvista.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'``

        xlabel : str, optional
            Title of the x axis.  Default ``"X Axis"``.

        ylabel : str, optional
            Title of the y axis.  Default ``"Y Axis"``.

        zlabel : str, optional
            Title of the z axis.  Default ``"Z Axis"``.

        use_2d : bool, optional
            This can be enabled for smoother plotting.

            .. warning::
               A bug with vtk 6.3 in Windows seems to cause this
               function to crash.

        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, optional
            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, optional
            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, optional
            If ``all_edges````, this is the factor along each axis to
            draw the default box. Default is 0.5 to show 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, optional
            If ``True``, also plot minor ticks on all axes.

        padding : float, optional
            An optional percent padding along each axial direction to
            cushion the datasets in the scene from the axes
            annotations. Defaults to 0 (no padding).

        render : bool, optional
            If the render window is being shown, trigger a render
            after showing bounds.

        Returns
        -------
        vtk.vtkCubeAxesActor
            Bounds actor.

        Examples
        --------
        >>> import pyvista
        >>> mesh = pyvista.Sphere()
        >>> plotter = pyvista.Plotter()
        >>> actor = plotter.add_mesh(mesh)
        >>> actor = plotter.show_bounds(
        ...     grid='front',
        ...     location='outer',
        ...     all_edges=True,
        ... )
        >>> 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

        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 = _vtk.vtkCubeAxesActor()
        if use_2d or not np.allclose(self.scale, [1.0, 1.0, 1.0]):
            cube_axes_actor.SetUse2DMode(True)
        else:
            cube_axes_actor.SetUse2DMode(False)

        if grid:
            if isinstance(grid, str) and grid.lower() in ('front', 'frontface'):
                cube_axes_actor.SetGridLineLocation(cube_axes_actor.VTK_GRID_LINES_CLOSEST)
            if isinstance(grid, str) and grid.lower() in ('both', 'all'):
                cube_axes_actor.SetGridLineLocation(cube_axes_actor.VTK_GRID_LINES_ALL)
            else:
                cube_axes_actor.SetGridLineLocation(cube_axes_actor.VTK_GRID_LINES_FURTHEST)
            # 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(ticks, str):
            ticks = ticks.lower()
            if ticks in ('inside'):
                cube_axes_actor.SetTickLocationToInside()
            elif ticks in ('outside'):
                cube_axes_actor.SetTickLocationToOutside()
            elif ticks in ('both'):
                cube_axes_actor.SetTickLocationToBoth()
            else:
                raise ValueError(
                    f'Value of ticks ("{ticks}") should be either "inside", "outside", '
                    'or "both".'
                )
        elif ticks is not None:
            raise TypeError('ticks must be a string')

        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.SetBounds(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.SetXAxisRange(axes_ranges[0], axes_ranges[1])
            cube_axes_actor.SetYAxisRange(axes_ranges[2], axes_ranges[3])
            cube_axes_actor.SetZAxisRange(axes_ranges[4], axes_ranges[5])

        # show or hide axes
        cube_axes_actor.SetXAxisVisibility(show_xaxis)
        cube_axes_actor.SetYAxisVisibility(show_yaxis)
        cube_axes_actor.SetZAxisVisibility(show_zaxis)

        # disable minor ticks
        if not minor_ticks:
            cube_axes_actor.XAxisMinorTickVisibilityOff()
            cube_axes_actor.YAxisMinorTickVisibilityOff()
            cube_axes_actor.ZAxisMinorTickVisibilityOff()

        cube_axes_actor.SetCamera(self.camera)

        # 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)

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

        # show lines
        if show_xaxis:
            cube_axes_actor.SetXTitle(xlabel)
            if not show_xlabels:
                cube_axes_actor.SetAxisLabels(0, self._empty_str)
        else:
            cube_axes_actor.SetXTitle('')
            cube_axes_actor.SetAxisLabels(0, self._empty_str)

        if show_yaxis:
            cube_axes_actor.SetYTitle(ylabel)
            if not show_ylabels:
                cube_axes_actor.SetAxisLabels(1, self._empty_str)
        else:
            cube_axes_actor.SetYTitle('')
            cube_axes_actor.SetAxisLabels(1, self._empty_str)

        if show_zaxis:
            cube_axes_actor.SetZTitle(zlabel)
            if not show_zlabels:
                cube_axes_actor.SetAxisLabels(2, self._empty_str)
        else:
            cube_axes_actor.SetZTitle('')
            cube_axes_actor.SetAxisLabels(2, self._empty_str)

        # set font
        font_family = parse_font_family(font_family)
        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)

        # 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)

        if fmt is not None:
            cube_axes_actor.SetXLabelFormat(fmt)
            cube_axes_actor.SetYLabelFormat(fmt)
            cube_axes_actor.SetZLabelFormat(fmt)

        self.Modified()
        return cube_axes_actor

    def show_grid(self, **kwargs):
        """Show gridlines and axes labels.

        A wrapped implementation of ``show_bounds`` to change default
        behaviour to use gridlines and showing the axes labels on the
        outer edges. This is intended to be similar to
        ``matplotlib``'s ``grid`` function.

        Parameters
        ----------
        **kwargs : dict, optional
            See :func:`Renderer.show_bounds` for additional keyword
            arguments.

        Returns
        -------
        vtk.vtkAxesActor
            Bounds actor.

        Examples
        --------
        >>> import pyvista
        >>> from pyvista import examples
        >>> pl = pyvista.Plotter()
        >>> _ = pl.add_mesh(examples.download_guitar())
        >>> _ = 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, optional
            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 : color_like, optional
            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, optional
            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, optional
            Opacity of mesh.  Default 1.0 and should be between 0 and 1.

        render_lines_as_tubes : bool, optional
            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 is ``True``. when ``False``, a box with faces is
            shown with the specified culling.

        culling : str, optional
            Does not render faces that are culled. Options are
            ``'front'`` or ``'back'``. Default is ``'front'`` for
            bounding box.

        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, optional
            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, optional
            Number of points on the plane in the i direction.

        j_resolution : int, optional
            Number of points on the plane in the j direction.

        color : color_like, 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, optional
            The opacity of the generated surface.

        show_edges : bool, optional
            Flag on whether to show the mesh edges for tiling.

        line_width : float, optional
            Thickness of lines.  Only valid for wireframe and surface
            representations.  Default ``None``.

        lighting : bool, optional
            Enable or disable view direction lighting.  Default
            ``False``.

        edge_color : color_like, optional
            Color of of the edges of the mesh.

        reset_camera : bool, optional
            Resets the camera when ``True`` after adding the floor.

        pad : float, optional
            Percentage padding between 0 and 1.

        offset : float, optional
            Percentage offset along plane normal.

        pickable : bool, optional
            Make this floor actor pickable in the renderer.

        store_floor_kwargs : bool, optional
            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, optional
            Clear default floor arguments.  Default ``True``.

        render : bool, optional
            Render upon removing the floor.  Default ``True``.

        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 hasattr(self, 'cube_axes_actor'):
            self.remove_actor(self.cube_axes_actor)
            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):
        """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 0x7f1dd8155820>,
         <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(self):
        """Remove all actors and properties."""
        if self._actors:
            for actor in list(self._actors):
                try:
                    self.remove_actor(actor, reset_camera=False, render=False)
                except KeyError:
                    pass

        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
            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):
        """Set camera position to a point.

        Parameters
        ----------
        point : sequence
            Cartesian point to focus on in the form of ``[x, y, z]``.

        reset : bool, optional
            Whether to reset the camera after setting the camera
            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()
        self.camera_set = True
        self.Modified()

    def set_viewup(self, vector, reset=True):
        """Set camera viewup vector.

        Parameters
        ----------
        vector : sequence
            New 3 value camera viewup vector.

        reset : bool, optional
            Whether to reset the camera after setting the camera
            position.

        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()

        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):
        """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):
        """Set parallel projection state of all active render windows."""
        self.camera.parallel_projection = state
        self.Modified()

    @property
    def parallel_scale(self):
        """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):
        """Set parallel scale of all active render windows."""
        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
        self.parent.scalar_bars._remove_mapper_from_plotter(actor)
        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()
        elif not self.camera_set and reset_camera is None:
            self.reset_camera()
        elif render:
            self.parent.render()

        self.Modified()
        return True

    def set_scale(self, xscale=None, yscale=None, zscale=None, reset_camera=True):
        """Scale all the datasets 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.

        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, optional
            Resets camera so all actors can be seen.  Default ``True``.

        Examples
        --------
        Set the scale in the z direction to be 5 times that of
        nominal.  Leave the other axes unscaled.

        >>> import pyvista
        >>> pl = pyvista.Plotter()
        >>> pl.set_scale(zscale=5)
        >>> _ = 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]

        # Update the camera's coordinate system
        transform = np.diag([xscale, yscale, zscale, 1.0])
        self.camera.model_transform_matrix = transform
        self.parent.render()
        if reset_camera:
            self.update_bounds_axes()
            self.reset_camera()
        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
            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 hasattr(self, 'cube_axes_actor'):
            self.cube_axes_actor.SetBounds(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
            Trigger a render after resetting the camera.
        bounds : iterable(int)
            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):
        """Reset the camera to a default isometric view.

        The view will show all the actors in the scene.

        Parameters
        ----------
        negative : bool, optional
            View from the other isometric direction.

        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()

    def view_vector(self, vector, viewup=None):
        """Point the camera in the direction of the given vector.

        Parameters
        ----------
        vector : sequence
            Three item sequence to point the camera in.

        viewup : sequence, optional
            Three item sequence describing the view up of the camera.

        """
        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()

    def view_xy(self, negative=False):
        """View the XY plane.

        Parameters
        ----------
        negative : bool, optional
            View from the opposite direction.

        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()

        """
        vec = np.array([0, 0, 1])
        viewup = np.array([0, 1, 0])
        if negative:
            vec *= -1
        self.view_vector(vec, viewup)

    def view_yx(self, negative=False):
        """View the YX plane.

        Parameters
        ----------
        negative : bool, optional
            View from the opposite direction.

        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()

        """
        vec = np.array([0, 0, -1])
        viewup = np.array([1, 0, 0])
        if negative:
            vec *= -1
        self.view_vector(vec, viewup)

    def view_xz(self, negative=False):
        """View the XZ plane.

        Parameters
        ----------
        negative : bool, optional
            View from the opposite direction.

        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()

        """
        vec = np.array([0, -1, 0])
        viewup = np.array([0, 0, 1])
        if negative:
            vec *= -1
        self.view_vector(vec, viewup)

    def view_zx(self, negative=False):
        """View the ZX plane.

        Parameters
        ----------
        negative : bool, optional
            View from the opposite direction.

        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()

        """
        vec = np.array([0, 1, 0])
        viewup = np.array([1, 0, 0])
        if negative:
            vec *= -1
        self.view_vector(vec, viewup)

    def view_yz(self, negative=False):
        """View the YZ plane.

        Parameters
        ----------
        negative : bool, optional
            View from the opposite direction.

        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()

        """
        vec = np.array([1, 0, 0])
        viewup = np.array([0, 0, 1])
        if negative:
            vec *= -1
        self.view_vector(vec, viewup)

    def view_zy(self, negative=False):
        """View the ZY plane.

        Parameters
        ----------
        negative : bool, optional
            View from the opposite direction.

        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()

        """
        vec = np.array([-1, 0, 0])
        viewup = np.array([0, 1, 0])
        if negative:
            vec *= -1
        self.view_vector(vec, viewup)

    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 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()

        """
        if hasattr(self, 'edl_pass'):
            return self
        # create the basic VTK render steps
        basic_passes = _vtk.vtkRenderStepsPass()
        # blur the resulting image
        # The blur delegates rendering the unblured image to the basic_passes
        self.edl_pass = _vtk.vtkEDLShading()
        self.edl_pass.SetDelegatePass(basic_passes)

        # tell the renderer to use our render pass pipeline
        self.glrenderer = _vtk.vtkOpenGLRenderer.SafeDownCast(self)
        self.glrenderer.SetPass(self.edl_pass)
        self.Modified()
        return self.glrenderer

    def disable_eye_dome_lighting(self):
        """Disable eye dome lighting (EDL).

        Examples
        --------
        >>> import pyvista
        >>> pl = pyvista.Plotter()
        >>> pl.disable_eye_dome_lighting()

        """
        if not hasattr(self, 'edl_pass'):
            return
        self.SetPass(None)
        self.edl_pass.ReleaseGraphicsResources(self.parent.ren_win)
        del self.edl_pass
        self.Modified()

    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()

        """
        if self._shadow_pass is not None:
            # shadows are already enabled for this renderer
            return

        shadows = _vtk.vtkShadowMapPass()

        passes = _vtk.vtkRenderPassCollection()
        passes.AddItem(shadows.GetShadowMapBakerPass())
        passes.AddItem(shadows)

        seq = _vtk.vtkSequencePass()
        seq.SetPasses(passes)

        # Tell the renderer to use our render pass pipeline
        self._shadow_pass = _vtk.vtkCameraPass()
        self._shadow_pass.SetDelegatePass(seq)
        self.SetPass(self._shadow_pass)
        self.Modified()

    def disable_shadows(self):
        """Disable shadows.

        Examples
        --------
        >>> import pyvista
        >>> pl = pyvista.Plotter()
        >>> pl.disable_shadows()

        """
        if self._shadow_pass is None:
            # shadows are already disabled
            return

        self.SetPass(None)
        if hasattr(self.parent, 'ren_win'):
            self._shadow_pass.ReleaseGraphicsResources(self.parent.ren_win)
        self._shadow_pass = None
        self.Modified()

    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 : color_like, 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 : color_like, 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 : vtk.vtkTexture
            Texture.

        is_srgb : bool, optional
            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 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 hasattr(self, 'cube_axes_actor'):
            del self.cube_axes_actor
        if hasattr(self, 'edl_pass'):
            del self.edl_pass
        if hasattr(self, '_box_object'):
            self.remove_bounding_box(render=render)
        if self._shadow_pass is not None:
            self.disable_shadows()
        if self.__charts is not None:
            self.__charts.deep_clean()
            self.__charts = None

        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):
        """Return or set the current layer of this renderer."""
        return self.GetLayer()

    @layer.setter
    def layer(self, layer):
        self.SetLayer(layer)

    @property
    def viewport(self):
        """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):
        """Width of the renderer."""
        xmin, _, xmax, _ = self.viewport
        return self.parent.window_size[0] * (xmax - xmin)

    @property
    def height(self):
        """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 <BasePlotter.add_mesh>`
            - :func:`add_lines <BasePlotter.add_lines>`
            - :func:`add_points <BasePlotter.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 : color_like, optional
            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, optional
            Controls if there will be a border around the legend.
            Default False.

        size : sequence, optional
            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, optional
            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 or pyvista.PolyData, optional
            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`

            Default is ``'triangle'``.  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, optional
            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):
        """Legend actor."""
        return self._legend


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``."""

    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 = []

        # 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 group id of the given location index or ``None`` if this location is not part of any group."""
        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, tuple, or list
            Index of the renderer to add the actor to.  For example,
            ``loc=2`` or ``loc=(1, 1)``.

        Returns
        -------
        idx : 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."""
        for renderer in self._renderers:
            yield renderer

    @property
    def active_index(self):
        """Return the 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."""
        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):
        """Return the active renderer."""
        return self._renderers[self._active_index]

    @property
    def shape(self):
        """Return the 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
            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 deep_clean(self):
        """Clean all renderers."""
        # Do not remove the renderers on the clean
        for renderer in self:
            renderer.deep_clean()
        if hasattr(self, '_shadow_renderer'):
            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, optional
            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, optional
            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):
        """Return ``True`` when Renderer has an active 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(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):
        """Shadow renderer."""
        return self._shadow_renderer

    def set_background(self, color, top=None, all_renderers=True):
        """Set the background color.

        Parameters
        ----------
        color : color_like, 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 : color_like, 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
            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')
        >>> 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 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."""
        if hasattr(self, '_shadow_renderer'):
            del self._shadow_renderer


# pyvista/plotting/scalar_bars.py

"""PyVista Scalar bar module."""

import numpy as np

import pyvista
from pyvista import _vtk

from .colors import Color
from .tools import parse_font_family


class ScalarBars:
    """Plotter Scalar Bars."""

    def __init__(self, plotter):
        """Initialize ScalarBars."""
        self._plotter = 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):
        """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, optional
            Render upon scalar bar removal.  Set this to ``False`` to
            stop the render window from rendering when an 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, optional
            Title of the scalar bar.  Default ``''`` which 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, optional
            Number of labels to use for the scalar bar.

        italic : bool, optional
            Italicises title and bar labels.  Default ``False``.

        bold  : bool, optional
            Bolds title and bar labels.  Default ``True``.

        title_font_size : float, optional
            Sets the size of the title font.  Defaults to ``None`` and is sized
            according to :attr:`pyvista.themes.DefaultTheme.font`.

        label_font_size : float, optional
            Sets the size of the title font.  Defaults to ``None`` and is sized
            according to :attr:`pyvista.themes.DefaultTheme.font`.

        color : color_like, optional
            Either a string, rgb list, or hex color string.  Default
            set by :attr:`pyvista.themes.DefaultTheme.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.themes.DefaultTheme.font`.

        shadow : bool, optional
            Adds a black shadow to the text.  Defaults to ``False``.

        width : float, optional
            The percentage (0 to 1) width of the window for the colorbar.
            Default set by
            :attr:`pyvista.themes.DefaultTheme.colorbar_vertical` or
            :attr:`pyvista.themes.DefaultTheme.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.themes.DefaultTheme.colorbar_vertical` or
            :attr:`pyvista.themes.DefaultTheme.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.themes.DefaultTheme.colorbar_vertical` or
            :attr:`pyvista.themes.DefaultTheme.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.themes.DefaultTheme.colorbar_vertical` or
            :attr:`pyvista.themes.DefaultTheme.colorbar_horizontal`
            depending on the value of ``vertical``.

        vertical : bool, optional
            Use vertical or horizontal scalar bar.  Default set by
            :attr:`pyvista.themes.DefaultTheme.colorbar_orientation`.

        interactive : bool, optional
            Use a widget to control the size and location of the scalar bar.
            Default set by :attr:`pyvista.themes.DefaultTheme.interactive`.

        fmt : str, optional
            ``printf`` format for labels.
            Default set by :attr:`pyvista.themes.DefaultTheme.font`.

        use_opacity : bool, optional
            Optionally display the opacity mapping on the scalar bar.

        outline : bool, optional
            Optionally outline the scalar bar to make opacity mappings more
            obvious.

        nan_annotation : bool, optional
            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 : color_like, 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, optional
            Draw a filled box behind the scalar bar with the
            ``background_color``.

        render : bool, optional
            Force a render when True.  Default ``True``.

        theme : pyvista.themes.DefaultTheme, 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:
            try:
                slot = min(self._plotter._scalar_bar_slots)
                self._plotter._scalar_bar_slots.remove(slot)
                self._plotter._scalar_bar_slot_lookup[title] = slot
            except:
                raise RuntimeError('Maximum number of color bars reached.')
            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 = _vtk.vtkLookupTable()
            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 not None:
            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:
            scalar_bar.DrawAboveRangeSwatchOn()
            scalar_bar.SetAboveRangeAnnotation(above_label)
        if below_label:
            scalar_bar.DrawBelowRangeSwatchOn()
            scalar_bar.SetBelowRangeAnnotation(below_label)

        # 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/theme.py

"""Here for backwards compatibility with pyvistaqt."""

from pyvista import rcParams  # noqa

from .tools import parse_color  # noqa


# pyvista/plotting/tools.py

"""Module containing useful plotting tools."""

from collections.abc import Sequence
from enum import Enum
import os
import platform
from subprocess import PIPE, Popen
import warnings

import numpy as np

import pyvista
from pyvista import _vtk
from pyvista.utilities import PyvistaDeprecationWarning

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."""
    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)
        proc.communicate()
        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)
        proc.communicate()
        return proc.returncode == 0
    except OSError:
        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 : color_like, optional
        Unknown

    x_color : color_like, optional
        Color of the x axis text.

    y_color : color_like, optional
        Color of the y axis text.

    z_color : color_like, 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.

    labels_off : bool, optional
        Enable or disable the text labels for the axes.

    line_width : float, optional
        The width of the marker lines.

    cone_radius: float, optional
        The radius of the axes arrow tips.

    shaft_length: float, optional
        The length of the axes arrow shafts.

    ambient: float, optional
        The ambient of the axes arrows.

    label_size: sequence, optoinal
        The width and height of the axes label actors.

    Returns
    -------
    vtk.vtkAxesActor
        Axes actor.

    """
    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 : color_like, optional
        Color of the edges.

    x_color : color_like, optional
        Color of the x axis text.

    y_color : color_like, optional
        Color of the y axis text.

    z_color : color_like, 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 : color_like, optional
        Color used for the x axis arrow.  Defaults to theme axes
        parameters.

    y_face_color : color_like, optional
        Color used for the y axis arrow.  Defaults to theme axes
        parameters.

    z_face_color : color_like, 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 : color_like, 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 = _vtk.vtkActor()
        cube_actor.SetMapper(cube_mapper)
        cube_actor.GetProperty().BackfaceCullingOn()
        cube_actor.GetProperty().SetOpacity(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]."""
    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_3-10'.
        Append an '_r' to any of those names to reverse that mapping.
        This can also be a custom array/list of values that will be
        interpolated across the ``n_color`` range for user defined mappings.

    n_colors : int
        The amount 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 interepolation kind if ``interpolate`` is true and ``scipy`` is
        available. Options are ('linear', 'nearest', 'zero', 'slinear',
        'quadratic', 'cubic', 'previous', 'next'.

    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.
    >>> # 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_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)),
    }
    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 KeyError(f'opactiy transfer function ({mapping}) unknown.')
    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_color(color, opacity=None, default_color=None):  # pragma: no cover
    """Parse color into a VTK friendly RGB(A) tuple.

    .. deprecated:: 0.34.0
        Use :class:`Color` to parse and convert colors instead.

    If ``color`` is a sequence of RGBA floats, the ``opacity`` parameter
    is ignored.

    Values returned will be between 0 and 1.

    Parameters
    ----------
    color : color_like
        Either a string, RGB sequence, RGBA sequence, or hex color string.
        RGB(A) sequences should only contain values between 0 and 1.
        For example:

        * ``'white'``
        * ``'w'``
        * ``[1.0, 1.0, 1.0]``
        * ``[0.5, 1.0, 0.7, 1.0]``
        * ``'#FFFFFF'``

    opacity : float, optional
        Default opacity of the returned color. Used when ``color`` is
        not a length 4 RGBA sequence. Only opacities between 0 and 1
        are allowed.

    default_color : color_like, optional
        Default color to use when ``color`` is None.  If this value is
        ``None``, then defaults to the global theme color.  Format is
        identical to ``color``.

    Returns
    -------
    tuple
        Either a length 3 RGB sequence if opacity is unset, or an RGBA
        sequence when ``opacity`` is set or the input ``color`` is an
        RGBA sequence.

    Examples
    --------
    >>> import pyvista
    >>> pyvista.parse_color('blue')
    (0.0, 0.0, 1.0)

    >>> pyvista.parse_color('k')
    (0.0, 0.0, 0.0)

    >>> pyvista.parse_color('#FFFFFF')
    (1.0, 1.0, 1.0)

    >>> pyvista.parse_color((0.4, 0.3, 0.4, 1))
    (0.4, 0.3, 0.4, 1.0)

    """
    # Deprecated on v0.34.0, estimated removal on v0.37.0
    warnings.warn(
        "The usage of `parse_color` is deprecated in favor of the new `Color` class.",
        PyvistaDeprecationWarning,
    )
    color_valid = True
    if color is None:
        if default_color is None:
            color = pyvista.global_theme.color
        else:
            color = default_color
    if isinstance(color, str):
        color = Color(color).float_rgb
    elif isinstance(color, (Sequence, np.ndarray)):
        try:
            color = np.asarray(color, dtype=np.float64)
            if (
                color.ndim != 1
                or color.size not in (3, 4)
                or not np.all((0 <= color) & (color <= 1))
            ):
                color_valid = False
            elif len(color) == 4:
                opacity = color[3]
                color = color[:3]
        except ValueError:
            color_valid = False
    else:
        color_valid = False
    if not color_valid:
        raise ValueError(
            "\n"
            f"\tInvalid color input: ({color})\n"
            "\tMust be string, rgb list, or hex color string.  For example:\n"
            "\t\tcolor='white'\n"
            "\t\tcolor='w'\n"
            "\t\tcolor=[1, 1, 1]\n"
            "\t\tcolor='#FFFFFF'"
        )
    if opacity is not None:
        if isinstance(opacity, (float, int)) and 0 <= opacity <= 1:
            color = [color[0], color[1], color[2], float(opacity)]
        else:
            raise ValueError(
                "\n"
                f"\tInvalid opacity input: {opacity}\n"
                "\tMust be a scalar value between 0 and 1."
            )
    return tuple(color)


def parse_font_family(font_family):
    """Check font name."""
    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


# pyvista/plotting/widgets.py

"""Module dedicated to widgets."""

import numpy as np

import pyvista
from pyvista import _vtk
from pyvista.utilities import (
    NORMALS,
    generate_plane,
    get_array,
    get_array_association,
    try_callback,
)

from .colors import Color


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 = []

    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=_vtk.vtkCommand.EndInteractionEvent,
    ):
        """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 : color_like, optional
            Either a string, rgb sequence, or hex color string.
            Defaults to :attr:`pyvista.global_theme.font.color
            <pyvista.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, optional
            The VTK interaction event to use for triggering the callback.

        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`.

        """
        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=_vtk.vtkCommand.EndInteractionEvent,
        **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
            The input dataset to add to the scene and clip.

        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 : color_like, 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, optional
            The VTK interaction event to use for triggering the callback.

        **kwargs : dict, optional
            All additional keyword arguments are passed to
            :func:`BasePlotter.add_mesh` to control how the mesh is
            displayed.

        Returns
        -------
        vtk.vtkActor
            VTK actor of the 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))

        self.add_mesh(mesh.outline(), name=f"{name}-outline", opacity=0.0)

        port = 1 if invert else 0

        if crinkle:
            mesh.cell_data['cell_ids'] = np.arange(mesh.n_cells)

        alg = _vtk.vtkBoxClipDataSet()
        if not merge_points:
            # vtkBoxClipDataSet uses vtkMergePoints by default
            alg.SetLocator(_vtk.vtkNonMergingPointLocator())
        alg.SetInputDataObject(mesh)
        alg.GenerateClippedOutputOn()

        box_clipped_mesh = pyvista.wrap(alg.GetOutput(port))
        self.box_clipped_meshes.append(box_clipped_mesh)

        def callback(planes):
            bounds = []
            for i in range(planes.GetNumberOfPlanes()):
                plane = planes.GetPlane(i)
                bounds.append(plane.GetNormal())
                bounds.append(plane.GetOrigin())

            alg.SetBoxClip(*bounds)
            alg.Update()
            clipped = pyvista.wrap(alg.GetOutput(port))
            if crinkle:
                clipped = mesh.extract_cells(np.unique(clipped.cell_data['cell_ids']))
            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,
        )

        return self.add_mesh(box_clipped_mesh, 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=_vtk.vtkCommand.EndInteractionEvent,
    ):
        """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 : color_like, 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, optional
            The VTK interaction event to use for triggering the callback.

        Returns
        -------
        vtk.vtkImplicitPlaneWidget or vtk.vtkPlaneWidget
            Plane widget.

        """
        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.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(interaction_event, _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, _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=_vtk.vtkCommand.EndInteractionEvent,
        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
            The input dataset to add to the scene and clip.

        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 : color_like, 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, 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:`BasePlotter.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

        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(mesh.outline(), name=f"{name}-outline", opacity=0.0)

        if crinkle:
            mesh.cell_data['cell_ids'] = np.arange(0, mesh.n_cells, dtype=int)

        if isinstance(mesh, _vtk.vtkPolyData):
            alg = _vtk.vtkClipPolyData()
        # elif isinstance(mesh, vtk.vtkImageData):
        #     alg = vtk.vtkClipVolume()
        #     alg.SetMixed3DCellGeneration(True)
        else:
            alg = _vtk.vtkTableBasedClipDataSet()
        alg.SetInputDataObject(mesh)  # Use the grid as the data we desire to cut
        alg.SetValue(value)
        alg.SetInsideOut(invert)  # invert the clip if needed

        plane_clipped_mesh = _get_output(alg)
        self.plane_clipped_meshes.append(plane_clipped_mesh)

        def callback(normal, loc):
            function = generate_plane(normal, loc)
            alg.SetClipFunction(function)  # the implicit function
            alg.Update()  # Perform the Cut
            clipped = pyvista.wrap(alg.GetOutput())
            if crinkle:
                clipped = mesh.extract_cells(np.unique(clipped.cell_data['cell_ids']))
            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,
        )

        return self.add_mesh(plane_clipped_mesh, **kwargs)

    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
            The input dataset to add to the scene and slice.

        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 : color_like, 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:`BasePlotter.add_mesh` to control how the mesh is
            displayed.

        Returns
        -------
        vtk.vtkActor
            VTK actor of the 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(mesh.outline(), name=f"{name}-outline", opacity=0.0)

        alg = _vtk.vtkCutter()  # Construct the cutter object
        alg.SetInputDataObject(mesh)  # Use the grid as the data we desire to cut
        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):
            # 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(plane_sliced_mesh, **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
            The input dataset to add to the scene and threshold.

        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 : color_like, 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:`BasePlotter.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 : color_like, optional, defaults to white
            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 : boollist
            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,
        event_type='end',
        style=None,
    ):
        """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 : color_like, optional
            Either a string, RGB list, or hex color string.  Defaults
            to :attr:`pyvista.global_theme.font.color
            <pyvista.themes._Font.color>`.

        event_type : str, optional
            Either ``'start'``, ``'end'`` or ``'always'``, this
            defines how often the slider interacts with the callback.

        style : str, optional
            The name of the slider style. The list of available styles
            are in ``pyvista.global_theme.slider_styles``. Defaults to
            ``None``.

        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,
            event_type=event_type,
            style=style,
        )
        slider_rep = slider_widget.GetRepresentation()
        slider_rep.ShowSliderLabelOff()

        def title_callback(widget, event):
            value = widget.GetRepresentation().GetValue()
            idx = int(value / delta)
            # handle limit index
            if idx == n_states:
                idx = n_states - 1
            slider_rep.SetTitleText(data[idx])

        if event_type == 'start':
            slider_widget.AddObserver(_vtk.vtkCommand.StartInteractionEvent, title_callback)
        elif event_type == 'end':
            slider_widget.AddObserver(_vtk.vtkCommand.EndInteractionEvent, title_callback)
        elif event_type == 'always':
            slider_widget.AddObserver(_vtk.vtkCommand.InteractionEvent, title_callback)
        else:
            raise ValueError(
                "Expected value for `event_type` is 'start',"
                f" 'end' or 'always': {event_type} was given."
            )
        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,
        event_type='end',
        style=None,
        title_height=0.03,
        title_opacity=1.0,
        title_color=None,
        fmt=None,
    ):
        """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
            The method called every time the slider is updated. This
            should take a single parameter: the float value of the
            slider.

        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 : color_like, optional
            Either a string, RGB list, or hex color string.  Defaults
            to :attr:`pyvista.global_theme.font.color
            <pyvista.themes._Font.color>`.

        pass_widget : bool, optional
            If ``True``, the widget will be passed as the last
            argument of the callback.

        event_type : str, optional
            Either ``'start'``, ``'end'`` or ``'always'``, this
            defines how often the slider interacts with the callback.

        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 : color_like, 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``.

        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 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):
            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)

        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()
        if not isinstance(event_type, str):
            raise TypeError(f"Expected type for `event_type` is str: {type(event_type)} was given.")
        if event_type == 'start':
            slider_widget.AddObserver(_vtk.vtkCommand.StartInteractionEvent, _the_callback)
        elif event_type == 'end':
            slider_widget.AddObserver(_vtk.vtkCommand.EndInteractionEvent, _the_callback)
        elif event_type == 'always':
            slider_widget.AddObserver(_vtk.vtkCommand.InteractionEvent, _the_callback)
        else:
            raise ValueError(
                "Expected value for `event_type` is 'start',"
                f" 'end' or 'always': {event_type} was given."
            )
        _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,
        **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
            The input dataset to add to the scene and threshold.

        scalars : str, optional
            The string name of the scalars on the mesh to threshold and display.

        invert : bool, optional
            Invert (flip) the threshold.

        widget_color : color_like, 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, optional
            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, optional
            The relative coordinates of the left point of the slider
            on the display port.

        pointb : sequence, optional
            The relative coordinates of the right point of the slider
            on the display port.

        continuous : bool, optional
            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.

        **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.

        """
        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(mesh.outline(), name=f"{name}-outline", opacity=0.0)

        alg = _vtk.vtkThreshold()
        alg.SetInputDataObject(mesh)
        alg.SetInputArrayToProcess(
            0, 0, 0, field.value, scalars
        )  # args: (idx, port, connection, field, name)
        alg.SetUseContinuousCellRange(continuous)

        threshold_mesh = pyvista.wrap(alg.GetOutput())
        self.threshold_meshes.append(threshold_mesh)

        def callback(value):
            if invert:
                alg.ThresholdByLower(value)
            else:
                alg.ThresholdByUpper(value)
            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(threshold_mesh, 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.

        Parameters
        ----------
        mesh : pyvista.DataSet
            The input dataset to add to the scene and contour.

        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 : color_like, 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:`BasePlotter.add_mesh` to control how the mesh is
            displayed.

        Returns
        -------
        vtk.vtkActor
            VTK actor of the mesh.

        """
        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()
        alg.SetInputDataObject(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(mesh.outline(), name=f"{name}-outline", opacity=0.0)

        isovalue_mesh = pyvista.wrap(alg.GetOutput())
        self.isovalue_meshes.append(isovalue_mesh)

        def callback(value):
            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(isovalue_mesh, 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 : 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.

        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 : color_like, 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 : color_like, 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
            The input dataset to add to the scene and slice along the spline.

        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 : color_like, 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 : color_like, 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:`BasePlotter.add_mesh` to control how the mesh is
            displayed.

        Returns
        -------
        vtk.vtkActor
            VTK actor of the 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(mesh.outline(), name=f"{name}-outline", opacity=0.0)

        alg = _vtk.vtkCutter()  # Construct the cutter object
        alg.SetInputDataObject(mesh)  # Use the grid as the data we desire to cut
        if not generate_triangles:
            alg.GenerateTrianglesOff()

        spline_sliced_mesh = pyvista.wrap(alg.GetOutput())
        self.spline_sliced_meshes.append(spline_sliced_mesh)

        def callback(spline):
            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(spline_sliced_mesh, **kwargs)

    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).  If multiple centers
            are passed in the ``center`` parameter, the callback must
            also accept an index of that widget.

        center : tuple(float), optional
            Length 3 array for the XYZ 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 : color_like, 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 : color_like, optional
            Color of the widget when selected during interaction.

        indices : sequence, 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_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, optional
            The default state of the button.

        position : tuple(float), optional
            The absolute coordinates of the bottom left point of the button.

        size : int, optional
            The size of the button in number of pixels.

        border_size : int, optional
            The size of the borders of the button in pixels.

        color_on : color_like, optional
            The color used when the button is checked. Default is ``'blue'``.

        color_off : color_like, optional
            The color used when the button is not checked. Default is ``'grey'``.

        background_color : color_like, 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`.

        """

        def create_button(color1, color2, color3, dims=(size, size, 1)):
            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.UniformGrid(dims=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, optional
            Enable or disable jump-to-axis-view animation.
        n_frames : int, optional
            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()

        """
        widget = _vtk.lazy_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()


# pyvista/plotting/_property.py
"""This module contains the Property class."""
from functools import lru_cache

import pyvista as pv
from pyvista import _vtk

from .colors import Color


@lru_cache(maxsize=None)
def _check_supports_pbr():
    """Check if VTK supports physically based rendering."""
    if not _vtk.VTK9:  # pragma: no cover
        from pyvista.core.errors import VTKVersionError

        raise VTKVersionError('Physically based rendering requires VTK 9 or newer.')


class Property(_vtk.vtkProperty):
    """Wrap vtkProperty and expose it pythonically.

    This class is used to set the property of actors.

    Parameters
    ----------
    theme : pyvista.themes.DefaultTheme, optional
        Plot-specific theme.

    interpolation : str, optional
        Set the method of shading. One of the following:

        * ``'Physically based rendering'`` - Physically based rendering.
        * ``'pbr'`` - Alias for Physically based rendering.
        * ``'Phong'`` - Phong shading.
        * ``'Gouraud'`` - Gouraud shading.
        * ``'Flat'`` - Flat Shading.

        This parameter is case insensitive.

    color : color_like, optional
        Used 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.

    style : str, optional
        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.

    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.

    point_size : float, optional
        Size of the points represented by this property.

    opacity : float, optional
        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.

    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.

    show_edges : bool, optional
        Shows the edges.  Does not apply to a wireframe
        representation.

    edge_color : color_like, optional
        The solid color to give the edges when ``show_edges=True``.
        Either a string, RGB list, or hex color string.

    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``.

    lighting : bool, optional
        Enable or disable view direction lighting.

    line_width : float, optional
        Thickness of lines.  Only valid for wireframe and surface
        representations.

    culling : str, bool, optional
        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. Defaults to
        ``'none'``. One of the following:

        * ``"back"`` - Enable backface culling
        * ``"front"`` - Enable frontface culling
        * ``'none'`` - Disable both backface and frontface culling

    Examples
    --------
    Create a vtk Actor and assign properties to it.

    >>> import vtk
    >>> import pyvista as pv
    >>> prop = pv.Property(
    ...     color='r',
    ...     show_edges=True,
    ...     interpolation='Physically based rendering',
    ...     metallic=0.5,
    ...     roughness=0.1
    ... )
    >>> actor = vtk.vtkActor()
    >>> actor.SetProperty(prop)

    Visualize how the property would look when applied to a mesh.

    >>> prop.plot()

    Set custom properties not directly available in
    :func:`pyvista.Plotter.add_mesh`. Here, we set diffuse, ambient, and
    specular power and colors.

    >>> pl = pv.Plotter()
    >>> actor = pl.add_mesh(pv.Sphere())
    >>> prop = actor.GetProperty()
    >>> prop.diffuse = 0.6
    >>> prop.diffuse_color = 'w'
    >>> prop.ambient = 0.3
    >>> prop.ambient_color = 'r'
    >>> prop.specular = 0.5
    >>> prop.specular_color = 'b'
    >>> pl.show()

    """

    def __init__(
        self,
        theme=None,
        interpolation=None,
        color=None,
        style=None,
        metallic=None,
        roughness=None,
        point_size=None,
        opacity=None,
        ambient=None,
        diffuse=None,
        specular=None,
        specular_power=None,
        show_edges=None,
        edge_color=None,
        render_points_as_spheres=None,
        render_lines_as_tubes=None,
        lighting=None,
        line_width=None,
        culling=None,
    ):
        """Initialize this property."""
        self._theme = pv.themes.DefaultTheme()
        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)

        if interpolation is not None:
            self.interpolation = interpolation

        self.color = color

        if style is not None:
            self.style = style

        if interpolation in ['Physically based rendering', 'pbr']:
            if metallic is not None:
                self.metallic = metallic
            if roughness is not None:
                self.roughness = roughness

        if point_size is not None:
            self.point_size = point_size
        if opacity is not None:
            self.opacity = opacity
        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 show_edges is None:
            self.show_edges = self._theme.show_edges
        else:
            self.show_edges = show_edges

        self.edge_color = edge_color
        if render_points_as_spheres is not None:
            self.render_points_as_spheres = render_points_as_spheres
        if render_lines_as_tubes is not None:
            self.render_lines_as_tubes = render_lines_as_tubes
        self.lighting = lighting
        if line_width is not None:
            self.line_width = line_width
        if culling is not None:
            self.culling = culling

    @property
    def style(self) -> str:
        """Return or set Visualization style of the mesh.

        One of the following (case insensitive):

        * ``'surface'``
        * ``'wireframe'``
        * ``'points'``

        Examples
        --------
        Set the representation style to ``'Wireframe'``

        >>> import pyvista as pv
        >>> prop = pv.Property()
        >>> prop.style = 'wireframe'
        >>> prop.style
        'Wireframe'

        Visualize default surface representation style.

        >>> prop.style = 'surface'
        >>> prop.plot()

        Visualize wireframe representation style.

        >>> prop.style = 'wireframe'
        >>> prop.plot()

        Visualize points representation style.

        >>> prop.style = 'points'
        >>> prop.point_size = 5.0
        >>> prop.plot()
        """
        return self.GetRepresentationAsString()

    @style.setter
    def style(self, new_style: str):
        new_style = new_style.lower()

        if new_style == 'wireframe':
            self.SetRepresentationToWireframe()
            if not self._color_set:
                self.color = self._theme.outline_color
        elif new_style == 'points':
            self.SetRepresentationToPoints()
        elif new_style == 'surface':
            self.SetRepresentationToSurface()
        else:
            raise ValueError(
                f'Invalid style "{new_style}".  Must be one of the following:\n'
                '\t"surface"\n'
                '\t"wireframe"\n'
                '\t"points"\n'
            )

    @property
    def color(self) -> Color:
        """Return or set the color of this property.

        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.

        Examples
        --------
        Set the color to blue.

        >>> import pyvista as pv
        >>> prop = pv.Property()
        >>> prop.color = 'b'
        >>> prop.color
        Color(name='blue', hex='#0000ffff')

        Visualize setting the property to blue.

        >>> prop.color = 'b'
        >>> prop.plot()

        Visualize setting the color using an RGB value.

        >>> prop.color = (0.5, 0.5, 0.1)
        >>> prop.plot()

        """
        return Color(self.GetColor())

    @color.setter
    def color(self, value):
        self._color_set = value is None
        rgb_color = Color(value, default_color=self._theme.color)
        self.SetColor(rgb_color.float_rgb)

    @property
    def edge_color(self) -> Color:
        """Return or set the edge color of this property.

        The solid color to give the edges when ``show_edges=True``.
        Either a string, RGB list, or hex color string.

        Examples
        --------
        >>> import pyvista as pv
        >>> prop = pv.Property()
        >>> prop.edge_color = 'red'
        >>> prop.edge_color
        Color(name='red', hex='#ff0000ff')

        Visualize red edges. Set the edges visibility to ``True`` so we can see
        them.

        >>> prop.show_edges = True
        >>> prop.edge_color = 'red'
        >>> prop.plot()

        """
        return Color(self.GetEdgeColor())

    @edge_color.setter
    def edge_color(self, value):
        rgb_color = Color(value, default_color=self._theme.edge_color)
        self.SetEdgeColor(rgb_color.float_rgb)

    @property
    def opacity(self) -> float:
        """Return or set the opacity of this property.

        Opacity of the mesh. A single float value that will be applied globally
        opacity of the mesh and uniformly applied everywhere. Between 0 and 1.

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

        >>> import pyvista as pv
        >>> prop = pv.Property()
        >>> prop.opacity = 0.5
        >>> prop.opacity
        0.5

        Visualize default opacity of ``1.0``.

        >>> prop.opacity = 1.0
        >>> prop.plot()

        Visualize opacity of ``0.75``.

        >>> prop.opacity = 0.75
        >>> prop.plot()

        Visualize opacity of ``0.25``.

        >>> prop.opacity = 0.25
        >>> prop.plot()


        """
        return self.GetOpacity()

    @opacity.setter
    def opacity(self, value: float):
        self.SetOpacity(value)

    @property
    def show_edges(self) -> bool:
        """Return or set the visibility of edges.

        Shows or hides the edges.  Does not apply to a wireframe
        representation.

        Examples
        --------
        >>> import pyvista as pv
        >>> prop = pv.Property()
        >>> prop.show_edges = True
        >>> prop.show_edges
        True

        Visualize default edge visibility of ``False``.

        >>> prop.show_edges = False
        >>> prop.plot()

        Visualize edge visibility of ``True``.

        >>> prop.show_edges = True
        >>> prop.plot()

        """
        return bool(self.GetEdgeVisibility())

    @show_edges.setter
    def show_edges(self, value: bool):
        self.SetEdgeVisibility(value)

    @property
    def lighting(self) -> bool:
        """Return or set view direction lighting.

        Examples
        --------
        Disable lighting.

        >>> import pyvista as pv
        >>> prop = pv.Property()
        >>> prop.lighting = False
        >>> prop.lighting
        False

        Visualize it.

        >>> prop.plot()

        """
        return self.GetLighting()

    @lighting.setter
    def lighting(self, value: bool):
        if value is None:
            value = self._theme.lighting
        self.SetLighting(value)

    @property
    def ambient(self) -> float:
        """Return or set ambient.

        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.

        Examples
        --------
        >>> import pyvista as pv
        >>> prop = pv.Property()
        >>> prop.ambient = 0.2
        >>> prop.ambient
        0.2

        Visualize default ambient light.

        >>> prop.ambient = 0.0
        >>> prop.plot()

        Visualize ambient at ``0.5``.

        >>> prop.ambient = 0.5
        >>> prop.plot()

        Visualize ambient at ``1.0``.

        >>> prop.ambient = 1.0
        >>> prop.plot()

        """
        return self.GetAmbient()

    @ambient.setter
    def ambient(self, value: float):
        self.SetAmbient(value)

    @property
    def diffuse(self) -> float:
        """Return or set the diffuse lighting coefficient.

        Default 1.0.

        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.

        Examples
        --------
        >>> import pyvista as pv
        >>> prop = pv.Property()
        >>> prop.diffuse = 0.2
        >>> prop.diffuse
        0.2

        Visualize default diffuse light.

        >>> prop.diffuse = 1.0
        >>> prop.plot()

        Visualize diffuse at ``0.5``.

        >>> prop.diffuse = 0.5
        >>> prop.plot()

        Visualize diffuse at ``0.0``.

        >>> prop.diffuse = 0.0
        >>> prop.plot()

        """
        return self.GetDiffuse()

    @diffuse.setter
    def diffuse(self, value: float):
        self.SetDiffuse(value)

    @property
    def specular(self) -> float:
        """Return or set specular.

        Default 0.0

        Specular lighting simulates the bright spot of a light that appears on
        shiny objects.

        Examples
        --------
        >>> import pyvista as pv
        >>> prop = pv.Property()
        >>> prop.specular = 0.2
        >>> prop.specular
        0.2

        Visualize default specular light.

        >>> prop.specular = 0.0
        >>> prop.plot()

        Visualize specular at ``0.5``.

        >>> prop.specular = 0.5
        >>> prop.plot()

        Visualize specular at ``1.0``.

        >>> prop.specular = 1.0
        >>> prop.plot()

        """
        return self.GetSpecular()

    @specular.setter
    def specular(self, value: float):
        self.SetSpecular(value)

    @property
    def specular_power(self) -> float:
        """Return or set specular power.

        The specular power. Between 0.0 and 128.0. Default 1.0

        Examples
        --------
        Set specular power to 5.0

        >>> import pyvista as pv
        >>> prop = pv.Property()
        >>> prop.specular = 0.1  # enable specular
        >>> prop.specular_power = 5.0
        >>> prop.specular_power
        5.0

        Visualize default specular power.

        >>> prop.specular_power = 1.0
        >>> prop.plot()

        Visualize specular power at ``0.1``.

        >>> prop.specular_power = 0.1
        >>> prop.plot()

        Visualize specular power at ``5.0``.

        >>> prop.specular_power = 5.0
        >>> prop.plot()

        Visualize specular power at ``128.0``.

        >>> prop.specular_power = 128.0
        >>> prop.plot()

        """
        return self.GetSpecularPower()

    @specular_power.setter
    def specular_power(self, value: float):
        self.SetSpecularPower(value)

    @property
    def metallic(self) -> float:
        """Return or set metallic.

        This requires that the interpolation be set to ``'Physically based
        rendering'``

        Examples
        --------
        Set metallic to 0.1

        >>> import pyvista as pv
        >>> prop = pv.Property()
        >>> prop.interpolation = 'pbr'  # requires physically based rendering
        >>> prop.metallic = 0.1
        >>> prop.metallic
        0.1

        Visualize default metallic.

        >>> prop.metallic = 0.0
        >>> prop.plot()

        Visualize metallic at ``0.5``.

        >>> prop.metallic = 0.5
        >>> prop.plot()

        Visualize metallic at ``1.0``.

        >>> prop.metallic = 1.0
        >>> prop.plot()

        """
        _check_supports_pbr()
        return self.GetMetallic()

    @metallic.setter
    def metallic(self, value: float):
        _check_supports_pbr()
        self.SetMetallic(value)

    @property
    def roughness(self) -> float:
        """Return or set roughness.

        This requires that the interpolation be set to ``'Physically based
        rendering'``

        Examples
        --------
        Set roughness to 0.1

        >>> import pyvista as pv
        >>> prop = pv.Property()
        >>> prop.interpolation = 'pbr'  # requires physically based rendering
        >>> prop.metallic = 0.5  # helps to visualize metallic
        >>> prop.roughness = 0.1
        >>> prop.roughness
        0.1

        Visualize default roughness with metallic of ``0.5``.

        >>> prop.roughness = 0.5
        >>> prop.plot()

        Visualize roughness at ``0.0`` with metallic of ``0.5``.

        >>> prop.roughness = 0.0
        >>> prop.plot()

        Visualize roughness at ``1.0`` with metallic of ``0.5``.

        >>> prop.roughness = 1.0
        >>> prop.plot()

        """
        _check_supports_pbr()
        return self.GetRoughness()

    @roughness.setter
    def roughness(self, value: bool):
        _check_supports_pbr()
        self.SetRoughness(value)

    @property
    def interpolation(self) -> str:
        """Return or set the method of shading.

        One of the following options.

        * ``'Physically based rendering'`` - Physically based rendering.
        * ``'pbr'`` - Alias for Physically based rendering.
        * ``'Phong'`` - Phong shading.
        * ``'Gouraud'`` - Gouraud shading.
        * ``'Flat'`` - Flat Shading.

        This parameter is case insensitive.

        Examples
        --------
        Set interpolation to physically based rendering.

        >>> import pyvista as pv
        >>> prop = pv.Property()
        >>> prop.interpolation = 'pbr'
        >>> prop.interpolation
        'Physically based rendering'

        Visualize default flat shading.

        >>> prop.interpolation = 'Flat'
        >>> prop.plot()

        Visualize gouraud shading.

        >>> prop.interpolation = 'Gouraud'
        >>> prop.plot()

        Visualize phong shading.

        >>> prop.interpolation = 'Phong'
        >>> prop.plot()

        Visualize physically based rendering.

        >>> prop.interpolation = 'Physically based rendering'
        >>> prop.plot()

        """
        return self.GetInterpolationAsString()

    @interpolation.setter
    def interpolation(self, value: str):
        if not isinstance(value, str):
            raise TypeError(f'`interpolation` must be a string, not {type(value)}')

        # normalize to spaces and lowercase
        value = value.lower().replace('-', ' ')

        if value in ['physically based rendering', 'pbr']:
            _check_supports_pbr()
            self.SetInterpolationToPBR()
        elif value == 'phong':
            self.SetInterpolationToPhong()
        elif value == 'gouraud':
            self.SetInterpolationToGouraud()
        elif value == 'flat':
            self.SetInterpolationToFlat()
        else:
            raise ValueError(
                f'Invalid interpolation "{value}". Should be one of the '
                'following:\n'
                '    - "Physically based rendering"\n'
                '    - "pbr"\n'
                '    - "Phong"\n'
                '    - "Gouraud"\n'
                '    - "Flat"\n'
                '    - None'
            )

    @property
    def render_points_as_spheres(self) -> bool:
        """Return or set rendering points as spheres.

        Requires representation style be set to ``'points'``.

        Examples
        --------
        Enable rendering points as spheres

        >>> import pyvista as pv
        >>> prop = pv.Property()
        >>> prop.style = 'points'
        >>> prop.point_size = 20
        >>> prop.render_points_as_spheres = True
        >>> prop.render_points_as_spheres
        True

        Visualize default point rendering.

        >>> prop.render_points_as_spheres = False
        >>> prop.plot()

        Visualize rendering points as spheres.

        >>> prop.render_points_as_spheres = True
        >>> prop.plot()

        """
        return self.GetRenderPointsAsSpheres()

    @render_points_as_spheres.setter
    def render_points_as_spheres(self, value: bool):
        self.SetRenderPointsAsSpheres(value)

    @property
    def render_lines_as_tubes(self) -> bool:
        """Return or set rendering lines as tubes.

        Requires representation style be set to ``'wireframe'``.

        Examples
        --------
        Enable rendering lines as tubes.

        >>> import pyvista as pv
        >>> prop = pv.Property()
        >>> prop.style = 'wireframe'
        >>> prop.line_width = 10
        >>> prop.render_lines_as_tubes = True
        >>> prop.render_lines_as_tubes
        True

        Visualize default line rendering.

        >>> prop.render_lines_as_tubes = False
        >>> prop.plot()

        Visualize rendering lines as tubes

        >>> prop.render_lines_as_tubes = True
        >>> prop.plot()

        """
        return self.GetRenderLinesAsTubes()

    @render_lines_as_tubes.setter
    def render_lines_as_tubes(self, value: bool):
        self.SetRenderLinesAsTubes(value)

    @property
    def line_width(self) -> float:
        """Return or set the line width.

        Examples
        --------
        Change the line width to ``10``.

        >>> import pyvista as pv
        >>> prop = pv.Property()
        >>> prop.line_width = 10
        >>> prop.line_width
        10.0

        Visualize the default line width.

        >>> prop.line_width = 1.0
        >>> prop.show_edges = True
        >>> prop.plot()

        Visualize the a line width of 5.0

        >>> prop.line_width = 5.0
        >>> prop.plot()

        """
        return self.GetLineWidth()

    @line_width.setter
    def line_width(self, value: bool):
        self.SetLineWidth(value)

    @property
    def point_size(self):
        """Return or set the point size.

        Examples
        --------
        Change the point size to ``10.0``.

        >>> import pyvista as pv
        >>> prop = pv.Property()
        >>> prop.point_size = 10
        >>> prop.point_size
        10.0

        Visualize a point size of ``5.0``.

        >>> prop.point_size = 5.0
        >>> prop.style = 'points'
        >>> prop.plot()

        Visualize the a point size of ``10.0``.

        >>> prop.point_size = 10.0
        >>> prop.plot()

        """
        return self.GetPointSize()

    @point_size.setter
    def point_size(self, new_size):
        self.SetPointSize(new_size)

    @property
    def culling(self) -> str:
        """Return or set face culling.

        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. Defaults to ``'none'``. One of the
        following:

        * ``"back"`` - Enable backface culling
        * ``"front"`` - Enable frontface culling
        * ``'none'`` - Disable both backface and frontface culling

        Examples
        --------
        Enable back face culling

        >>> import pyvista as pv
        >>> prop = pv.Property()
        >>> prop.culling = 'back'
        >>> prop.culling
        'back'

        Plot default culling.

        >>> prop.culling = 'none'
        >>> prop.plot()

        Plot backface culling. This looks the same as the default culling
        ``'none'`` because the forward facing faces are already obscuring the
        back faces.

        >>> prop.culling = 'back'
        >>> prop.plot()

        Plot frontface culling. Here, the forward facing faces are hidden
        entirely.

        >>> prop.culling = 'front'
        >>> prop.plot()

        """
        if self.GetBackfaceCulling():
            return 'back'
        elif self.GetFrontfaceCulling():
            return 'front'
        return 'none'

    @culling.setter
    def culling(self, value):
        if isinstance(value, str):
            value = value.lower()

        if value == 'back':
            try:
                self.BackfaceCullingOn()
                self.FrontfaceCullingOff()
            except AttributeError:  # pragma: no cover
                pass
        elif value == 'front':
            try:
                self.FrontfaceCullingOn()
                self.BackfaceCullingOff()
            except AttributeError:  # pragma: no cover
                pass
        elif value == 'none':
            self.FrontfaceCullingOff()
            self.BackfaceCullingOff()
        else:
            raise ValueError(
                f'Invalid culling "{value}". Should be either:\n'
                '"backface", "frontface", or "None"'
            )

    @property
    def ambient_color(self) -> Color:
        """Return or set the ambient color of this property.

        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.

        Examples
        --------
        Set the ambient color to blue.

        >>> import pyvista as pv
        >>> prop = pv.Property()
        >>> prop.ambient_color = 'b'
        >>> prop.ambient_color
        Color(name='blue', hex='#0000ffff')

        Visualize setting the ambient color to blue with ``ambient = 0.1``

        >>> prop.ambient = 0.1
        >>> prop.ambient_color = 'b'
        >>> prop.plot()

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

    @ambient_color.setter
    def ambient_color(self, value):
        self.SetAmbientColor(Color(value).float_rgb)

    @property
    def specular_color(self) -> Color:
        """Return or set the specular color of this property.

        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'``.

        Examples
        --------
        Set the specular color to blue.

        >>> import pyvista as pv
        >>> prop = pv.Property()
        >>> prop.specular_color = 'b'
        >>> prop.specular_color
        Color(name='blue', hex='#0000ffff')

        Visualize setting the specular color to blue with ``specular = 0.2``

        >>> prop.specular = 0.2
        >>> prop.specular_color = 'r'
        >>> prop.plot()

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

    @specular_color.setter
    def specular_color(self, value):
        self.SetSpecularColor(Color(value).float_rgb)

    @property
    def diffuse_color(self) -> Color:
        """Return or set the diffuse color of this property.

        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'``.

        Examples
        --------
        Set the diffuse color to blue.

        >>> import pyvista as pv
        >>> prop = pv.Property()
        >>> prop.diffuse_color = 'b'
        >>> prop.diffuse_color
        Color(name='blue', hex='#0000ffff')

        Visualize setting the diffuse color to white with ``diffuse = 0.5``

        >>> prop.diffuse = 0.5
        >>> prop.diffuse_color = 'w'
        >>> prop.plot()

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

    @diffuse_color.setter
    def diffuse_color(self, value):
        self.SetDiffuseColor(Color(value).float_rgb)

    @property
    def anisotropy(self):
        """Return or set the anisotropy coefficient.

        This value controls the anisotropy of the material (0.0 means
        isotropic). This requires physically based rendering.

        For further details see `PBR Journey Part 2 : Anisotropy model with VTK
        <https://www.kitware.com/pbr-journey-part-2-anisotropy-model-with-vtk/>`_

        Notes
        -----
        This attribute requires VTK v9.1.0 or newer.

        Examples
        --------
        Set anisotropy to 0.1

        >>> import pyvista as pv
        >>> prop = pv.Property()
        >>> prop.interpolation = 'pbr'  # requires physically based rendering
        >>> prop.anisotropy
        0.1

        """
        if not hasattr(self, 'GetAnisotropy'):  # pragma: no cover
            from pyvista.core.errors import VTKVersionError

            raise VTKVersionError('Anisotropy requires VTK v9.1.0 or newer.')
        return self.GetAnisotropy()

    @anisotropy.setter
    def anisotropy(self, value: float):
        if not hasattr(self, 'SetAnisotropy'):  # pragma: no cover
            from pyvista.core.errors import VTKVersionError

            raise VTKVersionError('Anisotropy requires VTK v9.1.0 or newer.')
        self.SetAnisotropy(value)

    def plot(self, **kwargs) -> None:
        """Plot this property on the Stanford Bunny.

        This is useful for visualizing how this property would be applied to an
        actor.

        Parameters
        ----------
        **kwargs : dict, optional
            Keyword arguments for :class:`pyvista.Plotter`.

        Examples
        --------
        >>> import pyvista as pv
        >>> prop = pv.Property(
        ...     show_edges=True,
        ...     color='brown',
        ...     edge_color='blue',
        ...     line_width=4,
        ...     specular=1.0
        ... )
        >>> prop.plot()

        """
        from pyvista import examples  # avoid circular import

        before_close_callback = kwargs.pop('before_close_callback', None)

        pl = pv.Plotter(**kwargs)
        actor = pl.add_mesh(examples.download_bunny_coarse())
        actor.SetProperty(self)

        if self.interpolation == 'Physically based rendering':
            cubemap = examples.download_sky_box_cube_map()
            pl.set_environment_texture(cubemap)

        pl.camera_position = 'xy'
        pl.show(before_close_callback=before_close_callback)
