{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Rendering MultibodyPlant Tutorial\n", "\n", "For instructions on how to run these tutorial notebooks, please see\n", "the [README](https://github.com/RobotLocomotion/drake/blob/master/tutorials/README.md)." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This shows examples of:\n", "* Adding a `MultibodyPlant` and `SceneGraph` to a diagram\n", "* Adding two separate IIWAs to the `MultibodyPlant`\n", "* Adding LCM visualization for Drake Visualizer\n", "* Adding `meshcat` visualization\n", "* Adding a camera with a VTK renderer\n", "* Rendering color and label images (at zero configuration)\n", "* Using `SceneGraphInspector` to query `SceneGraph` geometries\n", "* Associating `SceneGraph` geometries with `MultibodyPlant` bodies\n", "* Extracting `RenderLabel`s from given geometries\n", "* Remapping labels to only distinguish by `ModelInstanceIndex`." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Necessary Imports" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import os\n", "\n", "import matplotlib.pyplot as plt\n", "import matplotlib as mpl\n", "import numpy as np" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from pydrake.common import FindResourceOrThrow\n", "from pydrake.geometry import ConnectDrakeVisualizer\n", "from pydrake.geometry.render import (\n", " DepthCameraProperties,\n", " RenderLabel,\n", " MakeRenderEngineVtk,\n", " RenderEngineVtkParams,\n", ")\n", "from pydrake.math import RigidTransform, RollPitchYaw\n", "from pydrake.multibody.parsing import Parser\n", "from pydrake.multibody.plant import AddMultibodyPlantSceneGraph\n", "from pydrake.multibody.tree import BodyIndex\n", "from pydrake.systems.analysis import Simulator\n", "from pydrake.systems.framework import DiagramBuilder\n", "from pydrake.systems.meshcat_visualizer import MeshcatVisualizer\n", "from pydrake.systems.sensors import RgbdSensor" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Define helper methods" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def xyz_rpy_deg(xyz, rpy_deg):\n", " \"\"\"Shorthand for defining a pose.\"\"\"\n", " rpy_deg = np.asarray(rpy_deg)\n", " return RigidTransform(RollPitchYaw(rpy_deg * np.pi / 180), xyz)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "reserved_labels = [\n", " RenderLabel.kDoNotRender,\n", " RenderLabel.kDontCare,\n", " RenderLabel.kEmpty,\n", " RenderLabel.kUnspecified,\n", "]\n", "\n", "def colorize_labels(image):\n", " \"\"\"Colorizes labels.\"\"\"\n", " # TODO(eric.cousineau): Revive and use Kuni's palette.\n", " cc = mpl.colors.ColorConverter()\n", " color_cycle = plt.rcParams[\"axes.prop_cycle\"]\n", " colors = np.array([cc.to_rgb(c[\"color\"]) for c in color_cycle])\n", " bg_color = [0, 0, 0]\n", " image = np.squeeze(image)\n", " background = np.zeros(image.shape[:2], dtype=bool)\n", " for label in reserved_labels:\n", " background |= image == int(label)\n", " color_image = colors[image % len(colors)]\n", " color_image[background] = bg_color\n", " return color_image" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Create diagram builder with plant and scene graph." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "builder = DiagramBuilder()\n", "plant, scene_graph = AddMultibodyPlantSceneGraph(builder, 0.0)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Add first IIWA at origin." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "parser = Parser(plant)\n", "iiwa_file = FindResourceOrThrow(\n", " \"drake/manipulation/models/iiwa_description/sdf/\"\n", " \"iiwa14_no_collision.sdf\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "iiwa_1 = parser.AddModelFromFile(iiwa_file, model_name=\"iiwa_1\")\n", "plant.WeldFrames(\n", " plant.world_frame(), plant.GetFrameByName(\"iiwa_link_0\", iiwa_1),\n", " X_AB=xyz_rpy_deg([0, 0, 0], [0, 0, 0]))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Add second IIWA at next to first." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "iiwa_2 = parser.AddModelFromFile(iiwa_file, model_name=\"iiwa_2\")\n", "plant.WeldFrames(\n", " plant.world_frame(), plant.GetFrameByName(\"iiwa_link_0\", iiwa_2),\n", " X_AB=xyz_rpy_deg([0, 1, 0], [0, 0, 0]))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Add renderer." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "renderer_name = \"renderer\"\n", "scene_graph.AddRenderer(\n", " renderer_name, MakeRenderEngineVtk(RenderEngineVtkParams()))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Add camera with same color and depth properties." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# N.B. These properties are chosen arbitrarily.\n", "depth_prop = DepthCameraProperties(\n", " width=640, height=480, fov_y=np.pi/4,\n", " renderer_name=renderer_name,\n", " z_near=0.01, z_far=10.)\n", "\n", "world_id = plant.GetBodyFrameIdOrThrow(plant.world_body().index())\n", "X_WB = xyz_rpy_deg([4, 0, 0], [-90, 0, 90])\n", "sensor = RgbdSensor(\n", " world_id, X_PB=X_WB,\n", " color_properties=depth_prop, depth_properties=depth_prop)\n", "builder.AddSystem(sensor)\n", "builder.Connect(\n", " scene_graph.get_query_output_port(),\n", " sensor.query_object_input_port())" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Add Drake Visualizer.\n", "\n", "You will need to have launched the `drake_visualizer` binary\n", "before calling `simulator.Initialize(...)`." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "ConnectDrakeVisualizer(builder, scene_graph)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Add and show `meshcat` Visualizer.\n", "\n", "This will show a `meshcat` widget inside of this notebook.\n", "\n", "**Note**: This currently does *not* work in a remote workflow (e.g.\n", "Docker without appropriate port forwarding, Binder, Google Colab, etc.).\n", "Please see [#12645](https://github.com/RobotLocomotion/drake/issues/12645)\n", "for more details. If this does appear to work, then it is most likely due\n", "to you running a local instance of the `meshcat` server.\n", "\n", "" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "meshcat_vis = builder.AddSystem(\n", " MeshcatVisualizer(scene_graph, zmq_url=\"new\", open_browser=False))\n", "builder.Connect(\n", " scene_graph.get_pose_bundle_output_port(),\n", " meshcat_vis.get_input_port(0))\n", "meshcat_vis.vis.jupyter_cell()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Finalize plant and build diagram." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "plant.Finalize()\n", "diagram = builder.Build()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Create context and get subsystem contexts." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "diagram_context = diagram.CreateDefaultContext()\n", "sensor_context = sensor.GetMyMutableContextFromRoot(diagram_context)\n", "sg_context = scene_graph.GetMyMutableContextFromRoot(diagram_context)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Publish visualization message with a default context." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "Simulator(diagram).Initialize()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Render color and label images using matplotlib\n", "Note that this uses the default labeling scheme, using `body.index()`." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "color = sensor.color_image_output_port().Eval(sensor_context).data\n", "label = sensor.label_image_output_port().Eval(sensor_context).data\n", "fig, ax = plt.subplots(1, 2, figsize=(10, 5))\n", "ax[0].imshow(color)\n", "ax[1].imshow(colorize_labels(label))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Change labels to model instance by direct remapping." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We will loop through each geometry item, get it's corresponding body, and then\n", "remap the original label to a label that is only distinct for model intances.\n", "\n", "**NOTE**: If the labels in the given plant merge the two model instances together,\n", "then this will not fix that. The correct behavior would be to update the RenderLabel\n", "values in the geometry instances themselves.\n", "\n", "*TODO(eric.cousineau)*: Add an example of updating only the RenderLabel." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "query_object = scene_graph.get_query_output_port().Eval(sg_context)\n", "inspector = query_object.inspector()\n", "\n", "label_by_model = label.copy()\n", "for geometry_id in inspector.GetAllGeometryIds():\n", " body = plant.GetBodyFromFrameId(inspector.GetFrameId(geometry_id))\n", " geometry_label = inspector.GetPerceptionProperties(\n", " geometry_id).GetProperty(\"label\", \"id\")\n", " # WARNING: If you do not cast the `geometry_label` to `int`, this\n", " # comparison will take a long time since NumPy will do\n", " # element-by-element comparison using `RenderLabel.__eq__`.\n", " mask = (label == int(geometry_label))\n", " label_by_model[mask] = int(body.model_instance())\n", "\n", "plt.imshow(colorize_labels(label_by_model))" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "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.6.9" } }, "nbformat": 4, "nbformat_minor": 2 }