-
Notifications
You must be signed in to change notification settings - Fork 30
/
functions.py
2219 lines (1806 loc) · 77.9 KB
/
functions.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 json
from gpu_extras.batch import batch_for_shader
import os
import math
import time
import datetime
from collections import OrderedDict
from mathutils import Vector, Euler
from bpy.app.handlers import persistent
from . import constants as const
TAG_REFRESH_LIGHT_LIST = False
# Persistent settings functions
def init_persistent_settings(set_name=None, set_value=None):
"""Initialize persistent settings file with option to change a default value"""
settings = {}
# Some settings might already exist
if os.path.exists(const.settings_file):
with open(const.settings_file) as f:
try:
settings = json.load(f)
except json.JSONDecodeError:
settings = {}
# First time use in 2.8, copy path from 2.7
if "hdri_paths" not in settings and "hdri_path" in settings:
settings["hdri_paths"] = [settings["hdri_path"]]
defaults = {"show_hdri_haven": True, "hdri_path": "", "hdri_paths": [""]} # Legacy
for d in defaults:
if d not in settings:
settings[d] = defaults[d]
if set_name is not None:
settings[set_name] = set_value
with open(const.settings_file, "w") as f:
f.write(json.dumps(settings, indent=4))
return settings
def get_persistent_setting(name):
if os.path.exists(const.settings_file):
with open(const.settings_file) as f:
try:
settings = json.load(f)
except json.JSONDecodeError:
settings = {}
if name in settings:
return settings[name]
initial_settings = init_persistent_settings()
return initial_settings[name] if name in initial_settings else None
def set_persistent_setting(name, value):
if not os.path.exists(const.settings_file):
init_persistent_settings(name, value)
else:
with open(const.settings_file) as f:
settings = json.load(f)
settings[name] = value
with open(const.settings_file, "w") as f:
f.write(json.dumps(settings, indent=4))
# Utils
def log(text, timestamp=True, also_print=False):
ts = datetime.datetime.fromtimestamp(time.time()).strftime("%Y-%m-%d %H:%M:%S")
with open(const.log_file, "a") as f:
if also_print:
print(text)
if timestamp:
f.write(ts + " " + text + "\n")
else:
f.write(" " * len(ts) + " " + text + "\n")
def cleanup_logs():
"""Delete log lines that are older than 1 week to keep the file size down"""
if os.path.exists(const.log_file):
with open(const.log_file, "r") as f:
lines = f.readlines()
i = 0 # Where the most recent line is that's older than 7 days
for ln_no, l in enumerate(lines):
try:
d = datetime.datetime.strptime(l[:19], "%Y-%m-%d %H:%M:%S")
except ValueError:
pass
else:
age = time.time() - time.mktime(d.timetuple())
if age / 60 / 60 / 24 > 7:
i = ln_no
else:
break
if i > 0:
new_lines = lines[i + 1 :]
with open(const.log_file, "w") as f:
f.writelines(new_lines)
def hastebin_file(filepath, extra_string=""):
if os.path.exists(filepath):
with open(filepath, "r") as f:
lines = f.read()
from requests import post as requests_post
r = requests_post("https://hastebin.com/documents", lines + "\n" * 4 + extra_string)
url = "https://hastebin.com/" + json.loads(r.content.decode())["key"]
bpy.ops.wm.url_open(url=url)
def dpifac():
prefs = bpy.context.preferences.system
# python access to this was only added recently, assume non-retina display is used if using older blender
if hasattr(prefs, "pixel_size"):
retinafac = bpy.context.preferences.system.pixel_size
else:
retinafac = 1
return bpy.context.preferences.system.dpi / (72 / retinafac)
def time_execution(func):
"""Decorator to log execution time of a function if it takes longer than 100 ms"""
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
execution_time = (end_time - start_time) * 1000 # in milliseconds
if execution_time > 100:
log(f"Function '{func.__name__}' took {execution_time:.2f} ms")
return result
return wrapper
# Light list functions
@time_execution
def refresh_light_list(scene):
def get_next_available_value_socket(node):
current_node = node
found_node = node.name
found_socket = -1
i = 0
max_iterations = 1000 # Prevent infinite loop
while found_socket == -1:
i += 1
if i == max_iterations:
print("Gaffer Warning: Max iterations hit in get_next_available_value_socket for " + node.name)
break
if len(current_node.inputs) == 0:
# End of the line.
break
for si, s in enumerate(current_node.inputs):
if s.type == "VALUE":
if not s.is_linked:
found_node = current_node.name
found_socket = si
break
else:
current_node = s.links[0].from_node
return found_node, found_socket
global TAG_REFRESH_LIGHT_LIST
TAG_REFRESH_LIGHT_LIST = False
detected_lights = []
if not hasattr(bpy.types.Object, "GafferFalloff"):
bpy.types.Object.GafferFalloff = bpy.props.EnumProperty(
name="Light Falloff",
items=(
("constant", "Constant", "No light falloff", "IPO_CONSTANT", 1),
(
"linear",
"Linear",
"Fade light strength linearly over the distance it travels",
"IPO_LINEAR",
2,
),
(
"quadratic",
"Quadratic",
"(Realisic) Light strength is inversely proportional to the square of the distance it travels",
"IPO_QUAD",
3,
),
),
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 in ["CYCLES", "BLENDER_EEVEE", "BLENDER_EEVEE_NEXT"]:
for obj in objects:
light_mats = []
if obj.type == "LIGHT":
if obj.data.use_nodes:
invalid_node = False
if obj.name in light_dict:
if light_dict[obj.name] == "None": # 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:
(
node_name,
socket_index,
) = get_next_available_value_socket(node)
detected_lights.append(
[
obj.name,
None,
node_name,
"i" + str(socket_index),
]
)
break
else:
node = obj.data.node_tree.nodes[light_dict[obj.name]]
if node.inputs:
node_name, socket_index = get_next_available_value_socket(node)
detected_lights.append([obj.name, None, node_name, "i" + str(socket_index)])
elif node.outputs:
socket_index = 0
for oupt in node.outputs:
if oupt.type == "VALUE": # use first Value socket as strength
detected_lights.append(
[
obj.name,
None,
node.name,
"o" + str(socket_index),
]
)
break
socket_index += 1
else:
detected_lights.append([obj.name, None, None])
elif obj.type == "MESH" and len(obj.material_slots) > 0 and scene.render.engine == "CYCLES":
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": # Previously did not use nodes
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:
(
node_name,
socket_index,
) = get_next_available_value_socket(node)
detected_lights.append(
[
obj.name,
slot.material.name,
node_name,
"i" + str(socket_index),
]
)
light_mats.append(slot.material) # Skip this material next time
slot_break = True
break
else:
node = slot.material.node_tree.nodes[light_dict[obj.name]]
if node.inputs:
(
node_name,
socket_index,
) = get_next_available_value_socket(node)
detected_lights.append(
[
obj.name,
slot.material.name,
node_name,
"i" + str(socket_index),
]
)
elif node.outputs:
socket_index = 0
for oupt in node.outputs:
if oupt.type == "VALUE": # use first Value socket as strength
detected_lights.append(
[
obj.name,
slot.material.name,
node.name,
"o" + str(socket_index),
]
)
break
socket_index += 1
else: # Unsupported engines
for obj in objects:
if obj.type == "LIGHT":
detected_lights.append([obj.name, None, None])
for light in detected_lights:
obj = bpy.data.objects[light[0]]
nodes = None
if obj.type == "LIGHT":
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.gaf_props.Lights = str(detected_lights)
if scene.gaf_props.SoloActive == "":
getHiddenStatus(scene, stringToNestedList(scene.gaf_props.Lights, True))
if bpy.context.area:
refresh_bgl() # update the radius/label as well
def force_update(context, obj=None):
if not obj:
context.space_data.node_tree.update_tag()
else:
obj.data.node_tree.update_tag()
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
# Color functions
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 * math.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 * math.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):
# normalize wavelength into a number between 0 and 80 and use it as the index for the list
return const.wavelength_list[min(80, max(0, int((wavelength - 380) * 0.2)))]
# Visibility functions
def getHiddenStatus(scene, lights):
statelist = []
temparr = []
for light in lights:
if light[0]:
temparr = [
light[0],
bpy.data.objects[light[0]].hide_viewport,
bpy.data.objects[light[0]].hide_render,
]
statelist.append(temparr)
temparr = [
"WorldEnviroLight",
scene.gaf_props.WorldVis,
scene.gaf_props.WorldReflOnly,
]
statelist.append(temparr)
scene.gaf_props.LightsHiddenRecord = str(statelist)
def visibleCollections():
def check_child(c, vis_cols):
if c.is_visible:
vis_cols.append(c.collection)
for sc in c.children:
vis_cols = check_child(sc, vis_cols)
return vis_cols
vis_cols = [bpy.context.scene.collection]
for c in bpy.context.window.view_layer.layer_collection.children:
check_child(c, vis_cols)
return vis_cols
def isInVisibleCollection(obj, vis_cols):
for oc in obj.users_collection:
if oc in vis_cols:
return True
return False
# Misc functions
def dictOfLights():
# Create dict of light name as key with node name as value
lights = stringToNestedList(bpy.context.scene.gaf_props.Lights, 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.gaf_props.Lights, stripquotes=True)
if obj is 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.gaf_props.Lights = str(lights)
def do_update_falloff(self):
light = self
scene = bpy.context.scene
lights = stringToNestedList(scene.gaf_props.Lights, 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 == "LIGHT":
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":
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)
force_update(bpy.context, light)
except (KeyError, IndexError, AttributeError):
print("Warning: do_update_falloff failed, node may not exist anymore")
def _update_falloff(self, context):
do_update_falloff(self)
def tag_refresh_light_list():
global TAG_REFRESH_LIGHT_LIST
TAG_REFRESH_LIGHT_LIST = True
def depsgraph_update_includes_all(depsgraph, types):
for id_type in types:
if not depsgraph.id_type_updated(id_type):
return False
return True
@persistent
def depsgraph_update_post_handler(scene, depsgraph):
# Debug mode to see what depsgraph updates are happening
if bpy.app.debug_value == 666:
types_updated = [id_type for id_type in const.depsgraph_id_types if depsgraph.id_type_updated(id_type)]
print("Updated types:", types_updated)
for update in depsgraph.updates:
print(
" Update:",
update.id,
update.is_updated_geometry,
update.is_updated_transform,
update.is_updated_shading,
)
prefs = bpy.context.preferences.addons[__package__].preferences
if prefs.auto_refresh_light_list:
# A light has been added
if depsgraph_update_includes_all(depsgraph, ["COLLECTION", "LIGHT", "OBJECT", "SCENE"]):
log("Gaffer light list auto-refresh triggered by depsgraph update", also_print=True)
refresh_light_list(scene)
return
# A UI draw function has requested a refresh, usually when a light is deleted
global TAG_REFRESH_LIGHT_LIST
if TAG_REFRESH_LIGHT_LIST:
TAG_REFRESH_LIGHT_LIST = False
log("Gaffer light list auto-refresh triggered by TAG_REFRESH_LIGHT_LIST", also_print=True)
refresh_light_list(scene)
# Light has been renamed
if (
depsgraph.id_type_updated("OBJECT")
and len(depsgraph.updates) == 1
and not depsgraph.updates[0].is_updated_transform
and not depsgraph.id_type_updated("SCENE")
):
lights_str = scene.gaf_props.Lights
lights = stringToNestedList(lights_str)
all_objects = {obj.name for obj in bpy.data.objects}
if any(light[0][1:-1] not in all_objects for light in lights):
log("Gaffer light list auto-refresh triggered by light rename", also_print=True)
refresh_light_list(scene)
return
# Keep background mix node blend mode in sync when it should be.
if depsgraph_update_includes_all(depsgraph, ["WORLD", "NODETREE"]):
gaf_hdri_props = scene.world.gaf_hdri_props
context = bpy.context
extra_nodes = any(
[
gaf_hdri_props.hdri_use_jpg_background,
gaf_hdri_props.hdri_use_separate_brightness,
gaf_hdri_props.hdri_use_separate_contrast,
gaf_hdri_props.hdri_use_separate_saturation,
gaf_hdri_props.hdri_use_separate_warmth,
gaf_hdri_props.hdri_use_separate_tint,
gaf_hdri_props.hdri_use_separate_color,
]
)
if not gaf_hdri_props.hdri_use_separate_color and extra_nodes:
n = handler_node(context, "ShaderNodeMix", fetch_only=True)
bn = handler_node(context, "ShaderNodeMix", background=True, fetch_only=True)
if n and bn and n.blend_type != bn.blend_type:
bn.blend_type = n.blend_type
# World vis functions
def do_set_world_refl_only(context):
scene = context.scene
if scene.gaf_props.WorldReflOnly and not scene.gaf_props.WorldVis:
scene.gaf_props.WorldVis = True
scene.gaf_props.WorldReflOnly = True
if scene.gaf_props.WorldVis:
world = scene.world
world.cycles_visibility.glossy = True
world.cycles_visibility.camera = not scene.gaf_props.WorldReflOnly
world.cycles_visibility.diffuse = not scene.gaf_props.WorldReflOnly
world.cycles_visibility.transmission = not scene.gaf_props.WorldReflOnly
world.cycles_visibility.scatter = not scene.gaf_props.WorldReflOnly
world.update_tag()
def _update_world_refl_only(self, context):
do_set_world_refl_only(context)
def do_set_world_vis(context):
scene = context.scene
world = scene.world
if scene.gaf_props.WorldVis:
# Show
try:
previous_state = json.loads(scene.gaf_props.WorldHiddenRecord)
except json.JSONDecodeError:
pass # No previous state
else:
world.cycles_visibility.glossy = previous_state[0]
world.cycles_visibility.camera = previous_state[1]
world.cycles_visibility.diffuse = previous_state[2]
world.cycles_visibility.transmission = previous_state[3]
world.cycles_visibility.scatter = previous_state[4]
else:
# Hide
current_state = json.dumps(
[
world.cycles_visibility.glossy,
world.cycles_visibility.camera,
world.cycles_visibility.diffuse,
world.cycles_visibility.transmission,
world.cycles_visibility.scatter,
]
)
scene.gaf_props.WorldHiddenRecord = current_state
world.cycles_visibility.glossy = False
world.cycles_visibility.camera = False
world.cycles_visibility.diffuse = False
world.cycles_visibility.transmission = False
world.cycles_visibility.scatter = False
world.update_tag()
def _update_world_vis(self, context):
do_set_world_vis(context)
# Drawing functions
def refresh_bgl():
if bpy.context.scene.gaf_props.IsShowingRadius:
bpy.ops.gaffer.show_radius("INVOKE_DEFAULT")
bpy.ops.gaffer.show_radius("INVOKE_DEFAULT")
if bpy.context.scene.gaf_props.IsShowingLabel:
bpy.ops.gaffer.show_label("INVOKE_DEFAULT")
bpy.ops.gaffer.show_label("INVOKE_DEFAULT")
def draw_rect(shader, x1, y1, x2, y2):
verts = ((x1, y1), (x1, y2), (x2, y1), (x2, y2))
indices = ((0, 1, 2), (1, 2, 3))
batch = batch_for_shader(shader, "TRIS", {"pos": verts}, indices=indices)
batch.draw(shader)
def draw_corner(shader, 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
verts = [(x, y)]
for i in range(r1, r2 + 1):
cosine = r * math.cos(i * 2 * math.pi / sides) + x
sine = r * math.sin(i * 2 * math.pi / sides) + y
verts.append((cosine, sine))
indices = []
for i in range(r2 - r1):
indices.append((0, i + 1, i + 2))
batch = batch_for_shader(shader, "TRIS", {"pos": verts}, indices=indices)
batch.draw(shader)
def draw_rounded_rect(shader, x1, y1, x2, y2, r):
draw_rect(shader, x1, y1, x2, y2) # Main quad
draw_rect(shader, x1 - r, y1, x1, y2) # Left edge
draw_rect(shader, x2, y1, x2 + r, y2) # Right edge
draw_rect(shader, x1, y2, x2, y2 + r) # Top edge
draw_rect(shader, x1, y1 - r, x2, y1) # Bottom edge
draw_corner(shader, x1, y1, r, "BL") # Bottom left
draw_corner(shader, x1, y2, r, "TL") # Top left
draw_corner(shader, x2, y2, r, "TR") # Top right
draw_corner(shader, x2, y1, r, "BR") # Bottom right
# HDRI functions
def update_hdri_path(self, context):
hdri_paths = get_persistent_setting("hdri_paths")
for i, hp in enumerate(hdri_paths):
if hp.startswith("//"):
hdri_paths[i] = os.path.abspath(bpy.path.abspath(hp))
# For some reason bpy.path.abspath often still includes some
# relativeness, such as "C:/path/../real_path/to/file.jpg"
# So running os.path.abspath(bpy.path.abspath) should resolve
# to "C:/real_path/to/file.jpg"
detect_hdris(self, context)
get_hdri_haven_list(force_update=True)
def get_hdri_basename(f):
separators = ["_", "-", ".", " "]
fn, ext = os.path.splitext(f)
sep = ""
for c in fn[::-1][:-1]: # Reversed filename to see which separator is last
if c in separators:
sep = c
break
if sep != "":
# Remove all character after the separator - what's left is the hdri name without resolution etc.
hdri_name = sep.join(fn.split(sep)[:-1])
else:
hdri_name = fn
return hdri_name
def polyhaven_asset_lib(context):
"""Get the Poly Haven asset library path if it exists"""
for l in context.preferences.filepaths.asset_libraries:
if l.name.lower() == "poly haven":
return l.path
return None
def paths_are_equal(p1, p2):
"""Check if two paths are equal, regardless of case or slashes"""
if p1 is None or p2 is None:
return False
return os.path.normcase(os.path.normpath(p1)) == os.path.normcase(os.path.normpath(p2))
def path_contains(parent, child):
"""Check if parent contains child, regardless of case or slashes"""
return os.path.normcase(os.path.normpath(child)).startswith(os.path.normcase(os.path.normpath(parent)))
def detect_hdris(self, context):
log("FN: Detect HDRIs")
show_hdrihaven()
hdris = {}
def check_folder_for_HDRIs(path, is_polyhaven_asset_lib=False):
prefs = bpy.context.preferences.addons[__package__].preferences
l_allowed_file_types = const.allowed_file_types
if not prefs.include_8bit:
l_allowed_file_types = const.hdr_file_types
if os.path.exists(path):
files = []
for f in os.listdir(path):
if os.path.isfile(os.path.join(path, f)):
fn, ext = os.path.splitext(f)
if not any([fn.lower().endswith(b) for b in const.thumb_endings]):
if ext.lower() in l_allowed_file_types and not fn.startswith("."):
files.append(f)
else:
if is_polyhaven_asset_lib and f == "textures":
continue # Don't detect exr textures as HDRIs in Poly Haven asset library
if f != "_MACOSX":
check_folder_for_HDRIs(os.path.join(path, f), is_polyhaven_asset_lib)
hdri_file_pairs = []
for f in files:
hdri_name = get_hdri_basename(f)
hdri_file_pairs.append([hdri_name, os.path.join(path, f)])
for h in hdri_file_pairs:
if h[0] in hdris:
hdris[h[0]].append(h[1])
else:
hdris[h[0]] = [h[1]]
hdri_paths = get_persistent_setting("hdri_paths")
if hdri_paths[0] != "":
for hp in hdri_paths:
if not os.path.exists(hp):
continue
check_folder_for_HDRIs(hp, paths_are_equal(polyhaven_asset_lib(context), hp))
# Sort variations by filesize
for h in hdris:
hdris[h] = sorted(hdris[h], key=lambda x: os.path.getsize(x))
# Sort HDRI list alphabetically
hdris = OrderedDict(sorted(hdris.items(), key=lambda x: x[0].lower()))
with open(const.hdri_list_path, "w") as f:
f.write(json.dumps(hdris, indent=4))
const.hdri_list = hdris
if "hdri" in context.scene.world.gaf_hdri_props:
if context.scene.world.gaf_hdri_props["hdri"] >= len(const.hdri_list):
context.scene.world.gaf_hdri_props["hdri"] = 0
refresh_previews()
prefs = bpy.context.preferences.addons[__package__].preferences
prefs.ForcePreviewsRefresh = True
switch_hdri(self, context)
def get_hdri_list(use_search=False):
if os.path.exists(const.hdri_list_path):
with open(const.hdri_list_path) as f:
try:
data = json.load(f)
except json.JSONDecodeError:
data = {}
if data:
data = OrderedDict(sorted(data.items(), key=lambda x: x[0].lower()))
if use_search:
gaf_hdri_props = bpy.context.scene.world.gaf_hdri_props
if gaf_hdri_props.hdri_favorite:
new_data = {name: value for name, value in data.items() if name in get_favorites()}
data = new_data
if gaf_hdri_props.hdri_folder_filter:
new_data = {
name: value
for name, value in data.items()
if path_contains(gaf_hdri_props.hdri_folder_filter, value[0])
}
data = new_data
search_string = gaf_hdri_props.hdri_search
if search_string:
search_string = search_string.replace(",", " ").replace(";", " ")
search_terms = search_string.split(" ")
tags = get_tags()
matched_data = {}
for name in data:
matchables = [name]