-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtimer.py
More file actions
872 lines (749 loc) · 33.8 KB
/
Copy pathtimer.py
File metadata and controls
872 lines (749 loc) · 33.8 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
bl_info = {
"name": "Sun Shadow Plane",
"author": "Claude",
"version": (5, 0, 0),
"blender": (3, 0, 0),
"location": "View3D > Sidebar > Sun Shadow",
"description": "Shadow casting via ray casting - adaptive grid or surface sampling.",
"category": "Object",
}
import bpy
import bmesh
import math
import time
import random
from mathutils import Vector, Matrix
PLANE_OBJ_NAME = "SunShadowPlane"
PLANE_MESH_NAME = "SunShadowPlane_Mesh"
PLANE_MAT_NAME = "SunShadowPlane_Mat"
EMPTIES_COLL = "SunShadow_Empties"
# ---------------------------------------------------------------------------
# Sun
# ---------------------------------------------------------------------------
def get_sun_light(context):
for obj in context.scene.objects:
if obj.type == "LIGHT" and obj.data.type == "SUN":
return obj
return None
def sun_direction(sun_obj):
return (sun_obj.matrix_world.to_3x3() @ Vector((0, 0, -1))).normalized()
# ---------------------------------------------------------------------------
# Scene geometry
# ---------------------------------------------------------------------------
def is_shadow_helper(obj):
return bool(obj.get("sun_shadow_plane") or obj.get("sun_shadow_empty"))
def scene_mesh_objects(context, sun_obj):
return [
o for o in context.scene.objects
if o != sun_obj and o.type == "MESH"
and not is_shadow_helper(o) and o.visible_get()
]
def collect_world_vertices(context, sun_obj):
verts = []
for obj in scene_mesh_objects(context, sun_obj):
me = obj.to_mesh()
if me:
for v in me.vertices:
verts.append(obj.matrix_world @ v.co)
obj.to_mesh_clear()
return verts
def build_sun_visible_faces(mesh_objs, sun_dir):
visible = set()
for obj in mesh_objs:
mat3 = obj.matrix_world.to_3x3()
for poly in obj.data.polygons:
if (mat3 @ poly.normal).normalized().dot(sun_dir) <= 0:
visible.add((obj.name, poly.index))
return visible
def get_scene_extent(world_verts, sun_dir):
projs = [v.dot(sun_dir) for v in world_verts]
return max(projs) - min(projs)
# ---------------------------------------------------------------------------
# Fast cleanup
# ---------------------------------------------------------------------------
def purge_shadow_helpers():
coll = bpy.data.collections.get(EMPTIES_COLL)
if coll:
for obj in list(coll.objects):
coll.objects.unlink(obj)
if obj.users == 0:
bpy.data.objects.remove(obj)
bpy.data.collections.remove(coll)
for obj in list(bpy.data.objects):
if obj.get("sun_shadow_empty") and obj.users == 0:
bpy.data.objects.remove(obj)
plane_obj = bpy.data.objects.get(PLANE_OBJ_NAME)
if plane_obj:
bpy.data.objects.remove(plane_obj, do_unlink=True)
me = bpy.data.meshes.get(PLANE_MESH_NAME)
if me and me.users == 0:
bpy.data.meshes.remove(me)
# ---------------------------------------------------------------------------
# Plane material
# ---------------------------------------------------------------------------
def ensure_plane_material():
if PLANE_MAT_NAME in bpy.data.materials:
return bpy.data.materials[PLANE_MAT_NAME]
mat = bpy.data.materials.new(PLANE_MAT_NAME)
mat.blend_method = "BLEND"
mat.use_nodes = True
nodes, links = mat.node_tree.nodes, mat.node_tree.links
nodes.clear()
out = nodes.new("ShaderNodeOutputMaterial")
emit = nodes.new("ShaderNodeEmission")
transp = nodes.new("ShaderNodeBsdfTransparent")
mix = nodes.new("ShaderNodeMixShader")
emit.inputs["Color"].default_value = (0.1, 0.6, 1.0, 1.0)
emit.inputs["Strength"].default_value = 0.5
mix.inputs["Fac"].default_value = 0.5
links.new(emit.outputs["Emission"], mix.inputs[1])
links.new(transp.outputs["BSDF"], mix.inputs[2])
links.new(mix.outputs["Shader"], out.inputs["Surface"])
return mat
# ---------------------------------------------------------------------------
# Adaptive grid
# ---------------------------------------------------------------------------
class Cell:
__slots__ = ("center", "half_u", "half_v", "u_axis", "v_axis")
def __init__(self, center, half_u, half_v, u_axis, v_axis):
self.center = center; self.half_u = half_u; self.half_v = half_v
self.u_axis = u_axis; self.v_axis = v_axis
def build_plane_axes(normal):
arb = Vector((0, 0, 1)) if abs(normal.dot(Vector((0, 0, 1)))) < 0.99 else Vector((1, 0, 0))
u = normal.cross(arb).normalized()
return u, normal.cross(u).normalized()
def make_base_grid(plane_center, u_axis, v_axis, half_u, half_v, grid_size):
nu = round(2 * half_u / grid_size)
nv = round(2 * half_v / grid_size)
cells = []
for j in range(nv):
for i in range(nu):
cu = -half_u + (i + 0.5) * grid_size
cv = -half_v + (j + 0.5) * grid_size
cells.append(Cell(plane_center + u_axis*cu + v_axis*cv,
grid_size/2, grid_size/2, u_axis, v_axis))
return cells, nu, nv
def expand_to_8_neighbours(cells, shadow_indices, u_axis, v_axis):
expanded = set(shadow_indices)
EPS = 1e-5
for idx in shadow_indices:
c = cells[idx]
for j, other in enumerate(cells):
if j in expanded: continue
diff = other.center - c.center
if (abs(diff.dot(u_axis)) <= c.half_u + other.half_u + EPS and
abs(diff.dot(v_axis)) <= c.half_v + other.half_v + EPS):
expanded.add(j)
return expanded
def subdivide_cell_list(cells, shadow_indices, u_axis, v_axis):
expanded = expand_to_8_neighbours(cells, shadow_indices, u_axis, v_axis)
result = []; old_to_new = {}
for idx, cell in enumerate(cells):
if idx in expanded:
q = cell.half_u / 2; subs = []
for dj in (-1, 1):
for di in (-1, 1):
subs.append(len(result))
result.append(Cell(cell.center + cell.u_axis*(di*q) + cell.v_axis*(dj*q),
q, q, cell.u_axis, cell.v_axis))
old_to_new[idx] = subs
else:
old_to_new[idx] = [len(result)]; result.append(cell)
return result, expanded, old_to_new
def build_mesh_from_cells(cells, mesh_name):
bm = bmesh.new()
for cell in cells:
c, hu, hv, u, v = cell.center, cell.half_u, cell.half_v, cell.u_axis, cell.v_axis
bm.faces.new([bm.verts.new(c - u*hu - v*hv), bm.verts.new(c + u*hu - v*hv),
bm.verts.new(c + u*hu + v*hv), bm.verts.new(c - u*hu + v*hv)])
bm.verts.ensure_lookup_table()
bmesh.ops.remove_doubles(bm, verts=bm.verts, dist=1e-5)
me = bpy.data.meshes.get(mesh_name) or bpy.data.meshes.new(mesh_name)
bm.to_mesh(me); bm.free(); me.update()
return me
# ---------------------------------------------------------------------------
# Surface sampling
# ---------------------------------------------------------------------------
def _build_silhouette_edges(mesh_objs, sun_visible_faces):
edge_face_count = {}; edge_info = {}
for obj in mesh_objs:
me = obj.data
for poly in me.polygons:
if (obj.name, poly.index) not in sun_visible_faces: continue
n = len(poly.vertices)
for i in range(n):
vi_a = poly.vertices[i]; vi_b = poly.vertices[(i+1) % n]
key = (obj.name, min(vi_a, vi_b), max(vi_a, vi_b))
edge_face_count[key] = edge_face_count.get(key, 0) + 1
edge_info[key] = (vi_a, vi_b, obj)
return {k for k, cnt in edge_face_count.items() if cnt == 1}, edge_info
def _find_poly_for_edge(obj, vi_a, vi_b, sun_visible_faces):
vi_set = {vi_a, vi_b}
for poly in obj.data.polygons:
if (obj.name, poly.index) not in sun_visible_faces: continue
if vi_set.issubset(set(poly.vertices)): return poly.index
return 0
def _triangle_area(a, b, c):
return (b - a).cross(c - a).length * 0.5
def _random_point_in_triangle(a, b, c):
r1 = random.random(); r2 = random.random()
if r1 + r2 > 1.0: r1, r2 = 1.0 - r1, 1.0 - r2
return a + (b - a) * r1 + (c - a) * r2
def _random_face(verts_world, poly, obj, dist_min):
pts = []; v0 = verts_world[0]
for i in range(1, len(verts_world) - 1):
tri = (v0, verts_world[i], verts_world[i+1])
n_pts = max(0, int(_triangle_area(*tri) / (dist_min * dist_min)))
for _ in range(n_pts):
pts.append((_random_point_in_triangle(*tri), obj, poly.index))
return pts
def _poisson_face(verts_world, poly, obj, dist_min):
if len(verts_world) < 3: return []
normal_world = sum(
(verts_world[i] - verts_world[0]).cross(verts_world[(i+1) % len(verts_world)] - verts_world[0])
for i in range(len(verts_world))).normalized()
arb = Vector((0,0,1)) if abs(normal_world.dot(Vector((0,0,1)))) < 0.99 else Vector((1,0,0))
fu = normal_world.cross(arb).normalized()
fv = normal_world.cross(fu).normalized()
origin = verts_world[0]
verts2d = [((p - origin).dot(fu), (p - origin).dot(fv)) for p in verts_world]
xs = [p[0] for p in verts2d]; ys = [p[1] for p in verts2d]
min_x, max_x = min(xs), max(xs); min_y, max_y = min(ys), max(ys)
def in_poly(px, py):
inside = False; x1, y1 = verts2d[-1]
for x2, y2 in verts2d:
if ((y1 > py) != (y2 > py)) and (px < (x2-x1)*(py-y1)/(y2-y1+1e-12)+x1):
inside = not inside
x1, y1 = x2, y2
return inside
r = dist_min; cell_sz = r / math.sqrt(2)
cols = max(1, int(math.ceil((max_x - min_x) / cell_sz)))
rows = max(1, int(math.ceil((max_y - min_y) / cell_sz)))
if cols * rows > 200000: return _random_face(verts_world, poly, obj, dist_min)
grid = [None] * (cols * rows); active = []; result = []; K = 30
def gidx(px, py):
return max(0, min(rows-1, int((py-min_y)/cell_sz))) * cols + max(0, min(cols-1, int((px-min_x)/cell_sz)))
def too_close(px, py):
c0 = int((px-min_x)/cell_sz); r0 = int((py-min_y)/cell_sz)
for dr in range(-2, 3):
for dc in range(-2, 3):
nc, nr = c0+dc, r0+dr
if 0 <= nc < cols and 0 <= nr < rows:
nb = grid[nr*cols+nc]
if nb and (nb[0]-px)**2+(nb[1]-py)**2 < r*r: return True
return False
for _ in range(100):
sx = random.uniform(min_x, max_x); sy = random.uniform(min_y, max_y)
if in_poly(sx, sy):
grid[gidx(sx, sy)] = (sx, sy); active.append((sx, sy)); result.append((sx, sy)); break
while active:
idx = random.randint(0, len(active)-1); ax, ay = active[idx]; found = False
for _ in range(K):
angle = random.uniform(0, 2*math.pi); rad = random.uniform(r, 2*r)
nx, ny = ax + rad*math.cos(angle), ay + rad*math.sin(angle)
if min_x <= nx <= max_x and min_y <= ny <= max_y and in_poly(nx, ny) and not too_close(nx, ny):
grid[gidx(nx, ny)] = (nx, ny); active.append((nx, ny)); result.append((nx, ny)); found = True
if not found: active.pop(idx)
return [(origin + fu*px + fv*py, obj, poly.index) for px, py in result]
def _merge_by_distance_2d(face_points, sun_dir, merge_dist):
if not face_points or merge_dist <= 0: return face_points
arb = Vector((0,0,1)) if abs(sun_dir.dot(Vector((0,0,1)))) < 0.99 else Vector((1,0,0))
pu = sun_dir.cross(arb).normalized(); pv = sun_dir.cross(pu).normalized()
cell_sz = merge_dist; grid = {}; result = []; md2 = merge_dist * merge_dist
for pt, obj, poly_idx in face_points:
u = pt.dot(pu); v = pt.dot(pv)
ci = int(math.floor(u / cell_sz)); cj = int(math.floor(v / cell_sz))
too_close = False
for dj in (-1, 0, 1):
for di in (-1, 0, 1):
nb = grid.get((ci+di, cj+dj))
if nb:
for nu, nv in nb:
if (nu-u)**2+(nv-v)**2 < md2: too_close = True; break
if too_close: break
if too_close: break
if not too_close:
grid.setdefault((ci, cj), []).append((u, v))
result.append((pt, obj, poly_idx))
return result
def sample_points_on_visible_faces(mesh_objs, sun_visible_faces, sun_dir, dist_min, mode, merge_dist):
edge_points = []; face_points = []
silhouette_keys, edge_info = _build_silhouette_edges(mesh_objs, sun_visible_faces)
for key in silhouette_keys:
vi_a, vi_b, obj = edge_info[key]
mw = obj.matrix_world
a = mw @ obj.data.vertices[vi_a].co; b = mw @ obj.data.vertices[vi_b].co
length = (b - a).length
n_pts = max(0, int(math.floor(length / dist_min)) - 1)
poly_idx = _find_poly_for_edge(obj, vi_a, vi_b, sun_visible_faces)
for k in range(1, n_pts + 1):
edge_points.append((a.lerp(b, k / (n_pts + 1)), obj, poly_idx))
for obj in mesh_objs:
me = obj.data; mw = obj.matrix_world
for poly in me.polygons:
if (obj.name, poly.index) not in sun_visible_faces: continue
verts_world = [mw @ me.vertices[vi].co for vi in poly.vertices]
pts = _poisson_face(verts_world, poly, obj, dist_min) if mode == "POISSON" \
else _random_face(verts_world, poly, obj, dist_min)
face_points.extend(pts)
return edge_points + _merge_by_distance_2d(face_points, sun_dir, merge_dist)
# ---------------------------------------------------------------------------
# Ray casting — single ray functions (BVH global)
# ---------------------------------------------------------------------------
def face_normal_world(obj, poly):
return (obj.matrix_world.to_3x3() @ poly.normal).normalized()
def cast_one_ray_m1(scene, depsgraph, sun_dir, cell, start_offset, sun_visible_faces):
EPSILON = 1e-4
ray_origin = cell.center - sun_dir * start_offset
current = ray_origin + sun_dir * EPSILON
remaining = start_offset * 2.0
hits = []; iterations = 0
while remaining > EPSILON and iterations < 512:
iterations += 1
ok, loc, _n, poly_idx, obj, _mx = scene.ray_cast(depsgraph, current, sun_dir, distance=remaining)
if not ok or obj is None: break
dist = (loc - current).length
if dist < EPSILON: break
if (obj.name, poly_idx) in sun_visible_faces:
hits.append(((loc - ray_origin).length, obj.name, poly_idx, loc))
current = loc + sun_dir * EPSILON; remaining -= dist + EPSILON
hits.sort(key=lambda h: h[0])
return hits
def cast_one_ray_m2(scene, depsgraph, sun_dir, origin, src_obj, src_poly_idx,
ray_length, sun_visible_faces):
EPSILON = 1e-4
current = origin + sun_dir * EPSILON
remaining = ray_length; hits = {}; iterations = 0
while remaining > EPSILON and iterations < 512:
iterations += 1
ok, loc, _n, poly_idx, obj, _mx = scene.ray_cast(depsgraph, current, sun_dir, distance=remaining)
if not ok or obj is None: break
dist = (loc - current).length
if dist < EPSILON: break
if not (obj.name == src_obj.name and poly_idx == src_poly_idx) \
and (obj.name, poly_idx) in sun_visible_faces:
hits.setdefault((obj.name, poly_idx), []).append(loc.copy())
current = loc + sun_dir * EPSILON; remaining -= dist + EPSILON
return hits
# ---------------------------------------------------------------------------
# Empties
# ---------------------------------------------------------------------------
def create_empties_collection(context):
coll = bpy.data.collections.new(EMPTIES_COLL)
context.scene.collection.children.link(coll)
return coll
def add_empties_for_face_data(face_data, mesh_objs, coll):
obj_map = {o.name: o for o in mesh_objs}; count = 0
for (obj_name, poly_idx), data in face_data.items():
if data["status"] != "shadow": continue
obj = obj_map.get(obj_name)
if not obj or poly_idx >= len(obj.data.polygons): continue
poly = obj.data.polygons[poly_idx]
normal = face_normal_world(obj, poly)
positions = data["hit_points"] if data["hit_points"] else [obj.matrix_world @ poly.center]
for idx, pos in enumerate(positions):
ename = f"Shadow_{obj_name}_f{poly_idx}" + (f"_{idx}" if idx > 0 else "")
empty = bpy.data.objects.new(ename, None)
empty.empty_display_type = "SINGLE_ARROW"; empty.empty_display_size = 0.15
empty.location = pos
z = normal
arb = Vector((0,1,0)) if abs(z.dot(Vector((0,0,1)))) > 0.99 else Vector((0,0,1))
x = z.cross(arb).normalized(); y = z.cross(x).normalized()
empty.rotation_euler = Matrix(((x.x,y.x,z.x),(x.y,y.y,z.y),(x.z,y.z,z.z))).to_euler()
empty["sun_shadow_empty"] = True; coll.objects.link(empty); count += 1
return count
# ---------------------------------------------------------------------------
# Header progress helper
# ---------------------------------------------------------------------------
def _set_header(text):
for window in bpy.context.window_manager.windows:
for area in window.screen.areas:
if area.type == "VIEW_3D":
area.header_text_set(text)
area.tag_redraw()
return
def _clear_header():
for window in bpy.context.window_manager.windows:
for area in window.screen.areas:
if area.type == "VIEW_3D":
area.header_text_set(None)
area.tag_redraw()
return
def fmt_time(seconds):
return f"{seconds:.2f}s" if seconds < 60 else f"{int(seconds//60)}m {seconds%60:.1f}s"
# ---------------------------------------------------------------------------
# Background timer state (shared between timer callback and operators)
# ---------------------------------------------------------------------------
_state = {} # holds all mutable state for the running job
def _tick_grid():
"""
Timer callback for method 1 (adaptive grid).
Called by bpy.app.timers — no UI event loop involved.
Returns the interval for the next call, or None to stop.
"""
s = _state
if not s or not s.get("running"):
_clear_header()
return None
props = bpy.context.scene.ssp_props
batch = props.batch_size
scene = s["scene"]; depsgraph = s["depsgraph"]
sun_dir = s["sun_dir"]; sun_vis = s["sun_vis"]
start_offset = s["extent"] + 1.0
cells = s["cells"]
cursor = s["cursor"]
results = s["ray_results"]
end = min(cursor + batch, len(cells))
for i in range(cursor, end):
results[i] = cast_one_ray_m1(scene, depsgraph, sun_dir,
cells[i], start_offset, sun_vis)
s["cursor"] = end
total = len(cells)
pct = int(100 * end / total) if total else 100
_set_header(f"Sun Shadow [Grid Lv {s['level']}] — {end}/{total} rays ({pct}%) | Cancel to stop")
if end < total:
return 0.0 # call again immediately — no sleep, no UI refresh
# --- Batch complete ---
phase = s["phase"]
if phase == "base":
shadow_idx = {i for i, h in enumerate(results) if h and len(h) >= 2}
max_level = s["max_level"]
if not shadow_idx or s["level"] >= max_level:
# Move to final cast on sub-cells
_start_final_grid(s)
return 0.0
# Subdivide and repeat
s["cells"], s["expanded"], s["old_to_new"] = subdivide_cell_list(
cells, shadow_idx, s["u_axis"], s["v_axis"]
)
s["level"] += 1
s["ray_results"] = [None] * len(s["cells"])
s["cursor"] = 0
return 0.0
if phase == "final":
_finish_grid(s)
return None # stop timer
return None
def _start_final_grid(s):
if s["max_level"] == 0 or not s.get("expanded"):
sub_cells = s["cells"]
else:
sub_idx = sorted({ni for oi in s["expanded"] for ni in s["old_to_new"][oi]})
sub_cells = [s["cells"][i] for i in sub_idx]
s["full_cells"] = s["cells"] # keep for mesh building
s["cells"] = sub_cells
s["ray_results"] = [None] * len(sub_cells)
s["cursor"] = 0
s["phase"] = "final"
def _finish_grid(s):
face_data = {}
for hits in s["ray_results"]:
if not hits: continue
for i, (d, obj_name, poly_idx, hit_pt) in enumerate(hits):
key = (obj_name, poly_idx)
if key not in face_data:
face_data[key] = {"status": "lit", "hit_points": []}
if i == 0:
if face_data[key]["status"] != "shadow":
face_data[key]["status"] = "lit"
else:
face_data[key]["status"] = "shadow"
face_data[key]["hit_points"].append(hit_pt.copy())
all_cells = s.get("full_cells") or s["cells"]
me = build_mesh_from_cells(all_cells, PLANE_MESH_NAME)
plane_obj = bpy.data.objects.new(PLANE_OBJ_NAME, me)
bpy.context.collection.objects.link(plane_obj)
plane_obj["sun_shadow_plane"] = True
plane_obj.matrix_world = Matrix.Identity(4)
plane_obj.data.materials.append(ensure_plane_material())
coll = create_empties_collection(bpy.context)
empty_count = add_empties_for_face_data(face_data, s["mesh_objs"], coll)
shadow_count = sum(1 for v in face_data.values() if v["status"] == "shadow")
lit_count = sum(1 for v in face_data.values() if v["status"] == "lit")
elapsed = time.time() - s["t0"]
props = bpy.context.scene.ssp_props
props.last_op_time = elapsed
props.last_cell_count = len(all_cells)
props.last_empty_count = empty_count
props.is_running = False
_clear_header()
_state.clear()
print(f"[Sun Shadow Grid] Lv {s['level']} | Cells: {len(all_cells)} | "
f"Shadow: {shadow_count}/{empty_count} | Lit: {lit_count} | {fmt_time(elapsed)}")
def _tick_surface():
"""Timer callback for method 2 (surface sampling)."""
s = _state
if not s or not s.get("running"):
_clear_header(); return None
props = bpy.context.scene.ssp_props
batch = props.batch_size
scene = s["scene"]; depsgraph = s["depsgraph"]
sun_dir = s["sun_dir"]; sun_vis = s["sun_vis"]
samples = s["samples"]; cursor = s["cursor"]
ray_length = s["ray_length"]; face_data = s["face_data"]
end = min(cursor + batch, len(samples))
for i in range(cursor, end):
origin, src_obj, src_poly_idx = samples[i]
hits = cast_one_ray_m2(scene, depsgraph, sun_dir, origin,
src_obj, src_poly_idx, ray_length, sun_vis)
for key, pts in hits.items():
if key not in face_data:
face_data[key] = {"status": "shadow", "hit_points": []}
face_data[key]["hit_points"].extend(pts)
s["cursor"] = end
total = len(samples)
pct = int(100 * end / total) if total else 100
_set_header(f"Sun Shadow [Surface] — {end}/{total} rays ({pct}%) | Cancel to stop")
if end < total:
return 0.0
# Finished
coll = create_empties_collection(bpy.context)
empty_count = add_empties_for_face_data(face_data, s["mesh_objs"], coll)
elapsed = time.time() - s["t0"]
props.last_op_time = elapsed
props.last_cell_count = total
props.last_empty_count = empty_count
props.is_running = False
_clear_header()
_state.clear()
print(f"[Sun Shadow Surface] Points: {total} | "
f"Shadow faces: {len(face_data)}/{empty_count} | {fmt_time(elapsed)}")
return None
# ---------------------------------------------------------------------------
# Operators
# ---------------------------------------------------------------------------
class SSP_OT_RunGrid(bpy.types.Operator):
bl_idname = "ssp.run_grid"
bl_label = "Run (Adaptive Grid)"
bl_description = "Compute cast shadows with adaptive grid. Use Cancel to stop."
bl_options = {"REGISTER", "UNDO"}
def execute(self, context):
props = context.scene.ssp_props
sun = get_sun_light(context)
if not sun:
self.report({"ERROR"}, "No SUN light found."); return {"CANCELLED"}
sun_dir = sun_direction(sun)
mesh_objs = scene_mesh_objects(context, sun)
world_verts = collect_world_vertices(context, sun)
if not world_verts:
self.report({"ERROR"}, "No visible mesh found."); return {"CANCELLED"}
purge_shadow_helpers()
projs = [v.dot(sun_dir) for v in world_verts]
farthest = world_verts[projs.index(max(projs))]
u_axis, v_axis = build_plane_axes(sun_dir)
us = [(p - farthest).dot(u_axis) for p in world_verts]
vs = [(p - farthest).dot(v_axis) for p in world_verts]
g = props.grid_size
def ceil_g(dim): return max(1, math.ceil(dim / g)) * g
ru = ceil_g(max(us) - min(us)); rv = ceil_g(max(vs) - min(vs))
plane_center = (farthest + u_axis*((min(us)+max(us))/2)
+ v_axis*((min(vs)+max(vs))/2))
extent = get_scene_extent(world_verts, sun_dir)
cells, nu, nv = make_base_grid(plane_center, u_axis, v_axis, ru/2, rv/2, g)
_state.clear()
_state.update({
"running": True,
"phase": "base",
"t0": time.time(),
"scene": context.scene,
"depsgraph": context.evaluated_depsgraph_get(),
"sun_dir": sun_dir,
"sun_vis": build_sun_visible_faces(mesh_objs, sun_dir),
"extent": extent,
"u_axis": u_axis,
"v_axis": v_axis,
"mesh_objs": mesh_objs,
"max_level": props.max_detail_level,
"level": 0,
"cells": cells,
"ray_results":[None] * len(cells),
"cursor": 0,
"expanded": set(),
"old_to_new": {i: [i] for i in range(len(cells))},
})
props.is_running = True
bpy.app.timers.register(_tick_grid, first_interval=0.0, persistent=False)
return {"FINISHED"}
class SSP_OT_RunSurface(bpy.types.Operator):
bl_idname = "ssp.run_surface"
bl_label = "Run (Surface Sampling)"
bl_description = "Compute cast shadows via surface sampling. Use Cancel to stop."
bl_options = {"REGISTER", "UNDO"}
def execute(self, context):
props = context.scene.ssp_props
sun = get_sun_light(context)
if not sun:
self.report({"ERROR"}, "No SUN light found."); return {"CANCELLED"}
sun_dir = sun_direction(sun)
mesh_objs = scene_mesh_objects(context, sun)
world_verts = collect_world_vertices(context, sun)
if not world_verts:
self.report({"ERROR"}, "No visible mesh found."); return {"CANCELLED"}
purge_shadow_helpers()
sun_vis = build_sun_visible_faces(mesh_objs, sun_dir)
extent = get_scene_extent(world_verts, sun_dir)
samples = sample_points_on_visible_faces(
mesh_objs, sun_vis, sun_dir,
props.surface_dist_min, props.surface_mode, props.surface_merge_dist
)
if not samples:
self.report({"ERROR"}, "No points sampled. Reduce minimum distance.")
return {"CANCELLED"}
_state.clear()
_state.update({
"running": True,
"t0": time.time(),
"scene": context.scene,
"depsgraph": context.evaluated_depsgraph_get(),
"sun_dir": sun_dir,
"sun_vis": sun_vis,
"mesh_objs": mesh_objs,
"ray_length":extent + 2.0,
"samples": samples,
"cursor": 0,
"face_data": {},
})
props.is_running = True
bpy.app.timers.register(_tick_surface, first_interval=0.0, persistent=False)
return {"FINISHED"}
class SSP_OT_Cancel(bpy.types.Operator):
bl_idname = "ssp.cancel"
bl_label = "Cancel"
bl_description = "Stop the running calculation."
bl_options = {"INTERNAL"}
def execute(self, context):
_state["running"] = False
context.scene.ssp_props.is_running = False
_clear_header()
return {"FINISHED"}
# ---------------------------------------------------------------------------
# Properties
# ---------------------------------------------------------------------------
class SSP_Properties(bpy.types.PropertyGroup):
method: bpy.props.EnumProperty(
name="Method",
items=[
("GRID", "Adaptive Grid", "Grid on the plane, refined in shadow zones", "MESH_GRID", 0),
("SURFACE", "Surface Sampling", "Points sampled on sun-visible surfaces", "POINTCLOUD_DATA", 1),
],
default="GRID",
)
grid_size: bpy.props.FloatProperty(
name="Base Cell Size", description="Side length of the base grid cell in metres",
default=1.0, min=0.01, max=100.0, unit="LENGTH", precision=3,
)
max_detail_level: bpy.props.IntProperty(
name="Detail Level", description="Number of refinement passes (0 = base grid only)",
default=2, min=0, max=8,
)
surface_dist_min: bpy.props.FloatProperty(
name="Min Distance", description="Minimum distance between sampled points (m)",
default=0.5, min=0.001, max=100.0, unit="LENGTH", precision=3,
)
surface_mode: bpy.props.EnumProperty(
name="Distribution",
items=[
("POISSON", "Poisson Disk", "Uniform distribution with guaranteed minimum distance", "OUTLINER_OB_POINTCLOUD", 0),
("RANDOM", "Random", "Uniform random distribution by area (faster)", "RNDCURVE", 1),
],
default="POISSON",
)
surface_merge_dist: bpy.props.FloatProperty(
name="Merge Distance",
description="Discard face points closer than this on the solar projection plane. 0 = disabled.",
default=0.0, min=0.0, max=100.0, unit="LENGTH", precision=3,
)
batch_size: bpy.props.IntProperty(
name="Batch Size",
description="Rays per timer tick. Higher = faster, less responsive cancel.",
default=256, min=16, max=8192,
)
is_running: bpy.props.BoolProperty(default=False)
last_op_time: bpy.props.FloatProperty(default=0.0)
last_cell_count: bpy.props.IntProperty(default=0)
last_empty_count: bpy.props.IntProperty(default=0)
# ---------------------------------------------------------------------------
# Panel
# ---------------------------------------------------------------------------
class SSP_PT_Panel(bpy.types.Panel):
bl_label = "Sun Shadow Plane"
bl_idname = "SSP_PT_main"
bl_space_type = "VIEW_3D"
bl_region_type = "UI"
bl_category = "Sun Shadow"
def draw(self, context):
layout = self.layout
props = context.scene.ssp_props
sun = get_sun_light(context)
box = layout.box()
if sun:
box.label(text=f"Sun: {sun.name}", icon="LIGHT_SUN")
d = sun_direction(sun)
c = box.column(align=True)
c.label(text=f"Dir X: {d.x:.3f}")
c.label(text=f"Dir Y: {d.y:.3f}")
c.label(text=f"Dir Z: {d.z:.3f}")
else:
box.label(text="No Sun light found!", icon="ERROR")
layout.separator()
row = layout.row(); row.enabled = not props.is_running
row.prop(props, "method", expand=True)
layout.separator()
box2 = layout.box(); box2.enabled = not props.is_running
if props.method == "GRID":
box2.label(text="Adaptive Grid", icon="MESH_GRID")
box2.prop(props, "grid_size")
box2.prop(props, "max_detail_level", slider=True)
else:
box2.label(text="Surface Sampling", icon="POINTCLOUD_DATA")
box2.prop(props, "surface_dist_min")
box2.prop(props, "surface_mode", expand=True)
r2 = box2.row(align=True)
r2.prop(props, "surface_merge_dist")
if props.surface_merge_dist <= 0:
r2.label(text="(disabled)", icon="CANCEL")
layout.separator()
perf = layout.box(); perf.enabled = not props.is_running
perf.label(text="Performance", icon="MOD_MULTIRES")
perf.prop(props, "batch_size", slider=True)
layout.separator()
if props.is_running:
col = layout.column(); col.scale_y = 1.6; col.alert = True
col.operator("ssp.cancel", icon="X")
else:
col = layout.column(); col.scale_y = 1.6; col.enabled = sun is not None
if props.method == "GRID":
col.operator("ssp.run_grid", icon="LIGHT_SUN")
else:
col.operator("ssp.run_surface", icon="LIGHT_SUN")
if props.last_op_time > 0 and not props.is_running:
layout.separator()
b = layout.box(); b.label(text="Last run", icon="INFO")
c2 = b.column(align=True)
lbl = "Cells" if props.method == "GRID" else "Sampled points"
ico = "MESH_GRID" if props.method == "GRID" else "POINTCLOUD_DATA"
c2.label(text=f"{lbl}: {props.last_cell_count}", icon=ico)
c2.label(text=f"Empties: {props.last_empty_count}", icon="EMPTY_SINGLE_ARROW")
c2.label(text=f"Time: {fmt_time(props.last_op_time)}", icon="TIME")
# ---------------------------------------------------------------------------
# Registration
# ---------------------------------------------------------------------------
classes = (
SSP_Properties,
SSP_OT_RunGrid,
SSP_OT_RunSurface,
SSP_OT_Cancel,
SSP_PT_Panel,
)
def register():
for cls in classes:
bpy.utils.register_class(cls)
bpy.types.Scene.ssp_props = bpy.props.PointerProperty(type=SSP_Properties)
def unregister():
# Stop any running timer on unregister
_state["running"] = False
for cls in reversed(classes):
bpy.utils.unregister_class(cls)
del bpy.types.Scene.ssp_props
if __name__ == "__main__":
register()