-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfuzzy_tools.py
2048 lines (1687 loc) · 71.2 KB
/
fuzzy_tools.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
# SPDX-License-Identifier: GPL-2.0-or-later
bl_info = {
"name" : "Fuzzy Tools",
"author" : "Sacha Goedegebure",
"version" : (3,0,1),
"blender" : (3,6,0),
"location" : "View3d > Sidebar > Fuzzy. Alt+M to move keyframes and markers",
"description" : "Tools for an efficient 1-person pipeline and multi-camera workflow",
"doc_url" : "https://github.com/sagotoons/fuzzytools/wiki",
"tracker_url" : "https://github.com/sagotoons/fuzzytools/issues",
"category" : "Interface",
}
import bpy
import math
from bpy.props import (BoolProperty,
FloatProperty,
IntProperty,
FloatVectorProperty,
EnumProperty,
PointerProperty,
)
from bpy.types import (Panel,
Operator,
PropertyGroup,
)
from math import radians, degrees
from bpy.app.handlers import persistent
# check blender version for Eevee Next
def is_next_version(min_version=(4, 2, 0)):
current_version = bpy.app.version
return current_version >= min_version
# find HDRI studio light when used in Fuzzy World shader during start up
@persistent
def reload_image(dummy):
world = bpy.context.scene.world
nodes = world.node_tree.nodes
if world.name != 'Fuzzy World':
return
try:
node = nodes['World HDRI']
except KeyError: ## for files created with Fuzzy Tools 2.0.0 or older
nodes['Environment Texture'].name = 'World HDRI'
node = nodes['World HDRI']
# remove suffix
name = node.image.name.rsplit('.', 1)[0]
valid_names = {'city', 'courtyard', 'forest', 'interior', 'night', 'studio', 'sunrise', 'sunset'}
if name not in valid_names or node.image.file_format == 'OPEN_EXR':
return
node.image.name = name + "_old"
try:
hdri = bpy.data.images.load(
bpy.context.preferences.studio_lights[name + '.exr'].path, check_existing=True
)
node.image = hdri
except Exception as e:
print(f"Error loading HDRI: {e}")
# handler initialized during render
@persistent
def auto_animate_scene(scene, context):
prop = bpy.context.scene.fuzzy_props
prop.scene_animate = True
bpy.app.handlers.render_init.append(auto_animate_scene)
# handler for removing previous handler during canceling or completing render
@persistent
def disable_animate_scene(scene, context):
prop = bpy.context.scene.fuzzy_props
handlers = bpy.app.handlers.frame_change_post
check_handlers = [handler for handler in handlers if 'check' in str(handler)]
# method below due to unique functions for handlers
if len(check_handlers) == 1:
prop.scene_animate = False
if len(check_handlers) == 2:
prop.scene_animate = False
prop.scene_animate = False
prop.scene_animate = True
bpy.app.handlers.render_cancel.append(disable_animate_scene)
bpy.app.handlers.render_complete.append(disable_animate_scene)
# LIST CHARACTERS
## can ignore when not working with 'Project Fuzzy' characters
## to avoid Error, do not remove list. Optional to replace or remove content of list
character_list = {
'B': 'COLORSET_04_VEC',
'Bo': 'COLORSET_03_VEC',
'Bob': 'COLORSET_11_VEC',
'Bobi': 'COLORSET_05_VEC'
}
# ------------------------------------------------------------------------
# SCENE PROPERTIES
# ------------------------------------------------------------------------
def check(self):
# check motion blur markers
scene = bpy.context.scene
frame = scene.frame_current
markers = scene.timeline_markers
if is_next_version():
version = scene.render
else:
version = scene.eevee
if any(marker.name.startswith('mblur') for marker in markers):
mblur = False
# check mblur markers in reversed order
for k, v in reversed(sorted(markers.items(), key=lambda it: it[1].frame)):
if v.frame <= frame and v.name.startswith('mblur_on'):
version.use_motion_blur = True
val = v.name.strip('mblur_on')
try:
version.motion_blur_shutter = float(val)
except ValueError:
pass
mblur = True
break
elif v.frame <= frame and v.name == 'mblur_off':
version.use_motion_blur = False
mblur = True
break
# check for first mblur marker
if not mblur:
for k, v in sorted(markers.items(), key=lambda it: it[1].frame):
if v.frame >= frame and v.name.startswith('mblur_on'):
version.use_motion_blur = True
val = v.name.strip('mblur_on')
try:
version.motion_blur_shutter = float(val)
except ValueError:
pass
break
elif v.frame >= frame and v.name == 'mblur_off':
version.use_motion_blur = False
break
def check_scene(self, context):
if self.scene_animate:
bpy.app.handlers.frame_change_post.append(check)
else:
bpy.app.handlers.frame_change_post.remove(check)
class FuzzyProperties(PropertyGroup):
scene_animate: BoolProperty(
name='Update Motion Blur',
description="""Update animated motion blur properties in viewport.
Enables automatically during rendering""",
default=False,
update=check_scene
)
fuzzy_color1: FloatVectorProperty(
name="Palette Color 1",
subtype='COLOR',
default=(0.09, 0.17, 1.0),
min=0.0, max=1.0,
)
fuzzy_color2: FloatVectorProperty(
name="Palette Color 2",
subtype='COLOR',
default=(0.02, 0.05, 0.40),
min=0.0, max=1.0,
)
# ------------------------------------------------------------------------
# OPERATOR - Build All
# ------------------------------------------------------------------------
class SCENE_OT_build_all(Operator):
"""Place a camera, floor, sun light and rim light. Create a new Fuzzy World. Optimize Eevee settings.
Replace existing floor and active world, if available.
Delete the default cube, camera, and light"""
bl_idname = "scene.build_all"
bl_label = "Build All"
bl_options = {'UNDO'}
@classmethod
def poll(cls, context):
return context.mode == 'OBJECT'
def execute(self, context):
ops = bpy.ops
ops.object.fuzzy_camera()
ops.mesh.fuzzy_floor()
ops.world.fuzzy_sky()
ops.object.fuzzy_sun()
ops.object.fuzzy_rimlight()
ops.scene.fuzzy_eevee()
self.report({'INFO'}, "POP!")
return {'FINISHED'}
# ------------------------------------------------------------------------
# OPERATOR - Camera
# ------------------------------------------------------------------------
class OBJECT_OT_fuzzy_camera(Operator):
"""Place an optimized camera.
Delete the default camera"""
bl_idname = "object.fuzzy_camera"
bl_label = "Build Camera"
bl_options = {'UNDO'}
@classmethod
def poll(cls, context):
return context.mode == 'OBJECT'
def execute(self, context):
scene = context.scene
objects = scene.objects
objs = bpy.data.objects
# CAMERA PROPERTIES
loc_y = -25
loc_z = 2.5
rot_x = 90
lens = 85
clip_start = 1
clip_end = 250
# Delete default camera
if 'Camera' in objects:
objs.remove(objs["Camera"])
# Add new camera and set rotation
bpy.ops.object.camera_add(rotation=(radians(rot_x), 0, 0))
ob = context.active_object
# List all objects with "CAM." prefix
cams = [obj for obj in objs if obj.name.startswith("CAM.")]
if not cams:
ob.name = "CAM.001"
ob.location = (0, loc_y, loc_z)
else:
# Remove "CAM." from names to leave only numbers + letter
cams_ABC = [s[4:] for s in [obj.name for obj in cams]]
# Remove possible letter suffix
cams_no_ABC = [s[:3] for s in cams_ABC]
# Find the smallest available number
available_numbers = set(range(1, max(map(int, cams_no_ABC)) + 2))
used_numbers = set(map(int, cams_no_ABC))
i = min(available_numbers - used_numbers)
# Change name of camera with increasing number
ob.name = f"CAM.{i:03}"
# Place camera distance away from previous camera's origin
ob.location = (1.5*(-1 + i), loc_y, loc_z)
# create collection 'Cameras' if it doesn't exist yet
link_to_name = 'Cameras'
link_to = scene.collection.children.get(link_to_name)
if link_to is None:
link_to = bpy.data.collections.new(link_to_name)
scene.collection.children.link(link_to)
# link new camera to collection 'Cameras'
oldcoll = ob.users_collection[0]
if oldcoll.name == 'Scene Collection':
context.collection.objects.unlink(ob)
else:
oldcoll.objects.unlink(ob)
bpy.data.collections['Cameras'].objects.link(ob)
ob.show_name = True
data = ob.data
data.name = ob.name
# optimize camera settings
data.show_limits = False
data.show_name = True
data.clip_start = clip_start
data.clip_end = clip_end
data.lens = lens
data.passepartout_alpha = 0.8
data.dof.focus_distance = abs(loc_y)
# make new camera active
objects = context.view_layer.objects
try:
if ob.name in objects:
objects.active = ob
except RuntimeError:
pass
self.report({'INFO'}, f"Camera '{ob.name}' added to scene")
return {'FINISHED'}
# ------------------------------------------------------------------------
# OPERATOR - Fuzzy floor (shadow only)
# ------------------------------------------------------------------------
class MESH_OT_fuzzy_floor(Operator):
"""Place a floor with shadow only and replace the old one.
Delete the default cube"""
bl_idname = "mesh.fuzzy_floor"
bl_label = "Build Floor"
bl_options = {'UNDO'}
@classmethod
def poll(cls, context):
return context.mode == 'OBJECT'
def execute(self, context):
scene = context.scene
objects = scene.objects
# delete objects
for name in ["Cube", "Fuzzy floor", "floor normal"]:
if name in objects:
obj = bpy.data.objects[name]
if name == "Cube":
if hasattr(obj.data, 'polygons') and len(obj.data.polygons) == 6:
bpy.data.objects.remove(obj)
else:
bpy.data.objects.remove(obj)
# add floor
bpy.ops.mesh.primitive_plane_add(size=60, location=(0, 0, 0))
# name new Plane 'Fuzzy floor'
floor = context.active_object
floor.name = "Fuzzy floor"
# create collection 'Set' if it doesn't exist yet
link_to_name = 'Set'
try:
link_to = scene.collection.children[link_to_name]
except KeyError:
link_to = bpy.data.collections.new(link_to_name)
scene.collection.children.link(link_to)
# link floor to collection 'Set'
oldcoll = floor.users_collection[0]
if oldcoll.name == 'Scene Collection':
context.collection.objects.unlink(floor)
else:
oldcoll.objects.unlink(floor)
bpy.data.collections['Set'].objects.link(floor)
# create empty as Target for floor Normal Edit modifier
bpy.ops.object.empty_add(location=(15, -20, 20))
empty = context.object
empty.name = "floor normal"
empty.empty_display_size = 6
empty.empty_display_type = 'SINGLE_ARROW'
link_to_name = 'Set'
track = empty.constraints.new('DAMPED_TRACK')
track.target = floor
track.track_axis = 'TRACK_Z'
# link empty to collection 'Set'
oldcoll = empty.users_collection[0].name
if oldcoll == 'Scene Collection':
context.collection.objects.unlink(empty)
else:
bpy.data.collections[oldcoll].objects.unlink(empty)
bpy.data.collections['Set'].objects.link(empty)
# objects settings ## error exception added for blender 4.1
try:
floor.data.use_auto_smooth = True
except AttributeError:
pass
# create modifier 'Normal Edit' and set empty as Target
normal = floor.modifiers.new("Normal Direction", 'NORMAL_EDIT')
normal.mode = 'DIRECTIONAL'
normal.use_direction_parallel = True
normal.target = bpy.data.objects["floor normal"]
normal.no_polynors_fix = True
# object settings
floor.hide_select = True
floor.show_wire = True
# Get material
oldmat = bpy.data.materials.get("floor_shadow")
if oldmat is not None:
oldmat.name = "floor_shadow_old"
# create material
mat = bpy.data.materials.new(name="floor_shadow")
# Assign it to object
if floor.data.materials:
# assign to 1st material slot
floor.data.materials[0] = mat
else:
# no slots
floor.data.materials.append(mat)
mat.use_nodes = True
# build node shader
nodes = bpy.data.materials['floor_shadow'].node_tree.nodes
nodes.remove(nodes.get('Principled BSDF'))
matoutput = nodes.get("Material Output")
matoutput.location = (600, 80)
matoutput.target = 'EEVEE'
mixshader = nodes.new("ShaderNodeMixShader")
mixshader.location = (200, 60)
shadow = nodes.new("ShaderNodeBsdfDiffuse")
shadow.location = (0, 10)
shadow.inputs[0].default_value = (0, 0, 0, 1)
holdout = nodes.new("ShaderNodeHoldout")
holdout.location = (-200, -160)
clamp_shadow = nodes.new("ShaderNodeClamp")
clamp_shadow.location = (-200, 240)
mix_AO = nodes.new("ShaderNodeMixRGB")
mix_AO.location = (-570, 100)
mix_AO.inputs[0].default_value = 0.7
mix_AO.blend_type = 'MULTIPLY'
mix_AO.mute = True
shader_RGB = nodes.new("ShaderNodeShaderToRGB")
shader_RGB.location = (-770, 0)
diffuse = nodes.new("ShaderNodeBsdfDiffuse")
diffuse.location = (-970, -100)
diffuse.inputs[0].default_value = (1, 1, 1, 1)
dodge_floor = nodes.new("ShaderNodeMixRGB")
dodge_floor.location = (-380, 60)
dodge_floor.inputs[0].default_value = 1
dodge_floor.blend_type = 'DODGE'
power = nodes.new("ShaderNodeMath")
power.location = (0, 180)
power.operation = 'POWER'
power.use_clamp = True
value = nodes.new("ShaderNodeMath")
value.name = "Shadow Value"
value.location = (-200, 60)
value.operation = 'MULTIPLY_ADD'
value.inputs[0].default_value = 0
value.inputs[1].default_value = -1
value.inputs[2].default_value = 1
value_dodge = nodes.new("ShaderNodeMix")
value_dodge.name = "Dodge Value"
value_dodge.location = (-570, -150)
value_dodge.inputs[0].default_value = 0.1
value_dodge.inputs[3].default_value = 1
value_clamp = nodes.new("ShaderNodeMix")
value_clamp.name = "Clamp Value"
value_clamp.location = (-380, 260)
value_clamp.inputs[0].default_value = 0.1
value_clamp.inputs[3].default_value = 1
alpha_mix = nodes.new("ShaderNodeMixShader")
alpha_mix.name = "Floor Alpha"
alpha_mix.location = (0, -160)
BG_group = nodes.new("ShaderNodeGroup")
BG_group.name = "Floor Group"
BG_group.location = (-200, -260)
# check for Fuzzy BG node group
BG = 'Fuzzy BG'
groups = bpy.data.node_groups
if BG not in groups:
alpha_mix.inputs[0].default_value = 0.0
else:
alpha_mix.inputs[0].default_value = 1.0
BG_group.node_tree = groups[BG]
# link nodes
link = mat.node_tree.links.new
link(mixshader.outputs[0], matoutput.inputs[0])
link(shadow.outputs[0], mixshader.inputs[1])
link(holdout.outputs[0], alpha_mix.inputs[1])
link(alpha_mix.outputs[0], mixshader.inputs[2])
link(clamp_shadow.outputs[0], power.inputs[0])
link(mix_AO.outputs[0], dodge_floor.inputs[1])
link(value.outputs[0], power.inputs[1])
link(power.outputs[0], mixshader.inputs[0])
link(shader_RGB.outputs[0], mix_AO.inputs[1])
link(diffuse.outputs[0], shader_RGB.inputs[0])
link(dodge_floor.outputs[0], clamp_shadow.inputs[0])
link(value_dodge.outputs[0], dodge_floor.inputs[2])
link(value_clamp.outputs[0], clamp_shadow.inputs[1])
if BG in groups:
link(BG_group.outputs[0], alpha_mix.inputs[2])
# material settings
mat.use_backface_culling = True
mat.blend_method = 'BLEND'
# cycles material nodes
matoutput2 = nodes.new("ShaderNodeOutputMaterial")
matoutput2.location = (400, -80)
matoutput2.target = 'CYCLES'
link(diffuse.outputs[0], matoutput2.inputs[0])
# cycles material settings
floor.is_shadow_catcher = True
floor.visible_diffuse = False
floor.visible_glossy = False
floor.visible_transmission = False
# viewport settings
space = context.space_data
space.overlay.show_relationship_lines = False
# 4.2 or above
if is_next_version():
mix_AO.mute = False
mix_AO.name = "AO Factor"
AO = nodes.new("ShaderNodeAmbientOcclusion")
AO.name = "AO"
AO.location = (-770, 230)
AO.inputs[1].default_value = 1.6
link(AO.outputs[1], mix_AO.inputs[2])
mixshader2 = nodes.new("ShaderNodeMixShader")
mixshader2.location = (400, 60)
link(mixshader.outputs[0], mixshader2.inputs[1])
link(mixshader2.outputs[0], matoutput.inputs[0])
lightpath = nodes.new("ShaderNodeLightPath")
lightpath.location = (200, 140)
for output in lightpath.outputs:
output.hide = True
link(lightpath.outputs[1], mixshader2.inputs[0])
transp = nodes.new("ShaderNodeBsdfTransparent")
transp.location = (200, -80)
link(transp.outputs[0], mixshader2.inputs[2])
else:
mat.shadow_method = 'NONE'
self.report({'INFO'}, f"'{floor.name}' and '{empty.name}' added to scene")
return {'FINISHED'}
# ------------------------------------------------------------------------
# OPERATOR - World (Sky)
# ------------------------------------------------------------------------
class WORLD_OT_fuzzy_sky(Operator):
"""Create a new world and replace the active one"""
bl_idname = "world.fuzzy_sky"
bl_label = "New Fuzzy Sky"
bl_options = {'UNDO'}
@classmethod
def poll(cls, context):
return context.mode == 'OBJECT'
def execute(self, context):
scene = context.scene
# rename "Fuzzy World" if it exists
if "Fuzzy World" in bpy.data.worlds:
bpy.data.worlds['Fuzzy World'].name = 'Old World'
else:
pass
# create "Fuzzy World", make it scene world & enable Use Nodes
bpy.data.worlds.new("Fuzzy World")
scene.world = bpy.data.worlds['Fuzzy World']
scene.world.use_nodes = True
# build node shader
nodes = scene.world.node_tree.nodes
nodes.remove(nodes.get('Background'))
# HDR nodes
worldoutput = nodes.get("World Output")
worldoutput.location = (900, 50)
# dictionary
ref = {}
# list with ref_name, name, type, locx, locy
node_list = [
('texcoord1', "Texture Coordinate", "TexCoord", -1000, 440), # row 1
('mapskytex1',"Mapping", "Mapping", -800, 440), # row 2
('mapskytex2',"HDRI Rotation", "Mapping", -600, 440), # row 3
('clamprefl', "Clamp Reflection", "Value", -600, 60),
('multiply', "Multiply", "Math", -600, -40),
('skytex', "World HDRI", "TexEnvironment", -400, 400), # row 4
('greater', "Greater Than", "Math", -400, 160),
('lightpath', "Light Path", "LightPath", -400, -40),
('sepHSV', "Separate Color", "SeparateColor", -100, 400), # row 5
('darken', "Darken", "MixRGB", -100, 240),
('mixrefl', "Mix Reflection", "MixRGB", 100, 400), #row6
('comHSV', "Combine Color", "CombineColor", 300, 400), #row7
('BG1', "HDRI Strength", "Background", 500, 160), #row8
('BG2', "Background", "Background", 500, -100),
('mixshader',"Mix Shader", "MixShader", 700, 60), #row9
]
# create nodes
for ref_name, name, type, locx, locy in node_list:
node = nodes.new("ShaderNode"+type)
node.location = (locx, locy)
node.label = name
node.name = name
# Save ref_name in dictionary
ref[ref_name] = node
# extra node properties
ref['mapskytex1'].inputs[2].default_value[2] = radians(90)
ref['clamprefl'].outputs[0].default_value = 2
ref['multiply'].operation = 'MULTIPLY'
ref['multiply'].inputs[1].default_value = 10
ref['greater'].operation = 'GREATER_THAN'
ref['greater'].inputs[1].default_value = 0
for output in ref['lightpath'].outputs:
output.hide = True
ref['sepHSV'].mode = 'HSV'
ref['darken'].blend_type = 'DARKEN'
ref['comHSV'].mode = 'HSV'
# connect nodes
link = scene.world.node_tree.links.new
link(ref['texcoord1'].outputs[0], ref['mapskytex1'].inputs[0])
link(ref['mapskytex1'].outputs[0], ref['mapskytex2'].inputs[0])
link(ref['mapskytex2'].outputs[0], ref['skytex'].inputs[0])
link(ref['clamprefl'].outputs[0], ref['multiply'].inputs[0])
link(ref['clamprefl'].outputs[0], ref['greater'].inputs[0])
link(ref['multiply'].outputs[0], ref['darken'].inputs[2])
link(ref['skytex'].outputs[0], ref['sepHSV'].inputs[0])
link(ref['greater'].outputs[0], ref['mixrefl'].inputs[0])
link(ref['lightpath'].outputs[3], ref['darken'].inputs[0])
link(ref['lightpath'].outputs[0], ref['mixshader'].inputs[0])
for i in range(2):
link(ref['sepHSV'].outputs[i], ref['comHSV'].inputs[i])
link(ref['sepHSV'].outputs[2], ref['darken'].inputs[1])
link(ref['sepHSV'].outputs[2], ref['mixrefl'].inputs[1])
link(ref['darken'].outputs[0], ref['mixrefl'].inputs[2])
link(ref['mixrefl'].outputs[0], ref['comHSV'].inputs[2])
link(ref['comHSV'].outputs[0], ref['BG1'].inputs[0])
link(ref['BG1'].outputs[0], ref['mixshader'].inputs[1])
link(ref['BG2'].outputs[0], ref['mixshader'].inputs[2])
link(ref['mixshader'].outputs[0], worldoutput.inputs[0])
# load the texture from Blender data folder
hdri = bpy.data.images.load(
context.preferences.studio_lights['sunset.exr'].path, check_existing=True)
ref['skytex'].image = hdri
# check for Fuzzy BG node group and remove
BG = 'Fuzzy BG'
groups = bpy.data.node_groups
if BG in groups:
groups.remove(groups[BG])
# create Fuzzy BG node group
BG_group = groups.new(BG, 'ShaderNodeTree')
if bpy.app.version_string.startswith('3'):
BG_group.outputs.new('NodeSocketColor', "Color")
else:
BG_group.interface.new_socket("Color", in_out='OUTPUT',
socket_type='NodeSocketColor')
# create empty group node and apply Fuzzy BG
group = nodes.new("ShaderNodeGroup")
group.location = (300, -100)
group.name = "BG Group"
group.node_tree = BG_group
# BG group nodes
nodes = BG_group.nodes
# dictionary
ref = {}
# list with ref_name, name, type, locx, locy
node_list = [
('texcoord2', "Tex Coord", "TexCoord", -1860, -100), # row 1
('gradscale', "Scale Gradient", "Mix", -1860, -500),
('radialloc', "Radial Location", "VectorMath", -1650, 220), # row 2
('radialscale', "Radial Scale", "VectorMath", -1650, -40),
('vectrans', "", "VectorTransform", -1650, -300),
('power', "", "Math", -1650, -480),
('mapsphere', "", "Mapping", -1450, 50), # row 3
('divide', "", "MixRGB", -1450, -350),
('maplinear3d', "", "Mapping", -1250, -400), # row 4
('maplinear', "", "Mapping", -1250, -30),
('gradsphere', "", "TexGradient", -1050, -80), #row5
('window3d', "Window to 3D", "MixRGB", -1050, -240),
('invert', "", "Invert", -880, -80), #row6
('gradlinear', "Gradient Linear", "TexGradient", -880, -240),
('rampradial', "Radial Ease", "ValToRGB", -700, 20), #row7
('ramplinear', "Linear Ease", "ValToRGB", -700, -200),
('col1', "BG Color 1", "RGB", -680, -440),
('col2', "BG Color 2", "RGB", -680, -640),
('linear2ease', "Linear Ease", "Mix", -420, -200), #row8
('swapcol1', "Swap Colors 1", "MixRGB", -420, -440),
('swapcol2', "Swap Colors 2", "MixRGB", -420, -640),
('radial2linear', "Radial to Linear", "MixRGB", -220, -80), #row9
('colgradient', "Color Gradient", "MixRGB",-40, -300), #row10
('flat2gradient', "Flat to Gradient", "MixRGB", 140, -100), #row11
]
# create nodes
for ref_name, name, type, locx, locy in node_list:
node = nodes.new("ShaderNode"+type)
node.location = (locx, locy)
node.label = name
node.name = name
# Save ref_name in dictionary
ref[ref_name] = node
# extra node properties
ref['radialloc'].inputs[1].default_value = (0.5, 0.5, 0)
ref['radialscale'].operation = 'MULTIPLY'
ref['radialscale'].inputs[0].default_value = (1, 1, 0)
ref['radialscale'].inputs[1].default_value = (0.71, 0.71, 1)
ref['divide'].blend_type = 'DIVIDE'
ref['divide'].inputs[0].default_value = 1
ref['gradscale'].inputs[2].default_value = 0.001
ref['gradscale'].inputs[3].default_value = 1
ref['gradsphere'].gradient_type = 'SPHERICAL'
ref['maplinear'].inputs[2].default_value[2] = 1.5708
ref['maplinear'].vector_type = 'TEXTURE'
ref['maplinear3d'].inputs[1].default_value[2] = -0.5
ref['maplinear3d'].inputs[2].default_value[1] = -1.5708
ref['maplinear3d'].vector_type = 'TEXTURE'
ref['mapsphere'].vector_type = 'TEXTURE'
ref['power'].inputs[1].default_value = 2
ref['power'].operation = 'POWER'
ref['ramplinear'].color_ramp.interpolation = "EASE"
ref['rampradial'].color_ramp.interpolation = "EASE"
ref['col1'].outputs[0].default_value = (0.09, 0.17, 1, 1)
ref['col2'].outputs[0].default_value = (0.02, 0.05, 0.40, 1)
ref['vectrans'].convert_from = 'CAMERA'
ref['vectrans'].convert_to = 'WORLD'
ref['vectrans'].vector_type = 'NORMAL'
# output node
output = nodes.new("NodeGroupOutput")
output.location = (340, -100)
switches = [
("Color Swap", -880, -600, True),
("Flat Gradient", -40, -100, True),
("Radial Linear", -420, -40, False),
("Window Global", -1450, -560, False),
]
for name, locx, locy, clamp in switches:
switch = nodes.new("ShaderNodeMix")
switch.location = (locx, locy)
switch.name = name
switch.label = name
switch.clamp_factor = clamp
switch.inputs[0].default_value = -1
switch.inputs[2].default_value = 1
switch.inputs[3].default_value = 2
for input in switch.inputs:
input.hide = True
# connect nodes
link(group.outputs[0], scene.world.node_tree.nodes['Background'].inputs[0])
# connect group nodes
link = BG_group.links.new
node_links = {
'radialloc': [('mapsphere', 1)],
'radialscale': [('mapsphere', 3)],
'colgradient': [('flat2gradient', 2)],
'divide': [('maplinear3d', 0)],
'gradlinear': [('ramplinear', 0), ('linear2ease', 2)],
'gradsphere': [('invert', 1)],
'gradscale': [('power', 0)],
'invert': [('rampradial', 0)],
'linear2ease': [('radial2linear', 2)],
'maplinear': [('window3d', 1)],
'maplinear3d': [('window3d', 2)],
'mapsphere': [('gradsphere', 0)],
'power': [('divide', 2)],
'radial2linear': [('colgradient', 0)],
'ramplinear': [('linear2ease', 3)],
'rampradial': [('radial2linear', 1)],
'col1': [('swapcol1', 2), ('swapcol2', 1)],
'col2': [('swapcol1', 1), ('swapcol2', 2)],
'swapcol1': [('colgradient', 1), ('flat2gradient', 1)],
'swapcol2': [('colgradient', 2)],
'vectrans': [('divide', 1)],
'window3d': [('gradlinear', 0)],
}
for name, targets in node_links.items():
for target, input_index in targets:
link(ref[name].outputs[0], ref[target].inputs[input_index])
# remaining links
link(ref['flat2gradient'].outputs[0], output.inputs[0])
link(ref['texcoord2'].outputs[4], ref['vectrans'].inputs[0])
link(ref['texcoord2'].outputs[5], ref['mapsphere'].inputs[0])
link(ref['texcoord2'].outputs[5], ref['maplinear'].inputs[0])
switch_links = {
'Color Swap': ['swapcol1', 'swapcol2'],
'Flat Gradient': ['flat2gradient'],
'Radial Linear': ['radial2linear'],
'Window Global': ['linear2ease', 'window3d'],
}
for name, targets in switch_links.items():
for target in targets:
link(nodes[name].outputs[0], ref[target].inputs[0])
# check for Fuzzy Floor and set Fuzzy BG node group
obj = bpy.data.objects
if 'Fuzzy floor' in obj:
tree = bpy.data.materials['floor_shadow'].node_tree
floor_group = tree.nodes['Floor Group']
floor_alpha = tree.nodes['Floor Alpha']
floor_group.node_tree = BG_group
tree.links.new(floor_group.outputs[0], floor_alpha.inputs[2])
floor_alpha.inputs[0].default_value = 1.0
self.report({'INFO'}, "World 'Fuzzy World' created")
return {'FINISHED'}
# ------------------------------------------------------------------------
# OPERATOR - Sun
# ------------------------------------------------------------------------
class OBJECT_OT_fuzzy_sun(Operator):
"""Place an optimized sun light.
Delete the default light"""
bl_idname = "object.fuzzy_sun"
bl_label = "Build Sun"
bl_options = {'UNDO'}
@classmethod
def poll(cls, context):
return context.mode == 'OBJECT'
def execute(self, context):
scene = context.scene
objects = scene.objects
objs = bpy.data.objects
# list of current Sun lights
suns = [obj for obj in objects if obj.type == 'LIGHT' and obj.name.startswith('Sun')]
if 'Light' in objects:
objs.remove(objs["Light"])
# add sun light
bpy.ops.object.light_add(
type='SUN', align='WORLD', location=(20+len(suns), -10, 10))
# name new light 'Sun'
ob = context.active_object
if len(suns) == 0:
ob.name = "Sun"
else:
v = str(len(suns)).zfill(3)
ob.name = f"Sun.{v}"
ob.data.name = ob.name
# create collection 'Set' if it doesn't exist yet
link_to_name = 'Set'
try:
link_to = scene.collection.children[link_to_name]
except KeyError:
link_to = bpy.data.collections.new(link_to_name)
scene.collection.children.link(link_to)
# link new light to collection 'Set'
oldcoll = ob.users_collection[0].name
if oldcoll == 'Scene Collection':
context.collection.objects.unlink(ob)
else:
bpy.data.collections[oldcoll].objects.unlink(ob)
bpy.data.collections['Set'].objects.link(ob)
# light rotation
ob.rotation_euler = (radians(50), 0, radians(40))
# light settings
ob.data.energy = 1.5
ob.data.angle = radians(15)
## EEVEE NEXT
if is_next_version():
ob.data.use_shadow_jitter = True
else:
ob.data.use_contact_shadow = True
# make new Sun active
objects = context.view_layer.objects
try:
if ob.name in objects:
objects.active = ob
except RuntimeError:
pass
self.report({'INFO'}, f"'{ob.name}' added to scene")
return {'FINISHED'}
# ------------------------------------------------------------------------
# OPERATOR - Rim Light
# ------------------------------------------------------------------------
class OBJECT_OT_fuzzy_rimlight(Operator):
"""Place an optimized rim light"""
bl_idname = "object.fuzzy_rimlight"
bl_label = "Build Rim Light"
bl_options = {'UNDO'}
@classmethod
def poll(cls, context):
return context.mode == 'OBJECT'
def execute(self, context):
scene = context.scene
objects = scene.objects
objs = bpy.data.objects
# list of current rim lights
rimlights = [obj for obj in objects if obj.type == 'LIGHT' and obj.name.startswith('RimLight')]
# add sun light
bpy.ops.object.light_add(
type='SUN', align='WORLD', location=(-20-len(rimlights), 10, 10))
# name new light 'RimLight'
ob = context.active_object
if len(rimlights) == 0:
ob.name = "RimLight"
else:
v = str(len(rimlights)).zfill(3)
ob.name = f"RimLight.{v}"
ob.data.name = ob.name
# create collection 'Set' if it doesn't exist yet
link_to_name = 'Set'
link_to = scene.collection.children.get(link_to_name)
if link_to is None:
link_to = bpy.data.collections.new(link_to_name)
scene.collection.children.link(link_to)
oldcoll = ob.users_collection[0].name
if oldcoll == 'Scene Collection':
context.collection.objects.unlink(ob)
else:
bpy.data.collections[oldcoll].objects.unlink(ob)
bpy.data.collections['Set'].objects.link(ob)
# light rotation
ob.rotation_euler = (radians(65), 0, radians(-155))
# light settings
ob.data.energy = 5
ob.data.specular_factor = 0.1
ob.data.angle = radians(10)
## EEVEE NEXT
if is_next_version():
ob.data.use_shadow_jitter = True
else:
ob.data.use_contact_shadow = True
# make new Rim Light active
objects = context.view_layer.objects
try:
if ob.name in objects:
objects.active = ob
except RuntimeError:
pass
self.report({'INFO'}, f"'{ob.name}' added to scene")
return {'FINISHED'}