/
picking.py
1287 lines (1046 loc) · 44.4 KB
/
picking.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Module managing picking events."""
from functools import partial
import warnings
import weakref
import numpy as np
import pyvista
from pyvista import _vtk
from pyvista.utilities import try_callback
from .composite_mapper import CompositePolyDataMapper
def _launch_pick_event(interactor, event):
"""Create a Pick event based on coordinate or left-click."""
click_x, click_y = interactor.GetEventPosition()
click_z = 0
picker = interactor.GetPicker()
renderer = interactor.GetInteractorStyle()._parent()._plotter.renderer
picker.Pick(click_x, click_y, click_z, renderer)
class PickingHelper:
"""An internal class to hold picking related features."""
def __init__(self, *args, **kwargs):
"""Initialize the picking helper."""
super().__init__(*args, **kwargs)
self.picked_cells = None
self._picked_point = None
self._picked_mesh = None
self.picked_path = None
self.picked_geodesic = None
self.picked_horizon = None
self._picking_left_clicking_observer = None
self._picking_text = None
self._picker = None
self._picked_block_index = None
def get_pick_position(self):
"""Get the pick position or area.
Returns
-------
sequence
Picked position or area as ``(x0, y0, x1, y1)``.
"""
return self.renderer.get_pick_position()
def enable_mesh_picking(
self,
callback=None,
show=True,
show_message=True,
style='wireframe',
line_width=5,
color='pink',
font_size=18,
left_clicking=False,
use_actor=False,
**kwargs,
):
"""Enable picking of a mesh.
Parameters
----------
callback : callable, optional
When input, calls this callable after a selection is made. The
``mesh`` is input as the first parameter to this callable.
show : bool, optional
Show the selection interactively. Best when combined with
``left_clicking``.
show_message : bool or str, optional
Show the message about how to use the mesh picking tool. If this
is a string, that will be the message shown.
style : str, optional
Visualization style of the selection. Defaults to
``'wireframe'``. One of the following:
* ``'surface'``
* ``'wireframe'``
* ``'points'``
line_width : float, optional
Thickness of selected mesh edges. Default 5.
color : ColorLike, optional
The color of the selected mesh when shown.
font_size : int, optional
Sets the font size of the message.
left_clicking : bool, optional
When ``True``, meshes can be picked by clicking the left
mousebutton. Default to ``False``.
.. note::
If enabled, left-clicking will **not** display the bounding box
around the picked point.
use_actor : bool, default: False
If True, the callback will be passed the picked actor instead of
the mesh object.
**kwargs : dict, optional
All remaining keyword arguments are used to control how
the picked path is interactively displayed.
Returns
-------
vtk.vtkPropPicker
Property picker.
Examples
--------
Add a sphere and a cube to a plot and enable mesh picking. Enable
``left_clicking`` to immediately start picking on the left click and
disable showing the box. You can still press the ``p`` key to select
meshes.
>>> import pyvista as pv
>>> mesh = pv.Sphere(center=(1, 0, 0))
>>> cube = pv.Cube()
>>> pl = pv.Plotter()
>>> _ = pl.add_mesh(mesh)
>>> _ = pl.add_mesh(cube)
>>> _ = pl.enable_mesh_picking(left_clicking=True)
See :ref:`mesh_picking_example` for a full example using this method.
"""
def end_pick_call_back(picked, event):
is_valid_selection = False
self_ = weakref.ref(self)
actor = picked.GetActor()
if actor:
mesh = actor.GetMapper().GetInputAsDataSet()
is_valid_selection = True
if is_valid_selection:
self_()._picked_mesh = mesh
if callback and is_valid_selection:
if use_actor:
try_callback(callback, actor)
else:
try_callback(callback, mesh)
if show and is_valid_selection:
# Select the renderer where the mesh is added.
active_renderer_index = self_().renderers._active_index
for index in range(len(self.renderers)):
renderer = self.renderers[index]
for actor in renderer._actors.values():
mapper = actor.GetMapper()
if (
isinstance(mapper, _vtk.vtkDataSetMapper)
and mapper.GetInputAsDataSet() == mesh
):
loc = self_().renderers.index_to_loc(index)
self_().subplot(*loc)
break
# Use try in case selection is empty or invalid
try:
self_().add_mesh(
mesh,
name='_mesh_picking_selection',
style=style,
color=color,
line_width=line_width,
pickable=False,
reset_camera=False,
**kwargs,
)
except Exception as e: # pragma: no cover
warnings.warn("Unable to show mesh when picking:\n\n%s", str(e))
# Reset to the active renderer.
loc = self_().renderers.index_to_loc(active_renderer_index)
self_().subplot(*loc)
# render here prior to running the callback
self_().render()
elif not is_valid_selection:
self.remove_actor('_mesh_picking_selection')
self_()._picked_mesh = None
# add on-screen message about point-selection
if show_message:
if show_message is True:
show_message = "\nPress P to pick a single dataset under the mouse pointer."
if left_clicking:
show_message += "\nor click to select a dataset under the mouse pointer."
self._picking_text = self.add_text(
str(show_message), font_size=font_size, name='_mesh_picking_message'
)
if left_clicking:
self._picking_left_clicking_observer = self.iren.interactor.AddObserver(
"LeftButtonPressEvent",
partial(try_callback, _launch_pick_event),
)
self._picker = _vtk.vtkPropPicker()
self._picker.AddObserver(_vtk.vtkCommand.EndPickEvent, end_pick_call_back)
self.enable_trackball_style()
self.iren.set_picker(self._picker)
return self._picker
def enable_cell_picking(
self,
callback=None,
through=True,
show=True,
show_message=True,
style='wireframe',
line_width=5,
color='pink',
font_size=18,
start=False,
**kwargs,
):
"""Enable picking at cells.
Press ``"r"`` to enable retangle based selection. Press
``"r"`` again to turn it off. Selection will be saved to
``self.picked_cells``. Also press ``"p"`` to pick a single
cell under the mouse location.
All meshes in the scene are available for picking by default.
If you would like to only pick a single mesh in the scene,
use the ``pickable=False`` argument when adding the other
meshes to the scene.
When multiple meshes are being picked, the picked cells
in ``self.picked_cells`` will be a :class:`MultiBlock`
dataset for each mesh's selection.
Uses last input mesh for input by default.
.. warning::
Visible cell picking (``through=False``) will only work if
the mesh is displayed with a ``'surface'`` representation
style (the default).
.. warning::
Cell picking can only be enabled for a single renderer
or subplot at a time.
Parameters
----------
callback : callable, optional
When input, calls this callable after a selection is made.
The picked_cells are input as the first parameter to this
callable.
through : bool, optional
When ``True`` (default) the picker will select all cells
through the mesh(es). When ``False``, the picker will select
only visible cells on the selected surface(s).
show : bool, optional
Show the selection interactively.
show_message : bool or str, optional
Show the message about how to use the cell picking tool. If this
is a string, that will be the message shown.
style : str, optional
Visualization style of the selection. One of the
following: ``style='surface'``, ``style='wireframe'``, or
``style='points'``. Defaults to ``'wireframe'``.
line_width : float, optional
Thickness of selected mesh edges. Default 5.
color : ColorLike, optional
The color of the selected mesh when shown.
font_size : int, optional
Sets the font size of the message.
start : bool, optional
Automatically start the cell selection tool.
**kwargs : dict, optional
All remaining keyword arguments are used to control how
the selection is interactively displayed.
Examples
--------
Add a mesh and a cube to a plot and enable cell picking.
>>> import pyvista as pv
>>> mesh = pv.Sphere(center=(1, 0, 0))
>>> cube = pv.Cube()
>>> pl = pv.Plotter()
>>> _ = pl.add_mesh(mesh)
>>> _ = pl.add_mesh(cube)
>>> _ = pl.enable_cell_picking(left_clicking=True)
"""
self_ = weakref.ref(self)
# make sure to consistently use renderer
renderer_ = weakref.ref(self.renderer)
def end_pick_helper(picker, event_id):
# Merge the selection into a single mesh
picked = self_().picked_cells
if isinstance(picked, pyvista.MultiBlock):
if picked.n_blocks > 0:
picked = picked.combine()
else:
picked = pyvista.UnstructuredGrid()
# Check if valid
is_valid_selection = picked.n_cells > 0
if show and is_valid_selection:
# Select the renderer where the mesh is added.
active_renderer_index = self_().renderers._active_index
for index in range(len(self.renderers)):
renderer = self.renderers[index]
for actor in renderer._actors.values():
mapper = actor.GetMapper()
if isinstance(mapper, _vtk.vtkDataSetMapper):
loc = self_().renderers.index_to_loc(index)
self_().subplot(*loc)
break
# Use try in case selection is empty
self_().add_mesh(
picked,
name='_cell_picking_selection',
style=style,
color=color,
line_width=line_width,
pickable=False,
reset_camera=False,
**kwargs,
)
# Reset to the active renderer.
loc = self_().renderers.index_to_loc(active_renderer_index)
self_().subplot(*loc)
# render here prior to running the callback
self_().render()
elif not is_valid_selection:
self.remove_actor('_cell_picking_selection')
self_().picked_cells = None
if callback is not None:
try_callback(callback, self_().picked_cells)
# TODO: Deactivate selection tool
return
def through_pick_call_back(picker, event_id):
picked = pyvista.MultiBlock()
for actor in renderer_().actors.values():
if actor.GetMapper() and actor.GetPickable():
input_mesh = pyvista.wrap(actor.GetMapper().GetInputAsDataSet())
input_mesh.cell_data['orig_extract_id'] = np.arange(input_mesh.n_cells)
extract = _vtk.vtkExtractGeometry()
extract.SetInputData(input_mesh)
extract.SetImplicitFunction(picker.GetFrustum())
extract.Update()
picked.append(pyvista.wrap(extract.GetOutput()))
if len(picked) == 1:
self_().picked_cells = picked[0]
else:
self_().picked_cells = picked
return end_pick_helper(picker, event_id)
def visible_pick_call_back(picker, event_id):
picked = pyvista.MultiBlock()
x0, y0, x1, y1 = renderer_().get_pick_position()
if x0 >= 0: # initial pick position is (-1, -1, -1, -1)
selector = _vtk.vtkOpenGLHardwareSelector()
selector.SetFieldAssociation(_vtk.vtkDataObject.FIELD_ASSOCIATION_CELLS)
selector.SetRenderer(renderer_())
selector.SetArea(x0, y0, x1, y1)
selection = selector.Select()
for node in range(selection.GetNumberOfNodes()):
selection_node = selection.GetNode(node)
if selection_node is None: # pragma: no cover
# No selection
continue
cids = pyvista.convert_array(selection_node.GetSelectionList())
actor = selection_node.GetProperties().Get(_vtk.vtkSelectionNode.PROP())
# TODO: this is too hacky - find better way to avoid non-dataset actors
if not actor.GetMapper() or not hasattr(
actor.GetProperty(), 'GetRepresentation'
):
continue
# if not a surface
if actor.GetProperty().GetRepresentation() != 2: # pragma: no cover
warnings.warn(
"Display representations other than `surface` will result in incorrect results."
)
smesh = pyvista.wrap(actor.GetMapper().GetInputAsDataSet())
smesh = smesh.copy()
smesh["original_cell_ids"] = np.arange(smesh.n_cells)
tri_smesh = smesh.extract_surface().triangulate()
cids_to_get = tri_smesh.extract_cells(cids)["original_cell_ids"]
picked.append(smesh.extract_cells(cids_to_get))
# memory leak issues on vtk==9.0.20210612.dev0
# See: https://gitlab.kitware.com/vtk/vtk/-/issues/18239#note_973826
selection.UnRegister(selection)
if len(picked) == 1:
self_().picked_cells = picked[0]
else:
self_().picked_cells = picked
return end_pick_helper(picker, event_id)
self._picker = _vtk.vtkRenderedAreaPicker()
if through:
self._picker.AddObserver(_vtk.vtkCommand.EndPickEvent, through_pick_call_back)
else:
# NOTE: there can be issues with non-triangulated meshes
# Reference:
# https://github.com/pyvista/pyvista/issues/277
# https://github.com/pyvista/pyvista/pull/281
# https://discourse.vtk.org/t/visible-cell-selection-hardwareselector-py-example-is-not-working-reliably/1262
self._picker.AddObserver(_vtk.vtkCommand.EndPickEvent, visible_pick_call_back)
self.enable_rubber_band_style()
self.iren.set_picker(self._picker)
# Now add text about cell-selection
if show_message:
if show_message is True:
show_message = "Press R to toggle selection tool"
if not through:
show_message += "\nPress P to pick a single cell under the mouse"
self._picking_text = self.add_text(
str(show_message), font_size=font_size, name='_cell_picking_message'
)
if start:
self.iren._style_class.StartSelect()
@property
def picked_mesh(self):
"""Return the picked mesh.
This returns the picked mesh after selecting a mesh with
:func:`enable_mesh_picking <pyvista.Plotter.enable_mesh_picking>` or
:func:`enable_point_picking <pyvista.Plotter.enable_point_picking>`.
Returns
-------
pyvista.DataSet or None
Picked mesh if available.
"""
return self._picked_mesh
@property
def picked_point(self):
"""Return the picked point.
This returns the picked point after selecting a point.
Returns
-------
numpy.ndarray or None
Picked point if available.
"""
return self._picked_point
@property
def picked_block_index(self):
"""Return the picked block index.
This returns the picked block index after selecting a point with
:func:`enable_point_picking <pyvista.Plotter.enable_point_picking>`.
Returns
-------
int or None
Picked block if available. If ``-1``, then a non-composite dataset
was selected.
"""
return self._picked_block_index
def enable_surface_picking(
self,
callback=None,
show_message=True,
font_size=18,
color='pink',
show_point=True,
point_size=10,
tolerance=0.025,
pickable_window=False,
left_clicking=False,
**kwargs,
):
"""Enable picking of a point on the surface of a mesh.
Parameters
----------
callback : callable, optional
When input, calls this callable after a selection is made. The
``mesh`` is input as the first parameter to this callable.
show_message : bool or str, optional
Show the message about how to use the mesh picking tool. If this
is a string, that will be the message shown.
font_size : int, optional
Sets the font size of the message.
color : ColorLike, optional
The color of the selected mesh when shown.
show_point : bool, optional
Show the selection interactively. Default ``True``.
point_size : int, optional
Size of picked points if ``show_point`` is
``True``. Default 10.
tolerance : float, optional
Specify tolerance for performing pick operation. Tolerance
is specified as fraction of rendering window
size. Rendering window size is measured across diagonal.
pickable_window : bool, optional
When ``True``, points in the 3D window are pickable. Default to ``False``.
left_clicking : bool, optional
When ``True``, meshes can be picked by clicking the left
mousebutton. Default to ``False``.
.. note::
If enabled, left-clicking will **not** display the bounding box
around the picked mesh.
**kwargs : dict, optional
All remaining keyword arguments are used to control how
the picked path is interactively displayed.
Returns
-------
vtk.vtkPropPicker
Property picker.
Notes
-----
Picked point can be accessed from :attr:`picked_point
<pyvista.Plotter.picked_point>` attribute.
Examples
--------
Add a cube to a plot and enable cell picking. Enable ``left_clicking``
to immediately start picking on the left click and disable showing the
box. You can still press the ``p`` key to select meshes.
>>> import pyvista as pv
>>> cube = pv.Cube()
>>> pl = pv.Plotter()
>>> _ = pl.add_mesh(cube)
>>> _ = pl.enable_surface_picking(left_clicking=True)
See :ref:`surface_picking_example` for a full example using this method.
"""
def _end_pick_event(picker, event):
picked_point_id = picker.GetPointId()
if not pickable_window and picked_point_id < 0:
self._picked_point = None
return
self._picked_point = np.array(picker.GetPickPosition())
self._picked_mesh = picker.GetDataSet()
if show_point:
self.add_mesh(
self.picked_point,
color=color,
point_size=point_size,
name='_picked_point',
pickable=False,
reset_camera=False,
**kwargs,
)
if callable(callback):
try_callback(callback, self.picked_point)
picker = _vtk.vtkCellPicker()
picker.SetTolerance(tolerance)
self._picker = picker
picker.AddObserver(_vtk.vtkCommand.EndPickEvent, _end_pick_event)
self.enable_trackball_style()
self.iren.set_picker(picker)
if left_clicking:
self._picking_left_clicking_observer = self.iren.interactor.AddObserver(
"LeftButtonPressEvent",
partial(try_callback, _launch_pick_event),
)
# add on-screen message about point-selection
if show_message:
if show_message is True:
show_message = "\nPress P to pick a point on the surface under the mouse pointer."
if left_clicking:
show_message += "\nor click to select a point under the mouse pointer."
self._picking_text = self.add_text(
str(show_message), font_size=font_size, name='_surf_picking_message'
)
return picker
def enable_point_picking(
self,
callback=None,
show_message=True,
font_size=18,
color='pink',
point_size=10,
use_mesh=False,
show_point=True,
tolerance=0.025,
pickable_window=False,
left_clicking=False,
**kwargs,
):
"""Enable picking at points.
Enable picking a point at the mouse location in the render
view using the ``P`` key. This point is saved to the
``.picked_point`` attribute on the plotter. Pass a callback
that takes that point as an argument. The picked
point can either be a point on the first intersecting mesh, or
a point in the 3D window.
Parameters
----------
callback : callable, optional
When input, calls this callable after a pick is made. The
picked point is input as the first parameter to this
callable. If ``use_mesh`` is ``True``, the callback
callable will be passed a pointer to the picked mesh and
the point ID of the selected mesh.
show_message : bool or str, optional
Show the message about how to use the point picking
tool. If this is a string, that will be the message shown.
font_size : int, optional
Sets the size of the message.
color : ColorLike, optional
The color of the selected mesh when shown.
point_size : int, optional
Size of picked points if ``show_point`` is
``True``. Default 10.
use_mesh : bool, optional
If ``True``, the callback will be passed a pointer to the picked
mesh and the point ID of the selected mesh.
show_point : bool, optional
Show the picked point after clicking.
tolerance : float, optional
Specify tolerance for performing pick operation. Tolerance
is specified as fraction of rendering window
size. Rendering window size is measured across diagonal.
pickable_window : bool, optional
When ``True``, points in the 3D window are pickable. Default to ``False``.
left_clicking : bool, optional
When ``True``, points can be picked by clicking the left mouse button.
Default to ``False``. Note, if enabled, left-clicking will **not**
display the bounding box around the picked mesh.
**kwargs : dict, optional
All remaining keyword arguments are used to control how
the picked point is interactively displayed.
Examples
--------
Enable point picking with a custom message.
>>> import pyvista as pv
>>> pl = pv.Plotter()
>>> _ = pl.add_mesh(pv.Sphere())
>>> _ = pl.add_mesh(pv.Cube(), pickable=False)
>>> pl.enable_point_picking(show_message="Press P to pick")
See :ref:`point_picking_example` for a full example using this method.
"""
def _end_pick_event(picker, event):
picked_point_id = picker.GetPointId()
if (not pickable_window) and (picked_point_id < 0):
return None
self._picked_point = np.array(picker.GetPickPosition())
self._picked_mesh = picker.GetDataSet()
self._picked_block_index = picker.GetFlatBlockIndex()
self.picked_point_id = picked_point_id
if show_point:
self.add_mesh(
self.picked_point,
color=color,
point_size=point_size,
name='_picked_point',
pickable=False,
reset_camera=False,
**kwargs,
)
if callable(callback):
if use_mesh:
try_callback(callback, self.picked_mesh, self.picked_point_id)
else:
try_callback(callback, self.picked_point)
point_picker = _vtk.vtkPointPicker()
point_picker.SetTolerance(tolerance)
self._picker = point_picker
point_picker.AddObserver(_vtk.vtkCommand.EndPickEvent, _end_pick_event)
self.enable_trackball_style()
self.iren.set_picker(point_picker)
if left_clicking:
self._picking_left_clicking_observer = self.iren.add_observer(
"LeftButtonPressEvent",
partial(try_callback, _launch_pick_event),
)
# Now add text about cell-selection
if show_message:
if show_message is True and left_clicking:
show_message = "Left-click or press P to pick under the mouse"
elif show_message is True:
show_message = "Press P to pick under the mouse"
self._picking_text = self.add_text(
str(show_message), font_size=font_size, name='_point_picking_message'
)
def enable_path_picking(
self,
callback=None,
show_message=True,
font_size=18,
color='pink',
point_size=10,
line_width=5,
show_path=True,
tolerance=0.025,
**kwargs,
):
"""Enable picking at paths.
This is a convenience method for :func:`enable_point_picking
<pyvista.Plotter.enable_point_picking>` to keep track of the
picked points and create a line using those points.
The line is saved to the ``.picked_path`` attribute of this
plotter
Parameters
----------
callback : callable, optional
When given, calls this callable after a pick is made. The
entire picked path is passed as the only parameter to this
callable.
show_message : bool or str, optional
Show the message about how to use the point picking
tool. If this is a string, that will be the message shown.
font_size : int, optional
Sets the size of the message.
color : ColorLike, optional
The color of the selected mesh when shown.
point_size : int, optional
Size of picked points if ``show_path`` is
``True``. Default 10.
line_width : float, optional
Thickness of path representation if ``show_path`` is
``True``. Default 5.
show_path : bool, optional
Show the picked path interactively.
tolerance : float, optional
Specify tolerance for performing pick operation. Tolerance
is specified as fraction of rendering window
size. Rendering window size is measured across diagonal.
**kwargs : dict, optional
All remaining keyword arguments are used to control how
the picked path is interactively displayed.
"""
kwargs.setdefault('pickable', False)
def make_line_cells(n_points):
cells = np.arange(0, n_points, dtype=np.int_)
cells = np.insert(cells, 0, n_points)
return cells
the_points = []
the_ids = []
def _the_callback(mesh, idx):
if mesh is None:
return
the_ids.append(idx)
the_points.append(mesh.points[idx])
self.picked_path = pyvista.PolyData(np.array(the_points))
self.picked_path.lines = make_line_cells(len(the_points))
if show_path:
self.add_mesh(
self.picked_path,
color=color,
name='_picked_path',
line_width=line_width,
point_size=point_size,
reset_camera=False,
**kwargs,
)
if callable(callback):
try_callback(callback, self.picked_path)
def _clear_path_event_watcher():
del the_points[:]
del the_ids[:]
self.remove_actor('_picked_path')
self.add_key_event('c', _clear_path_event_watcher)
if show_message is True:
show_message = "Press P to pick under the mouse\nPress C to clear"
self.enable_point_picking(
callback=_the_callback,
use_mesh=True,
font_size=font_size,
show_message=show_message,
show_point=False,
tolerance=tolerance,
)
def enable_geodesic_picking(
self,
callback=None,
show_message=True,
font_size=18,
color='pink',
point_size=10,
line_width=5,
tolerance=0.025,
show_path=True,
keep_order=True,
**kwargs,
):
"""Enable picking at geodesic paths.
This is a convenience method for ``enable_point_picking`` to
keep track of the picked points and create a geodesic path
using those points.
The geodesic path is saved to the ``.picked_geodesic``
attribute of this plotter.
Parameters
----------
callback : callable, optional
When given, calls this callable after a pick is made. The
entire picked, geodesic path is passed as the only
parameter to this callable.
show_message : bool or str, optional
Show the message about how to use the point picking
tool. If this is a string, that will be the message shown.
font_size : int, optional
Sets the size of the message.
color : ColorLike, optional
The color of the selected mesh when shown.
point_size : int, optional
Size of picked points if ``show_path`` is
``True``. Default 10.
line_width : float, optional
Thickness of path representation if ``show_path`` is
``True``. Default 5.
tolerance : float, optional
Specify tolerance for performing pick operation. Tolerance
is specified as fraction of rendering window
size. Rendering window size is measured across diagonal.
show_path : bool, optional
Show the picked path interactively.
keep_order : bool, optional
If ``True``, the created geodesic path is a single ordered
and cleaned line from the first point to the last.
.. note::
In older versions there were apparent discontinuities
in the resulting path due to the behavior of the
underlying VTK filter which corresponds to
``keep_order=False``.
.. versionadded:: 0.32.0
**kwargs : dict, optional
All remaining keyword arguments are used to control how
the picked path is interactively displayed.
"""
kwargs.setdefault('pickable', False)
self.picked_geodesic = pyvista.PolyData()
self._last_picked_idx = None
def _the_callback(mesh, idx):
if mesh is None:
return
point = mesh.points[idx]
if self._last_picked_idx is None:
self.picked_geodesic = pyvista.PolyData(point)
self.picked_geodesic['vtkOriginalPointIds'] = [idx]
else:
surface = mesh.extract_surface().triangulate()
locator = _vtk.vtkPointLocator()
locator.SetDataSet(surface)
locator.BuildLocator()
start_idx = locator.FindClosestPoint(mesh.points[self._last_picked_idx])
end_idx = locator.FindClosestPoint(point)
self.picked_geodesic += surface.geodesic(start_idx, end_idx, keep_order=keep_order)
if keep_order:
# it makes sense to remove adjacent duplicate points
self.picked_geodesic.clean(
inplace=True,
lines_to_points=False,
polys_to_lines=False,
strips_to_polys=False,
)
self._last_picked_idx = idx
if show_path:
self.add_mesh(
self.picked_geodesic,
color=color,
name='_picked_path',
line_width=line_width,
point_size=point_size,
reset_camera=False,
**kwargs,
)
if callable(callback):
try_callback(callback, self.picked_geodesic)
def _clear_g_path_event_watcher():
self.picked_geodesic = pyvista.PolyData()
self.remove_actor('_picked_path')