forked from gregzaal/Gaffer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgaffer.py
2452 lines (2096 loc) · 103 KB
/
gaffer.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 #####
bl_info = {
"name": "Gaffer",
"description": "Manage all your lights together quickly and efficiently from the 3D View toolbar",
"author": "Greg Zaal",
"version": (2, 3),
"blender": (2, 73, 0),
"location": "3D View > Tools",
"warning": "",
"wiki_url": "",
"tracker_url": "",
"category": "3D View"}
import bpy
from collections import OrderedDict
import bgl, blf
from math import pi, cos, sin, log
from mathutils import Vector, Matrix
from bpy_extras.view3d_utils import location_3d_to_region_2d
from bpy.app.handlers import persistent
supported_renderers = ['BLENDER_RENDER', 'CYCLES']
col_temp = {"01_Flame (1700)": 1700,
"02_Tungsten (3200)": 3200,
"03_Sunset (5000)": 5000,
"04_Daylight (5500)": 5500,
"05_Overcast (6500)": 6500,
"06_Monitor (7000)": 7000,
"07_Shade (8000)": 8000,
"08_LCD (10500)": 10500,
"09_Sky (12000)": 12000}
'''
FUNCTIONS
'''
@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 GafShowLightRadius._handle is not None:
bpy.types.SpaceView3D.draw_handler_remove(GafShowLightRadius._handle, 'WINDOW')
if GafShowLightLabel._handle is not None:
bpy.types.SpaceView3D.draw_handler_remove(GafShowLightLabel._handle, 'WINDOW')
bpy.context.scene.GafferIsShowingRadius = False
bpy.context.scene.GafferIsShowingLabel = False
def refresh_light_list(scene):
m = []
if not hasattr(bpy.types.Object, "GafferFalloff"):
bpy.types.Object.GafferFalloff = bpy.props.EnumProperty(
name="Light Falloff",
items=(("constant","Constant","No light falloff"),
("linear","Linear","Fade light strength linearly over the distance it travels"),
("quadratic","Quadratic","(Realisic) Light strength is inversely proportional to the square of the distance it travels")),
default="quadratic",
description="The rate at which the light loses intensity over distance",
update=_update_falloff)
light_dict = dictOfLights()
objects = sorted(scene.objects, key=lambda x: x.name)
if scene.render.engine == 'BLENDER_RENDER':
for obj in objects:
if obj.type == 'LAMP':
m.append([obj.name, None, None]) # only use first element of list to keep usage consistent with cycles mode
elif scene.render.engine == 'CYCLES':
for obj in objects:
light_mats = []
if obj.type == 'LAMP':
if obj.data.use_nodes:
invalid_node = False
if obj.name in light_dict:
if light_dict[obj.name] == "None": # A light that previously did not use nodes (like default light)
invalid_node = True
elif light_dict[obj.name] not in obj.data.node_tree.nodes:
invalid_node = True
if obj.name not in light_dict or invalid_node:
for node in obj.data.node_tree.nodes:
if node.name != "Emission Viewer":
if node.type == 'EMISSION':
if node.outputs[0].is_linked:
if node.inputs[1].is_linked:
socket_index = 0
subnode = node.inputs[1].links[0].from_node
if subnode.inputs:
for inpt in subnode.inputs:
if inpt.type == 'VALUE': # use first Value socket as strength
m.append([obj.name, None, subnode.name, 'i'+str(socket_index)])
break
else:
m.append([obj.name, None, node.name, 1])
break
else:
node = obj.data.node_tree.nodes[light_dict[obj.name]]
socket_index = 0
if node.inputs:
for inpt in node.inputs:
if inpt.type == 'VALUE': # use first Value socket as strength
m.append([obj.name, None, node.name, 'i'+str(socket_index)])
break
socket_index += 1
elif node.outputs:
for oupt in node.outputs:
if oupt.type == 'VALUE': # use first Value socket as strength
m.append([obj.name, None, node.name, 'o'+str(socket_index)])
break
socket_index += 1
else:
m.append([obj.name, None, None])
elif obj.type == 'MESH' and len(obj.material_slots) > 0:
slot_break = False
for slot in obj.material_slots:
if slot_break:
break # only use first emission material in slots
if slot.material:
if slot.material not in light_mats:
if slot.material.use_nodes:
invalid_node = False
if obj.name in light_dict:
if light_dict[obj.name] == "None": # A light that previously did not use nodes (like default light)
invalid_node = True
elif light_dict[obj.name] not in slot.material.node_tree.nodes:
invalid_node = True
if obj.name not in light_dict or invalid_node:
for node in slot.material.node_tree.nodes:
if node.name != "Emission Viewer":
if node.type == 'EMISSION':
if node.outputs[0].is_linked:
if node.inputs[1].is_linked:
socket_index = 0
subnode = node.inputs[1].links[0].from_node
if subnode.inputs:
for inpt in subnode.inputs:
if inpt.type == 'VALUE': # use first Value socket as strength
m.append([obj.name, slot.material.name, subnode.name, 'i'+str(socket_index)])
light_mats.append(slot.material)
slot_break = True
break
else:
m.append([obj.name, slot.material.name, node.name, 1])
light_mats.append(slot.material) # skip this material next time it's checked
slot_break = True
break
else:
node = slot.material.node_tree.nodes[light_dict[obj.name]]
socket_index = 0
if node.inputs:
for inpt in node.inputs:
if inpt.type == 'VALUE': # use first Value socket as strength
m.append([obj.name, slot.material.name, node.name, 'i'+str(socket_index)])
break
socket_index += 1
elif node.outputs:
for oupt in node.outputs:
if oupt.type == 'VALUE': # use first Value socket as strength
m.append([obj.name, slot.material.name, node.name, 'o'+str(socket_index)])
break
socket_index += 1
for light in m:
obj = bpy.data.objects[light[0]]
nodes = None
if obj.type == 'LAMP':
if obj.data.use_nodes:
nodes = obj.data.node_tree.nodes
else:
if bpy.data.materials[light[1]].use_nodes:
nodes = bpy.data.materials[light[1]].node_tree.nodes
if nodes:
if light[2]:
if nodes[light[2]].type != 'LIGHT_FALLOFF' and bpy.data.objects[light[0]].GafferFalloff != 'quadratic':
bpy.data.objects[light[0]].GafferFalloff = 'quadratic'
scene.GafferLights = str(m)
def hack_force_update(context, nodes):
node = nodes.new('ShaderNodeMath')
node.inputs[0].default_value = 0.0
nodes.remove(node)
return False
def stringToList(str="", stripquotes=False):
raw = str.split(", ")
raw[0] = (raw[0])[1:]
raw[-1] = (raw[-1])[:-1]
if stripquotes:
tmplist = []
for item in raw:
tmpvar = item
if tmpvar.startswith("'"):
item = tmpvar[1:-1]
tmplist.append(item)
raw = tmplist
return raw
def stringToNestedList(str="", stripquotes=False):
raw = str.split("], ")
raw[0] = (raw[0])[1:]
raw[-1] = (raw[-1])[:-2]
i = 0
for item in raw:
raw[i] += ']'
i += 1
newraw = []
for item in raw:
newraw.append(stringToList(item, stripquotes))
return newraw
def castBool(str):
if str == 'True':
return True
else:
return False
def setColTemp(node, temp):
node.inputs[0].default_value = temp
def convert_temp_to_RGB(colour_temperature):
"""
Converts from K to RGB, algorithm courtesy of
http://www.tannerhelland.com/4435/convert-temperature-rgb-algorithm-code/
Python implementation by petrklus: https://gist.github.com/petrklus/b1f427accdf7438606a6
"""
# limits: 0 -> 12000
if colour_temperature < 1:
colour_temperature = 1
elif colour_temperature > 12000:
colour_temperature = 12000
tmp_internal = colour_temperature / 100.0
# red
if tmp_internal <= 66:
red = 255
else:
tmp_red = 329.698727446 * pow(tmp_internal - 60, -0.1332047592)
if tmp_red < 0:
red = 0
elif tmp_red > 255:
red = 255
else:
red = tmp_red
# green
if tmp_internal <=66:
tmp_green = 99.4708025861 * log(tmp_internal) - 161.1195681661
if tmp_green < 0:
green = 0
elif tmp_green > 255:
green = 255
else:
green = tmp_green
else:
tmp_green = 288.1221695283 * pow(tmp_internal - 60, -0.0755148492)
if tmp_green < 0:
green = 0
elif tmp_green > 255:
green = 255
else:
green = tmp_green
# blue
if tmp_internal >=66:
blue = 255
elif tmp_internal <= 19:
blue = 0
else:
tmp_blue = 138.5177312231 * log(tmp_internal - 10) - 305.0447927307
if tmp_blue < 0:
blue = 0
elif tmp_blue > 255:
blue = 255
else:
blue = tmp_blue
return [red/255, green/255, blue/255] # return RGB in a 0-1 range
def convert_wavelength_to_RGB(wavelength):
# List of RGB values that correlate to the 380-780 wavelength range. Even though this
# is the exact list from the Cycles code, for some reason it doesn't always match :(
wavelength_list = ((0.0014,0.0000,0.0065), (0.0022,0.0001,0.0105), (0.0042,0.0001,0.0201),
(0.0076,0.0002,0.0362), (0.0143,0.0004,0.0679), (0.0232,0.0006,0.1102),
(0.0435,0.0012,0.2074), (0.0776,0.0022,0.3713), (0.1344,0.0040,0.6456),
(0.2148,0.0073,1.0391), (0.2839,0.0116,1.3856), (0.3285,0.0168,1.6230),
(0.3483,0.0230,1.7471), (0.3481,0.0298,1.7826), (0.3362,0.0380,1.7721),
(0.3187,0.0480,1.7441), (0.2908,0.0600,1.6692), (0.2511,0.0739,1.5281),
(0.1954,0.0910,1.2876), (0.1421,0.1126,1.0419), (0.0956,0.1390,0.8130),
(0.0580,0.1693,0.6162), (0.0320,0.2080,0.4652), (0.0147,0.2586,0.3533),
(0.0049,0.3230,0.2720), (0.0024,0.4073,0.2123), (0.0093,0.5030,0.1582),
(0.0291,0.6082,0.1117), (0.0633,0.7100,0.0782), (0.1096,0.7932,0.0573),
(0.1655,0.8620,0.0422), (0.2257,0.9149,0.0298), (0.2904,0.9540,0.0203),
(0.3597,0.9803,0.0134), (0.4334,0.9950,0.0087), (0.5121,1.0000,0.0057),
(0.5945,0.9950,0.0039), (0.6784,0.9786,0.0027), (0.7621,0.9520,0.0021),
(0.8425,0.9154,0.0018), (0.9163,0.8700,0.0017), (0.9786,0.8163,0.0014),
(1.0263,0.7570,0.0011), (1.0567,0.6949,0.0010), (1.0622,0.6310,0.0008),
(1.0456,0.5668,0.0006), (1.0026,0.5030,0.0003), (0.9384,0.4412,0.0002),
(0.8544,0.3810,0.0002), (0.7514,0.3210,0.0001), (0.6424,0.2650,0.0000),
(0.5419,0.2170,0.0000), (0.4479,0.1750,0.0000), (0.3608,0.1382,0.0000),
(0.2835,0.1070,0.0000), (0.2187,0.0816,0.0000), (0.1649,0.0610,0.0000),
(0.1212,0.0446,0.0000), (0.0874,0.0320,0.0000), (0.0636,0.0232,0.0000),
(0.0468,0.0170,0.0000), (0.0329,0.0119,0.0000), (0.0227,0.0082,0.0000),
(0.0158,0.0057,0.0000), (0.0114,0.0041,0.0000), (0.0081,0.0029,0.0000),
(0.0058,0.0021,0.0000), (0.0041,0.0015,0.0000), (0.0029,0.0010,0.0000),
(0.0020,0.0007,0.0000), (0.0014,0.0005,0.0000), (0.0010,0.0004,0.0000),
(0.0007,0.0002,0.0000), (0.0005,0.0002,0.0000), (0.0003,0.0001,0.0000),
(0.0002,0.0001,0.0000), (0.0002,0.0001,0.0000), (0.0001,0.0000,0.0000),
(0.0001,0.0000,0.0000), (0.0001,0.0000,0.0000), (0.0000,0.0000,0.0000))
# normalize wavelength into a number between 0 and 80 and use it as the index for the list
return wavelength_list[min(80, max(0, int((wavelength - 380) * 0.2)))]
def getHiddenStatus(scene, lights):
statelist = []
temparr = []
for light in lights:
if light[0]:
temparr = [light[0], bpy.data.objects[light[0]].hide, bpy.data.objects[light[0]].hide_render]
statelist.append(temparr)
temparr = ["WorldEnviroLight", scene.GafferWorldVis, scene.GafferWorldReflOnly]
statelist.append(temparr)
scene.GafferLightsHiddenRecord = str(statelist)
def isOnVisibleLayer(obj, scene):
obj_layers = []
for i, layer in enumerate(obj.layers):
if layer == True:
obj_layers.append(i)
scene_layers = []
for i, layer in enumerate(scene.layers):
if layer == True:
scene_layers.append(i)
common = set(obj_layers) & set(scene_layers)
if common:
return True
else:
return False
def dictOfLights():
# Create dict of light name as key with node name as value
lights = stringToNestedList(bpy.context.scene.GafferLights, stripquotes=True)
lights_with_nodes = []
light_dict = {}
if lights:
for light in lights: # TODO check if node still exists
if len(light) > 1:
lights_with_nodes.append(light[0])
lights_with_nodes.append(light[2])
light_dict = dict(lights_with_nodes[i:i + 2] for i in range(0, len(lights_with_nodes), 2))
return light_dict
def setGafferNode(context, nodetype, tree=None, obj=None):
if nodetype == 'STRENGTH':
list_nodeindex = 2
list_socketindex = 3
elif nodetype == 'COLOR':
list_nodeindex = 4
list_socketindex = 5
if tree:
nodetree = tree
else:
nodetree = context.space_data.node_tree
node = nodetree.nodes.active
lights = stringToNestedList(context.scene.GafferLights, stripquotes=True)
if obj == None:
obj = context.object
for light in lights:
# TODO poll for pinned nodetree (active object is not necessarily the one that this tree belongs to)
if light[0] == obj.name:
light[list_nodeindex] = node.name
socket_index = 0
if node.inputs:
for socket in node.inputs:
if socket.type == 'VALUE' and not socket.is_linked: # use first Value socket as strength
light[list_socketindex] = 'i' + str(socket_index)
break
socket_index += 1
break
elif node.outputs:
for socket in node.outputs:
if socket.type == 'VALUE': # use first Value socket as strength
light[list_socketindex] = 'o' + str(socket_index)
break
socket_index += 1
break
# TODO catch if there is no available socket to use
context.scene.GafferLights = str(lights)
def do_update_falloff(self):
light = self
scene = bpy.context.scene
lights = stringToNestedList(scene.GafferLights, stripquotes=True)
lightitems = []
for l in lights:
if l[0] == light.name:
lightitems = l
break
socket_no = 2
falloff = light.GafferFalloff
if falloff == 'linear':
socket_no = 1
elif falloff == 'quadratic':
socket_no = 0
connections = []
if light.type == 'LAMP':
tree = light.data.node_tree
else:
tree = bpy.data.materials[lightitems[1]].node_tree
try:
node = tree.nodes[lightitems[2]]
if node.type == 'LIGHT_FALLOFF':
for outpt in node.outputs:
if outpt.is_linked:
for link in outpt.links:
connections.append(link.to_socket)
for link in connections:
tree.links.new(node.outputs[socket_no], link)
else:
if light.GafferFalloff != 'quadratic': # No point making Light Falloff node if you're setting it to quadratic and a falloff node already exists
fnode = tree.nodes.new('ShaderNodeLightFalloff')
fnode.inputs[0].default_value = node.inputs[int(str(lightitems[3])[-1])].default_value
fnode.location.x = node.location.x - 250
fnode.location.y = node.location.y
tree.links.new(fnode.outputs[socket_no], node.inputs[int(str(lightitems[3])[-1])])
tree.nodes.active = fnode
setGafferNode(bpy.context, 'STRENGTH', tree, light)
hack_force_update(bpy.context, tree.nodes)
except:
print ("Warning: do_update_falloff failed, node may not exist anymore")
def _update_falloff(self, context):
do_update_falloff(self)
def refresh_bgl():
print ("refreshed bgl")
if bpy.context.scene.GafferIsShowingRadius:
bpy.ops.gaffer.show_radius('INVOKE_DEFAULT')
bpy.ops.gaffer.show_radius('INVOKE_DEFAULT')
if bpy.context.scene.GafferIsShowingLabel:
bpy.ops.gaffer.show_label('INVOKE_DEFAULT')
bpy.ops.gaffer.show_label('INVOKE_DEFAULT')
def draw_rect(x1, y1, x2, y2):
# For each quad, the draw order is important. Start with bottom left and go anti-clockwise.
bgl.glBegin(bgl.GL_QUADS)
bgl.glVertex2f(x1,y1)
bgl.glVertex2f(x1,y2)
bgl.glVertex2f(x2,y2)
bgl.glVertex2f(x2,y1)
bgl.glEnd()
def draw_corner(x, y, r, corner):
sides = 16
if corner == 'BL':
r1 = 8
r2 = 12
elif corner == 'TL':
r1 = 4
r2 = 8
elif corner == 'BR':
r1 = 12
r2 = 16
elif corner == 'TR':
r1 = 0
r2 = 4
bgl.glBegin(bgl.GL_TRIANGLE_FAN)
bgl.glVertex2f(x, y)
for i in range(r1, r2+1):
cosine = r * cos(i * 2 * pi / sides) + x
sine = r * sin(i * 2 * pi / sides) + y
bgl.glVertex2f(cosine, sine)
bgl.glEnd()
def draw_rounded_rect(x1, y1, x2, y2, r):
draw_rect(x1, y1, x2, y2) # Main quad
draw_rect(x1-r, y1, x1, y2) # Left edge
draw_rect(x2, y1, x2+r, y2) # Right edge
draw_rect(x1, y2, x2, y2+r) # Top edge
draw_rect(x1, y1-r, x2, y1) # Bottom edge
draw_corner(x1, y1, r, 'BL') # Bottom left
draw_corner(x1, y2, r, 'TL') # Top left
draw_corner(x2, y2, r, 'TR') # Top right
draw_corner(x2, y1, r, 'BR') # Bottom right
'''
OPERATORS
'''
class GafRename(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:")
oldname = ""
def invoke(self, context, event):
self.oldname = self.light
return context.window_manager.invoke_props_popup(self, event)
def execute(self, context):
context.scene.objects[self.oldname].name = self.light
refresh_light_list(context.scene)
return {'FINISHED'}
class GafSetTemp(bpy.types.Operator):
'Set the color temperature to a preset'
bl_idname = 'gaffer.col_temp_preset'
bl_label = 'Color Temperature Preset'
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 == 'LAMP':
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 = col_temp[self.temperature]
return {'FINISHED'}
class GafTempShowList(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.GafferColTempExpand = True
context.scene.GafferLightUIIndex = self.l_index
return {'FINISHED'}
class GafTempHideList(bpy.types.Operator):
'Hide color temperature presets'
bl_idname = 'gaffer.col_temp_hide'
bl_label = 'Hide Presets'
def execute(self, context):
context.scene.GafferColTempExpand = False
return {'FINISHED'}
class GafShowMore(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.GafferMoreExpand
# 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.GafferMoreExpand = exp_list
return {'FINISHED'}
class GafHideMore(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.GafferMoreExpand = context.scene.GafferMoreExpand.replace("_Light:_(" + self.light + ")_", "")
return {'FINISHED'}
class GafHideShowLight(bpy.types.Operator):
'Hide/Show this light (in viewport and in render)'
bl_idname = 'gaffer.hide_light'
bl_label = 'Hide Light'
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 = self.hide
light.hide_render = self.hide
else:
if dataname.startswith('LAMP'):
data = bpy.data.lamps[(dataname[4:])] # actual data name (minus the prepended 'LAMP')
for obj in bpy.data.objects:
if obj.data == data:
obj.hide = self.hide
obj.hide_render = self.hide
else:
mat = bpy.data.materials[(dataname[3:])] # actual data name (minus the prepended 'MAT')
for obj in bpy.data.objects:
if obj.type == 'MESH':
for slot in obj.material_slots:
if slot.material == mat:
obj.hide = self.hide
obj.hide_render = self.hide
return {'FINISHED'}
class GafSelectLight(bpy.types.Operator):
'Select this light'
bl_idname = 'gaffer.select_light'
bl_label = 'Select'
light = bpy.props.StringProperty()
dataname = bpy.props.StringProperty()
@classmethod
def poll(cls, context):
return context.mode == 'OBJECT'
def execute(self, context):
for item in bpy.data.objects:
item.select = False
dataname = self.dataname
if dataname == "__SINGLE_USER__":
obj = bpy.data.objects[self.light]
obj.select = True
context.scene.objects.active = obj
else:
if dataname.startswith('LAMP'):
data = bpy.data.lamps[(dataname[4:])] # actual data name (minus the prepended 'LAMP')
for obj in bpy.data.objects:
if obj.data == data:
obj.select = True
else:
mat = bpy.data.materials[(dataname[3:])] # actual data name (minus the prepended 'MAT')
for obj in bpy.data.objects:
if obj.type == 'MESH':
for slot in obj.material_slots:
if slot.material == mat:
obj.select = True
context.scene.objects.active = bpy.data.objects[self.light]
return {'FINISHED'}
class GafSolo(bpy.types.Operator):
'Hide all other lights but this one'
bl_idname = 'gaffer.solo'
bl_label = 'Solo Light'
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.GafferBlacklist
# Get object names that share data with the solo'd object:
dataname = self.dataname
linked_lights = []
if dataname not in ["__SINGLE_USER__", "__EXIT_SOLO__"] and showhide: # only make list if going into Solo and obj has multiple users
if dataname.startswith('LAMP'):
data = bpy.data.lamps[(dataname[4:])] # actual data name (minus the prepended 'LAMP')
for obj in bpy.data.objects:
if obj.data == data:
linked_lights.append(obj.name)
else:
mat = bpy.data.materials[(dataname[3:])] # actual data name (minus the prepended 'MAT')
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 = stringToNestedList(scene.GafferLightsHiddenRecord, True)
if showhide: # Enter Solo mode
bpy.ops.gaffer.refresh_lights()
scene.GafferSoloActive = light
getHiddenStatus(scene, stringToNestedList(scene.GafferLights, True))
for l in statelist: # first check if lights still exist
if l[0] != "WorldEnviroLight":
try:
obj = bpy.data.objects[l[0]]
except:
# TODO not sure if this ever happens, if it does, doesn't it break?
getHiddenStatus(scene, stringToNestedList(scene.GafferLights, True))
bpy.ops.gaffer.solo()
return {'FINISHED'} # if one of the lights has been deleted/changed, update the list and dont restore visibility
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 = False
obj.hide_render = False
else:
obj.hide = True
obj.hide_render = True
if context.scene.render.engine == 'CYCLES':
if worldsolo:
if not scene.GafferWorldVis:
scene.GafferWorldVis = True
else:
if scene.GafferWorldVis:
scene.GafferWorldVis = False
else: # Exit solo
oldlight = scene.GafferSoloActive
scene.GafferSoloActive = ''
for l in statelist:
if l[0] != "WorldEnviroLight":
try:
obj = bpy.data.objects[l[0]]
except:
# TODO not sure if this ever happens, if it does, doesn't it break?
bpy.ops.gaffer.refresh_lights()
getHiddenStatus(scene, stringToNestedList(scene.GafferLights, True))
scene.GafferSoloActive = oldlight
bpy.ops.gaffer.solo()
return {'FINISHED'}
if obj.name not in blacklist:
obj.hide = castBool(l[1])
obj.hide_render = castBool(l[2])
elif context.scene.render.engine == 'CYCLES':
scene.GafferWorldVis = castBool(l[1])
scene.GafferWorldReflOnly = castBool(l[2])
return {'FINISHED'}
class GafLampUseNodes(bpy.types.Operator):
'Make this lamp use nodes'
bl_idname = 'gaffer.lamp_use_nodes'
bl_label = 'Use Nodes'
light = bpy.props.StringProperty()
def execute(self, context):
obj = bpy.data.objects[self.light]
if obj.type == 'LAMP':
obj.data.use_nodes = True
bpy.ops.gaffer.refresh_lights()
return {'FINISHED'}
class GafNodeSetStrength(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'
@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):
setGafferNode(context, 'STRENGTH')
return {'FINISHED'}
class GafRefreshLightList(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
refresh_light_list(scene)
self.report({'INFO'}, "Light list refreshed")
if scene.GafferSoloActive == '':
getHiddenStatus(scene, stringToNestedList(scene.GafferLights, True))
refresh_bgl() # update the radius/label as well
return {'FINISHED'}
class GafCreateEnviroWidget(bpy.types.Operator):
'Create an Empty which drives the rotation of the background texture'
bl_idname = 'gaffer.envwidget'
bl_label = 'Create Enviro Rotation Widget (EXPERIMENTAL)'
radius = bpy.props.FloatProperty(default = 16.0,
description = "How big the created empty should be (distance from center to edge)")
# TODO add op to delete widget and drivers
# TODO add op to select widget (poll if it exists)
# TODO poll for supported vector input, uses nodes, widget doesn't already exist
'''
This is an experimental function.
It's barely usable at present, but blender lacks a few important things to make it really useful:
Cannot draw bgl over viewport render (can't see what you're doing or interact with a custom widget)
Can't draw a texture on a sphere when the rest of the viewport is solid-shaded
World rotation is pretty weird, doesn't match up to rotation of a 3d sphere
For those reasons, this won't be included in the UI, but the code might as well stay here for future use.
'''
def execute(self, context):
scene = context.scene
nodes = scene.world.node_tree.nodes
# Get mapping nodes
mapping_nodes = []
for node in nodes:
if node.type == 'MAPPING':
mapping_nodes.append(node)
if not mapping_nodes:
pass # TODO handle when no mapping nodes
n = mapping_nodes[0] # use rotation of first mapping node
map_rotation = [n.rotation[0],
n.rotation[1],
n.rotation[2]]
'''
POINT is the default vector type, but rotates inversely to the widget.
Setting the vector type to TEXTURE behaves as expected,
but we must invert the rotation values to keep the same visual rotation.
'''
if n.vector_type == 'POINT':
map_rotation = [i*-1 for i in map_rotation]
widget_data = bpy.data.objects.new("Environment Rotation Widget", None)
scene.objects.link(widget_data)
widget = scene.objects["Environment Rotation Widget"]
widget.location = scene.cursor_location
widget.rotation_euler = map_rotation
widget.empty_draw_type = 'SPHERE'
widget.empty_draw_size = self.radius
widget.layers = scene.layers
# TODO handle if mapping node has drivers or is animated (ask to override or ignore)
for node in mapping_nodes:
node.vector_type = 'TEXTURE'
# TODO check it works when node name includes math (e.g. "mapping*2")
dr = node.driver_add("rotation")
# X axis:
dr[0].driver.type = 'AVERAGE'
var = dr[0].driver.variables.new()
var.name = "x-rotation"
var.type = 'TRANSFORMS'
target = var.targets[0]
target.id = widget
target.transform_type = 'ROT_X'
# Y axis:
dr[1].driver.type = 'AVERAGE'
var = dr[1].driver.variables.new()
var.name = "y-rotation"
var.type = 'TRANSFORMS'
target = var.targets[0]
target.id = widget
target.transform_type = 'ROT_Y'
# Z axis:
dr[2].driver.type = 'AVERAGE'
var = dr[2].driver.variables.new()
var.name = "z-rotation"
var.type = 'TRANSFORMS'
target = var.targets[0]
target.id = widget
target.transform_type = 'ROT_Z'
return {'FINISHED'}
class GafLinkSkyToSun(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]
lampob = bpy.data.objects[context.scene.GafferSunObject]
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
varname = nodename + "_" + str(context.scene.GafferVarNameCounter) # create unique variable name for each node
context.scene.GafferVarNameCounter += 1
dr[0].driver.expression = varname
var = dr[0].driver.variables.new()
var.name = varname
var.type = 'SINGLE_PROP'
var.targets[0].id = lampob
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 = lampob
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 = lampob
var.targets[0].data_path = 'matrix_world[2][2]'
return {'FINISHED'}
class GafShowLightRadius(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