{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import panel as pn\n",
    "pn.extension('vtk')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The ``VTK`` pane renders VTK objects and vtk.js files inside a panel, making it possible to interact with complex geometries in 3D.\n",
    "\n",
    "#### Parameters:\n",
    "\n",
    "For layout and styling related parameters see the [customization user guide](../../user_guide/Customization.ipynb).\n",
    "\n",
    "* **``axes``** (dict): A dictionary with the parameters of the axes to construct in the 3d view.\n",
    "    Must contain at least ``xticker``, ``yticker`` and ``zticker``.\n",
    "    - ``[x|y|z]ticker`` is a dictionary which contains:\n",
    "        - ``ticks`` (array of numbers) - required. Positions in the scene coordinates\n",
    "        of the coresponding axe ticks\n",
    "        - ``labels`` (array of strings) - optional. Label displayed respectively to\n",
    "        the `ticks` positions.\n",
    "\n",
    "        If `labels` are not defined they are infered from the `ticks` array.\n",
    "    - ``digits``: number of decimal digits when `ticks` are converted to `labels`.\n",
    "    - ``fontsize``: size in pts of the ticks labels.\n",
    "    - ``show_grid``: boolean. If true (default) the axes grid is visible.\n",
    "    - ``grid_opacity``: float between 0-1. Defines the grid opacity.\n",
    "    - ``axes_opacity``: float between 0-1. Defines the axes lines opacity.\n",
    "* **``camera``** (dict): A dictionary reflecting the current state of the VTK camera\n",
    "* **``enable_keybindings``** (bool): A boolean to activate/deactivate keybindings. Bound keys are:\n",
    "  - s: set representation of all actors to *surface*\n",
    "  - w: set representation of all actors to *wireframe*\n",
    "  - v: set representation of all actors to *vertex*\n",
    "  - r: center the actors and move the camera so that all actors are visible\n",
    "  \n",
    "  The mouse must be over the pane to work\n",
    "  <br>**Warning**: These keybindings may not work as expected in a notebook context, if they interact with already bound keys\n",
    "* **``orientation_widget``** (bool): A boolean to activate/deactivate the orientation widget in the 3D pane. This widget is clickable and allows to rotate the scene in one of the orthographic projections.\n",
    "* **``object``** (str or object): Can be a string pointing to a local or remote file with a `.vtkjs` extension, or a `vtkRenderWindow` object  \n",
    "* **``serialize_on_instantiation``** (bool): It defines when the serialization of the 3D scene occurs. If set to `True` (default) the scene object is serialized when the panel is created else when the panel is displayed to the screen. This parameter is constant, once set it can't be modified\n",
    "___"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The simplest way to construct a VTK pane is to give it a vtk.js file which it will serialize and embed in the plot. The ``VTK`` pane also supports the regular sizing options provided by Bokeh, including responsive sizing modes:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "vtk_pane = pn.pane.VTK('https://raw.githubusercontent.com/Kitware/vtk-js/master/Data/StanfordDragon.vtkjs',\n",
    "                     sizing_mode='stretch_width', height=400, enable_keybindings=True, orientation_widget=True,\n",
    "                     serialize_on_instantiation=True)\n",
    "vtk_pane"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The ``VTK`` pane can also be updated like all other pane objects by replacing the ``object``:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "vtk_pane.object = \"https://github.com/Kitware/vtk-js-datasets/raw/master/data/vtkjs/TBarAssembly.vtkjs\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Controls\n",
    "\n",
    "The `VTK` pane exposes a number of options which can be changed from both Python and Javascript. Try out the effect of these parameters interactively:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "pn.Row(vtk_pane.controls(jslink=True), vtk_pane)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Camera control\n",
    "\n",
    "Once a VTK pane has been displayed it will automatically sync the camera state with the Pane object. We can read the camera state on the corresponding parameter:\n",
    "\n",
    "```python\n",
    "> vtk_pane.camera\n",
    "\n",
    "{'position': [-21.490090356222225, 14.44963146483641, 26.581314468858984],\n",
    " 'focalPoint': [0, 4.969950199127197, 0],\n",
    " 'viewUp': [0.17670012087160802, 0.9635684210080306, -0.20078088883170594],\n",
    " 'directionOfProjection': [0.605834463228546,\n",
    "  -0.2672449261957517,\n",
    "  -0.749362897791989],\n",
    " 'parallelProjection': False,\n",
    " 'useHorizontalViewAngle': False,\n",
    " 'viewAngle': 30,\n",
    " 'parallelScale': 9.180799381276024,\n",
    " 'clippingRange': [26.442079567041056, 44.714416678555395],\n",
    " 'thickness': 1000,\n",
    " 'windowCenter': [0, 0],\n",
    " 'useOffAxisProjection': False,\n",
    " 'screenBottomLeft': [-0.5, -0.5, -0.5],\n",
    " 'screenBottomRight': [0.5, -0.5, -0.5],\n",
    " 'screenTopRight': [0.5, 0.5, -0.5],\n",
    " 'freezeFocalPoint': False,\n",
    " 'useScissor': False,\n",
    " 'projectionMatrix': None,\n",
    " 'viewMatrix': None,\n",
    " 'physicalTranslation': [0, -4.969950199127197, 0],\n",
    " 'physicalScale': 9.180799381276024,\n",
    " 'physicalViewUp': [0, 1, 0],\n",
    " 'physicalViewNorth': [0, 0, -1],\n",
    " 'mtime': 2237,\n",
    " 'distance': 35.47188491341284}\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This technique also makes it possible to link the camera of two or more VTK panes together:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "dragon1 = pn.pane.VTK('https://raw.githubusercontent.com/Kitware/vtk-js/master/Data/StanfordDragon.vtkjs',\n",
    "                      height=400, sizing_mode='stretch_width')\n",
    "dragon2 = pn.pane.VTK('https://raw.githubusercontent.com/Kitware/vtk-js/master/Data/StanfordDragon.vtkjs',\n",
    "                      height=400, sizing_mode='stretch_width')\n",
    "\n",
    "dragon1.jslink(dragon2, camera='camera', bidirectional=True)\n",
    "\n",
    "pn.Row(dragon1, dragon2)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "and to modify the camera state in Python and trigger an update:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "if dragon1.camera:\n",
    "    dragon1.camera['viewAngle'] = 50\n",
    "    dragon1.param.trigger('camera')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Rendering VTK objects\n",
    "\n",
    "In addition to support for plotting vtkjs files the VTK pane can also render objects defined using the ``vtk`` Python library.\n",
    "\n",
    "There are slight differences with classical code generally used. As rendering of the objects and interactions with the view are handle by the VTK panel, we don't need to make a call to the `Render` method of the `vtkRenderWindow` (which would pop up the classical VTK window) or to specify a `vtkRenderWindowInteractor`. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import vtk\n",
    "from vtk.util.colors import tomato\n",
    "\n",
    "# This creates a polygonal cylinder model with eight circumferential\n",
    "# facets.\n",
    "cylinder = vtk.vtkCylinderSource()\n",
    "cylinder.SetResolution(8)\n",
    "\n",
    "# The mapper is responsible for pushing the geometry into the graphics\n",
    "# library. It may also do color mapping, if scalars or other\n",
    "# attributes are defined.\n",
    "cylinderMapper = vtk.vtkPolyDataMapper()\n",
    "cylinderMapper.SetInputConnection(cylinder.GetOutputPort())\n",
    "\n",
    "# The actor is a grouping mechanism: besides the geometry (mapper), it\n",
    "# also has a property, transformation matrix, and/or texture map.\n",
    "# Here we set its color and rotate it -22.5 degrees.\n",
    "cylinderActor = vtk.vtkActor()\n",
    "cylinderActor.SetMapper(cylinderMapper)\n",
    "cylinderActor.GetProperty().SetColor(tomato)\n",
    "# We must set ScalarVisibilty to 0 to use tomato Color\n",
    "cylinderMapper.SetScalarVisibility(0)\n",
    "cylinderActor.RotateX(30.0)\n",
    "cylinderActor.RotateY(-45.0)\n",
    "\n",
    "# Create the graphics structure. The renderer renders into the render\n",
    "# window.\n",
    "ren = vtk.vtkRenderer()\n",
    "renWin = vtk.vtkRenderWindow()\n",
    "renWin.AddRenderer(ren)\n",
    "\n",
    "# Add the actors to the renderer, set the background and size\n",
    "ren.AddActor(cylinderActor)\n",
    "ren.SetBackground(0.1, 0.2, 0.4)\n",
    "\n",
    "geom_pane = pn.pane.VTK(renWin, width=500, height=500)\n",
    "\n",
    "geom_pane"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can also add additional actors to the plot and then trigger an update:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sphere = vtk.vtkSphereSource()\n",
    "\n",
    "sphereMapper = vtk.vtkPolyDataMapper()\n",
    "sphereMapper.SetInputConnection(sphere.GetOutputPort())\n",
    "\n",
    "sphereActor = vtk.vtkActor()\n",
    "sphereActor.SetMapper(sphereMapper)\n",
    "sphereActor.GetProperty().SetColor(tomato)\n",
    "sphereMapper.SetScalarVisibility(0)\n",
    "sphereActor.RotateX(30.0)\n",
    "sphereActor.RotateY(-45.0)\n",
    "sphereActor.SetPosition(0.5, 0.5, 0.5)\n",
    "\n",
    "ren.AddActor(sphereActor)\n",
    "\n",
    "geom_pane.param.trigger('object')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Construction of ColorBars for VTK objects\n",
    "\n",
    "When working with VTK objects, a `scalar array` can be associated with `vertices` or `cells` of an `actor` `mesh`. With the help of a `look-up table`, scalar values are associated with colors at rendering time.\n",
    "\n",
    "**Colorbars** are used to represent the association between scalars and colors. The `VTK pane` allows constructing colorbars for the `vtk actors` in the scene using the `construct_colorbars`  method. This method will return a bokeh plot containing colorbars for each actor that uses a scalar array and a lookup table.\n",
    "\n",
    "If no colorbar is found in the scene the method return `None`."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We present an example of the use of `construct_colorbars`. Here we use `pyvista` module which simplifies the construction of VTK scenes"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pyvista as pv\n",
    "import numpy as np\n",
    "def make_points():\n",
    "    \"\"\"Helper to make XYZ points\"\"\"\n",
    "    theta = np.linspace(-4 * np.pi, 4 * np.pi, 100)\n",
    "    z = np.linspace(-2, 2, 100)\n",
    "    r = z**2 + 1\n",
    "    x = r * np.sin(theta)\n",
    "    y = r * np.cos(theta)\n",
    "    return np.column_stack((x, y, z))\n",
    "\n",
    "def lines_from_points(points):\n",
    "    \"\"\"Given an array of points, make a line set\"\"\"\n",
    "    poly = pv.PolyData()\n",
    "    poly.points = points\n",
    "    cells = np.full((len(points)-1, 3), 2, dtype=np.int)\n",
    "    cells[:, 1] = np.arange(0, len(points)-1, dtype=np.int)\n",
    "    cells[:, 2] = np.arange(1, len(points), dtype=np.int)\n",
    "    poly.lines = cells\n",
    "    return poly\n",
    "\n",
    "points = make_points()\n",
    "line = lines_from_points(points)\n",
    "line[\"scalars\"] = np.arange(line.n_points) # By default pyvista use viridis colormap\n",
    "tube = line.tube(radius=0.1) #=> the object we will represent in the scene\n",
    "\n",
    "\n",
    "#pyvista plotter => it constructs a vtkRenderWindow under the attribute ren_win\n",
    "pl = pv.Plotter(notebook=True)\n",
    "pl.camera_position =  [(4.440892098500626e-16, -21.75168228149414, 4.258553981781006),\n",
    "                       (4.440892098500626e-16, 0.8581731039809382, 0),\n",
    "                       (0, 0.1850949078798294, 0.982720673084259)]\n",
    "\n",
    "pl.add_mesh(tube, smooth_shading=True)\n",
    "pan = pn.panel(pl.ren_win, sizing_mode='stretch_width', orientation_widget=True)\n",
    "pn.Row(pn.Column(pan, pan.construct_colorbars()), pn.pane.Str(type(pl.ren_win), width=500))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Adding axes to the VTK scene\n",
    "\n",
    "Using the `axes` parameter, it is possible to add an axes into the 3d view."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "axes = dict(\n",
    "    origin = [-5, 5, -2],\n",
    "    xticker = {'ticks': np.linspace(-5,5,5)},\n",
    "    yticker = {'ticks': np.linspace(-5,5,5)},\n",
    "    zticker = {'ticks': np.linspace(-2,2,5), 'labels': [''] + [str(int(item)) for item in np.linspace(-2,2,5)[1:]]},\n",
    "    fontsize = 12,\n",
    "    digits = 1,\n",
    "    grid_opacity = 0.5,\n",
    "    show_grid=True\n",
    ")\n",
    "pan.axes = axes"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python",
   "pygments_lexer": "ipython3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
