{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Render a textured mesh\n",
    "\n",
    "This tutorial shows how to:\n",
    "- load a mesh and textures from an `.obj` file. \n",
    "- set up a renderer \n",
    "- render the mesh \n",
    "- vary the rendering settings such as lighting and camera position\n",
    "- use the batching features of the pytorch3d API to render the mesh from different viewpoints"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Import modules"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "import torch\n",
    "import matplotlib.pyplot as plt\n",
    "from skimage.io import imread\n",
    "\n",
    "# Util function for loading meshes\n",
    "from pytorch3d.io import load_obj\n",
    "\n",
    "# Data structures and functions for rendering\n",
    "from pytorch3d.structures import Meshes, Textures\n",
    "from pytorch3d.renderer import (\n",
    "    look_at_view_transform,\n",
    "    OpenGLPerspectiveCameras, \n",
    "    PointLights, \n",
    "    DirectionalLights, \n",
    "    Materials, \n",
    "    RasterizationSettings, \n",
    "    MeshRenderer, \n",
    "    MeshRasterizer,  \n",
    "    TexturedPhongShader\n",
    ")\n",
    "\n",
    "# add path for demo utils\n",
    "import sys\n",
    "import os\n",
    "sys.path.append(os.path.abspath(''))\n",
    "from utils import image_grid"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "### Load a mesh and texture file\n",
    "\n",
    "Load an `.obj` file and it's associated `.mtl` file and create a **Textures** and **Meshes** object. \n",
    "\n",
    "**Meshes** is a unique datastructure provided in PyTorch3d for working with batches of meshes of different sizes. \n",
    "\n",
    "**Textures** is an auxillary datastructure for storing texture information about meshes. \n",
    "\n",
    "**Meshes** has several class methods which are used throughout the rendering pipeline."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Setup\n",
    "device = torch.device(\"cuda:0\")\n",
    "torch.cuda.set_device(device)\n",
    "\n",
    "# Set paths\n",
    "DATA_DIR = \"./data\"\n",
    "obj_filename = os.path.join(DATA_DIR, \"cow_mesh/cow.obj\")\n",
    "\n",
    "# Load obj file\n",
    "verts, faces, aux = load_obj(obj_filename)\n",
    "faces_idx = faces.verts_idx.to(device)\n",
    "verts = verts.to(device)\n",
    "\n",
    "# Get textures from the outputs of the load_obj function\n",
    "# the `aux` variable contains the texture maps and vertex uv coordinates. \n",
    "# Refer to the `obj_io.load_obj` function for full API reference. \n",
    "# Here we only have one texture map for the whole mesh. \n",
    "verts_uvs = aux.verts_uvs[None, ...].to(device)       # (N, V, 2)\n",
    "faces_uvs = faces.textures_idx[None, ...].to(device)  # (N, F, 3)\n",
    "tex_maps = aux.texture_images\n",
    "texture_image = list(tex_maps.values())[0]\n",
    "texture_image = texture_image[None, ...].to(device)   # (N, H, W, 3)\n",
    "\n",
    "# Create a textures object\n",
    "tex = Textures(verts_uvs=verts_uvs, faces_uvs=faces_uvs, maps=texture_image)\n",
    "\n",
    "# Create a meshes object with textures\n",
    "mesh = Meshes(verts=[verts], faces=[faces_idx], textures=tex)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Let's visualize the texture map"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(-0.5, 1023.5, 1023.5, -0.5)"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "data": {
      "image/png": "[encoded data, 25148 characters]\n",
      "text/plain": [
       "<Figure size 504x504 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "plt.figure(figsize=(7,7))\n",
    "plt.imshow(texture_image.squeeze().cpu().numpy())\n",
    "plt.grid(\"off\")\n",
    "plt.axis('off')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Create a renderer\n",
    "\n",
    "A renderer in PyTorch3d is composed of a **rasterizer** and a **shader** which each have a number of subcomponents such as a **camera** (orthgraphic/perspective). Here we initialize some of these components and use default values for the rest.\n",
    "\n",
    "In this example we will first create a **renderer** which uses a **perspective camera**, a **point light** and applies **phong shading**. Then we learn how to vary different components using the modular API.  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Initialize an OpenGL perspective camera.\n",
    "R, T = look_at_view_transform(2.7, 10, 20)\n",
    "cameras = OpenGLPerspectiveCameras(device=device, R=R, T=T)\n",
    "\n",
    "# Define the settings for rasterization and shading. Here we set the output image to be of size\n",
    "# 512x512. As we are rendering images for visualization purposes only we will set faces_per_pixel=1\n",
    "# and blur_radius=0.0. Refer to rasterize_meshes.py for explanations of these parameters. \n",
    "raster_settings = RasterizationSettings(\n",
    "    image_size=512, \n",
    "    blur_radius=0.0, \n",
    "    faces_per_pixel=1, \n",
    "    bin_size=0\n",
    ")\n",
    "\n",
    "# Place a point light in front of the object\n",
    "lights = PointLights(device=device, location=[[1.0, 1.0, -2.0]])\n",
    "\n",
    "# Create a phong renderer by composing a rasterizer and a shader. The textured phong shader will \n",
    "# interpolate the texture uv coordinates for each vertex, sample from a texture image and \n",
    "# apply the Phong lighting model\n",
    "renderer = MeshRenderer(\n",
    "    rasterizer=MeshRasterizer(\n",
    "        cameras=cameras, \n",
    "        raster_settings=raster_settings\n",
    "    ),\n",
    "    shader=TexturedPhongShader(\n",
    "        device=device, \n",
    "        cameras=cameras,\n",
    "        lights=lights\n",
    "    )\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Render the mesh"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The light is in front of the object so it is bright and the image has specular highlights."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(-0.5, 511.5, 511.5, -0.5)"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "data": {
      "image/png": "[encoded data, 52392 characters]\n",
      "text/plain": [
       "<Figure size 720x720 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "images = renderer(mesh)\n",
    "plt.figure(figsize=(10, 10))\n",
    "plt.imshow(images[0, ..., :3].cpu().numpy())\n",
    "plt.grid(\"off\")\n",
    "plt.axis(\"off\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Move the light behind the object and re-render\n",
    "\n",
    "We can pass arbirary keyword arguments to the `rasterizer`/`shader` via the call to the `renderer` so the renderer does not need to be reinitialized if any of the settings change/\n",
    "\n",
    "In this case, we can simply update the location of the lights and pass them into the call to the renderer. \n",
    "\n",
    "The image is now dark as there is only ambient lighting, and there are no specular highlights."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "lights.location = torch.tensor([0.0, 0.0, +1.0], device=device)[None]\n",
    "images = renderer(mesh, lights=lights)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(-0.5, 511.5, 511.5, -0.5)"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "data": {
      "image/png": "[encoded data, 36932 characters]\n",
      "text/plain": [
       "<Figure size 720x720 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "plt.figure(figsize=(10, 10))\n",
    "plt.imshow(images[0, ..., :3].cpu().numpy())\n",
    "plt.grid(\"off\")\n",
    "plt.axis(\"off\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Rotate the object, modify the material properties or light properties\n",
    "\n",
    "We can also change many other settings in the rendering pipeline. Here we:\n",
    "\n",
    "- change the **viewing angle** of the camera\n",
    "- change the **position** of the point light\n",
    "- change the **material reflectance** properties of the mesh"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Rotate the object by increasing the azimuth angle\n",
    "R, T = look_at_view_transform(dist=2.7, elev=10, azim=50)\n",
    "cameras = OpenGLPerspectiveCameras(device=device, R=R, T=T)\n",
    "\n",
    "# Move the light location to be in front of the object again\n",
    "lights.location = torch.tensor([[5.0, 5.0, -2.0]], device=device)\n",
    "\n",
    "# Change specular color to green and change material shininess \n",
    "materials = Materials(\n",
    "    device=device,\n",
    "    specular_color=[[0.0, 1.0, 0.0]],\n",
    "    shininess=10.0\n",
    ")\n",
    "\n",
    "# Re render the mesh, passing in keyword arguments for the modified components.\n",
    "images = renderer(mesh, lights=lights, materials=materials, cameras=cameras)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(-0.5, 511.5, 511.5, -0.5)"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "data": {
      "image/png": "[encoded data, 58800 characters]\n",
      "text/plain": [
       "<Figure size 720x720 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "plt.figure(figsize=(10, 10))\n",
    "plt.imshow(images[0, ..., :3].cpu().numpy())\n",
    "plt.grid(\"off\")\n",
    "plt.axis(\"off\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Batched Rendering\n",
    "\n",
    "One of the core design choices of the PyTorch3d API is to suport **batched inputs for all components**. \n",
    "The renderer and associated components can take batched inputs and **render a batch of output images in one forward pass**. We will now use this feature to render the mesh from many different viewpoints.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Set batch size - this is the number of different viewpoints from which we want to render the mesh.\n",
    "batch_size = 20\n",
    "\n",
    "# Create a batch of meshes by repeating the cow mesh and associated textures. \n",
    "# Meshes has a useful `extend` method which allows us do this very easily. \n",
    "# This also extends the textures. \n",
    "meshes = mesh.extend(batch_size)\n",
    "\n",
    "# Get a batch of viewing angles. \n",
    "elev = torch.linspace(0, 360, batch_size)\n",
    "azim = torch.linspace(0, 360, batch_size)\n",
    "\n",
    "# All the cameras helper methods support mixed type inputs and broadcasting. So we can \n",
    "# view the camera from the same distance and specify dist=2.7 as a float,\n",
    "# and then specify elevation and azimuth angles for each viewpoint as tensors. \n",
    "R, T = look_at_view_transform(dist=2.7, elev=elev, azim=azim)\n",
    "cameras = OpenGLPerspectiveCameras(device=device, R=R, T=T)\n",
    "\n",
    "# Move the light back in front of the object\n",
    "lights.location = torch.tensor([[1.0, 1.0, -5.0]], device=device)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "# We can pass arbirary keyword arguments to the rasterizer/shader via the renderer\n",
    "# so the renderer does not need to be reinitialized if any of the settings change.\n",
    "images = renderer(meshes, cameras=cameras, lights=lights)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 158364 characters]\n",
      "text/plain": [
       "<Figure size 1080x648 with 20 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "image_grid(images.cpu().numpy(), rows=4, cols=5, rgb=True)"
   ]
  }
 ],
 "metadata": {
  "bento_stylesheets": {
   "bento/extensions/flow/main.css": true,
   "bento/extensions/kernel_selector/main.css": true,
   "bento/extensions/kernel_ui/main.css": true,
   "bento/extensions/new_kernel/main.css": true,
   "bento/extensions/system_usage/main.css": true,
   "bento/extensions/theme/main.css": true
  },
  "kernelspec": {
   "display_name": "p3d_dev7",
   "language": "python",
   "name": "p3d_dev7"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
