-
Notifications
You must be signed in to change notification settings - Fork 63
Expand file tree
/
Copy path_plot_area.py
More file actions
976 lines (773 loc) · 32.5 KB
/
_plot_area.py
File metadata and controls
976 lines (773 loc) · 32.5 KB
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
from inspect import getfullargspec
from typing import Literal, Union
from warnings import warn
import numpy as np
import pygfx
from pylinalg import vec_transform, vec_unproject
from rendercanvas import BaseRenderCanvas
from ._utils import create_controller
from ..graphics._base import Graphic, WORLD_OBJECT_TO_GRAPHIC
from ..graphics import ImageGraphic
from ..graphics.selectors._base_selector import BaseSelector
from ._graphic_methods_mixin import GraphicMethodsMixin
from ..legends import Legend
from ..tools import Tooltip
try:
get_ipython()
except NameError:
IS_IPYTHON = False
IPYTHON = None
else:
IS_IPYTHON = True
IPYTHON = get_ipython()
class PlotArea(GraphicMethodsMixin):
def __init__(
self,
parent: Union["PlotArea", "Figure"],
camera: pygfx.PerspectiveCamera,
controller: pygfx.Controller,
scene: pygfx.Scene,
canvas: BaseRenderCanvas,
renderer: pygfx.WgpuRenderer,
name: str = None,
):
"""
Base class for plot creation and management. ``PlotArea`` is not intended to be instantiated by users
but rather to provide functionality for ``subplots`` in a user ``Figure``
Parameters
----------
parent: PlotArea or Figure
parent object
position: Any
position of the plot area. In a ``subplot`` position would correspond to the ``[row, column]``
index of the ``subplot``. In docks this would correspond to a str name, "top", "right", "bottom" or "left"
camera: pygfx.PerspectiveCamera
Use perspective camera for both perspective and orthographic views. Set fov = 0 for orthographic projection
controller: pygfx.Controller
One of the pygfx controllers: "panzoom", "fly", "trackball", "orbit"
scene: pygfx.Scene
represents the root of a scene graph, will be viewed by the given ``camera``
canvas: BaseRenderCanvas
provides surface on which a scene will be rendered
renderer: pygfx.WgpuRenderer
renders the scene onto the canvas
name: str, optional
name this plot area
"""
self._parent = parent
self._scene = scene
self._canvas = canvas
self._renderer = renderer
self._viewport: pygfx.Viewport = pygfx.Viewport(renderer)
self._camera = camera
self._controller = controller
self.controller.add_camera(self._camera)
self.controller.register_events(
self.viewport,
)
self._animate_funcs_pre: list[callable] = list()
self._animate_funcs_post: list[callable] = list()
self._animate_funcs_persist: list[callable] = list()
# list of all graphics managed by this PlotArea
self._graphics: list[Graphic] = list()
# selectors are in their own list so they can be excluded from scene bbox calculations
self._selectors: list[BaseSelector] = list()
# legends, managed just like other graphics as explained above
self._legends: list[Legend] = list()
# keep all graphics in a separate group, makes bbox calculations etc. easier
# this is the "real scene" excluding axes, selection tools etc.
self._fpl_graphics_scene = pygfx.Group()
self.scene.add(self._fpl_graphics_scene)
self._name = name
# need to think about how to deal with children better
self.children = list()
self._background_material = pygfx.BackgroundMaterial(
(0.0, 0.0, 0.0, 1.0),
(0.0, 0.0, 0.0, 1.0),
(0.0, 0.0, 0.0, 1.0),
(0.0, 0.0, 0.0, 1.0),
alpha_mode="blend",
)
self._background = pygfx.Background(None, self._background_material)
self.scene.add(self._background)
self._ambient_light = pygfx.AmbientLight()
self._directional_light = pygfx.DirectionalLight()
self.scene.add(self._ambient_light)
self.scene.add(self._camera.add(self._directional_light))
self._tooltip = Tooltip()
self.get_figure()._fpl_overlay_scene.add(self._tooltip._fpl_world_object)
self.renderer.add_event_handler(self._fpl_set_tooltip, "pointer_move")
def get_figure(self, obj=None):
"""Get Figure instance that contains this plot area"""
if obj is None:
obj = self
if obj.parent.__class__.__name__.endswith("Figure"):
return obj.parent
else:
if obj.parent is None:
raise RecursionError
return self.get_figure(obj=obj.parent)
# several read-only properties
@property
def parent(self):
"""A parent if relevant"""
return self._parent
@property
def scene(self) -> pygfx.Scene:
"""The Scene where Graphics lie in this plot area"""
return self._scene
@property
def canvas(self) -> BaseRenderCanvas:
"""Canvas associated to the plot area"""
return self._canvas
@property
def renderer(self) -> pygfx.WgpuRenderer:
"""Renderer associated to the plot area"""
return self._renderer
@property
def viewport(self) -> pygfx.Viewport:
"""The rectangular area of the renderer associated to this plot area"""
return self._viewport
@property
def camera(self) -> pygfx.PerspectiveCamera:
"""camera used to view the scene"""
return self._camera
@camera.setter
def camera(self, new_camera: str | pygfx.PerspectiveCamera):
# user wants to set completely new camera, remove current camera from controller
if isinstance(new_camera, pygfx.PerspectiveCamera):
self.controller.remove_camera(self._camera)
# add directional light to new camera
new_camera.add(self._directional_light)
# add new camera to controller
self.controller.add_camera(new_camera)
self._camera = new_camera
# modify FOV if necessary
elif isinstance(new_camera, str):
if new_camera == "2d":
self._camera.fov = 0
elif new_camera == "3d":
# orthographic -> perspective only if fov = 0, i.e. if camera is in ortho mode
# otherwise keep same FOV
if self._camera.fov == 0:
self._camera.fov = 50
else:
raise ValueError(
"camera must be one of '2d', '3d' or a pygfx.PerspectiveCamera instance"
)
else:
raise ValueError(
"camera must be one of '2d', '3d' or a pygfx.PerspectiveCamera instance"
)
# in the future we can think about how to allow changing the controller
@property
def controller(self) -> pygfx.Controller:
"""controller used to control the camera"""
return self._controller
@controller.setter
def controller(self, new_controller: str | pygfx.Controller):
new_controller = create_controller(new_controller, self._camera)
cameras_list = list()
# remove all the cameras associated to this controller
for camera in self._controller.cameras:
self._controller.remove_camera(camera)
cameras_list.append(camera)
# add the associated cameras to the new controller
for camera in cameras_list:
new_controller.add_camera(camera)
new_controller.register_events(self.viewport)
# TODO: monkeypatch until we figure out a better
# pygfx plans on refactoring viewports anyways
if self.parent is not None:
if self.parent.__class__.__name__.endswith("Figure"):
for subplot in self.parent:
if subplot.camera in cameras_list:
new_controller.register_events(subplot.viewport)
subplot._controller = new_controller
self._controller = new_controller
@property
def graphics(self) -> tuple[Graphic, ...]:
"""Graphics in the plot area."""
return tuple(self._graphics)
@property
def selectors(self) -> tuple[BaseSelector, ...]:
"""Selectors in the plot area."""
return tuple(self._selectors)
@property
def legends(self) -> tuple[Legend, ...]:
"""Legends in the plot area."""
return tuple(self._legends)
@property
def objects(self) -> tuple[Graphic | BaseSelector | Legend, ...]:
return *self.graphics, *self.selectors, *self.legends
@property
def name(self) -> str:
"""The name of this plot area"""
return self._name
@name.setter
def name(self, name: str):
if name is None:
self._name = None
return
if not isinstance(name, str):
raise TypeError("PlotArea `name` must be of type <str>")
self._name = name
@property
def background_color(self) -> tuple[pygfx.Color, ...]:
"""background colors, (top left, top right, bottom right, bottom left)"""
return (
self._background_material.color_top_left,
self._background_material.color_top_right,
self._background_material.color_bottom_right,
self._background_material.color_bottom_left,
)
@background_color.setter
def background_color(self, colors: str | tuple[float]):
"""1, 2, or 4 colors, each color must be acceptable by pygfx.Color"""
self._background_material.set_colors(*colors)
@property
def ambient_light(self) -> pygfx.AmbientLight:
"""the ambient lighting in the scene"""
return self._ambient_light
@property
def directional_light(self) -> pygfx.DirectionalLight:
"""the directional lighting on the camera in the scene"""
return self._directional_light
@property
def animations(self) -> dict[str, list[callable]]:
"""Returns a dictionary of 'pre' and 'post' animation functions."""
return {"pre": self._animate_funcs_pre, "post": self._animate_funcs_post}
@property
def tooltip(self) -> Tooltip:
"""The tooltip in this PlotArea"""
return self._tooltip
def map_screen_to_world(
self, pos: tuple[float, float] | pygfx.PointerEvent, allow_outside: bool = False
) -> np.ndarray | None:
"""
Map screen (canvas) position to world position
Parameters
----------
pos: (float, float) | pygfx.PointerEvent
``(x, y)`` screen coordinates, or ``pygfx.PointerEvent``
Returns
-------
(float, float, float)
(x, y, z) position in world space, z is always 0
"""
if isinstance(pos, pygfx.PointerEvent):
pos = pos.x, pos.y
if not allow_outside and not self.viewport.is_inside(*pos):
return None
vs = self.viewport.logical_size
# get position relative to viewport
pos_rel = (
pos[0] - self.viewport.rect[0],
pos[1] - self.viewport.rect[1],
)
# convert screen position to NDC
pos_ndc = np.asarray([pos_rel[0] / vs[0] * 2 - 1, -(pos_rel[1] / vs[1] * 2 - 1), 0])
# get world position
pos_ndc += vec_transform(self.camera.world.position, self.camera.camera_matrix)
pos_world = vec_unproject(pos_ndc[:2], self.camera.camera_matrix)
# default z is zero for now
return np.array([*pos_world[:2], 0])
def map_world_to_screen(
self, pos: tuple[float, float, float] | np.ndarray
) -> tuple[float, float]:
"""
Map world position to screen (canvas) position
Parameters
----------
pos: (x, y, z)
world space position
Returns
-------
(float, float)
(x, y) position in screen (canvas) space
"""
if not len(pos) == 3:
raise ValueError(f"must pass 3d (x, y, z) position, you passed: {pos}")
# apply camera transform and get NDC position
ndc = vec_transform(np.asarray(pos), self.camera.camera_matrix)
# get viewport rect
x_offset, y_offset, w, h = self.viewport.rect
# ndc to screen position
x_screen = x_offset + (ndc[0] + 1) * 0.5 * w
y_screen = y_offset + (1 - ndc[1]) * 0.5 * h
return x_screen, y_screen
def get_pick_info(self, pos):
"""
Get pick info at this screen position
Parameters
----------
pos: (x, y)
screen space position
Returns
-------
dict | None
pick info if a graphic is at this position, else None
"""
info = self.renderer.get_pick_info(pos)
if info["world_object"] is not None:
# if this world object is owned by a graphic
if info["world_object"].id in WORLD_OBJECT_TO_GRAPHIC.keys():
info["graphic"] = WORLD_OBJECT_TO_GRAPHIC[info["world_object"].id]
return info
def _fpl_set_tooltip(self, ev: pygfx.PointerEvent):
# set tooltip using pointer position
if not self._tooltip.enabled:
return
# is pointer in this plot area
if not self.viewport.is_inside(ev.x, ev.y):
return
# is there a world object under the pointer
if ev.target is not None:
# is it owned by a graphic
if ev.target.id in WORLD_OBJECT_TO_GRAPHIC.keys():
graphic = WORLD_OBJECT_TO_GRAPHIC[ev.target.id]
if not graphic._fpl_support_tooltip:
return
pick_info = ev.pick_info
if graphic.tooltip_format is not None:
# custom formatter
info = graphic.tooltip_format(pick_info)
else:
# default formatter for this graphic
info = graphic.format_pick_info(pick_info)
self._tooltip.display((ev.x, ev.y), info)
return
# not over a graphic that supports tooltips
self._tooltip.clear()
def _fpl_update_tooltip_render(self):
# update tooltip on every render
# TODO: improve performance
if (not self._tooltip.visible) or (not self._tooltip.enabled):
return
pick_info = self.get_pick_info(self._tooltip.position)
# None if no graphic is at this position
if pick_info is not None:
graphic = pick_info["graphic"]
if graphic._fpl_support_tooltip:
if graphic.tooltip_format is not None:
# custom formatter
info = graphic.tooltip_format(pick_info)
else:
# default formatter for this graphic
info = graphic.format_pick_info(pick_info)
self._tooltip.display(self._tooltip.position, info)
return
# tooltip cleared if none of the above condiitionals reached the tooltip display call
self._tooltip.clear()
def _render(self):
self._call_animate_functions(self._animate_funcs_pre)
# does not flush, flush must be implemented in user-facing Plot objects
self.viewport.render(self.scene, self.camera)
for child in self.children:
child._render()
self._call_animate_functions(self._animate_funcs_post)
if self._tooltip.continuous_update:
self._fpl_update_tooltip_render()
def _call_animate_functions(self, funcs: list[callable]):
for fn in funcs:
try:
args = getfullargspec(fn).args
if len(args) > 0:
if args[0] == "self" and not len(args) > 1:
fn()
else:
fn(self)
else:
fn()
except (ValueError, TypeError):
warn(
f"Could not resolve argspec of {self.__class__.__name__} animation function: {fn}, "
f"calling it without arguments."
)
fn()
def add_animations(
self,
*funcs: callable,
pre_render: bool = True,
post_render: bool = False,
):
"""
Add function(s) that are called on every render cycle.
These are called at the Subplot level.
Parameters
----------
*funcs: callable(s)
function(s) that are called on each render cycle
pre_render: bool, default ``True``, optional keyword-only argument
if true, these function(s) are called before a render cycle
post_render: bool, default ``False``, optional keyword-only argument
if true, these function(s) are called after a render cycle
"""
for f in funcs:
if not callable(f):
raise TypeError(
f"all positional arguments to add_animations() must be callable types, you have passed a: {type(f)}"
)
if pre_render:
self._animate_funcs_pre += funcs
if post_render:
self._animate_funcs_post += funcs
def remove_animation(self, func):
"""
Removes the passed animation function from both pre and post render.
Parameters
----------
func: callable
The function to remove, raises a error if it's not registered as a pre or post animation function.
"""
if func not in self._animate_funcs_pre and func not in self._animate_funcs_post:
raise KeyError(
f"The passed function: {func} is not registered as an animation function. These are the animation "
f" functions that are currently registered:\n"
f"pre: {self._animate_funcs_pre}\n\npost: {self._animate_funcs_post}"
)
if func in self._animate_funcs_pre:
self._animate_funcs_pre.remove(func)
if func in self._animate_funcs_post:
self._animate_funcs_post.remove(func)
def clear_animations(self, removal: str = None):
"""
Remove animation functions.
Parameters
----------
removal: str, default ``None``
The type of animation functions to clear. One of 'pre' or 'post'. If `None`, removes all animation
functions.
"""
if removal is None:
# remove all
for func in self._animate_funcs_pre:
self._animate_funcs_pre.remove(func)
for func in self._animate_funcs_post:
self._animate_funcs_post.remove(func)
elif removal == "pre":
# only pre
for func in self._anima
6851
te_funcs_pre:
self._animate_funcs_pre.remove(func)
elif removal == "post":
# only post
for func in self._animate_funcs_post:
self._animate_funcs_post.remove(func)
else:
raise ValueError(
f"Animation type: {removal} must be one of 'pre' or 'post'. To remove all animation "
f"functions, pass `type=None`"
)
def _sort_images_by_depth(self):
"""
In general, we want to avoid setting the offset of a graphic, because the
z-dimension may actually mean something; we cannot know whether the user is
building a 3D scene or not. We could check whether the 3d dimension of line/point data
is all zeros, but maybe this is intended, and *other* graphics in the same scene
may be actually 3D. We could check camera.fov being zero, but maybe the user
switches to a 3D camera later, or uses a 3D orthographic camera.
The one exception, kindof, is images, which are inherently 2D, and for which
layering helps a lot to get things rendered correctly. So we basically layer the
images, in the order that they were added, pushing older images backwards (away
from the camera).
"""
count = 0
for graphic in reversed(self._graphics):
if isinstance(graphic, ImageGraphic):
count += 1
auto_depth = -count
user_changed_depth = graphic.offset[2] % 1 > 0.0 # i.e. is not integer
if not user_changed_depth:
graphic.offset = (*graphic.offset[:-1], auto_depth)
def add_graphic(self, graphic: Graphic, center: bool = True):
"""
Add a Graphic to the scene
Parameters
----------
graphic: Graphic or `:ref:GraphicCollection`
Add a Graphic or a GraphicCollection to the plot area.
Note: this must be a real Graphic instance and not a proxy
center: bool, default True
Center the camera on the newly added Graphic
"""
if graphic in self:
# graphic is already in this plot but was removed from the scene, add it back
self._fpl_graphics_scene.add(graphic.world_object)
return
self._add_or_insert_graphic(graphic=graphic, center=center, action="add")
if isinstance(graphic, ImageGraphic):
self._sort_images_by_depth()
def insert_graphic(
self,
graphic: Graphic,
center: bool = True,
index: int = 0,
auto_offset: int = None,
):
"""
Insert graphic into scene at given position ``index`` in stored graphics.
Parameters
----------
graphic: Graphic
Add a Graphic to the plot area at a given position.
Note: must be a real Graphic instance, not a weakref proxy to a Graphic
center: bool, default True
Center the camera on the newly added Graphic
index: int, default 0
Index to insert graphic.
auto_offset: bool, default True
If True and using an orthographic projection, sets z-axis offset of graphic to `index`
"""
if index > len(self._graphics):
raise IndexError(
f"Position {index} is out of bounds for number of graphics currently "
f"in the PlotArea: {len(self._graphics)}\n"
f"Call `add_graphic` method to insert graphic in the last position of the stored graphics"
)
self._add_or_insert_graphic(
graphic=graphic, center=center, action="insert", index=index
)
if isinstance(graphic, ImageGraphic):
self._sort_images_by_depth()
def _add_or_insert_graphic(
self,
graphic: Graphic,
center: bool = True,
action: Literal["insert", "add"] = "add",
index: int = 0,
):
"""Private method to handle inserting or adding a graphic to a PlotArea."""
if not isinstance(graphic, Graphic):
raise TypeError(
f"Can only add Graphic types to a PlotArea, you have passed a: {type(graphic)}"
)
if graphic.name is not None: # skip for those that have no name
self._check_graphic_name_exists(graphic.name)
if isinstance(graphic, BaseSelector):
obj_list = self._selectors
self.scene.add(graphic.world_object)
elif isinstance(graphic, Legend):
obj_list = self._legends
self.scene.add(graphic.world_object)
elif isinstance(graphic, Graphic):
obj_list = self._graphics
self._fpl_graphics_scene.add(graphic.world_object)
else:
raise TypeError("graphic must be of type Graphic | BaseSelector | Legend")
if action == "insert":
obj_list.insert(index, graphic)
elif action == "add":
obj_list.append(graphic)
else:
raise ValueError("valid actions are 'insert' | 'add'")
if center:
self.center_graphic(graphic)
graphic._fpl_add_plot_area_hook(self)
def _check_graphic_name_exists(self, name):
if name in self:
raise ValueError(
f"Graphic with given name already exists in subplot or plot area. "
f"All graphics within a subplot or plot area must have a unique name."
)
def center_graphic(self, graphic: Graphic, zoom: float = 1.0):
"""
Center the camera w.r.t. the passed graphic
Parameters
----------
graphic: Graphic
The graphic instance to center on
zoom: float
zoom the camera after centering
"""
self.camera.show_object(graphic.world_object)
# camera.show_object can cause the camera width and height to increase so apply a zoom to compensate
# probably because camera.show_object uses bounding sphere
self.camera.zoom = zoom
def center_scene(self, *, zoom: float = 1.0):
"""
Auto-center the scene, does not scale.
Parameters
----------
zoom: float
apply a zoom after centering the scene
"""
if not len(self._fpl_graphics_scene.children) > 0:
return
if self.parent.__class__.__name__.endswith("Figure"):
# always use figure._subplots.ravel() in internal fastplotlib code
# otherwise if we use `for subplot in figure`, this could conflict
# with a user's iterator where they are doing `for subplot in figure` !!!
for subplot in self.parent._subplots.ravel():
# scale all cameras associated with this controller
if subplot.camera in self.controller.cameras:
# skip if the scene is empty
if len(subplot._fpl_graphics_scene.children) < 1:
continue
# center the camera in the other subplot w.r.t. the scene in that other subplot!
self._auto_center_scene(
subplot.camera, subplot._fpl_graphics_scene, zoom
)
else:
# just change for this plot area
# this is probably a dock area
self._auto_center_scene(self.camera, self._fpl_graphics_scene, zoom)
def _auto_center_scene(
self, camera: pygfx.PerspectiveCamera, scene: pygfx.Scene, zoom: float
):
camera.show_object(scene)
# camera.show_object can cause the camera width and height to increase so apply a zoom to compensate
# probably because camera.show_object uses bounding sphere
camera.zoom = zoom
def auto_scale(
self,
*, # since this is often used as an event handler, don't want to coerce maintain_aspect = True
maintain_aspect: None | bool = None,
zoom: float = 0.75,
):
"""
Auto-scale the camera w.r.t to the scene
Parameters
----------
maintain_aspect: ``None`` or bool, default ``None``
Maintain the camera aspect ratio for all dimensions. If ``None``, the aspect is left unchanged.
if ``False`` the camera is scaled to the bounding box of the current scene.
zoom: float
zoom value for the camera after auto-scaling
"""
if not len(self._fpl_graphics_scene.children) > 0:
return
self.center_scene()
if maintain_aspect is None: # if not provided keep current setting
# use the same maintain apsect for all other cameras that this controller manages
# I think this make sense for most use cases, even when the other controllers are
# only managing one or 2 axes
maintain_aspect = self.camera.maintain_aspect
if self.parent.__class__.__name__.endswith("Figure"):
# always use figure._subplots.ravel() in internal fastplotlib code
# otherwise if we use `for subplot in figure`, this could conflict
# with a user's iterator where they are doing `for subplot in figure` !!!
for subplot in self.parent._subplots.ravel():
# skip if the scene is empty
if len(subplot._fpl_graphics_scene.children) < 1:
continue
# scale the camera in the other subplot w.r.t. the scene in that other subplot!
if subplot.camera in self.controller.cameras:
camera = subplot.camera
self._auto_scale_scene(
camera, subplot._fpl_graphics_scene, zoom, maintain_aspect
)
else:
# just change for this plot area, this is probably a dock area
self._auto_scale_scene(
self.camera, self._fpl_graphics_scene, zoom, maintain_aspect
)
def _auto_scale_scene(
self,
camera: pygfx.PerspectiveCamera,
scene: pygfx.Scene,
zoom: float,
maintain_aspect: bool,
):
camera.maintain_aspect = maintain_aspect
if len(scene.children) > 0:
width, height, depth = np.ptp(scene.get_world_bounding_box(), axis=0)
else:
width, height, depth = (1, 1, 1)
# make sure width and height are non-zero
if width < 0.01:
width = 1
if height < 0.01:
height = 1
camera.width = width
camera.height = height
camera.zoom = zoom
def remove_graphic(self, graphic: Graphic):
"""
Remove a ``Graphic`` from the scene. Note: This does not garbage collect the graphic,
you can add it back to the scene after removing it. Use ``delete_graphic()`` to
delete and garbage collect a ``Graphic``.
Parameters
----------
graphic: Graphic
The graphic to remove from the scene
"""
if isinstance(graphic, (BaseSelector, Legend)):
self.scene.remove(graphic.world_object)
elif isinstance(graphic, Graphic):
self._fpl_graphics_scene.remove(graphic.world_object)
def delete_graphic(self, graphic: Graphic):
"""
Delete the graphic, garbage collects and frees GPU VRAM.
Parameters
----------
graphic: Graphic
The graphic to delete
"""
if graphic not in self:
raise KeyError(f"Graphic not found in plot area: {graphic}")
if isinstance(graphic, BaseSelector):
self._selectors.remove(graphic)
elif isinstance(graphic, Legend):
self._legends.remove(graphic)
elif isinstance(graphic, Graphic):
self._graphics.remove(graphic)
# remove from scene if necessary
if graphic.world_object in self.scene.children:
self.scene.remove(graphic.world_object)
elif graphic.world_object in self._fpl_graphics_scene.children:
self._fpl_graphics_scene.remove(graphic.world_object)
# cleanup
graphic._fpl_prepare_del()
if IS_IPYTHON:
# remove any references that ipython might have made
# check both namespaces
for namespace in [IPYTHON.user_ns, IPYTHON.user_ns_hidden]:
# find the reference
for ref, obj in namespace.items():
if graphic is obj:
# we found the reference, remove from ipython
IPYTHON.del_var(ref)
break
def clear(self):
"""
Clear the Plot or Subplot. Also performs garbage collection, i.e. runs ``delete_graphic`` on all graphics.
"""
for g in self.objects:
self.delete_graphic(g)
def __getitem__(self, name: str):
for graphic in self.objects:
if graphic.name == name:
return graphic
raise IndexError(f"No graphic or selector of given name in plot area.\n")
def __contains__(self, item: str | Graphic):
if isinstance(item, Graphic):
if item in self.objects:
return True
else:
return False
elif isinstance(item, str):
for graphic in self.objects:
# only check named graphics
if graphic.name is None:
continue
if graphic.name == item:
return True
return False
raise TypeError("PlotArea `in` operator accepts only `Graphic` or `str` types")
def __str__(self):
if self.name is None:
name = "unnamed"
else:
name = self.name
return f"{name}: {self.__class__.__name__}"
def __repr__(self):
newline = "\n\t"
return (
f"{self}\n"
f" parent: {self.parent.__str__()}\n"
f" Graphics:\n"
f"\t{newline.join(graphic.__repr__() for graphic in self.graphics)}"
f"\n"
)
def __len__(self) -> int:
return len(self._graphics) + len(self.selectors)