Debian Codegraph @

pyvista/plotting/affine_widget.py

raw
1 """Affine widget module."""
2
3 from __future__ import annotations
4
5 from typing import TYPE_CHECKING
6 from typing import cast
7
8 import numpy as np
9
10 import pyvista as pv
11 from pyvista import _vtk
12 from pyvista._deprecate_positional_args import _deprecate_positional_args
13 from pyvista.core.utilities.misc import _NoNewAttrMixin
14 from pyvista.core.utilities.misc import try_callback
15
16 if TYPE_CHECKING:
17 from pyvista import Actor
18
19 DARK_YELLOW = (0.9647058823529412, 0.7450980392156863, 0)
20 GLOBAL_AXES = np.eye(3)
21
22
23 def _validate_axes(axes):
24 """Validate and normalize input axes.
25
26 Axes are expected to follow the right-hand rule (e.g. third axis is the
27 cross product of the first two.
28
29 Parameters
30 ----------
31 axes : sequence
32 The axes to be validated and normalized. Should be of shape (3, 3).
33
34 Returns
35 -------
36 dict
37 The validated and normalized axes.
38
39 """
40 axes = np.array(axes)
41 if axes.shape != (3, 3):
42 msg = '`axes` must be a (3, 3) array.'
43 raise ValueError(msg)
44
45 axes = axes / np.linalg.norm(axes, axis=1, keepdims=True)
46 if not np.allclose(np.cross(axes[0], axes[1]), axes[2]):
47 msg = '`axes` do not follow the right hand rule.'
48 raise ValueError(msg)
49
50 return axes
51
52
53 def _check_callable(func, name='callback'):
54 """Check if a variable is callable."""
55 if func and not callable(func):
56 msg = f'`{name}` must be a callable, not {type(func)}.'
57 raise TypeError(msg)
58 return func
59
60
61 def _make_quarter_arc():
62 """Make a quarter circle centered at the origin."""
63 circ = pv.Circle(resolution=100)
64 circ.faces = np.empty(0, dtype=int)
65 circ.lines = np.hstack(([26], np.arange(0, 26)))
66 return circ
67
68
69 def get_angle(v1, v2):
70 """Compute the angle between two vectors in degrees.
71
72 Parameters
73 ----------
74 v1 : numpy.ndarray
75 First input vector.
76 v2 : numpy.ndarray
77 Second input vector.
78
79 Returns
80 -------
81 float
82 Angle between vectors in degrees.
83
84 """
85 return np.rad2deg(np.arccos(np.clip(np.dot(v1, v2), -1.0, 1.0)))
86
87
88 @_deprecate_positional_args
89 def ray_plane_intersection(start_point, direction, plane_point, normal): # noqa: PLR0917
90 """Compute the intersection between a ray and a plane.
91
92 Parameters
93 ----------
94 start_point : ndarray
95 Starting point of the ray.
96 direction : ndarray
97 Direction of the ray.
98 plane_point : ndarray
99 A point on the plane.
100 normal : ndarray
101 Normal to the plane.
102
103 Returns
104 -------
105 ndarray
106 Intersection point.
107
108 """
109 t_value = np.dot(normal, (plane_point - start_point)) / np.dot(normal, direction)
110 return start_point + t_value * direction
111
112
113 class AffineWidget3D(_NoNewAttrMixin):
114 """3D affine transform widget.
115
116 This widget allows interactive transformations including translation and
117 rotation using the left mouse button.
118
119 Parameters
120 ----------
121 plotter : pyvista.Plotter
122 The plotter object.
123 actor : pyvista.Actor
124 The actor to which the widget is attached to.
125 origin : sequence[float], optional
126 Origin of the widget. Default is the center of the main actor.
127 start : bool, default: True
128 If True, start the widget immediately.
129 scale : float, default: 0.15
130 Scale factor for the widget relative to the length of the actor.
131 line_radius : float, default: 0.02
132 Relative radius of the lines composing the widget.
133 always_visible : bool, default: True
134 Make the widget always visible. Setting this to ``False`` will cause
135 the widget geometry to be hidden by other actors in the plotter.
136 axes_colors : tuple[ColorLike], optional
137 Uses the theme by default. Configure the individual axis colors by
138 modifying either the theme with ``pyvista.global_theme.axes.x_color =
139 <COLOR>`` or setting this with a ``tuple`` as in ``('r', 'g', 'b')``.
140 axes : numpy.ndarray, optional
141 ``(3, 3)`` Numpy array defining the X, Y, and Z axes. By default this
142 matches the default coordinate system.
143 release_callback : callable, optional
144 Call this method when releasing the left mouse button. It is passed the
145 ``user_matrix`` of the actor.
146 interact_callback : callable, optional
147 Call this method when moving the mouse with the left mouse button
148 pressed down and a valid movement actor selected. It is passed the
149 ``user_matrix`` of the actor.
150
151 Notes
152 -----
153 After interacting with the actor, the transform will be stored within
154 :attr:`pyvista.Prop3D.user_matrix` but will not be applied to the
155 dataset. Use this matrix in conjunction with
156 :func:`pyvista.DataObjectFilters.transform` to transform the dataset.
157
158 Requires VTK >= v9.2
159
160 Examples
161 --------
162 Create the affine widget outside of the plotter and add it.
163
164 >>> import pyvista as pv
165 >>> pl = pv.Plotter()
166 >>> actor = pl.add_mesh(pv.Sphere())
167 >>> widget = pv.AffineWidget3D(pl, actor)
168 >>> pl.show()
169
170 Access the transform from the actor.
171
172 >>> actor.user_matrix
173 array([[1., 0., 0., 0.],
174 [0., 1., 0., 0.],
175 [0., 0., 1., 0.],
176 [0., 0., 0., 1.]])
177
178 """
179
180 @_deprecate_positional_args(allowed=['plotter', 'actor'])
181 def __init__( # noqa: PLR0917
182 self,
183 plotter,
184 actor,
185 origin=None,
186 start: bool = True, # noqa: FBT001, FBT002
187 scale=0.15,
188 line_radius=0.02,
189 always_visible: bool = True, # noqa: FBT001, FBT002
190 axes_colors=None,
191 axes=None,
192 release_callback=None,
193 interact_callback=None,
194 ):
195 """Initialize the widget."""
196 self._axes = np.eye(4)
197 self._axes_inv = np.eye(4)
198 self._pl = plotter
199 self._main_actor = actor
200 self._selected_actor: Actor | None = None
201 self._init_position = None
202 self._mouse_move_observer: int | None = None
203 self._left_press_observer: int | None = None
204 self._left_release_observer: int | None = None
205
206 if self._main_actor.user_matrix is None:
207 self._main_actor.user_matrix = np.eye(4)
208 self._cached_matrix = self._main_actor.user_matrix
209
210 self._arrows = [] # type: ignore[var-annotated]
211 self._circles = [] # type: ignore[var-annotated]
212 self._pressing_down = False
213 origin = origin or actor.center
214 self._origin = np.array(origin)
215 if axes_colors is None:
216 axes_colors = (
217 pv.global_theme.axes.x_color,
218 pv.global_theme.axes.y_color,
219 pv.global_theme.axes.z_color,
220 )
221 self._axes_colors = axes_colors
222 self._circ = _make_quarter_arc()
223 self._actor_length = self._main_actor.GetLength()
224 self._line_radius = line_radius
225 self._user_interact_callback = _check_callable(interact_callback)
226 self._user_release_callback = _check_callable(release_callback)
227
228 self._init_actors(scale, always_visible)
229
230 # axes must be set after initializing actors
231 if axes is not None:
232 try:
233 _validate_axes(axes)
234 except ValueError:
235 for actor_ in self._arrows + self._circles:
236 self._pl.remove_actor(actor_)
237 raise
238 self.axes = axes
239
240 if start:
241 self.enable()
242
243 def _init_actors(self, scale, always_visible):
244 """Initialize the widget's actors."""
245 for ii, color in enumerate(self._axes_colors):
246 arrow = pv.Arrow(
247 start=(0, 0, 0),
248 direction=GLOBAL_AXES[ii],
249 scale=self._actor_length * scale * 1.15,
250 tip_radius=0.05,
251 shaft_radius=self._line_radius,
252 )
253 self._arrows.append(
254 self._pl.add_mesh(arrow, color=color, lighting=False, render=False)
255 )
256 axis_circ = self._circ.copy()
257 if ii == 0:
258 axis_circ = axis_circ.rotate_y(-90)
259 elif ii == 1:
260 axis_circ = axis_circ.rotate_x(90)
261 axis_circ.points *= self._main_actor.GetLength() * (scale * 1.6)
262 # axis_circ.points += self._origin
263 axis_circ = axis_circ.tube(
264 radius=self._line_radius * self._actor_length * scale,
265 absolute=True,
266 radius_factor=1.0,
267 )
268
269 self._circles.append(
270 self._pl.add_mesh(
271 axis_circ,
272 color=color,
273 lighting=False,
274 render_lines_as_tubes=True,
275 render=False,
276 ),
277 )
278
279 # update origin and assign a default user_matrix
280 for actor in self._arrows + self._circles:
281 matrix = np.eye(4)
282 matrix[:3, -1] = self._origin
283 actor.user_matrix = matrix
284
285 if always_visible:
286 for actor in self._arrows + self._circles:
287 actor.mapper.SetResolveCoincidentTopologyToPolygonOffset()
288 actor.mapper.SetRelativeCoincidentTopologyPolygonOffsetParameters(0, -20000)
289
290 def _get_world_coord_rot(self, interactor):
291 """Get the world coordinates given an interactor.
292
293 Unlike ``_get_world_coord_trans``, these coordinates are physically
294 accurate, but sensitive to the position of the camera. Rotation is zoom
295 independent.
296
297 """
298 x, y = interactor.GetEventPosition()
299 coordinate = _vtk.vtkCoordinate()
300 coordinate.SetCoordinateSystemToDisplay()
301 coordinate.SetValue(x, y, 0)
302 ren = interactor.GetRenderWindow().GetRenderers().GetFirstRenderer()
303 point = np.array(coordinate.GetComputedWorldValue(ren))
304 if self._selected_actor:
305 index = self._circles.index(self._selected_actor)
306 to_widget = np.array(ren.camera.position - self._origin)
307 point = ray_plane_intersection(
308 start_point=point,
309 direction=to_widget,
310 plane_point=self._origin,
311 normal=self.axes[index],
312 )
313 return point
314
315 def _get_world_coord_trans(self, interactor):
316 """Get the world coordinates given an interactor.
317
318 This uses a modified scaled approach to get the world coordinates that
319 are not physically accurate, but ignores zoom and works for
320 translation.
321
322 """
323 x, y = interactor.GetEventPosition()
324 ren = interactor.GetRenderWindow().GetRenderers().GetFirstRenderer()
325
326 # Get normalized view coordinates (-1, 1)
327 width, height = ren.GetSize()
328 ndc_x = 2 * (x / width) - 1
329 ndc_y = 2 * (y / height) - 1
330 ndc_z = 1
331
332 # convert camera coordinates to world coordinates
333 camera = ren.GetActiveCamera()
334 projection_matrix = pv.array_from_vtkmatrix(
335 camera.GetProjectionTransformMatrix(ren.GetTiledAspectRatio(), 0, 1),
336 )
337 inverse_projection_matrix = np.linalg.inv(projection_matrix)
338 camera_coords = np.dot(inverse_projection_matrix, [ndc_x, ndc_y, ndc_z, 1])
339 modelview_matrix = pv.array_from_vtkmatrix(camera.GetModelViewTransformMatrix())
340 inverse_modelview_matrix = np.linalg.inv(modelview_matrix)
341 world_coords = np.dot(inverse_modelview_matrix, camera_coords)
342
343 # Scale by twice actor length (experimentally determined for good UX)
344 return world_coords[:3] * self._actor_length * 2
345
346 def _move_callback(self, interactor, _event):
347 """Process actions for the move mouse event."""
348 click_x, click_y = interactor.GetEventPosition()
349 click_z = 0
350 picker = interactor.GetPicker()
351 renderer = interactor.GetInteractorStyle()._parent()._plotter.iren.get_poked_renderer()
352 picker.Pick(click_x, click_y, click_z, renderer)
353 actor = picker.GetActor()
354
355 if self._pressing_down:
356 if self._selected_actor in self._arrows:
357 current_pos = self._get_world_coord_trans(interactor)
358 index = self._arrows.index(self._selected_actor)
359 diff = current_pos - self._init_position
360 trans_matrix = np.eye(4)
361 trans_matrix[:3, -1] = self.axes[index] * np.dot(diff, self.axes[index])
362 matrix = trans_matrix @ self._cached_matrix
363 elif self._selected_actor in self._circles:
364 current_pos = self._get_world_coord_rot(interactor)
365 index = self._circles.index(self._selected_actor)
366 vec_current = current_pos - self._origin
367 vec_init = self._init_position - self._origin
368 normal = self.axes[index]
369 vec_current = vec_current - np.dot(vec_current, normal) * normal
370 vec_init = vec_init - np.dot(vec_init, normal) * normal
371 vec_current /= np.linalg.norm(vec_current)
372 vec_init /= np.linalg.norm(vec_init)
373 angle = get_angle(vec_init, vec_current)
374 cross = np.cross(vec_init, vec_current)
375 if cross[index] < 0:
376 angle = -angle
377
378 trans = _vtk.vtkTransform()
379 trans.Translate(self._origin) # type: ignore[call-overload]
380 trans.RotateWXYZ(
381 angle,
382 self._axes[index][0],
383 self._axes[index][1],
384 self._axes[index][2],
385 )
386 trans.Translate(-self._origin) # type: ignore[call-overload]
387 trans.Update()
388 rot_matrix = pv.array_from_vtkmatrix(trans.GetMatrix())
389 matrix = rot_matrix @ self._cached_matrix
390
391 if self._user_interact_callback:
392 try_callback(self._user_interact_callback, self._main_actor.user_matrix)
393
394 self._main_actor.user_matrix = matrix
395
396 elif self._selected_actor and self._selected_actor is not actor:
397 # Return the color of the currently selected actor to normal and
398 # deselect it
399 if self._selected_actor in self._arrows:
400 index = self._arrows.index(self._selected_actor)
401 elif self._selected_actor in self._circles:
402 index = self._circles.index(self._selected_actor)
403 self._selected_actor.prop.color = self._axes_colors[index]
404 self._selected_actor = None
405
406 # Highlight the actor if there is no selected actor
407 if actor and not self._selected_actor:
408 if actor in self._arrows:
409 index = self._arrows.index(actor)
410 self._arrows[index].prop.color = DARK_YELLOW
411 actor.prop.color = DARK_YELLOW
412 self._selected_actor = actor
413 elif actor in self._circles:
414 index = self._circles.index(actor)
415 self._circles[index].prop.color = DARK_YELLOW
416 actor.prop.color = DARK_YELLOW
417 self._selected_actor = actor
418 self._pl.render()
419
420 def _press_callback(self, interactor, _event):
421 """Process actions for the mouse button press event."""
422 if self._selected_actor:
423 self._pl.enable_trackball_actor_style()
424 self._pressing_down = True
425 if self._selected_actor in self._circles:
426 self._init_position = self._get_world_coord_rot(interactor)
427 else:
428 self._init_position = self._get_world_coord_trans(interactor)
429
430 def _release_callback(self, _interactor, _event):
431 """Process actions for the mouse button release event."""
432 self._pl.enable_trackball_style()
433 self._pressing_down = False
434 self._cached_matrix = self._main_actor.user_matrix
435 if self._user_release_callback:
436 try_callback(self._user_release_callback, self._main_actor.user_matrix)
437
438 def _reset(self):
439 """Reset the actor and cached transform."""
440 self._main_actor.user_matrix = np.eye(4)
441 self._cached_matrix = np.eye(4)
442
443 @property
444 def axes(self):
445 """Return or set the axes of the widget.
446
447 The axes will be checked for orthogonality. Non-orthogonal axes will
448 raise a ``ValueError``
449
450 Returns
451 -------
452 numpy.ndarray
453 ``(3, 3)`` array of axes.
454
455 """
456 return self._axes[:3, :3]
457
458 @axes.setter
459 def axes(self, axes):
460 mat = np.eye(4)
461 mat[:3, :3] = _validate_axes(axes)
462 mat[:3, -1] = self.origin
463 self._axes = mat
464 self._axes_inv = np.linalg.inv(self._axes) # type: ignore[assignment]
465 for actor in self._arrows + self._circles:
466 matrix = actor.user_matrix
467 # Be sure to use the inverse here
468 matrix[:3, :3] = self._axes_inv[:3, :3]
469 actor.user_matrix = matrix
470
471 @property
472 def origin(self) -> tuple[float, float, float]:
473 """Origin of the widget.
474
475 This is where the origin of the widget will be located and where the
476 actor will be rotated about.
477
478 Returns
479 -------
480 tuple
481 Widget origin.
482
483 """
484 return cast('tuple[float, float, float]', tuple(self._origin))
485
486 @origin.setter
487 def origin(self, value):
488 value = np.array(value)
489 diff = value - self._origin
490
491 for actor in self._circles + self._arrows:
492 if actor.user_matrix is None:
493 actor.user_matrix = np.eye(4)
494 matrix = actor.user_matrix
495 matrix[:3, -1] += diff
496 actor.user_matrix = matrix
497
498 self._origin = value
499
500 def enable(self):
501 """Enable the widget."""
502 if not self._pl.picking._picker_in_use:
503 self._pl.enable_mesh_picking(show_message=False, show=False, picker='hardware')
504 self._mouse_move_observer = self._pl.iren.add_observer(
505 'MouseMoveEvent',
506 self._move_callback,
507 )
508 self._left_press_observer = self._pl.iren.add_observer(
509 'LeftButtonPressEvent',
510 self._press_callback,
511 interactor_style_fallback=False,
512 )
513 self._left_release_observer = self._pl.iren.add_observer(
514 'LeftButtonReleaseEvent',
515 self._release_callback,
516 interactor_style_fallback=False,
517 )
518
519 def disable(self):
520 """Disable the widget."""
521 self._pl.disable_picking()
522 if self._mouse_move_observer:
523 self._pl.iren.remove_observer(self._mouse_move_observer)
524 if self._left_press_observer:
525 self._pl.iren.remove_observer(self._left_press_observer)
526 if self._left_release_observer:
527 self._pl.iren.remove_observer(self._left_release_observer)
528
529 def remove(self):
530 """Disable and delete all actors of this widget."""
531 self.disable()
532 for actor in self._circles + self._arrows:
533 self._pl.remove_actor(actor)
534 self._circles = []
535 self._arrows = []