-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathoperators.py
2195 lines (1789 loc) · 82.4 KB
/
operators.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 #####
#
# 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 2
# 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, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# END GPL LICENSE BLOCK #####
import bpy
import bgl
import blf
import gpu
import os
from gpu_extras.batch import batch_for_shader
from math import pi, cos, sin, ceil
from mathutils import Vector, Matrix
from bpy_extras.view3d_utils import location_3d_to_region_2d
from bpy.app.handlers import persistent
from bpy_extras.io_utils import ImportHelper
from time import sleep
from subprocess import run
from . import constants as const
from . import functions as fn
@persistent
def load_handler(dummy):
"""
We need to remove the draw handlers when loading a blend file,
otherwise a crapton of errors about the class being removed is printed
(If a blend is saved with the draw handler running, then it's loaded
with it running, but the class called for drawing no longer exists)
Ideally we should recreate the handler when loading the scene if it
was enabled when it was saved - however this function is called
before the blender UI finishes loading, and thus no 3D view exists yet.
"""
if GAFFER_OT_show_light_radius._handle is not None:
bpy.types.SpaceView3D.draw_handler_remove(GAFFER_OT_show_light_radius._handle, "WINDOW")
if GAFFER_OT_show_light_label._handle is not None:
bpy.types.SpaceView3D.draw_handler_remove(GAFFER_OT_show_light_label._handle, "WINDOW")
bpy.context.scene.gaf_props.IsShowingRadius = False
bpy.context.scene.gaf_props.IsShowingLabel = False
class GAFFER_OT_rename(bpy.types.Operator):
"Rename this light"
bl_idname = "gaffer.rename"
bl_label = "Rename This Light"
bl_options = {"REGISTER", "UNDO"}
light: bpy.props.StringProperty(name="New name")
multiuser: bpy.props.StringProperty(default="")
oldname = ""
users = []
def draw(self, context):
self.layout.prop(self, "light")
if self.multiuser != "":
self.layout.label(
text="You are renaming the "
+ ("light data" if self.multiuser.startswith("LIGHT") else "material")
+ ", which has multiple users"
)
def invoke(self, context, event):
self.oldname = self.light
return context.window_manager.invoke_props_popup(self, event)
def execute(self, context):
if self.multiuser.startswith("LIGHT"):
bpy.data.lights[self.oldname].name = self.light
elif self.multiuser.startswith("MAT"):
bpy.data.materials[self.oldname].name = self.light
else:
context.scene.objects[self.oldname].name = self.light
fn.refresh_light_list(context.scene)
return {"FINISHED"}
class GAFFER_OT_set_strength(bpy.types.Operator):
"Double/half the power of this light"
bl_idname = "gaffer.increase_decrease_strength"
bl_label = "Increase/Decrease Strength"
bl_options = {"REGISTER", "UNDO"}
mult = 0
increase: bpy.props.BoolProperty()
light: bpy.props.StringProperty()
socket_strength: bpy.props.IntProperty()
node: bpy.props.StringProperty()
material: bpy.props.StringProperty()
socket_strength_type: bpy.props.StringProperty()
def invoke(self, context, event):
if event.shift:
self.mult = 2 ** (1 / 4)
elif event.ctrl:
self.mult = 8
else:
self.mult = 2
if not self.increase:
self.mult = 1 / self.mult
return self.execute(context)
def execute(self, context):
light = context.scene.objects[self.light]
if self.node:
node = None
if self.material:
node = bpy.data.materials[self.material].node_tree.nodes[self.node]
else:
node = light.data.node_tree.nodes[self.node]
if self.socket_strength_type == "o":
socket = node.outputs[self.socket_strength]
else:
socket = node.inputs[self.socket_strength]
socket.default_value = socket.default_value * self.mult
else:
light.data.energy = light.data.energy * self.mult
return {"FINISHED"}
class GAFFER_OT_set_temp(bpy.types.Operator):
"Set the color temperature to a preset"
bl_idname = "gaffer.col_temp_preset"
bl_label = "Color Temperature Preset"
bl_options = {"REGISTER", "UNDO"}
temperature: bpy.props.StringProperty()
light: bpy.props.StringProperty()
material: bpy.props.StringProperty()
node: bpy.props.StringProperty()
def execute(self, context):
light = context.scene.objects[self.light]
if light.type == "LIGHT":
node = light.data.node_tree.nodes[self.node]
else:
node = bpy.data.materials[self.material].node_tree.nodes[self.node]
node.inputs[0].links[0].from_node.inputs[0].default_value = const.col_temp[self.temperature]
return {"FINISHED"}
class GAFFER_OT_show_temp_list(bpy.types.Operator):
"Set the color temperature to a preset"
bl_idname = "gaffer.col_temp_show"
bl_label = "Color Temperature Preset"
l_index: bpy.props.IntProperty()
def execute(self, context):
context.scene.gaf_props.ColTempExpand = True
context.scene.gaf_props.LightUIIndex = self.l_index
return {"FINISHED"}
class GAFFER_OT_hide_temp_list(bpy.types.Operator):
"Hide color temperature presets"
bl_idname = "gaffer.col_temp_hide"
bl_label = "Hide Presets"
def execute(self, context):
context.scene.gaf_props.ColTempExpand = False
return {"FINISHED"}
class GAFFER_OT_show_more(bpy.types.Operator):
"Show settings such as MIS, falloff, ray visibility..."
bl_idname = "gaffer.more_options_show"
bl_label = "Show more options"
light: bpy.props.StringProperty()
def execute(self, context):
exp_list = context.scene.gaf_props.MoreExpand
# prepend+append funny stuff so that the light name is
# unique (otherwise Fill_03 would also expand Fill_03.001)
exp_list += "_Light:_(" + self.light + ")_"
context.scene.gaf_props.MoreExpand = exp_list
return {"FINISHED"}
class GAFFER_OT_hide_more(bpy.types.Operator):
"Hide settings such as MIS, falloff, ray visibility..."
bl_idname = "gaffer.more_options_hide"
bl_label = "Hide more options"
light: bpy.props.StringProperty()
def execute(self, context):
context.scene.gaf_props.MoreExpand = context.scene.gaf_props.MoreExpand.replace(
"_Light:_(" + self.light + ")_", ""
)
return {"FINISHED"}
class GAFFER_OT_hide_show_light(bpy.types.Operator):
"Hide/Show this light (in viewport and in render)"
bl_idname = "gaffer.hide_light"
bl_label = "Hide Light"
bl_options = {"REGISTER", "UNDO"}
light: bpy.props.StringProperty()
hide: bpy.props.BoolProperty()
dataname: bpy.props.StringProperty()
def execute(self, context):
dataname = self.dataname
if dataname == "__SINGLE_USER__":
light = bpy.data.objects[self.light]
light.hide_viewport = self.hide
light.hide_render = self.hide
else:
if dataname.startswith("LIGHT"):
# actual data name (minus the prepended 'LIGHT')
data = bpy.data.lights[(dataname[5:])]
for obj in bpy.data.objects:
if obj.data == data:
obj.hide_viewport = self.hide
obj.hide_render = self.hide
else:
# actual data name (minus the prepended 'MAT')
mat = bpy.data.materials[(dataname[3:])]
for obj in bpy.data.objects:
if obj.type == "MESH":
for slot in obj.material_slots:
if slot.material == mat:
obj.hide_viewport = self.hide
obj.hide_render = self.hide
return {"FINISHED"}
class GAFFER_OT_select_light(bpy.types.Operator):
"Select this light"
bl_idname = "gaffer.select_light"
bl_label = "Select"
bl_options = {"REGISTER", "UNDO"}
light: bpy.props.StringProperty()
dataname: bpy.props.StringProperty()
@classmethod
def poll(cls, context):
return context.mode == "OBJECT"
def execute(self, context):
for item in context.scene.objects:
item.select_set(False)
dataname = self.dataname
if dataname == "__SINGLE_USER__":
obj = bpy.data.objects[self.light]
obj.select_set(True)
context.view_layer.objects.active = obj
else:
if dataname.startswith("LIGHT"):
# actual data name (minus the prepended 'LIGHT')
data = bpy.data.lights[(dataname[5:])]
for obj in bpy.data.objects:
if obj.data == data:
obj.select_set(True)
else:
# actual data name (minus the prepended 'MAT')
mat = bpy.data.materials[(dataname[3:])]
for obj in bpy.data.objects:
if obj.type == "MESH":
for slot in obj.material_slots:
if slot.material == mat:
obj.select_set(True)
context.view_layer.objects.active = bpy.data.objects[self.light]
return {"FINISHED"}
class GAFFER_OT_solo(bpy.types.Operator):
("Solo: Hide all other lights but this one.\nClick again to restore previous light visibility")
bl_idname = "gaffer.solo"
bl_label = "Solo Light"
bl_options = {"REGISTER", "UNDO"}
light: bpy.props.StringProperty()
showhide: bpy.props.BoolProperty()
worldsolo: bpy.props.BoolProperty(default=False)
dataname: bpy.props.StringProperty(default="__EXIT_SOLO__")
def execute(self, context):
light = self.light
showhide = self.showhide
worldsolo = self.worldsolo
scene = context.scene
blacklist = context.scene.gaf_props.Blacklist
# Get object names that share data with the solo'd object:
dataname = self.dataname
linked_lights = []
# Only make list if going into Solo and obj has multiple users
if dataname not in ["__SINGLE_USER__", "__EXIT_SOLO__"] and showhide:
if dataname.startswith("LIGHT"):
# actual data name (minus the prepended 'LIGHT')
data = bpy.data.lights[(dataname[5:])]
for obj in bpy.data.objects:
if obj.data == data:
linked_lights.append(obj.name)
else:
# actual data name (minus the prepended 'MAT')
mat = bpy.data.materials[(dataname[3:])]
for obj in bpy.data.objects:
if obj.type == "MESH":
for slot in obj.material_slots:
if slot.material == mat:
linked_lights.append(obj.name)
statelist = fn.stringToNestedList(scene.gaf_props.LightsHiddenRecord, True)
if showhide: # Enter Solo mode
fn.refresh_light_list(scene)
scene.gaf_props.SoloActive = light
fn.getHiddenStatus(scene, fn.stringToNestedList(scene.gaf_props.Lights, True))
for l in statelist: # first check if lights still exist
if l[0] != "WorldEnviroLight":
try:
obj = bpy.data.objects[l[0]]
except KeyError:
# TODO not sure if this ever happens, if it does, doesn't it break?
fn.getHiddenStatus(scene, fn.stringToNestedList(scene.gaf_props.Lights, True))
bpy.ops.gaffer.solo()
# If one of the lights has been deleted/changed, update the list and dont restore visibility
return {"FINISHED"}
for l in statelist: # then restore visibility
if l[0] != "WorldEnviroLight":
obj = bpy.data.objects[l[0]]
if obj.name not in blacklist:
if obj.name == light or obj.name in linked_lights:
obj.hide_viewport = False
obj.hide_render = False
else:
obj.hide_viewport = True
obj.hide_render = True
if context.scene.render.engine == "CYCLES":
if worldsolo:
if not scene.gaf_props.WorldVis:
scene.gaf_props.WorldVis = True
else:
if scene.gaf_props.WorldVis:
scene.gaf_props.WorldVis = False
else: # Exit solo
oldlight = scene.gaf_props.SoloActive
scene.gaf_props.SoloActive = ""
for l in statelist:
if l[0] != "WorldEnviroLight":
try:
obj = bpy.data.objects[l[0]]
except KeyError:
# TODO not sure if this ever happens, if it does, doesn't it break?
fn.refresh_light_list(scene)
fn.getHiddenStatus(scene, fn.stringToNestedList(scene.gaf_props.Lights, True))
scene.gaf_props.SoloActive = oldlight
bpy.ops.gaffer.solo()
return {"FINISHED"}
if obj.name not in blacklist:
obj.hide_viewport = fn.castBool(l[1])
obj.hide_render = fn.castBool(l[2])
elif context.scene.render.engine == "CYCLES":
scene.gaf_props.WorldVis = fn.castBool(l[1])
scene.gaf_props.WorldReflOnly = fn.castBool(l[2])
return {"FINISHED"}
class GAFFER_OT_light_use_nodes(bpy.types.Operator):
"Make this light use nodes"
bl_idname = "gaffer.light_use_nodes"
bl_label = "Use Nodes"
bl_options = {"REGISTER", "UNDO"}
light: bpy.props.StringProperty()
def execute(self, context):
obj = bpy.data.objects[self.light]
if obj.type == "LIGHT":
obj.data.use_nodes = True
fn.refresh_light_list(context.scene)
return {"FINISHED"}
class GAFFER_OT_node_set_strength(bpy.types.Operator):
"Use this node's first Value input as the Strength slider for this light in the Gaffer panel"
bl_idname = "gaffer.node_set_strength"
bl_label = "Set as Gaffer Strength"
bl_options = {"REGISTER", "UNDO"}
@classmethod
def poll(cls, context):
if context.space_data.type == "NODE_EDITOR":
return not context.space_data.pin
else:
return False
def execute(self, context):
fn.setGafferNode(context, "STRENGTH")
return {"FINISHED"}
class GAFFER_OT_refresh_light_list(bpy.types.Operator):
"Refresh the list of lights"
bl_idname = "gaffer.refresh_lights"
bl_label = "Refresh Light List"
def execute(self, context):
scene = context.scene
fn.refresh_light_list(scene)
self.report({"INFO"}, "Light list refreshed")
return {"FINISHED"}
class GAFFER_OT_set_light_data_user_names(bpy.types.Operator):
"""This light data is used by multiple objects.
Click to set the data name to match the object names.
Shift-click to set the names for each object to match the data name"""
bl_idname = "gaffer.set_light_data_user_names"
bl_label = "Match Object Names and Data Name"
bl_options = {"REGISTER", "UNDO"}
data_name: bpy.props.StringProperty()
data_type: bpy.props.StringProperty()
set_object_names: bpy.props.BoolProperty()
def invoke(self, context, event):
self.set_object_names = event.shift or event.ctrl # Shift or Ctrl in case they can't remember which.
return self.execute(context)
def execute(self, context):
data = getattr(bpy.data, self.data_type)[self.data_name]
if self.set_object_names:
i = 0
to_rename = {} # To avoid modifying object list while we're iterating over it
for obj in bpy.data.objects:
if self.data_type == "lights":
if obj.data == data:
i += 1
to_rename[obj.name] = self.data_name + "." + str(i).zfill(3)
else:
for slot in obj.material_slots:
if slot.material == data:
i += 1
to_rename[obj.name] = self.data_name + "." + str(i).zfill(3)
for obj in to_rename:
if bpy.data.objects[obj].name != to_rename[obj]:
bpy.data.objects[obj].name = to_rename[obj]
if i != 0:
fn.refresh_light_list(context.scene)
return {"FINISHED"}
else:
self.report({"ERROR"}, "No objects use this data")
return {"CANCELLED"}
else:
objects = []
for obj in bpy.data.objects:
if self.data_type == "lights":
if obj.data == data:
objects.append(obj.name)
else:
for slot in obj.material_slots:
if slot.material == data:
objects.append(obj.name)
if not objects:
self.report({"ERROR"}, "No objects use this data")
return {"CANCELLED"}
# Try to find the best name for the data
numberless_obj_names = []
for obj in objects:
# Remove any number at the end in the regex pattern of name.### (e.g. Light.001)
if len(obj) > 4:
if obj[-4] == "." and obj[-3:].isdigit():
numberless_obj_names.append(obj[:-4])
else:
numberless_obj_names.append(obj)
else:
numberless_obj_names.append(obj)
# Find the most common name
data.name = max(set(numberless_obj_names), key=numberless_obj_names.count)
fn.refresh_light_list(context.scene)
return {"FINISHED"}
class GAFFER_OT_apply_exposure(bpy.types.Operator):
"Apply Exposure\nAdjust the brightness of all lights by the exposure amount and set the exposure slider back to 0"
bl_idname = "gaffer.apply_exposure"
bl_label = "Apply Exposure"
bl_options = {"REGISTER", "UNDO"}
@classmethod
def poll(cls, context):
return context.scene.render.engine in const.supported_renderers
def execute(self, context):
scene = context.scene
fn.refresh_light_list(scene)
gaf_props = scene.gaf_props
lights_str = gaf_props.Lights
lights = fn.stringToNestedList(lights_str)
evs = scene.view_settings.exposure # CM exposure is set in EVs/stops
exposure = pow(2, evs) # Linear exposure adjustment
scene.view_settings.exposure = 0
# Almost all of this is copy pasted from ui.draw_cycles_eevee_UI.
# TODO make a function for finding the strength property.
# Store list of completed sockets to avoid duplicate work on multi-user data
completed_lights = []
for item in lights:
if item[0] != "":
light = scene.objects[item[0][1:-1]] # drop the apostrophes
if light.type == "LIGHT":
if light in completed_lights:
continue
light.data.energy *= exposure
completed_lights.append(light)
else:
use_nodes = True
material = bpy.data.materials[item[1][1:-1]]
if material.use_nodes:
node_strength = material.node_tree.nodes[item[2][1:-1]]
else:
use_nodes = False
if use_nodes:
if item[3].startswith("'"):
socket_strength_str = str(item[3][1:-1])
else:
socket_strength_str = str(item[3])
if socket_strength_str.startswith("o"):
socket_strength_type = "o"
socket_strength = int(socket_strength_str[1:])
elif socket_strength_str.startswith("i"):
socket_strength_type = "i"
socket_strength = int(socket_strength_str[1:])
else:
socket_strength_type = "i"
socket_strength = int(socket_strength_str)
strength_sockets = node_strength.inputs
if socket_strength_type == "o":
strength_sockets = node_strength.outputs
try:
skt = strength_sockets[socket_strength]
if skt in completed_lights:
continue
if (
(socket_strength_type == "i" and not skt.is_linked)
or (socket_strength_type == "o" and skt.is_linked)
) and hasattr(skt, "default_value"):
strength_sockets[socket_strength].default_value *= exposure
completed_lights.append(skt)
else:
self.report(
{"ERROR"},
item[0] + " does not have a valid node. Try refreshing the light list.",
)
except (KeyError, IndexError, AttributeError):
self.report(
{"ERROR"},
item[0] + " does not have a valid node. Try refreshing the light list.",
)
else:
self.report(
{"WARNING"},
item[0] + " does not use nodes and can't be adjusted.",
)
# World
gaf_hdri_props = scene.world.gaf_hdri_props
if gaf_hdri_props.hdri_handler_enabled:
gaf_hdri_props.hdri_brightness = gaf_hdri_props.hdri_brightness + evs
if gaf_hdri_props.hdri_use_separate_brightness:
gaf_hdri_props.hdri_background_brightness = gaf_hdri_props.hdri_background_brightness + evs
else:
world = scene.world
if world.use_nodes:
backgrounds = [] # make a list of all linked Background shaders, use the right-most one
background = None
for node in world.node_tree.nodes:
if node.type == "BACKGROUND":
if not node.name.startswith("HDRIHandler_"):
if node.outputs[0].is_linked:
backgrounds.append(node)
if backgrounds:
background = sorted(backgrounds, key=lambda x: x.location.x, reverse=True)[0]
# Strength
if background.inputs[1].is_linked:
strength_node = None
current_node = background.inputs[1].links[0].from_node
temp_current_node = None
# Failsafe in case of infinite loop (which can happen from accidental cyclic links)
i = 0
while strength_node is None and i < 1000: # limitted to 100 chained nodes
i += 1
if temp_current_node:
current_node = temp_current_node
for socket in current_node.inputs:
# stop at first node with an unconnected Value socket
if socket.type == "VALUE" and not socket.is_linked:
strength_node = current_node
else:
if socket.is_linked:
temp_current_node = socket.links[0].from_node
if strength_node:
for socket in strength_node.inputs:
if socket.type == "VALUE" and not socket.is_linked: # use first color socket
socket.default_value = socket.default_value * exposure
break
else:
background.inputs[1].default_value = background.inputs[1].default_value * exposure
return {"FINISHED"}
class GAFFER_OT_link_sky_to_sun(bpy.types.Operator):
bl_idname = "gaffer.link_sky_to_sun"
bl_label = "Link Sky Texture:"
bl_options = {"REGISTER", "UNDO"}
node_name: bpy.props.StringProperty(default="")
# Thanks to oscurart for the original script off which this is based!
# http://bit.ly/blsunsky
def execute(self, context):
tree = context.scene.world.node_tree
node = tree.nodes[self.node_name]
lightob = bpy.data.objects[context.scene.gaf_props.SunObject]
if tree.animation_data:
if tree.animation_data.action:
for fc in tree.animation_data.action.fcurves:
if fc.data_path == ('nodes["' + node.name + '"].sun_direction'):
self.report({"ERROR"}, "Sun Direction is animated")
return {"CANCELLED"}
elif tree.animation_data.drivers:
for dr in tree.animation_data.drivers:
if dr.data_path == ('nodes["' + node.name + '"].sun_direction'):
self.report({"ERROR"}, "Sun Direction has drivers")
return {"CANCELLED"}
dr = node.driver_add("sun_direction")
nodename = ""
for ch in node.name:
if ch.isalpha(): # make sure node name can be used in expression
nodename += ch
# Create unique variable name for each node
varname = nodename + "_" + str(context.scene.gaf_props.VarNameCounter)
context.scene.gaf_props.VarNameCounter += 1
dr[0].driver.expression = varname
var = dr[0].driver.variables.new()
var.name = varname
var.type = "SINGLE_PROP"
var.targets[0].id = lightob
var.targets[0].data_path = "matrix_world[2][0]"
# Y
dr[1].driver.expression = varname
var = dr[1].driver.variables.new()
var.name = varname
var.type = "SINGLE_PROP"
var.targets[0].id = lightob
var.targets[0].data_path = "matrix_world[2][1]"
# Y
dr[2].driver.expression = varname
var = dr[2].driver.variables.new()
var.name = varname
var.type = "SINGLE_PROP"
var.targets[0].id = lightob
var.targets[0].data_path = "matrix_world[2][2]"
return {"FINISHED"}
class GAFFER_OT_aim_light(bpy.types.Operator):
"Point the selected lights at a target"
bl_idname = "gaffer.aim"
bl_label = "Aim"
bl_options = {"REGISTER", "UNDO"}
target_type: bpy.props.StringProperty()
def aim(self, context, obj, target=[0, 0, 0]):
# Thanks to @kilbee for cleaning my crap up here :) See: https://github.com/gregzaal/Gaffer/commit/b920092
obj_loc = obj.matrix_world.to_translation()
direction = target - obj_loc
# point obj '-Z' and use its 'Y' as up
rot_quat = direction.to_track_quat("-Z", "Y")
if obj.rotation_mode == "QUATERNION":
obj.rotation_quaternion = rot_quat
else:
obj.rotation_euler = rot_quat.to_euler()
def execute(self, context):
if self.target_type == "CURSOR":
# Aim all selected objects at cursor
objects = context.selected_editable_objects
if not objects:
self.report({"ERROR"}, "No selected objects!")
return {"CANCELLED"}
for obj in context.selected_editable_objects:
self.aim(context, obj, context.scene.cursor.location)
return {"FINISHED"}
elif self.target_type == "SELECTED":
# Aim the active object at the average location of all other selected objects
active = context.view_layer.objects.active
objects = [obj for obj in context.selected_objects if obj != active]
num_objects = len(objects)
if not active:
self.report({"ERROR"}, "You need an active object!")
return {"CANCELLED"}
elif num_objects == 0:
if active.select_get():
self.report({"ERROR"}, "Select more than one object!")
else:
self.report({"ERROR"}, "No selected objects!")
return {"CANCELLED"}
total_x = 0
total_y = 0
total_z = 0
for obj in objects:
total_x += obj.location.x
total_y += obj.location.y
total_z += obj.location.z
avg_x = total_x / num_objects
avg_y = total_y / num_objects
avg_z = total_z / num_objects
self.aim(context, active, Vector((avg_x, avg_y, avg_z)))
return {"FINISHED"}
elif self.target_type == "ACTIVE":
# Aim the selected objects at the active object
active = context.view_layer.objects.active
objects = [obj for obj in context.selected_objects if obj != active]
if not active:
self.report({"ERROR"}, "No active object!")
return {"CANCELLED"}
elif not objects:
self.report({"ERROR"}, "No selected objects!")
return {"CANCELLED"}
for obj in objects:
self.aim(context, obj, active.location)
return {"FINISHED"}
return {"CANCELLED"}
class GAFFER_OT_aim_light_with_view(bpy.types.Operator):
"Aim the active object using the 3D view camera"
bl_idname = "gaffer.aim_view"
bl_label = "Aim With View"
bl_options = {"REGISTER", "UNDO"}
old_cam = None
old_lock = None
old_transf = None
@classmethod
def poll(cls, context):
return context.space_data.type == "VIEW_3D" and context.object
def modal(self, context, event):
obj = context.object
if event.type in ("RET", "SPACE") or (
event.type == "LEFTMOUSE" and event.value != "CLICK_DRAG"
): # Some weird pie menu bug
bpy.ops.view3d.view_camera()
context.scene.camera = self.old_cam
context.space_data.lock_camera = self.old_lock
context.area.header_text_set(None)
return {"FINISHED"}
elif event.type in ("RIGHTMOUSE", "ESC"):
bpy.ops.view3d.view_camera()
context.scene.camera = self.old_cam
context.space_data.lock_camera = self.old_lock
obj.location = self.old_transf[0]
obj.rotation_quaternion = self.old_transf[1]
obj.rotation_euler = self.old_transf[2]
context.area.header_text_set(None)
return {"CANCELLED"}
elif event.type in (
"MOUSEMOVE",
"INBETWEEN_MOUSEMOVE",
"MIDDLEMOUSE",
"WHEELDOWNMOUSE",
"WHEELUPMOUSE",
"LEFT_CTRL",
"LEFT_SHIFT",
"LEFT_ALT",
):
# Only allow navigation keys to prevent user from changing camera or doing anything else unexpected
return {"PASS_THROUGH"}
else:
return {"RUNNING_MODAL"}
return {"RUNNING_MODAL"}
def invoke(self, context, event):
if not context.object:
self.report({"ERROR"}, "No active object")
return {"CANCELLED"}
if context.space_data.type != "VIEW_3D":
self.report({"ERROR"}, "Must be run from the 3D view")
return {"CANCELLED"}
obj = context.object
self.old_cam = context.scene.camera
self.old_lock = context.space_data.lock_camera
self.old_transf = [
obj.location.copy(),
obj.rotation_quaternion.copy(),
obj.rotation_euler.copy(),
]
context.scene.camera = obj
context.space_data.lock_camera = True
bpy.ops.view3d.view_camera()
context.area.header_text_set("LMB/Enter/Space: Confirm Esc/RMB: Cancel")
context.window_manager.modal_handler_add(self)
return {"RUNNING_MODAL"}
class GAFFER_OT_show_light_radius(bpy.types.Operator):
"Display a circle around each light showing their radius"
bl_idname = "gaffer.show_radius"
bl_label = "Show Radius"
# CoDEmanX wrote a lot of this - thanks sir!
_handle = None
@staticmethod
def handle_add(self, context):
self._handle = bpy.types.SpaceView3D.draw_handler_add(
self.draw_callback_radius, (context,), "WINDOW", "POST_VIEW"
)
GAFFER_OT_show_light_radius._handle = self._handle
@staticmethod
def handle_remove(context):
if GAFFER_OT_show_light_radius._handle is not None:
bpy.types.SpaceView3D.draw_handler_remove(GAFFER_OT_show_light_radius._handle, "WINDOW")
GAFFER_OT_show_light_radius._handle = None
def draw_callback_radius(self, context):
scene = context.scene
try:
shader = gpu.shader.from_builtin("3D_UNIFORM_COLOR")
except ValueError:
shader = gpu.shader.from_builtin("UNIFORM_COLOR") # Blender 4.0+
if not context.space_data.overlay.show_overlays:
return
for item in self.objects:
gpu.state.blend_set("ALPHA")
obj = item[0]
if not scene.gaf_props.LightRadiusSelectedOnly or obj.select_get():
if obj:
if obj.data:
# in case user changes the type while running
if obj.data.type in ["POINT", "SUN", "SPOT"]:
# TODO check if this is still needed for Eevee
if scene.render.engine in const.supported_renderers:
if obj in context.visible_objects and obj.name not in [
o.name for o in scene.gaf_props.Blacklist
]:
if scene.gaf_props.LightRadiusUseColor:
if item[1][0] == "BLACKBODY":
color = fn.convert_temp_to_RGB(item[1][1].inputs[0].default_value)
elif item[1][0] == "WAVELENGTH":
color = fn.convert_wavelength_to_RGB(item[1][1].inputs[0].default_value)
else:
color = item[1]
else:
color = scene.gaf_props.DefaultRadiusColor
if scene.gaf_props.LightRadiusXray:
bgl.glClear(bgl.GL_DEPTH_BUFFER_BIT)
radius = obj.data.shadow_soft_size
origin = obj.matrix_world.translation
view_mat = context.space_data.region_3d.view_matrix
view_dir = view_mat.to_3x3()[2]
up = Vector((0, 0, 1))
angle = up.angle(view_dir)
axis = up.cross(view_dir)
mat = Matrix.Translation(origin) @ Matrix.Rotation(angle, 4, axis)
if scene.gaf_props.LightRadiusDrawType == "dotted":
sides = 24
else:
sides = 64
verts = []
for i in range(sides):
cosine = radius * cos(i * 2 * pi / sides)
sine = radius * sin(i * 2 * pi / sides)
vec = Vector((cosine, sine, 0))
c = mat @ vec
verts.append((c.x, c.y, c.z))
if scene.gaf_props.LightRadiusDrawType != "filled":
radius = radius * 0.9 # TODO thickness option
for i in range(sides):
cosine = radius * cos(i * 2 * pi / sides)
sine = radius * sin(i * 2 * pi / sides)
vec = Vector((cosine, sine, 0))
c = mat @ vec
verts.append((c.x, c.y, c.z))
else:
vec = Vector((0, 0, 0))
c = mat @ vec
verts.append((c.x, c.y, c.z))
indices = []
if scene.gaf_props.LightRadiusDrawType != "filled":
for i in range(sides):
if scene.gaf_props.LightRadiusDrawType == "dotted" and i % 2:
continue
a = i
b = i + 1
c = i + 1 + sides
d = i + sides
indices.append((a, b, c))
indices.append((a, c, d))
if i == sides - 2:
# We'll do the last 2 tris manually, math is a bit over my head :)
break
if scene.gaf_props.LightRadiusDrawType != "dotted":
indices.append((0, sides - 1, sides * 2 - 1))
indices.append((0, sides, sides * 2 - 1))
else:
for i in range(sides):
a = i
b = (i + 1) % sides
indices.append((a, b, sides))
shader.bind()
shader.uniform_float(
"color",
(
color[0],
color[1],
color[2],
scene.gaf_props.LightRadiusAlpha,