-
-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathlightfield_viewport.py
2426 lines (1750 loc) · 90 KB
/
lightfield_viewport.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
# ##### BEGIN GPL LICENSE BLOCK #####
#
# Copyright © 2021 Christian Stolze
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# ##### END GPL LICENSE BLOCK #####
# MODULE DESCRIPTION:
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# This includes everything that is related the "live view"
# ------------------ INTERNAL MODULES --------------------
from .globals import *
# ------------------- EXTERNAL MODULES -------------------
import sys, platform
import bpy, bgl
import gpu
import time, timeit
from math import *
from mathutils import *
from gpu_extras.batch import batch_for_shader
from gpu_extras.presets import draw_texture_2d, draw_circle_2d
from bpy_extras.view3d_utils import location_3d_to_region_2d, region_2d_to_origin_3d, region_2d_to_vector_3d
import numpy as np
# append the add-on's path to Blender's python PATH
sys.path.insert(0, LookingGlassAddon.path)
sys.path.insert(0, LookingGlassAddon.libpath)
# TODO: Would be better, if from .lib import pylightio could be called,
# but for some reason that does not import all modules and throws
# "AliceLG.lib.pylio has no attribute 'lookingglass"
import pylightio as pylio
# ---------------- GLOBAL ADDON LOGGER -------------------
import logging
LookingGlassAddonLogger = logging.getLogger('Alice/LG')
# ------------ CONTEXT OVERRIDE -------------
# Class for managing a SpaceView3D context override for offscreen rendering
class ContextOverride:
# ADDON SETTING DATA
__addon_settings_window_manager = None
__addon_settings_scene = None
# CONTEXT DATA
__context = None
__override = None
# CONTEXT DATA BACKUP
__shading_restore_backup = {}
__overlay_restore_backup = {}
# Inititalize the context override
def __init__(self, context):
# get the current settings of this scene
self.__context = context
# get the current settings of the window manager
self.__addon_settings_window_manager = context.window_manager.addon_settings
# get the current settings of this scene
self.__addon_settings_scene = context.scene.addon_settings
# create an override context from the invoking context
self.__override = context.copy()
# set a new context
def set_context(self, context):
# get the current settings of this scene
self.__context = context
# set up the camera for each view and the shader of the rendering object
def setupVirtualCameraForView(self, view, total_views, view_cone, aspect, viewMatrix, projectionMatrix):
# get focal plane distance depending on synchronization mode
if self.__addon_settings_scene.toggleFocalSync and self.__addon_settings_scene.lookingglassCamera:
focalPlane = self.__addon_settings_scene.lookingglassCamera.data.dof.focus_distance
else:
focalPlane = self.__addon_settings_scene.focalPlane
# The field of view set by the camera
# NOTE 1: - the Looking Glass Factory documentation suggests to use a FOV of 14°. We use the focal length of the Blender camera instead.
# NOTE 2: - we take the angle directly from the projection matrix
fov = 2.0 * atan(1 / projectionMatrix[1][1])
# calculate cameraSize from its distance to the focal plane and the FOV
# NOTE: - we take an arbitrary distance of 5 m (we could also use the focal distance of the camera, but might be confusing)
cameraDistance = focalPlane
cameraSize = cameraDistance * tan(fov / 2)
# start at viewCone * 0.5 and go up to -viewCone * 0.5
offsetAngle = (0.5 - view / (total_views - 1)) * radians(view_cone)
# calculate the offset that the camera should move
offset = cameraDistance * tan(offsetAngle)
# translate the view matrix (position) by the calculated offset in x-direction
viewMatrix = Matrix.Translation((offset, 0, 0)) @ viewMatrix
# modify the projection matrix, relative to the camera size and aspect ratio
projectionMatrix[0][2] += offset / (cameraSize * aspect)
# return the projection matrix
return viewMatrix, projectionMatrix
# Save the viewport settings
def saveViewportSettings(self):
# SHADING ATTRIBUTES
# define some exceptions that must not be taken into
attributeExceptions = ["__doc__", "__module__", "__slots__", "bl_rna", "rna_type", "color_type", "studio_light"]
# use the "space data" of the selected viewport
attributeList = dir(self.__override['space_data'].shading)
for attr in attributeList:
if not attr in attributeExceptions and hasattr(self.__override['space_data'].shading, attr):
#print("[SHADING]", attr, " = ", getattr(LookingGlassAddon.BlenderViewport.shading, attr))
try:
self.__shading_restore_backup[attr] = getattr(self.__override['space_data'].shading, attr)
except Exception as e:
#print(" # ", e)
pass
attributeList = dir(self.__override['space_data'].overlay)
for attr in attributeList:
if not attr in attributeExceptions and hasattr(self.__override['space_data'].overlay, attr):
#print("[OVERLAY]", attr, " = ", getattr(self.__override['space_data'].overlay, attr))
try:
self.__overlay_restore_backup[attr] = getattr(self.__override['space_data'].overlay, attr)
except Exception as e:
#print(" # ", e)
pass
# Update the viewport settings
def updateViewportSettings(self, space_data=None, force_context_data=False):
# get the space data into the override
if space_data:
self.__override['space_data'] = space_data
# save all shading & overlay settings
self.saveViewportSettings()
# APPLY CUSTOM SETTINGS IF REQUIRED
####################################################################
# if the custom settings shall be used OR the given space data is invalid
if (self.__addon_settings_scene.viewportMode == 'CUSTOM' and force_context_data == False) or space_data == None:
# SHADING ATTRIBUTES
self.__override['space_data'].shading.type = self.__addon_settings_scene.shadingMode
self.__override['space_data'].shading.show_xray = bool(self.__addon_settings_scene.viewport_show_xray)
self.__override['space_data'].shading.xray_alpha = float(self.__addon_settings_scene.viewport_xray_alpha)
self.__override['space_data'].shading.use_dof = bool(int(self.__addon_settings_scene.viewport_use_dof))
# OVERLAY ATTRIBUTES: Guides
self.__override['space_data'].overlay.show_floor = bool(int(self.__addon_settings_scene.viewport_show_floor))
self.__override['space_data'].overlay.show_axis_x = bool(int(self.__addon_settings_scene.viewport_show_axes[0]))
self.__override['space_data'].overlay.show_axis_y = bool(int(self.__addon_settings_scene.viewport_show_axes[1]))
self.__override['space_data'].overlay.show_axis_z = bool(int(self.__addon_settings_scene.viewport_show_axes[2]))
self.__override['space_data'].overlay.grid_scale = float(self.__addon_settings_scene.viewport_grid_scale)
# OVERLAY ATTRIBUTES: Objects
self.__override['space_data'].overlay.show_extras = bool(int(self.__addon_settings_scene.viewport_show_extras))
self.__override['space_data'].overlay.show_relationship_lines = bool(int(self.__addon_settings_scene.viewport_show_relationship_lines))
self.__override['space_data'].overlay.show_outline_selected = bool(int(self.__addon_settings_scene.viewport_show_outline_selected))
self.__override['space_data'].overlay.show_bones = bool(int(self.__addon_settings_scene.viewport_show_bones))
self.__override['space_data'].overlay.show_motion_paths = bool(int(self.__addon_settings_scene.viewport_show_motion_paths))
self.__override['space_data'].overlay.show_object_origins = bool(int(self.__addon_settings_scene.viewport_show_origins))
self.__override['space_data'].overlay.show_object_origins_all = bool(int(self.__addon_settings_scene.viewport_show_origins_all))
# OVERLAY ATTRIBUTES: Geometry
self.__override['space_data'].overlay.show_wireframes = bool(int(self.__addon_settings_scene.viewport_show_wireframes))
self.__override['space_data'].overlay.show_face_orientation = bool(int(self.__addon_settings_scene.viewport_show_face_orientation))
# if the settings rely on a specific viewport / SpaceView3D
elif (self.__addon_settings_scene.viewportMode != 'CUSTOM' or force_context_data == True) and space_data != None:
# if CYCLES is activated in the current viewport
if space_data.shading.type == 'RENDERED' and self.__context.engine == 'CYCLES':
# change the shading type to SOLID
self.__override['space_data'].shading.type = 'SOLID'
# notify user
self.report({"WARNING"}, "Render engine (%s) not supported in lightfield previews. Switched to SOLID mode." % self.__context.engine)
# always disable the hdri preview spheres
self.__override['space_data'].overlay.show_look_dev = False
# Restore the viewport settings
def restoreViewportSettings(self):
# SHADING ATTRIBUTES
# define some exceptions that must not be taken into
attributeExceptions = ["__doc__", "__module__", "__slots__", "bl_rna", "rna_type", "color_type", "studio_light", "type"]
# use the "space data" of the selected viewport
attributeList = dir(self.__override['space_data'].shading)
for attr in attributeList:
if not attr in attributeExceptions and hasattr(self.__override['space_data'].shading, attr):
if getattr(self.__override['space_data'].shading, attr) != self.__shading_restore_backup[attr]:
#print("[SHADING]", attr, " = ", self.__shading_restore_backup[attr])
try:
setattr(self.__override['space_data'].shading, attr, self.__shading_restore_backup[attr])
except Exception as e:
#print(" # ", e)
pass
attributeList = dir(self.__override['space_data'].overlay)
for attr in attributeList:
if not attr in attributeExceptions and hasattr(self.__override['space_data'].overlay, attr):
if getattr(self.__override['space_data'].overlay, attr) != self.__overlay_restore_backup[attr]:
# print("[OVERLAY]", attr, " = ", self.__overlay_restore_backup[attr])
try:
setattr(self.__override['space_data'].overlay, attr, self.__overlay_restore_backup[attr])
except Exception as e:
#print(" # ", e)
pass
# CLASS PROPERTIES
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# (A) context override properties
@property
def space_data(self):
return self.__override['space_data']
@space_data.setter
def space_data(self, value):
pass
@property
def region(self):
return self.__override['region']
@region.setter
def region(self, value):
pass
@property
def shading_to_dict(self):
return self.__shading_restore_backup
@shading_to_dict.setter
def shading_to_dict(self, value):
pass
@property
def overlay_to_dict(self):
return self.__overlay_restore_backup
@overlay_to_dict.setter
def overlay_to_dict(self, value):
pass
# ------------ LIGHTFIELD RENDERING -------------
# Modal operator for controlled redrawing of the lightfield window.
class LOOKINGGLASS_OT_render_viewport(bpy.types.Operator):
bl_idname = "render.viewport"
bl_label = "Looking Glass Lightfield Viewport rendering"
bl_options = {'REGISTER', 'INTERNAL'}
# PUBLIC CLASS MEMBERS
# ++++++++++++++++++++++++++++++++++++++++++++++++++
# ADDON SETTINGS
settings = None
# SETTINGS VARIABLES
preset = 1
last_preset = 1
# lightfield
lightfield_image = None
# DRAWING OPERATION VARIABLES
modal_redraw = True
depsgraph_update_time = 0
skip_views = 1
restricted_viewcone_limit = 0
# DEBUGING VARIABLES
start_multi_view = 0
# PROTECTED CLASS MEMBERS
# ++++++++++++++++++++++++++++++++++++++++++++++++++
# HANDLER IDENTIFIERS
_handle_trackDepsgraphUpdates = None
_handle_trackFrameChanges = None
_handle_trackActiveWindow = None
# CONTEXT OVERRIDE
_override = None
# SETTINGS BACKUP
_shading_restore_backup = {}
_overlay_restore_backup = {}
# METHODS
# ++++++++++++++++++++++++++++++++++++++++++++++++++
# poll method
@classmethod
def poll(self, context):
# check if the context is invalid
if not context:
LookingGlassAddonLogger.error("Could not open Lightfield Window. Operator was called from invalid context.")
return False
# return True, so the operator is executed
return True
# cancel the modal operator
def cancel(self, context):
# log info
LookingGlassAddonLogger.info("Closing lightfield viewport ...")
# stop timer
context.window_manager.event_timer_remove(self.timerEvent)
# remove the app handler that checks for depsgraph updates
bpy.app.handlers.depsgraph_update_post.remove(self.trackDepsgraphUpdates)
bpy.app.handlers.frame_change_post.remove(self.trackDepsgraphUpdates)
# remove the handler for the viewport tracking
if self._handle_trackActiveWindow: bpy.types.SpaceView3D.draw_handler_remove(self._handle_trackActiveWindow, 'WINDOW')
# log info
LookingGlassAddonLogger.info(" [#] Cancelled control handlers.")
# iterate through all presets
for i, preset in self.qs.items():
# loop through all required views
#for view in range(int((self.qs[self.preset]["total_views"] + 1) / 3), self.qs[self.preset]["total_views"] - int((self.qs[self.preset]["total_views"] + 1) / 3)):
for view in range(0, len(self.qs[i]["viewOffscreen"])):
# free the GPUOffscreen for the view rendering
self.qs[i]["viewOffscreen"][view].free()
# delete the list of offscreen objects
self.qs[i]["viewOffscreen"].clear()
# log info
LookingGlassAddonLogger.info(" [#] Freed GPUOffscreens of the lightfield views.")
# set status variables to default state
#LookingGlassAddon.BlenderWindow = None
LookingGlassAddon.BlenderViewport = None
# set the button controls for the lightfield window to False
if context: context.window_manager.addon_settings.ShowLightfieldWindow = False
# clear the quilt
self.device.clear()
# free the view data of the lightfield image
if self.lightfield_image: self.lightfield_image.clear_views()
# delete the current LightfieldImage
if self.lightfield_image: self.lightfield_image = None
# log info
LookingGlassAddonLogger.info(" [#] Done.")
# invoke the operator
def invoke(self, context, event):
start = time.time()
# log info
LookingGlassAddonLogger.info("Invoking lightfield viewport ...")
# get the current settings of this scene
self.addon_settings_window_manager = context.window_manager.addon_settings
self.addon_settings_scene = context.scene.addon_settings
# update the variable for the current Looking Glass device
if int(self.addon_settings_window_manager.activeDisplay) != -1: self.device = pylio.DeviceManager.get_active()
# PREPARE THE OFFSCREEN RENDERING
################################################################
# set to the currently chosen quality
self.preset = self.last_preset = int(context.scene.addon_settings.quiltPreset)
# get all quilt presets from pylio
self.qs = pylio.LookingGlassQuilt.formats.get()
# iterate through all presets
for i, preset in self.qs.items():
# create a list of offscreen objects for this preset
self.qs[i]["viewOffscreen"] = []
# loop through all required views
#for view in range(int((self.qs[self.preset]["total_views"] + 1) / 3), self.qs[self.preset]["total_views"] - int((self.qs[self.preset]["total_views"] + 1) / 3)):
for view in range(0, self.qs[i]["total_views"]):
# create a GPUOffscreen for the views
self.qs[i]["viewOffscreen"].append(gpu.types.GPUOffScreen(int(self.qs[i]["view_width"]), int(self.qs[i]["view_height"])))
# log info
LookingGlassAddonLogger.info(" [#] Prepared GPUOffscreens for view rendering.")
# PREPARE THE OVERRIDE CONTEXT THAT CONTAINS THE RENDER SETTINGS
################################################################
# create an override context from the invoking context
self._override = ContextOverride(context)
# update the viewport settings
self.updateViewportSettings(context)
# log info
LookingGlassAddonLogger.info(" [#] Created override context.")
# REGISTER ALL HANDLERS FOR THE LIGHTFIELD RENDERING
################################################################
# HANDLERS FOR CONTROL PURPOSES
# ++++++++++++++++++++++++++++++
# we exploit the draw_hanlder of the SpaceView3D to track the SpaceView which is currently modified by the user
self._handle_trackActiveWindow = bpy.types.SpaceView3D.draw_handler_add(self.trackActiveWindow, (context,), 'WINDOW', 'PRE_VIEW')
# Register app handlers that check if the LookingGlass shall be updated:
# (1) Every time something in the scene changed (for camera movement and scene editing)
# (2) Every time, the current frame changed (for animations)
self._handle_trackDepsgraphUpdates = bpy.app.handlers.depsgraph_update_post.append(self.trackDepsgraphUpdates)
self._handle_trackFrameChanges = bpy.app.handlers.frame_change_post.append(self.trackDepsgraphUpdates)
# log info
LookingGlassAddonLogger.info(" [#] Initialized control handlers.")
# HANDLERS FOR OPERATOR CONTROL
# ++++++++++++++++++++++++++++++
# Create timer event that runs every millisecond to check if the lightfield needs to be updated
self.timerEvent = context.window_manager.event_timer_add(0.01, window=context.window)
# add the modal handler
context.window_manager.modal_handler_add(self)
# log info
LookingGlassAddonLogger.info(" [#] Initialized modal operator.")
LookingGlassAddonLogger.info(" [#] Done.")
# keep the modal operator running
return {'RUNNING_MODAL'}
# modal operator for controlled redrawing of the lightfield
def modal(self, context, event):
# update the internal variable for the settings
self.addon_settings_window_manager = context.window_manager.addon_settings
self.addon_settings_scene = context.scene.addon_settings
# if the active scene was changed
if context.scene.addon_settings != self.addon_settings_scene:
# update the lightfield window
# Lightfield Viewport
if int(self.addon_settings_window_manager.renderMode) == 0:
context.window_manager.addon_settings.viewport_manual_refresh = True
# Quilt Viewer
elif int(self.addon_settings_window_manager.renderMode) == 1:
LookingGlassAddon.update_lightfield_window(int(self.addon_settings_window_manager.renderMode), LookingGlassAddon.quiltViewerLightfieldImage)
# cancel the operator, if the lightfield viewport was deactivated
if not self.addon_settings_window_manager.ShowLightfieldWindow:
self.cancel(context)
return {'FINISHED'}
# update the variable for the current Looking Glass device
if int(self.addon_settings_window_manager.activeDisplay) != -1: self.device = pylio.DeviceManager.get_active()
# Control lightfield redrawing in viewport mode
################################################################
# if the TIMER event for the lightfield rendering is called AND the automatic render mode is active
if event.type == 'TIMER' or event.type == 'Z':
# if something has changed OR the user requested a manual redrawing
if self.modal_redraw or (not self.modal_redraw and ((self.depsgraph_update_time > 0 and time.time() - self.depsgraph_update_time > LookingGlassAddon.low_resolution_preview_timout) or context.window_manager.addon_settings.viewport_manual_refresh == True)):
# update the viewport settings
self.updateViewportSettings(context)
if (not self.modal_redraw and ((self.depsgraph_update_time > 0 and time.time() - self.depsgraph_update_time > LookingGlassAddon.low_resolution_preview_timout) or context.window_manager.addon_settings.viewport_manual_refresh == True)):
# reset time of last depsgraph update
self.depsgraph_update_time = 0
# reset status variable for manual refreshes
context.window_manager.addon_settings.viewport_manual_refresh = False
# set to the currently chosen quality
self.preset = int(context.scene.addon_settings.quiltPreset)
# dont skip any views
self.skip_views = 1
self.restricted_viewcone_limit = 0
# set to redraw
self.modal_redraw = True
# render the views
self.render_view(context)
# Lightfield Viewport
if int(self.addon_settings_window_manager.renderMode) == 0 and self.lightfield_image:
# update the lightfield displayed on the device
LookingGlassAddon.update_lightfield_window(int(self.addon_settings_window_manager.renderMode), self.lightfield_image)
# Quilt Viewer
elif int(self.addon_settings_window_manager.renderMode) == 1 and LookingGlassAddon.quiltViewerLightfieldImage:
# update the lightfield displayed on the device
LookingGlassAddon.update_lightfield_window(int(self.addon_settings_window_manager.renderMode), LookingGlassAddon.quiltViewerLightfieldImage)
else:
# update the lightfield displayed on the device: show the demo quilt
LookingGlassAddon.update_lightfield_window(-1, None)
# running modal
return {'RUNNING_MODAL'}
# pass event through
return {'PASS_THROUGH'}
# Application handler that continously checks for changes of the depsgraph
def trackDepsgraphUpdates(self, scene, depsgraph):
# if no quilt rendering is currently Running
if not LookingGlassAddon.RenderInvoked:
# if automatic live view is activated AND something in the scene has changed
if (int(self.addon_settings_window_manager.renderMode) == 0 and int(self.addon_settings_window_manager.lightfieldMode) == 0) and len(depsgraph.updates.values()) > 0:
# print("DEPSGRAPH UPDATE: ", depsgraph.updates.values())
# remember time of last depsgraph update
self.depsgraph_update_time = time.time()
# allow an update of the Looking Glass viewport
self.modal_redraw = True
# if the "no preview" is activated
if self.addon_settings_window_manager.viewport_use_preview_mode and self.addon_settings_window_manager.lightfield_preview_mode == '0':
# don't allow an update of the Looking Glass viewport
self.modal_redraw = False
# we don't redraw, because changes are only updated after the user interaction finished
pass
# if the "low resolution preview" is activated
elif self.addon_settings_window_manager.viewport_use_preview_mode and self.addon_settings_window_manager.lightfield_preview_mode == '1':
# activate them
self.preset = int(list(pylio.LookingGlassQuilt.formats.get().keys())[-1])
# if the "skip views preview I" is activated
elif self.addon_settings_window_manager.viewport_use_preview_mode and self.addon_settings_window_manager.lightfield_preview_mode == '2':
# skip every second view during rendering
self.skip_views = 2
# if the "skip views preview II" is activated
elif self.addon_settings_window_manager.viewport_use_preview_mode and self.addon_settings_window_manager.lightfield_preview_mode == '3':
# skip every third view during rendering
self.skip_views = 3
# if the "restricted viewcone preview" is activated
elif self.addon_settings_window_manager.viewport_use_preview_mode and self.addon_settings_window_manager.lightfield_preview_mode == '4':
# only show the center 33% of all views
self.restricted_viewcone_limit = int(self.qs[self.preset]["total_views"] / 3)
else:
# set to the currently chosen quality
self.preset = int(scene.addon_settings.quiltPreset)
self.skip_views = 1
# if quilt viewer is active AND an image is selected
elif int(self.addon_settings_window_manager.renderMode) == 1 and self.addon_settings_window_manager.quiltImage != None:
# set status variable
changed = False
# set to the currently chosen quality
self.preset = int(scene.addon_settings.quiltPreset)
# TODO: Hacky, but this identifies color management changes
# go through the updates
for DepsgraphUpdate in depsgraph.updates.values():
#print(" # ", DepsgraphUpdate.is_updated_geometry, DepsgraphUpdate.is_updated_shading, DepsgraphUpdate.is_updated_transform, DepsgraphUpdate.id.name)
if DepsgraphUpdate.is_updated_geometry == True and DepsgraphUpdate.is_updated_shading == True and DepsgraphUpdate.is_updated_transform == True:
# update status variable
changed = False
break
# are there any changes in the image or color management settings?
if LookingGlassAddon.quiltViewAsRender != self.addon_settings_window_manager.quiltImage.use_view_as_render or LookingGlassAddon.quiltImageColorSpaceSetting.name != self.addon_settings_window_manager.quiltImage.colorspace_settings.name:
# update status variable
changed = True
# update the quilt image, if something had changed
if changed == True: self.addon_settings_window_manager.quiltImage = self.addon_settings_window_manager.quiltImage
# this function is called as a draw handler to enable the Looking Glass Addon
# to keep track of the SpaceView3D which is currently manipulated by the User
def trackActiveWindow(self, context):
# if the space data exists AND this is not the active window
if context.space_data != None and LookingGlassAddon.BlenderWindow != context.window:
# in any case, we need to track the active window
# NOTE: this is important for finding the correct "Scene" and "View Layer"
LookingGlassAddon.BlenderWindow = context.window
# set up the camera for each view and the shader of the rendering object
def setupVirtualCameraForView(self, view, viewMatrix, projectionMatrix):
# use the context override class method
return self._override.setupVirtualCameraForView(view, self.qs[self.preset]["total_views"], self.device.viewCone, self.device.aspect, viewMatrix, projectionMatrix)
# Save the viewport settings
def saveViewportSettings(self):
# use the context override class method
return self._override.saveViewportSettings()
# Update the viewport settings
def updateViewportSettings(self, context):
# if the settings shall be taken from a Blender viewport
if self.addon_settings_scene.viewportMode == 'BLENDER':
# check if the space still exists
found = False
for workspace in bpy.data.workspaces:
for screen in workspace.screens:
for area in screen.areas:
for space in area.spaces:
if space.type == 'VIEW_3D':
if LookingGlassAddon.BlenderViewport == space:
# get the area
LookingGlassAddon.BlenderViewportArea = area
found = True
break
# if the SpaceView3D still exists
if found == True:
# set the context
self._override.set_context(context)
# assign the selected viewport
return self._override.updateViewportSettings(LookingGlassAddon.BlenderViewport)
else:
# reset the global variable and fall back to custom settings
LookingGlassAddon.BlenderViewport = None
# set the context
self._override.set_context(context)
# assign the selected viewport
return self._override.updateViewportSettings(LookingGlassAddon.BlenderViewport)
# Restore the viewport settings
def restoreViewportSettings(self):
# use the context override class method
return self._override.restoreViewportSettings()
@staticmethod
def from_texture_to_numpy_array(offscreen, array):
"""copy the current texture to a numpy array"""
with offscreen.bind():
# TODO: IN LATER VERSIONS OF ALICE/LG THAT DO NOT SUPPORT 2.93
# ANYMORE, THE bgl.* CALLS SHOULD BE REMOVED
# for Blender versions earlier than 3.0 (prior to the major BGL changes)
if bpy.app.version < (3, 0, 0):
# activate the texture
bgl.glActiveTexture(bgl.GL_TEXTURE0)
bgl.glBindTexture(bgl.GL_TEXTURE_2D, offscreen.color_texture)
# then we pass the numpy array to the bgl.Buffer as template,
# which causes Blender to write the buffer data into the numpy array directly
buffer = bgl.Buffer(bgl.GL_BYTE, array.shape, array)
# set correct colormode
if array.shape[2] == 3: colormode = bgl.GL_RGB
if array.shape[2] == 4: colormode = bgl.GL_RGBA
# write pixel data from texture into the buffer (numpy array)
bgl.glGetTexImage(bgl.GL_TEXTURE_2D, 0, colormode, bgl.GL_UNSIGNED_BYTE, buffer)
bgl.glBindTexture(bgl.GL_TEXTURE_2D, 0)
# for Blender versions later than 3.0 (after the major BGL changes)
else:
# then we pass the numpy array to the gpu.types.Buffer as template,
# which causes Blender to write the buffer data into the numpy array directly
buffer = gpu.types.Buffer('UBYTE', array.shape, array)
# get the active framebuffer
framebuffer = gpu.state.active_framebuffer_get()
# write pixel data from texture into the buffer (numpy array)
framebuffer.read_color(0, 0, array.shape[1], array.shape[0], array.shape[2], 0, 'UBYTE', data=buffer)
# Draw function which copies data from the 3D View
def render_view(self, context):
# if the quilt must be redrawn
if (self.addon_settings_scene.lookingglassCamera or LookingGlassAddon.BlenderViewport):
# UPDATE QUILT SETTINGS
# ++++++++++++++++++++++++++++++++++++++++++++++++
self.start_multi_view = time.time()
# if the quilt and view settings changed
if self.last_preset != self.preset or self.lightfield_image == None:
# update the preset variable
self.last_preset = self.preset
# free the view data of the lightfield image
if self.lightfield_image: self.lightfield_image.clear_views()
# delete the current LightfieldImage
if self.lightfield_image: self.lightfield_image = None
# TODO: Actually we would use "RGB" and a numpy array with 3
# color channels, because that would be more efficient.
# But we can't read in RGB mode to gpu.types.Buffer
# due to Blender's default OpenGL settings:
#
# https://developer.blender.org/T91828
#
# If we don't so it that way, it causes crashes:
#
# https://github.com/regcs/AliceLG/issues/59
#
# The Blender behaviour was fixed for v.3.0+. At the
# point when Alice/LG does not support 2.93 anymore,
# we can change this. (because the Blender fix is not)
# create a pylio LightfieldImage
self.lightfield_image = pylio.LightfieldImage.new(pylio.LookingGlassQuilt, id=self.preset, colormode='RGBA')
# create a new set of LightfieldViews
self.lightfield_image.set_views([pylio.LightfieldView(np.empty((self.qs[self.preset]["view_height"], self.qs[self.preset]["view_width"], 4), dtype=np.uint8), pylio.LightfieldView.formats.numpyarray) for view in range(0, self.qs[self.preset]["total_views"])], pylio.LightfieldView.formats.numpyarray)
LookingGlassAddonLogger.debug("Start rendering lightfield views ...")
LookingGlassAddonLogger.debug(" [#] View dimensions: %i x %i" % (self.qs[self.preset]["view_width"], self.qs[self.preset]["view_height"]))
LookingGlassAddonLogger.debug(" [#] LightfieldImage views: %i" % len(self.lightfield_image.get_view_data()))
LookingGlassAddonLogger.debug(" [#] Using quilt preset: %i (%s, %i x %i)" % (self.preset, self.qs[self.preset]['description'], self.lightfield_image.metadata['quilt_width'], self.lightfield_image.metadata['quilt_height']))
LookingGlassAddonLogger.debug(" [#] Preview mode: %s (selected: %s)" % (self.addon_settings_window_manager.viewport_use_preview_mode, self.addon_settings_window_manager.lightfield_preview_mode))
# PREPARE VIEW & PROJECTION MATRIX
# ++++++++++++++++++++++++++++++++++++++++++++++++
# select camera that belongs to the view
camera = self.addon_settings_scene.lookingglassCamera
# PREPARE THE MODELVIEW AND PROJECTION MATRICES
# if a camera is selected
if camera != None:
# get camera's modelview matrix
view_matrix = camera.matrix_world.copy()
# correct for the camera scaling
view_matrix = view_matrix @ Matrix.Scale(1/camera.scale.x, 4, (1, 0, 0))
view_matrix = view_matrix @ Matrix.Scale(1/camera.scale.y, 4, (0, 1, 0))
view_matrix = view_matrix @ Matrix.Scale(1/camera.scale.z, 4, (0, 0, 1))
# calculate the inverted view matrix because this is what the draw_view_3D function requires
camera_view_matrix = view_matrix.inverted_safe()
# get the camera's projection matrix
camera_projection_matrix = camera.calc_matrix_camera(
depsgraph=context.view_layer.depsgraph,
x = self.qs[self.preset]["view_width"],
y = self.qs[self.preset]["view_height"],
scale_x = 1.0,
scale_y = (self.qs[self.preset]["rows"] / self.qs[self.preset]["columns"]) / self.device.aspect,
)
LookingGlassAddonLogger.debug(" [#] Geting view & projection matrices took %.6f s" % (time.time() - self.start_multi_view))
# RENDER THE VIEWS
# ++++++++++++++++++++++++++++++++++++++++++++++++
# loop through all required views
for view in range(0, self.qs[self.preset]["total_views"]):
with self.qs[self.preset]["viewOffscreen"][view].bind():
start_test = time.time()
# calculate the offset-projection of the current view
view_matrix, projection_matrix = self.setupVirtualCameraForView(view, camera_view_matrix.copy(), camera_projection_matrix.copy())
LookingGlassAddonLogger.debug(" [#] [%i] Setting up view camera took %.3f ms" % (view, (time.time() - start_test) * 1000))
start_test = time.time()
# if the "skip views preview" is activated AND this view shall be skipped
if (self.addon_settings_window_manager.viewport_use_preview_mode and (self.addon_settings_window_manager.lightfield_preview_mode == '2' or self.addon_settings_window_manager.lightfield_preview_mode == '3')) and view % self.skip_views:
# clear LightfieldView array's color data (so it appears black)
self.lightfield_image.views[view]['view'].data[:] = 0
LookingGlassAddonLogger.debug(" [#] [%i] Clearing skipped view's numpy array took %.3f ms" % (view, (time.time() - start_test) * 1000))
# if the "Restricted viewcone preview" is activated AND this view shall be skipped
elif (self.addon_settings_window_manager.viewport_use_preview_mode and self.addon_settings_window_manager.lightfield_preview_mode == '4') and (view < self.restricted_viewcone_limit or view > self.qs[self.preset]["total_views"] - self.restricted_viewcone_limit):
# clear LightfieldView array's color data (so it appears black)
self.lightfield_image.views[view]['view'].data[:] = 0
LookingGlassAddonLogger.debug(" [#] [%i] Clearing skipped view's numpy array took %.3f ms" % (view, (time.time() - start_test) * 1000))
else:
# if the lightfield window is not active anymore, stop
if not (context or context.window_manager.addon_settings.ShowLightfieldWindow):
continue
# draw the viewport rendering to the offscreen for the current view
self.qs[self.preset]["viewOffscreen"][view].draw_view3d(
# we use the "Scene" and the "View Layer" that is active in the Window
# the user currently works in
scene=context.scene,
view_layer=context.view_layer,
view3d=self._override.space_data,
region=self._override.region,
view_matrix=view_matrix,
projection_matrix=projection_matrix,
do_color_management = True)
LookingGlassAddonLogger.debug(" [#] [%i] Drawing view into offscreen took %.3f ms" % (view, (time.time() - start_test) * 1000))
# restore all viewport shading and overlay settings
self.restoreViewportSettings()
LookingGlassAddonLogger.debug("-----------------------------")
LookingGlassAddonLogger.debug("Rendering all views took in total %.3f ms" % ((time.time() - self.start_multi_view) * 1000))
LookingGlassAddonLogger.debug("-----------------------------")
# COPY THE VIEWS INTO A BUFFER
# NOTE: We do this in a separate loop, because for an unknown
# reason (probably something Blender internal), it is faster.
# ++++++++++++++++++++++++++++++++++++++++++++++++
self.start_multi_view = time.time()
# loop through all required views
for view in range(0, self.qs[self.preset]["total_views"]):
# if the "skip views preview" is activated AND this view shall be skipped
if (self.addon_settings_window_manager.viewport_use_preview_mode and (self.addon_settings_window_manager.lightfield_preview_mode == '2' or self.addon_settings_window_manager.lightfield_preview_mode == '3')) and view % self.skip_views:
continue
# if the "Restricted viewcone preview" is activated AND this view shall be skipped
elif (self.addon_settings_window_manager.viewport_use_preview_mode and self.addon_settings_window_manager.lightfield_preview_mode == '4') and (view < self.restricted_viewcone_limit or view > self.qs[self.preset]["total_views"] - self.restricted_viewcone_limit):
continue
else:
start_test = time.time()
# copy texture into LightfieldView array
self.from_texture_to_numpy_array(self.qs[self.preset]["viewOffscreen"][view], self.lightfield_image.views[view]['view'].data[:])
LookingGlassAddonLogger.debug(" [#] [%i] Copying texture to numpy array took %.3f ms" % (view, (time.time() - start_test) * 1000))
LookingGlassAddonLogger.debug("-----------------------------")
LookingGlassAddonLogger.debug("Copying all views took in total %.3f ms" % ((time.time() - self.start_multi_view) * 1000))
LookingGlassAddonLogger.debug("-----------------------------")
# reset draw variable:
# This is here to prevent excessive redrawing
self.modal_redraw = False
# ------------ CAMERA FRUSTUM RENDERING -------------
# Class for rendering a camera frustum reprsenting the Looking Glass
# in Blenders 3D viewport
class FrustumRenderer:
# Inititalize the camera frustum drawing
def __init__(self):
# Blender draw handler for the frustum
self.frustum_draw_handler = None
# variables for the frustum
self.frustum_indices_lines = None
self.frustum_indices_faces = None
self.frustum_indices_focalplane_outline = None
self.frustum_indices_focalplane_face = None
self.frustum_shader = None
# notify addon that frustum is activated
LookingGlassAddon.FrustumInitialized = True
# deinititalize the camera frustum drawing
def __del__(self):
# remove the draw handler for the frustum drawing
if self.frustum_draw_handler:
bpy.types.SpaceView3D.draw_handler_remove(self.frustum_draw_handler, 'WINDOW')
self.frustum_draw_handler = None
# notify addon that frustum is deactivated
LookingGlassAddon.FrustumInitialized = False
# cancel frustum drawing
def stop(self):