gepetto_visualizer.py
Go to the documentation of this file.
1 import warnings
2 
3 import numpy as np
4 from numpy.linalg import norm
5 
6 from .. import pinocchio_pywrap_default as pin
7 from ..utils import npToTuple
8 from . import BaseVisualizer
9 
10 try:
11  import hppfcl
12 
13  WITH_HPP_FCL_BINDINGS = True
14 except: # noqa: E722
15  WITH_HPP_FCL_BINDINGS = False
16 
17 
18 class GepettoVisualizer(BaseVisualizer):
19  """A Pinocchio display using Gepetto Viewer"""
20 
21  def getViewerNodeName(self, geometry_object, geometry_type):
22  """Return the name of the geometry object inside the viewer"""
23  if geometry_type is pin.GeometryType.VISUAL:
24  return self.viewerVisualGroupName + "/" + geometry_object.name
25  elif geometry_type is pin.GeometryType.COLLISION:
26  return self.viewerCollisionGroupName + "/" + geometry_object.name
27 
29  self,
30  viewer=None,
31  windowName="python-pinocchio",
32  sceneName="world",
33  loadModel=False,
34  ):
35  """Init GepettoViewer by loading the gui and creating a window."""
36 
37  try:
38  import gepetto.corbaserver
39  except ImportError:
40  import warnings
41 
42  msg = (
43  "Error while importing the viewer client.\n"
44  "Check whether gepetto-gui is properly installed"
45  )
46  warnings.warn(msg, category=UserWarning, stacklevel=2)
47 
48  try:
49  self.viewer = gepetto.corbaserver.Client() if viewer is None else viewer
50  gui = self.viewer.gui
51 
52  # Create window
53  window_l = gui.getWindowList()
54  if windowName not in window_l:
55  self.windowID = self.viewer.gui.createWindow(windowName)
56  else:
57  self.windowID = self.viewer.gui.getWindowID(windowName)
58 
59  # Create scene if needed
60  scene_l = gui.getSceneList()
61  if sceneName not in scene_l:
62  gui.createScene(sceneName)
63  self.sceneName = sceneName
64  gui.addSceneToWindow(sceneName, self.windowID)
65 
66  if loadModel:
67  self.loadViewerModel()
68  except: # noqa: E722
69  import warnings
70 
71  msg = (
72  "Error while starting the viewer client.\n"
73  "Check whether gepetto-viewer is properly started"
74  )
75  warnings.warn(msg, category=UserWarning, stacklevel=2)
76 
77  def loadPrimitive(self, meshName, geometry_object):
78  gui = self.viewer.gui
79 
80  meshColor = geometry_object.meshColor
81 
82  geom = geometry_object.geometry
83  if isinstance(geom, hppfcl.Capsule):
84  return gui.addCapsule(
85  meshName, geom.radius, 2.0 * geom.halfLength, npToTuple(meshColor)
86  )
87  elif isinstance(geom, hppfcl.Cylinder):
88  return gui.addCylinder(
89  meshName, geom.radius, 2.0 * geom.halfLength, npToTuple(meshColor)
90  )
91  elif isinstance(geom, hppfcl.Box):
92  w, h, d = npToTuple(2.0 * geom.halfSide)
93  return gui.addBox(meshName, w, h, d, npToTuple(meshColor))
94  elif isinstance(geom, hppfcl.Sphere):
95  return gui.addSphere(meshName, geom.radius, npToTuple(meshColor))
96  elif isinstance(geom, hppfcl.Cone):
97  return gui.addCone(
98  meshName, geom.radius, 2.0 * geom.halfLength, npToTuple(meshColor)
99  )
100  elif isinstance(geom, hppfcl.Plane) or isinstance(geom, hppfcl.Halfspace):
101  res = gui.createGroup(meshName)
102  if not res:
103  return False
104  planeName = meshName + "/plane"
105  res = gui.addFloor(planeName)
106  if not res:
107  return False
108  normal = geom.n
109  rot = pin.Quaternion.FromTwoVectors(normal, pin.ZAxis)
110  alpha = geom.d / norm(normal, 2) ** 2
111  trans = alpha * normal
112  plane_offset = pin.SE3(rot, trans)
113  gui.applyConfiguration(planeName, pin.SE3ToXYZQUATtuple(plane_offset))
114  elif isinstance(geom, hppfcl.Convex):
115  pts = [
116  npToTuple(geom.points(geom.polygons(f)[i]))
117  for f in range(geom.num_polygons)
118  for i in range(3)
119  ]
120  gui.addCurve(meshName, pts, npToTuple(meshColor))
121  gui.setCurveMode(meshName, "TRIANGLES")
122  gui.setLightingMode(meshName, "ON")
123  gui.setBoolProperty(meshName, "BackfaceDrawing", True)
124  return True
125  elif isinstance(geom, hppfcl.ConvexBase):
126  pts = [npToTuple(geom.points(i)) for i in range(geom.num_points)]
127  gui.addCurve(meshName, pts, npToTuple(meshColor))
128  gui.setCurveMode(meshName, "POINTS")
129  gui.setLightingMode(meshName, "OFF")
130  return True
131  else:
132  msg = f"Unsupported geometry type for {geometry_object.name} ({type(geom)})"
133  warnings.warn(msg, category=UserWarning, stacklevel=2)
134  return False
135 
136  def loadViewerGeometryObject(self, geometry_object, geometry_type):
137  """Load a single geometry object"""
138 
139  gui = self.viewer.gui
140 
141  meshName = self.getViewerNodeName(geometry_object, geometry_type)
142  meshPath = geometry_object.meshPath
143  meshTexturePath = geometry_object.meshTexturePath
144  meshScale = geometry_object.meshScale
145  meshColor = geometry_object.meshColor
146 
147  try:
148  if WITH_HPP_FCL_BINDINGS and isinstance(
149  geometry_object.geometry, hppfcl.ShapeBase
150  ):
151  success = self.loadPrimitive(meshName, geometry_object)
152  else:
153  if meshName == "":
154  msg = (
155  "Display of geometric primitives is supported only if "
156  "pinocchio is build with HPP-FCL bindings."
157  )
158  warnings.warn(msg, category=UserWarning, stacklevel=2)
159  return
160  success = gui.addMesh(meshName, meshPath)
161  if not success:
162  return
163  except Exception as e:
164  msg = (
165  "Error while loading geometry object: "
166  f"{geometry_object.name}\nError message:\n{e}"
167  )
168  warnings.warn(msg, category=UserWarning, stacklevel=2)
169  return
170 
171  gui.setScale(meshName, npToTuple(meshScale))
172  if geometry_object.overrideMaterial:
173  gui.setColor(meshName, npToTuple(meshColor))
174  if meshTexturePath != "":
175  gui.setTexture(meshName, meshTexturePath)
176 
177  def loadViewerModel(self, rootNodeName="pinocchio"):
178  """Create the scene displaying the robot meshes in gepetto-viewer"""
179 
180  # Start a new "scene" in this window, named "world", with just a floor.
181  gui = self.viewer.gui
182  self.viewerRootNodeName = self.sceneName + "/" + rootNodeName
183 
184  if not gui.nodeExists(self.viewerRootNodeName):
185  gui.createGroup(self.viewerRootNodeName)
186 
187  self.viewerCollisionGroupName = self.viewerRootNodeName + "/" + "collisions"
188  if not gui.nodeExists(self.viewerCollisionGroupName):
189  gui.createGroup(self.viewerCollisionGroupName)
190 
191  self.viewerVisualGroupName = self.viewerRootNodeName + "/" + "visuals"
192  if not gui.nodeExists(self.viewerVisualGroupName):
193  gui.createGroup(self.viewerVisualGroupName)
194 
195  # iterate over visuals and create the meshes in the viewer
196  if self.collision_model is not None:
197  for collision in self.collision_model.geometryObjects:
198  self.loadViewerGeometryObject(collision, pin.GeometryType.COLLISION)
199  # Display collision if we have them and there is no visual
200  self.displayCollisions(
201  self.collision_model is not None and self.visual_model is None
202  )
203 
204  if self.visual_model is not None:
205  for visual in self.visual_model.geometryObjects:
206  self.loadViewerGeometryObject(visual, pin.GeometryType.VISUAL)
207  self.displayVisuals(self.visual_model is not None)
208 
209  # Finally, refresh the layout to obtain your first rendering.
210  gui.refresh()
211 
212  def display(self, q=None):
213  """
214  Display the robot at configuration q in the viewer by placing all the bodies.
215  """
216  if "viewer" not in self.__dict__:
217  return
218 
219  gui = self.viewer.gui
220  # Update the robot kinematics and geometry.
221  if q is not None:
222  pin.forwardKinematics(self.model, self.data, q)
223 
224  if self.display_collisions:
225  pin.updateGeometryPlacements(
226  self.model, self.data, self.collision_model, self.collision_data
227  )
228  gui.applyConfigurations(
229  [
230  self.getViewerNodeName(collision, pin.GeometryType.COLLISION)
231  for collision in self.collision_model.geometryObjects
232  ],
233  [
234  pin.SE3ToXYZQUATtuple(
235  self.collision_data.oMg[
236  self.collision_model.getGeometryId(collision.name)
237  ]
238  )
239  for collision in self.collision_model.geometryObjects
240  ],
241  )
242 
243  if self.display_visuals:
244  pin.updateGeometryPlacements(
245  self.model, self.data, self.visual_model, self.visual_data
246  )
247  gui.applyConfigurations(
248  [
249  self.getViewerNodeName(visual, pin.GeometryType.VISUAL)
250  for visual in self.visual_model.geometryObjects
251  ],
252  [
253  pin.SE3ToXYZQUATtuple(
254  self.visual_data.oMg[
255  self.visual_model.getGeometryId(visual.name)
256  ]
257  )
258  for visual in self.visual_model.geometryObjects
259  ],
260  )
261 
262  gui.refresh()
263 
264  def displayCollisions(self, visibility):
265  """Set whether to display collision objects or not"""
266  gui = self.viewer.gui
267  self.display_collisions = visibility
268  if self.collision_model is None:
269  return
270 
271  if visibility:
272  visibility_mode = "ON"
273  else:
274  visibility_mode = "OFF"
275 
276  for collision in self.collision_model.geometryObjects:
277  nodeName = self.getViewerNodeName(collision, pin.GeometryType.COLLISION)
278  gui.setVisibility(nodeName, visibility_mode)
279 
280  def displayVisuals(self, visibility):
281  """Set whether to display visual objects or not"""
282  gui = self.viewer.gui
283  self.display_visuals = visibility
284  if self.visual_model is None:
285  return
286 
287  if visibility:
288  visibility_mode = "ON"
289  else:
290  visibility_mode = "OFF"
291 
292  for visual in self.visual_model.geometryObjects:
293  nodeName = self.getViewerNodeName(visual, pin.GeometryType.VISUAL)
294  gui.setVisibility(nodeName, visibility_mode)
295 
297  raise NotImplementedError()
298 
299  def setCameraTarget(self, target):
300  raise NotImplementedError()
301 
302  def setCameraPosition(self, position: np.ndarray):
303  raise NotImplementedError()
304 
305  def setCameraZoom(self, zoom: float):
306  raise NotImplementedError()
307 
308  def setCameraPose(self, pose: np.ndarray):
309  raise NotImplementedError()
310 
311  def captureImage(self, w=None, h=None):
312  raise NotImplementedError()
313 
315  raise NotImplementedError()
316 
318  raise NotImplementedError()
319 
320  def drawFrameVelocities(self, *args, **kwargs):
321  raise NotImplementedError()
322 
323 
324 __all__ = ["GepettoVisualizer"]
pinocchio.visualize.gepetto_visualizer.GepettoVisualizer.displayVisuals
def displayVisuals(self, visibility)
Definition: gepetto_visualizer.py:280
pinocchio.visualize.gepetto_visualizer.GepettoVisualizer.viewerRootNodeName
viewerRootNodeName
Definition: gepetto_visualizer.py:182
pinocchio.visualize.gepetto_visualizer.GepettoVisualizer.loadViewerGeometryObject
def loadViewerGeometryObject(self, geometry_object, geometry_type)
Definition: gepetto_visualizer.py:136
pinocchio.visualize.gepetto_visualizer.GepettoVisualizer.setBackgroundColor
def setBackgroundColor(self)
Definition: gepetto_visualizer.py:296
pinocchio.visualize.gepetto_visualizer.GepettoVisualizer.disableCameraControl
def disableCameraControl(self)
Definition: gepetto_visualizer.py:314
pinocchio.visualize.gepetto_visualizer.GepettoVisualizer.setCameraPosition
def setCameraPosition(self, np.ndarray position)
Definition: gepetto_visualizer.py:302
pinocchio.visualize.gepetto_visualizer.GepettoVisualizer.displayCollisions
def displayCollisions(self, visibility)
Definition: gepetto_visualizer.py:264
pinocchio.visualize.gepetto_visualizer.GepettoVisualizer.sceneName
sceneName
Definition: gepetto_visualizer.py:57
pinocchio.visualize.gepetto_visualizer.GepettoVisualizer.setCameraPose
def setCameraPose(self, np.ndarray pose)
Definition: gepetto_visualizer.py:308
pinocchio.visualize.gepetto_visualizer.GepettoVisualizer.initViewer
def initViewer(self, viewer=None, windowName="python-pinocchio", sceneName="world", loadModel=False)
Definition: gepetto_visualizer.py:28
pinocchio.visualize.gepetto_visualizer.GepettoVisualizer.setCameraZoom
def setCameraZoom(self, float zoom)
Definition: gepetto_visualizer.py:305
pinocchio.visualize.gepetto_visualizer.GepettoVisualizer.enableCameraControl
def enableCameraControl(self)
Definition: gepetto_visualizer.py:317
pinocchio.visualize.gepetto_visualizer.GepettoVisualizer.display
def display(self, q=None)
Definition: gepetto_visualizer.py:212
pinocchio.visualize.gepetto_visualizer.GepettoVisualizer.windowID
windowID
Definition: gepetto_visualizer.py:49
pinocchio.utils.npToTuple
def npToTuple(M)
Definition: bindings/python/pinocchio/utils.py:22
pinocchio.visualize.gepetto_visualizer.GepettoVisualizer.drawFrameVelocities
def drawFrameVelocities(self, *args, **kwargs)
Definition: gepetto_visualizer.py:320
pinocchio.visualize.gepetto_visualizer.GepettoVisualizer.display_collisions
display_collisions
Definition: gepetto_visualizer.py:267
pinocchio.visualize.gepetto_visualizer.GepettoVisualizer.captureImage
def captureImage(self, w=None, h=None)
Definition: gepetto_visualizer.py:311
pinocchio.visualize.gepetto_visualizer.GepettoVisualizer.display_visuals
display_visuals
Definition: gepetto_visualizer.py:283
pinocchio.visualize.gepetto_visualizer.GepettoVisualizer.viewerVisualGroupName
viewerVisualGroupName
Definition: gepetto_visualizer.py:191
pinocchio.visualize.gepetto_visualizer.GepettoVisualizer.viewerCollisionGroupName
viewerCollisionGroupName
Definition: gepetto_visualizer.py:187
pinocchio.visualize.gepetto_visualizer.GepettoVisualizer.setCameraTarget
def setCameraTarget(self, target)
Definition: gepetto_visualizer.py:299
pinocchio.visualize.gepetto_visualizer.GepettoVisualizer.loadPrimitive
def loadPrimitive(self, meshName, geometry_object)
Definition: gepetto_visualizer.py:77
pinocchio.visualize.gepetto_visualizer.GepettoVisualizer.getViewerNodeName
def getViewerNodeName(self, geometry_object, geometry_type)
Definition: gepetto_visualizer.py:21
pinocchio.visualize.gepetto_visualizer.GepettoVisualizer
Definition: gepetto_visualizer.py:18
pinocchio.visualize.gepetto_visualizer.GepettoVisualizer.viewer
viewer
Definition: gepetto_visualizer.py:43
pinocchio.visualize.gepetto_visualizer.GepettoVisualizer.loadViewerModel
def loadViewerModel(self, rootNodeName="pinocchio")
Definition: gepetto_visualizer.py:177


pinocchio
Author(s):
autogenerated on Sun Dec 22 2024 03:41:09