-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathLightEditor.py
More file actions
2496 lines (2269 loc) · 117 KB
/
Copy pathLightEditor.py
File metadata and controls
2496 lines (2269 loc) · 117 KB
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
import bpy
import fnmatch
from bpy.props import (
BoolProperty,
IntProperty,
FloatProperty,
StringProperty,
EnumProperty,
PointerProperty
)
from bpy.app.handlers import persistent
from bpy.app.translations import contexts as i18n_contexts
import re, os
# --- Global State Tracking (UI visuals, operator states) ---
isolate_env_header_state = False
isolate_env_surface_state = False
isolate_env_volume_state = False
current_active_light = None
current_exclusive_group = None
group_checkbox_1_state = {}
group_lights_original_state = {}
group_collapse_dict = {}
collections_with_lights = {}
group_checkbox_2_state = {}
other_groups_original_state = {}
emissive_material_cache = {}
group_mat_checkbox_state = {}
environment_checkbox_state = {'environment': True}
_surface_link_backup = None
_volume_link_backup = None
_light_isolate_state_backup = {}
emissive_isolate_icon_state = {}
_emissive_link_backup = {}
# Re-entrancy guard: set while the depsgraph handler reconciles light_enabled
# from hide_viewport/hide_render, so update_light_enabled() doesn't write the
# flags straight back and couple the two together.
_syncing_visibility = False
def is_blender_4_5_or_higher():
"""Check if the Blender version is 4.5 or higher."""
return bpy.app.version >= (4, 5, 0)
# --- New Unified Isolate System ---
class UnifiedOnOffManager:
def __init__(self):
# Backups for lights, emissive‐socket values, and environment links
self._light_backup = {}
self._material_backup = {}
self._env_backup = {}
def force_all_off(self, context, except_mode=None, except_identifier=None):
"""
Turn off every light, every emissive socket (Emission nodes & Principled BSDF emission),
and the world shader, except for the single item identified by (except_mode, except_identifier).
"""
# --- Backup & disable all lights except the isolated one ---
keep_lights = set()
if except_mode in {UnifiedIsolateMode.LIGHT_ROW, UnifiedIsolateMode.LIGHT_GROUP} and except_identifier:
keep_lights = except_identifier[0]
for obj in bpy.data.objects:
if obj.type == 'LIGHT':
# backup
self._light_backup[obj.name] = (
obj.hide_viewport, obj.hide_render, getattr(obj, "light_enabled", True)
)
if obj.name not in keep_lights:
obj.hide_viewport = True
obj.hide_render = True
obj.light_enabled = False
# --- Disable all emissive sockets except the isolated one ---
for mat in bpy.data.materials:
if not mat.use_nodes:
continue
for node in mat.node_tree.nodes:
# catch both pure Emission nodes and Principled BSDF emission sockets
strength_socket = node.inputs.get("Strength") or node.inputs.get("Emission Strength")
if not strength_socket:
continue
ident = (mat.name, node.name)
if not (except_mode == UnifiedIsolateMode.MATERIAL and except_identifier == ident):
# backup & disable
self._material_backup[ident] = strength_socket.default_value
strength_socket.default_value = 0.0
# --- Disconnect world Surface & Volume ---
world = context.scene.world
if world and world.use_nodes:
nt = world.node_tree
output = next((n for n in nt.nodes if n.type == 'OUTPUT_WORLD'), None)
if output:
for name in ("Surface", "Volume"):
sock = output.inputs.get(name)
if sock and sock.is_linked and sock.links:
link = sock.links[0]
self._env_backup[name] = (link.from_node.name, link.from_socket.name)
nt.links.remove(link)
# --- Redraw all areas ---
for area in context.screen.areas:
area.tag_redraw()
def restore_all(self):
"""Restore lights, emissive‐socket values, and world links from backup."""
# Restore lights
for obj in bpy.data.objects:
if obj.type == 'LIGHT' and obj.name in self._light_backup:
vp, rp, en = self._light_backup[obj.name]
obj.hide_viewport = vp
obj.hide_render = rp
obj.light_enabled = en
# Restore emissive sockets
for ident, val in self._material_backup.items():
mat_name, node_name = ident
mat = bpy.data.materials.get(mat_name)
if not mat or not mat.use_nodes:
continue
node = mat.node_tree.nodes.get(node_name)
if not node:
continue
strength_socket = node.inputs.get("Strength") or node.inputs.get("Emission Strength")
if strength_socket:
strength_socket.default_value = val
# Restore world links
world = bpy.context.scene.world
if world and world.use_nodes:
nt = world.node_tree
output = next((n for n in nt.nodes if n.type == 'OUTPUT_WORLD'), None)
if output:
for name, (from_n, from_s) in self._env_backup.items():
src = nt.nodes.get(from_n)
dst = output.inputs.get(name)
if src and dst and not dst.is_linked:
out_sock = src.outputs.get(from_s)
if out_sock:
nt.links.new(out_sock, dst)
# Clear backups
self._light_backup.clear()
self._material_backup.clear()
self._env_backup.clear()
class UnifiedIsolateMode:
"""Enum for different isolation modes."""
LIGHT_GROUP = "LIGHT_GROUP"
LIGHT_ROW = "LIGHT_ROW"
MATERIAL = "MATERIAL"
ENVIRONMENT = "ENVIRONMENT"
MATERIAL_GROUP = "MATERIAL_GROUP"
ENVIRONMENT_SURFACE = "ENVIRONMENT_SURFACE"
ENVIRONMENT_VOLUME = "ENVIRONMENT_VOLUME"
class UnifiedIsolateManager:
def __init__(self):
self._backup = {}
self._active_mode = None
self._active_identifier = None
def _redraw_areas(self, context):
for area in context.screen.areas:
if area.type in {'VIEW_3D', 'NODE_EDITOR', 'PROPERTIES'}:
area.tag_redraw()
def is_active(self, mode=None, identifier=None):
if mode is None:
return self._active_mode is not None
if identifier is None:
return self._active_mode == mode
return self._active_mode == mode and self._active_identifier == identifier
def get_active_info(self):
return self._active_mode, self._active_identifier
def activate(self, context, mode, identifier=None):
self._backup.clear()
self._active_mode = mode
self._active_identifier = identifier
# Initialize backup for all relevant states
for obj in context.view_layer.objects:
if obj.type == 'LIGHT':
self._backup[obj.name] = (obj.hide_viewport, obj.hide_render)
for obj, mat, node in find_emissive_objects(context):
key = (mat.name, node.name)
s = node.inputs.get("Strength") if node.type == 'EMISSION' else node.inputs.get("Emission Strength")
if s:
self._backup[key] = s.default_value
world = context.scene.world
if world and world.use_nodes:
nt = world.node_tree
output = next((n for n in nt.nodes if n.type == 'OUTPUT_WORLD'), None)
if output:
for name in ("Surface", "Volume"):
sock = output.inputs.get(name)
if sock and sock.is_linked and sock.links:
link = sock.links[0]
self._backup[f"env_link_{name}"] = (link.from_node.name, link.from_socket.name)
# Turn everything off except the one we're isolating
_unified_on_off_manager.force_all_off(context, except_mode=mode, except_identifier=identifier)
# Specific mode handling
if mode == UnifiedIsolateMode.LIGHT_GROUP or mode == UnifiedIsolateMode.LIGHT_ROW:
to_keep_enabled, _ = identifier if identifier else (set(), set())
for obj in context.view_layer.objects:
if obj.type == 'LIGHT' and obj.name in to_keep_enabled:
obj.hide_viewport = self._backup[obj.name][0]
obj.hide_render = self._backup[obj.name][1]
elif mode == UnifiedIsolateMode.MATERIAL:
_, node_name = identifier if identifier else (None, None)
for obj, mat, node in find_emissive_objects(context):
if (mat.name, node.name) == identifier:
s = node.inputs.get("Strength") if node.type == 'EMISSION' else node.inputs.get("Emission Strength")
if s:
s.default_value = self._backup[(mat.name, node.name)]
elif mode == UnifiedIsolateMode.ENVIRONMENT:
world = context.scene.world
if world and world.use_nodes:
nt = world.node_tree
output = next((n for n in nt.nodes if n.type == 'OUTPUT_WORLD'), None)
if output:
for name in ("Surface", "Volume"):
if f"env_link_{name}" in self._backup:
from_node_name, from_socket_name = self._backup[f"env_link_{name}"]
from_node = nt.nodes.get(from_node_name)
from_socket = from_node.outputs.get(from_socket_name) if from_node else None
to_socket = output.inputs.get(name)
if from_socket and to_socket and not to_socket.is_linked:
nt.links.new(from_socket, to_socket)
self._redraw_areas(context)
def deactivate(self, context):
# Restore everything from backup
for key, val in self._backup.items():
if isinstance(key, tuple): # Emissive nodes
mat_name, node_name = key
mat = bpy.data.materials.get(mat_name)
if mat and mat.use_nodes:
node = mat.node_tree.nodes.get(node_name)
if node:
s = node.inputs.get("Strength") if node.type == 'EMISSION' else node.inputs.get("Emission Strength")
if s:
s.default_value = val
elif key.startswith("env_link_"): # Environment links
world = context.scene.world
if world and world.use_nodes:
nt = world.node_tree
output = next((n for n in nt.nodes if n.type == 'OUTPUT_WORLD'), None)
if output:
socket_name = key.replace("env_link_", "")
from_node_name, from_socket_name = val
from_node = nt.nodes.get(from_node_name)
from_socket = from_node.outputs.get(from_socket_name) if from_node else None
to_socket = output.inputs.get(socket_name)
if from_socket and to_socket and not to_socket.is_linked:
nt.links.new(from_socket, to_socket)
else: # Lights
obj = bpy.data.objects.get(key)
if obj and obj.type == 'LIGHT':
obj.hide_viewport, obj.hide_render = val
obj.light_enabled = not (val[0] and val[1])
self._backup.clear()
self._active_mode = None
self._active_identifier = None
self._redraw_areas(context)
# --- Global instance of the manager ---
_unified_isolate_manager = UnifiedIsolateManager()
_unified_on_off_manager = UnifiedOnOffManager()
def update_render_layer(self, context):
"""Update the context to the selected render layer."""
selected_layer_name = self.light_editor_selected_render_layer
view_layer = context.scene.view_layers.get(selected_layer_name)
if view_layer and context.window.view_layer != view_layer:
context.window.view_layer = view_layer
def get_render_layer_items(self, context):
"""Generate items for the render layer enum property."""
items = []
for view_layer in context.scene.view_layers:
items.append((view_layer.name, view_layer.name, f"Switch to {view_layer.name} render layer"))
# Ensure the current view layer is always an option, even if list is somehow empty
if not items:
current_name = context.view_layer.name if context.view_layer else "Default"
items.append((current_name, current_name, "Current render layer"))
return items
def gather_layer_collections(parent_lc, result):
"""Recursively gather all layer collections."""
result.append(parent_lc)
for child in parent_lc.children:
gather_layer_collections(child, result)
def get_layer_collection_by_name(layer_collection, coll_name):
"""Find a layer collection by its name."""
if layer_collection.collection.name == coll_name:
return layer_collection
for child in layer_collection.children:
found = get_layer_collection_by_name(child, coll_name)
if found:
return found
return None
def update_light_enabled(self, context):
"""Update light visibility based on the light_enabled property."""
# When the depsgraph handler is the one reconciling light_enabled from the
# visibility flags, don't write the flags back — otherwise hiding a light in
# render alone would also hide it in the viewport (and vice versa).
if _syncing_visibility:
return
hidden = not self.light_enabled
if self.hide_viewport != hidden:
self.hide_viewport = hidden
if self.hide_render != hidden:
self.hide_render = hidden
def update_light_turn_off_others(self, context):
global group_checkbox_2_state, emissive_isolate_icon_state
scene = context.scene
world = scene.world
nt = world.node_tree if world and world.use_nodes else None
output_node = next((n for n in nt.nodes if n.type == 'OUTPUT_WORLD'), None) if nt else None
if self.light_turn_off_others:
# --- Activate Isolation ---
# 1. Manage mutual exclusivity
if scene.current_active_light and scene.current_active_light != self:
scene.current_active_light.light_turn_off_others = False
scene.current_active_light = self
# 2. Prepare identifier for UnifiedIsolateManager
to_keep_enabled = {self.name}
to_keep_emissive = set() # No emissive nodes kept active for light isolation
# 3. Activate isolation using UnifiedIsolateManager
_unified_isolate_manager.activate(context, UnifiedIsolateMode.LIGHT_ROW, identifier=(to_keep_enabled, to_keep_emissive))
# 4. Update UI states
group_key = f"light_{self.name}"
group_checkbox_2_state[group_key] = True
else:
# --- Deactivate Isolation ---
# 1. Clear active light tracking
if scene.current_active_light == self:
scene.current_active_light = None
# 2. Deactivate isolation using UnifiedIsolateManager
if _unified_isolate_manager.is_active(UnifiedIsolateMode.LIGHT_ROW):
_unified_isolate_manager.deactivate(context)
# 3. Update UI states
group_key = f"light_{self.name}"
group_checkbox_2_state[group_key] = False
for key in list(emissive_isolate_icon_state.keys()):
emissive_isolate_icon_state[key] = False # Reset emissive isolate icons
# --- Redraw UI ---
for area in context.screen.areas:
if area.type in {'VIEW_3D', 'NODE_EDITOR', 'PROPERTIES'}:
area.tag_redraw()
def get_all_collections(obj):
"""Get all collections an object belongs to, including nested paths."""
def _get_collections_recursive(collection, path=None):
if path is None:
path = []
path.append(collection.name)
yield path[:]
for child in collection.children:
yield from _get_collections_recursive(child, path)
path.pop()
all_collections = set()
for collection in obj.users_collection:
for path in _get_collections_recursive(collection):
all_collections.add(" > ".join(path))
return sorted(all_collections)
def find_emissive_objects(context, search_objects=None):
"""Find all objects with emissive materials, including all reachable emissive nodes."""
global emissive_material_cache
objects_to_search = search_objects if search_objects is not None else context.view_layer.objects
use_cache = (search_objects is None)
cache_key = f"{context.view_layer.name}_{len(bpy.data.materials)}_{len(bpy.data.objects)}" if use_cache else None
if use_cache and cache_key in emissive_material_cache:
return emissive_material_cache[cache_key]
emissive_objs = []
seen = set()
for obj in objects_to_search:
if obj.type != 'MESH':
continue
for slot in obj.material_slots:
mat = slot.material
if not mat or not mat.use_nodes or mat.name in seen:
continue
seen.add(mat.name)
nt = mat.node_tree
output_node = next((n for n in nt.nodes if n.type == 'OUTPUT_MATERIAL' and n.is_active_output), None)
if not output_node or not output_node.inputs.get('Surface') or not output_node.inputs['Surface'].is_linked:
continue
def find_emission_nodes(node, visited, found_nodes):
if node in visited:
return
visited.add(node)
if node.type == 'EMISSION':
found_nodes.append(node)
elif node.type == 'BSDF_PRINCIPLED' and node.inputs.get("Emission Strength"):
found_nodes.append(node)
for input_socket in node.inputs:
if input_socket.is_linked:
for link in input_socket.links:
find_emission_nodes(link.from_node, visited, found_nodes)
found_nodes = []
for link in output_node.inputs['Surface'].links:
find_emission_nodes(link.from_node, set(), found_nodes)
for node in found_nodes:
emissive_objs.append((obj, mat, node))
if use_cache:
if not emissive_objs:
if cache_key in emissive_material_cache:
del emissive_material_cache[cache_key]
else:
emissive_material_cache[cache_key] = emissive_objs
return emissive_objs
class LE_OT_ShowNodes(bpy.types.Operator):
"""Open this node tree in a Shader Editor"""
bl_idname = "le.show_nodes"
bl_label = "See Nodes"
bl_description = ("This value is driven by a node link and can't be edited here.\n"
"Click to show its node tree in an open Shader Editor")
obj_name: StringProperty()
shader_type: StringProperty(default='OBJECT')
def execute(self, context):
# Make the owning object active so the Shader Editor follows it.
if self.shader_type == 'OBJECT' and self.obj_name:
obj = context.view_layer.objects.get(self.obj_name)
if obj:
obj.select_set(True)
context.view_layer.objects.active = obj
for area in context.screen.areas:
if area.type != 'NODE_EDITOR':
continue
for space in area.spaces:
if space.type == 'NODE_EDITOR':
space.tree_type = 'ShaderNodeTree'
space.shader_type = self.shader_type
area.tag_redraw()
return {'FINISHED'}
self.report({'INFO'}, "Open a Shader Editor to see the node tree")
return {'CANCELLED'}
def draw_see_nodes(layout, obj_name="", shader_type='OBJECT'):
"""Draw the 'See Nodes' indicator for a socket driven by a node link."""
row = layout.row(align=True)
row.alignment = 'EXPAND'
op = row.operator("le.show_nodes", text="See Nodes", icon='NODETREE', emboss=False)
op.obj_name = obj_name
op.shader_type = shader_type
def draw_emissive_row(box, obj, mat, emissive_nodes):
"""
Draw a row for a material, with a collapsible sub-list for emissive nodes.
- If multiple_nodes OR single-node with linked socket, split into four equal columns.
- Otherwise, use the regular layout.
"""
row = box.row(align=True)
multiple_nodes = len(emissive_nodes) > 1
first_node = emissive_nodes[0]
group_key = f"mat_{mat.name}_{obj.name}"
collapsed = group_collapse_dict.get(group_key, False)
# --- Toggle & Isolate (header) ---
enabled = any(
(n.inputs.get("Strength") or n.inputs.get("Emission Strength")).default_value > 0 or
(n.inputs.get("Strength") or n.inputs.get("Emission Strength")).is_linked
for n in emissive_nodes
)
icon = 'OUTLINER_OB_LIGHT' if enabled else 'LIGHT_DATA'
op_toggle = row.operator("le.toggle_emission", text="", icon=icon, depress=enabled)
op_toggle.mat_name = mat.name
op_toggle.node_name = ""
iso_active = emissive_isolate_icon_state.get((mat.name, ""), False)
iso_icon = 'RADIOBUT_ON' if iso_active else 'RADIOBUT_OFF'
op_iso = row.operator("le.isolate_emissive", text="", icon=iso_icon)
op_iso.mat_name = mat.name
op_iso.node_name = ""
# --- Select & Expand ---
row.operator("le.select_light", text="",
icon="RESTRICT_SELECT_ON" if obj.select_get() else "RESTRICT_SELECT_OFF"
).name = obj.name
if multiple_nodes:
exp_icon = 'DOWNARROW_HLT' if not collapsed else 'RIGHTARROW'
row.operator("light_editor.toggle_group", text="", emboss=True, icon=exp_icon).group_key = group_key
else:
row.label(text="", icon='BLANK1')
# Determine if single-node linked case
color_input = first_node.inputs.get("Color") if first_node.type == 'EMISSION' else first_node.inputs.get("Emission Color")
strength_input = first_node.inputs.get("Strength") if first_node.type == 'EMISSION' else first_node.inputs.get("Emission Strength")
linked_case = (not multiple_nodes) and ((color_input and color_input.is_linked) or (strength_input and strength_input.is_linked))
# --- Header columns: equal for multi-node or linked single-node ---
if multiple_nodes or linked_case:
col_width = 12
# Object name
col_obj = row.column(align=True)
col_obj.ui_units_x = col_width
col_obj.prop(obj, "name", text="")
# Material name
col_mat = row.column(align=True)
col_mat.ui_units_x = col_width
col_mat.prop(mat, "name", text="")
# Color placeholder
col_color = row.column(align=True)
col_color.ui_units_x = col_width
draw_see_nodes(col_color, obj_name=obj.name)
# Strength placeholder
col_strength = row.column(align=True)
col_strength.ui_units_x = col_width
draw_see_nodes(col_strength, obj_name=obj.name)
else:
# --- Regular layout for single-node without links ---
# Object name
col_obj = row.column(align=True)
col_obj.scale_x = 0.5
col_obj.prop(obj, "name", text="")
# Material name
col_mat = row.column(align=True)
col_mat.scale_x = 0.5
col_mat.prop(mat, "name", text="")
# Color socket
col_color = row.column(align=True)
col_color.ui_units_x = 4
if color_input:
draw_socket_with_icon(col_color, color_input, text="")
else:
col_color.label(text="")
# Strength socket
col_strength = row.column(align=True)
col_strength.ui_units_x = 6
if strength_input:
draw_socket_with_icon(col_strength, strength_input, text="")
else:
col_strength.label(text="")
# --- Sub-rows for each emissive node ---
if multiple_nodes and not collapsed:
sub_box = box.box()
for subnode in sorted(emissive_nodes, key=lambda x: x.name.lower()):
sub_row = sub_box.row(align=True)
sub_row.label(text="", icon='BLANK1')
s_in = subnode.inputs.get("Strength") if subnode.type == 'EMISSION' else subnode.inputs.get("Emission Strength")
val = s_in.default_value if s_in else 0.0
ico = 'OUTLINER_OB_LIGHT' if (s_in and (s_in.is_linked or val > 0)) else 'LIGHT_DATA'
op_n = sub_row.operator("le.toggle_emission", text="", icon=ico, depress=(val > 0))
op_n.mat_name = mat.name
op_n.node_name = subnode.name
iso_n = emissive_isolate_icon_state.get((mat.name, subnode.name), False)
ico_ni = 'RADIOBUT_ON' if iso_n else 'RADIOBUT_OFF'
op_ni = sub_row.operator("le.isolate_emissive", text="", icon=ico_ni)
op_ni.mat_name = mat.name
op_ni.node_name = subnode.name
# Node name only
col_node = sub_row.column(align=True)
col_node.scale_x = 0.5
col_node.prop(subnode, "name", text="")
# Color socket
c_col = sub_row.column(align=True)
c_col.ui_units_x = 4
color_in = subnode.inputs.get("Color") if subnode.type == 'EMISSION' else subnode.inputs.get("Emission Color")
if color_in:
if color_in.is_linked:
draw_see_nodes(c_col, obj_name=obj.name)
else:
draw_socket_with_icon(c_col, color_in, text="")
else:
c_col.label(text="")
# Strength socket
c_str = sub_row.column(align=True)
c_str.ui_units_x = 6
if s_in:
if s_in.is_linked:
draw_see_nodes(c_str, obj_name=obj.name)
else:
draw_socket_with_icon(c_str, s_in, text="")
else:
c_str.label(text="")
def update_group_by_kind(self, context):
"""Ensure 'By Kind' and 'By Collection' are mutually exclusive."""
if self.light_editor_kind_alpha:
self.light_editor_group_by_collection = False
def update_group_by_collection(self, context):
"""Ensure 'By Kind' and 'By Collection' are mutually exclusive."""
if self.light_editor_group_by_collection:
self.light_editor_kind_alpha = False
def get_device_type(context):
"""Get the compute device type from Cycles preferences."""
return context.preferences.addons['cycles'].preferences.compute_device_type
def backend_has_active_gpu(context):
"""Check if Cycles has an active GPU device."""
return context.preferences.addons['cycles'].preferences.has_active_device()
def use_metal(context):
"""Check if Metal backend is being used."""
cscene = context.scene.cycles
return (get_device_type(context) == 'METAL' and cscene.device == 'GPU' and backend_has_active_gpu(context))
def use_mnee(context):
"""Check if MNEE is available (Metal-specific check)."""
if use_metal(context):
import platform
version, _, _ = platform.mac_ver()
major_version = version.split(".")[0]
if int(major_version) < 13:
return False
return True
def draw_extra_params(self, box, obj, light):
"""Draw extra light parameters based on the light type and render engine."""
if light and isinstance(light, bpy.types.Light):
layout = box
row = layout.row()
row.prop(light, "type", expand=True)
col = layout.column()
col.separator()
if is_blender_4_5_or_higher():
col.prop(light, "use_temperature", text="Use Temperature")
if light.use_temperature:
col.prop(light, "temperature", text="Temperature")
col.prop(light, "normalize", text="Normalize")
col.separator()
if bpy.context.engine == 'CYCLES':
clamp = light.cycles
if light.type in {'POINT', 'SPOT'}:
col.prop(light, "use_soft_falloff")
col.prop(light, "shadow_soft_size", text="Radius")
elif light.type == 'SUN':
col.prop(light, "angle")
elif light.type == 'AREA':
col.prop(light, "shape", text="Shape")
sub = col.column(align=True)
if light.shape in {'SQUARE', 'DISK'}:
sub.prop(light, "size")
elif light.shape in {'RECTANGLE', 'ELLIPSE'}:
sub.prop(light, "size", text="Size X")
sub.prop(light, "size_y", text="Y")
if not (light.type == 'AREA' and clamp.is_portal):
col.separator()
sub = col.column()
sub.prop(clamp, "max_bounces")
sub = col.column(align=True)
sub.active = not (light.type == 'AREA' and clamp.is_portal)
sub.prop(light, "use_shadow", text="Cast Shadow")
sub.prop(clamp, "use_multiple_importance_sampling", text="Multiple Importance")
if use_mnee(bpy.context):
sub.prop(clamp, "is_caustics_light", text="Shadow Caustics")
if light.type == 'AREA':
col.prop(clamp, "is_portal", text="Portal")
if light.type == 'SPOT':
col.separator()
row = col.row(align=True)
row.alignment = 'CENTER'
row.label(text="Spot Shape")
col.prop(light, "spot_size", text="Spot Size")
col.prop(light, "spot_blend", text="Blend", slider=True)
col.prop(light, "show_cone")
elif light.type == 'AREA':
col.separator()
row = col.row(align=True)
row.alignment = 'CENTER'
row.label(text="Beam Shape")
col.prop(light, "spread", text="Spread")
if ((bpy.context.engine == 'BLENDER_EEVEE') or (bpy.context.engine == 'BLENDER_EEVEE_NEXT')):
col.separator()
if light.type in {'POINT', 'SPOT'}:
col.prop(light, "use_soft_falloff")
col.prop(light, "shadow_soft_size", text="Radius")
elif light.type == 'SUN':
col.prop(light, "angle")
elif light.type == 'AREA':
col.prop(light, "shape")
sub = col.column(align=True)
if light.shape in {'SQUARE', 'DISK'}:
sub.prop(light, "size")
elif light.shape in {'RECTANGLE', 'ELLIPSE'}:
sub.prop(light, "size", text="Size X")
sub.prop(light, "size_y", text="Y")
if bpy.context.engine == 'BLENDER_EEVEE_NEXT':
col.separator()
col.prop(light, "use_shadow", text="Cast Shadow")
col.prop(light, "use_shadow_jitter")
col.prop(light, "shadow_jitter_overblur", text="Overblur")
col.prop(light, "shadow_filter_radius", text="Radius")
col.prop(light, "shadow_maximum_resolution", text="Resolution Limit")
if light and light.type == 'SPOT':
col.separator()
row = col.row(align=True)
row.alignment = 'CENTER'
row.label(text="Spot Shape")
col.prop(light, "spot_size", text="Size")
col.prop(light, "spot_blend", text="Blend", slider=True)
col.prop(light, "show_cone")
col.separator()
col.prop(light, "diffuse_factor", text="Diffuse")
col.prop(light, "specular_factor", text="Specular")
col.prop(light, "volume_factor", text="Volume", text_ctxt=i18n_contexts.id_id)
if light.type != 'SUN':
col.separator()
sub = col.column()
sub.prop(light, "use_custom_distance", text="Custom Distance")
sub.active = light.use_custom_distance
sub.prop(light, "cutoff_distance", text="Distance")
# --- Operators (refactored to use UnifiedIsolateManager) ---
class LE_OT_ToggleEnvironment(bpy.types.Operator):
"""Toggle the environment lighting on/off."""
bl_idname = "le.toggle_environment"
bl_label = "Toggle Environment Lighting"
def execute(self, context):
global environment_checkbox_state, _surface_link_backup, _volume_link_backup
world = context.scene.world
if not world or not world.use_nodes:
self.report({'WARNING'}, "No world or world shader found")
return {'CANCELLED'}
nt = world.node_tree
background_node = next((n for n in nt.nodes if n.type == 'BACKGROUND'), None)
if not background_node:
self.report({'WARNING'}, "No Background node found in world shader")
return {'CANCELLED'}
strength_input = background_node.inputs.get("Strength")
if not strength_input:
self.report({'WARNING'}, "Background node has no Strength input")
return {'CANCELLED'}
output_node = next((n for n in nt.nodes if n.type == 'OUTPUT_WORLD'), None)
if not output_node:
self.report({'WARNING'}, "No World Output node found")
return {'CANCELLED'}
is_on = environment_checkbox_state.get('environment', True)
if is_on:
# Store current state and disable
world['original_environment_strength'] = strength_input.default_value
strength_input.default_value = 0.0
# Disconnect Surface and Volume inputs
for socket_name in ("Surface", "Volume"):
socket = output_node.inputs.get(socket_name)
if socket and socket.is_linked and socket.links:
try:
link = socket.links[0]
if link.is_valid:
if socket_name == "Surface":
_surface_link_backup = (link.from_node.name, link.from_socket.name)
else:
_volume_link_backup = (link.from_node.name, link.from_socket.name)
nt.links.remove(link)
except Exception as e:
self.report({'WARNING'}, f"Failed to remove link for {socket_name}: {e}")
else:
# Restore state
restored_strength = world.get('original_environment_strength', 1.0)
strength_input.default_value = restored_strength
# Reconnect Surface and Volume inputs
for socket_name, backup in [("Surface", _surface_link_backup), ("Volume", _volume_link_backup)]:
if backup:
node_name, socket_name_from = backup
from_node = nt.nodes.get(node_name)
from_socket = from_node.outputs.get(socket_name_from) if from_node else None
to_socket = output_node.inputs.get(socket_name)
if from_socket and to_socket and not to_socket.is_linked:
try:
nt.links.new(from_socket, to_socket)
except Exception as e:
self.report({'WARNING'}, f"Failed to restore link for {socket_name}: {e}")
# Clear backup after restoration (optional, keeps it clean)
if socket_name == "Surface":
_surface_link_backup = None
else:
_volume_link_backup = None
environment_checkbox_state['environment'] = not is_on
# Redraw relevant areas
for area in context.screen.areas:
if area.type in ('VIEW_3D', 'NODE_EDITOR'):
area.tag_redraw()
return {'FINISHED'}
def execute(self, context):
global isolate_env_header_state, isolate_env_surface_state, isolate_env_volume_state
global env_isolated_ui_state # ← ADD THIS
flag_map = {
"HEADER": "isolate_env_header_state",
"SURFACE": "isolate_env_surface_state",
"VOLUME": "isolate_env_volume_state",
}
mode_map = {
"HEADER": UnifiedIsolateMode.ENVIRONMENT,
"SURFACE": UnifiedIsolateMode.ENVIRONMENT_SURFACE,
"VOLUME": UnifiedIsolateMode.ENVIRONMENT_VOLUME,
}
unified_mode = mode_map.get(self.mode, UnifiedIsolateMode.ENVIRONMENT)
is_currently_active = _unified_isolate_manager.is_active(unified_mode)
if not is_currently_active:
globals()[flag_map[self.mode]] = True
if self.mode == "HEADER":
env_isolated_ui_state = True # ← SET TRUE when activated
_unified_isolate_manager.activate(context, unified_mode)
else:
globals()[flag_map[self.mode]] = False
if self.mode == "HEADER":
env_isolated_ui_state = False # ← SET FALSE when deactivated
_unified_isolate_manager.deactivate(context)
return {'FINISHED'}
class LE_OT_SelectEnvironment(bpy.types.Operator):
"""Select the environment world in the Shader Editor."""
bl_idname = "le.select_environment"
bl_label = "Select Environment"
def execute(self, context):
world = context.scene.world
if not world:
self.report({'WARNING'}, "No world found")
return {'CANCELLED'}
for area in context.screen.areas:
if area.type == 'VIEW_3D':
for space in area.spaces:
if space.type == 'VIEW_3D':
space.shading.type = 'MATERIAL'
break
break
for area in context.screen.areas:
if area.type == 'NODE_EDITOR':
area.spaces.active.node_tree = world.node_tree
break
else:
self.report({'INFO'}, "No Shader Editor found; open one to edit world shader")
self.report({'INFO'}, f"Selected world: {world.name}")
return {'FINISHED'}
class LE_OT_SelectGroup(bpy.types.Operator):
"""Select all objects in the specified group."""
bl_idname = "le.select_group"
bl_label = "Select Group"
group_key: bpy.props.StringProperty()
def execute(self, context):
objects_to_select = []
objects_in_group = []
deselect_all_flag = False
filter_str = context.scene.light_editor_filter.lower()
# Handle different group types
if self.group_key.startswith("coll_"):
coll_name = self.group_key[5:]
if coll_name == "No Collection":
for obj in context.view_layer.objects:
if obj.type == 'LIGHT' or (obj.type == 'MESH' and any(mat in [m for o, m, n in find_emissive_objects(context)] for mat in obj.material_slots)):
objects_in_group.append(obj)
if len(obj.users_collection) == 1 and obj.users_collection[0].name == "Scene Collection":
if (not filter_str or re.search(filter_str, obj.name, re.I)) and (obj.type != 'LIGHT' or obj.light_enabled):
objects_to_select.append(obj)
else:
collection = bpy.data.collections.get(coll_name)
if collection:
for obj in collection.all_objects:
if obj.type == 'LIGHT' or (obj.type == 'MESH' and any(mat in [m for o, m, n in find_emissive_objects(context)] for mat in obj.material_slots)):
objects_in_group.append(obj)
if (not filter_str or re.search(filter_str, obj.name, re.I)) and (obj.type != 'LIGHT' or obj.light_enabled):
objects_to_select.append(obj)
elif self.group_key.startswith("kind_"):
kind = self.group_key[5:]
if kind == "EMISSIVE":
for obj, mat, node in find_emissive_objects(context):
if not filter_str or re.search(filter_str, obj.name, re.I) or re.search(filter_str, mat.name, re.I):
objects_in_group.append(obj)
objects_to_select.append(obj)
else:
for obj in context.view_layer.objects:
if obj.type == 'LIGHT' and obj.data.type == kind:
if obj.light_enabled:
objects_in_group.append(obj)
if (not filter_str or re.search(filter_str, obj.name, re.I)) and obj.light_enabled:
objects_to_select.append(obj)
elif self.group_key == "all_lights_alpha":
for obj in context.view_layer.objects:
if obj.type == 'LIGHT' and obj.light_enabled:
objects_in_group.append(obj)
if not filter_str or re.search(filter_str, obj.name, re.I):
objects_to_select.append(obj)
elif self.group_key == "all_emissives_alpha":
for obj, mat, node in find_emissive_objects(context):
if not filter_str or re.search(filter_str, obj.name, re.I) or re.search(filter_str, mat.name, re.I):
objects_in_group.append(obj)
objects_to_select.append(obj)
elif self.group_key == "selected_lights":
for obj in context.view_layer.objects:
if obj.type == 'LIGHT' and obj.select_get() and obj.light_enabled:
objects_in_group.append(obj)
if not filter_str or re.search(filter_str, obj.name, re.I):
objects_to_select.append(obj)
elif self.group_key == "selected_emissives":
for obj, mat, node in find_emissive_objects(context):
if obj.select_get():
if not filter_str or re.search(filter_str, obj.name, re.I) or re.search(filter_str, mat.name, re.I):
objects_in_group.append(obj)
objects_to_select.append(obj)
elif self.group_key == "not_selected_lights":
for obj in context.view_layer.objects:
if obj.type == 'LIGHT' and not obj.select_get() and obj.light_enabled:
objects_in_group.append(obj)
if not filter_str or re.search(filter_str, obj.name, re.I):
objects_to_select.append(obj)
elif self.group_key == "not_selected_emissives":
for obj, mat, node in find_emissive_objects(context):
if not obj.select_get():
if not filter_str or re.search(filter_str, obj.name, re.I) or re.search(filter_str, mat.name, re.I):
objects_in_group.append(obj)
objects_to_select.append(obj)
elif self.group_key == "env_header":
self.report({'INFO'}, "Selected world: {}".format(context.scene.world.name))
for area in context.screen.areas:
if area.type == 'NODE_EDITOR':
area.spaces.active.node_tree = context.scene.world.node_tree
return {'FINISHED'}
# --- Determine Action: Select or Deselect All ---
selected_objects = [obj for obj in objects_in_group if obj.name in context.view_layer.objects and obj.select_get()]
if objects_in_group and all(obj.select_get() for obj in objects_in_group if obj.name in context.view_layer.objects):
deselect_all_flag = True
# --- Perform Action ---
any_selected = False
if deselect_all_flag:
bpy.ops.object.select_all(action='DESELECT')
self.report({'INFO'}, f"Deselected all objects in group: {self.group_key}")
else:
bpy.ops.object.select_all(action='DESELECT')
for obj in objects_to_select:
if obj.name in context.view_layer.objects:
obj.select_set(True)
any_selected = True
if not context.view_layer.objects.active:
context.view_layer.objects.active = obj
if any_selected:
self.report({'INFO'}, f"Selected {len(objects_to_select)} objects in group: {self.group_key}")
else:
self.report({'INFO'}, f"No selectable objects found in group: {self.group_key}")
# Redraw the UI to update icons
for area in context.screen.areas:
if area.type in ('VIEW_3D', 'NODE_EDITOR', 'PROPERTIES'):
area.tag_redraw()