-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsection_tool.py
More file actions
1858 lines (1614 loc) · 69.5 KB
/
Copy pathsection_tool.py
File metadata and controls
1858 lines (1614 loc) · 69.5 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
# section_tool.py — Section Toolbox core (GPL v3)
# Author: Victor Calixto
# Version: 0.0.2 (core module)
# Blender: 3.5–4.5+
#
# Notes for Extension Review:
# - No bl_info here (kept in __init__.py for Extensions).
# - Avoids context-dependent bpy.ops calls for modifier reordering (uses obj.modifiers.move).
import bpy
import bmesh
import os
from mathutils import Vector, Matrix, Euler
from mathutils.bvhtree import BVHTree
from bpy.types import Operator, Panel, PropertyGroup
from bpy.props import (
BoolProperty, StringProperty, EnumProperty, PointerProperty, FloatProperty, IntProperty
)
import xml.etree.ElementTree as ET
# ------------------------------- Constants ----------------------------------
BOX_PREFIX = "SectionBox"
PLANE_PREFIX = "SectionPlane"
MOD_PREFIX = "SBX_"
PROP_TARGETS = "sbx_targets"
PROP_PTARGETS = "sbp_targets"
PROP_LAST_ITER_BOX = "sbx_last_iter_name"
PROP_LAST_ITER_TAGB = "sbx_last_iter_tag"
PROP_LAST_ITER_PLN = "sbp_last_iter_name"
PROP_LAST_ITER_TAGP = "sbp_last_iter_tag"
# -------------------------------- Utilities ---------------------------------
def _get_active_box(context):
ob = context.active_object
if ob and ob.type == "MESH" and ob.name.startswith(BOX_PREFIX):
return ob
return None
def _get_active_plane(context):
ob = context.active_object
if ob and ob.type == "MESH" and ob.name.startswith(PLANE_PREFIX):
return ob
return None
def _objects_from_target_mode(context, mode="SELECTION", collection_name=""):
objs = []
if mode == "SELECTION":
objs = [o for o in context.selected_objects if o.type == "MESH"]
elif mode == "COLLECTION":
col = bpy.data.collections.get(collection_name)
if col:
for o in col.all_objects:
if o.type == "MESH":
objs.append(o)
return objs
def _ensure_box_display(ob):
ob.display_type = "WIRE"
ob.show_in_front = True
ob.hide_render = True
ob.show_bounds = True
ob.display_bounds_type = "BOX"
def _ensure_plane_display(ob):
ob.display_type = "WIRE"
ob.show_in_front = True
ob.hide_render = True
def _selection_bbox(objs):
"""World-space AABB of evaluated selection (modifiers applied)."""
if not objs:
return Vector((0, 0, 0)), Vector((1, 1, 1))
deps = bpy.context.evaluated_depsgraph_get()
mins = Vector(( 1e18, 1e18, 1e18))
maxs = Vector((-1e18, -1e18, -1e18))
for ob in objs:
ob_eval = ob.evaluated_get(deps)
if ob_eval.type == "MESH":
me = ob_eval.to_mesh(preserve_all_data_layers=False)
if me and me.vertices:
mw = ob_eval.matrix_world
for v in me.vertices:
wv = mw @ v.co
mins.x = min(mins.x, wv.x); mins.y = min(mins.y, wv.y); mins.z = min(mins.z, wv.z)
maxs.x = max(maxs.x, wv.x); maxs.y = max(maxs.y, wv.y); maxs.z = max(maxs.z, wv.z)
ob_eval.to_mesh_clear()
continue
try:
bb = ob_eval.bound_box
mw = ob_eval.matrix_world
for c in bb:
wv = mw @ Vector(c)
mins.x = min(mins.x, wv.x); mins.y = min(mins.y, wv.y); mins.z = min(mins.z, wv.z)
maxs.x = max(maxs.x, wv.x); maxs.y = max(maxs.y, wv.y); maxs.z = max(maxs.z, wv.z)
except Exception:
pass
size = (maxs - mins)
size.x = max(size.x, 0.001); size.y = max(size.y, 0.001); size.z = max(size.z, 0.001)
center = (maxs + mins) * 0.5
return center, size
def _set_targets_prop_box(box, objs):
box[PROP_TARGETS] = ",".join([o.name for o in objs])
def _get_targets_from_box(box):
names = box.get(PROP_TARGETS, "")
if not names:
return []
out = []
for n in names.split(","):
o = bpy.data.objects.get(n)
if o:
out.append(o)
return out
def _set_targets_prop_plane(plane, objs):
plane[PROP_PTARGETS] = ",".join([o.name for o in objs])
def _get_targets_from_plane(plane):
names = plane.get(PROP_PTARGETS, "")
if not names:
return []
out = []
for n in names.split(","):
o = bpy.data.objects.get(n)
if o:
out.append(o)
return out
def _add_boolean(o, box):
mod_name = MOD_PREFIX + box.name
mod = o.modifiers.get(mod_name)
if not mod:
mod = o.modifiers.new(mod_name, "BOOLEAN")
mod.operation = "INTERSECT"
mod.solver = "EXACT"
mod.object = box
# Move boolean to the TOP using lower-level API (no bpy.ops).
try:
mods = o.modifiers
idx = list(mods).index(mod)
if idx != 0:
mods.move(idx, 0)
except Exception:
pass
def _remove_boolean(o, box):
mod_name = MOD_PREFIX + box.name
mod = o.modifiers.get(mod_name)
if mod:
o.modifiers.remove(mod)
def _link_exclusive_to_collection(obj, col):
"""Unlink obj from all collections, then link only to col (safe for Blender 4.5)."""
for c in tuple(obj.users_collection):
try:
c.objects.unlink(obj)
except Exception:
pass
if col.objects.get(obj.name) is None:
col.objects.link(obj)
scene_root = bpy.context.scene.collection
if scene_root.objects.get(obj.name):
try:
scene_root.objects.unlink(obj)
except Exception:
pass
# -------- Results collections (Box) --------
def _ensure_results_collection_box(box):
name = f"SBX_Results_{box.name}"
col = bpy.data.collections.get(name)
if not col:
col = bpy.data.collections.new(name)
if box.users_collection:
box.users_collection[0].children.link(col)
else:
bpy.context.scene.collection.children.link(col)
return col
def _next_iteration_collections_box(box, face_code):
root = _ensure_results_collection_box(box)
base = f"{root.name}__Section_"
idx = 1
while True:
main_name = f"{base}{idx:03d}_{face_code}"
if bpy.data.collections.get(main_name) is None:
break
idx += 1
col_main = bpy.data.collections.new(main_name); root.children.link(col_main)
col_cut = bpy.data.collections.new(main_name + "__Cut"); col_main.children.link(col_cut)
col_mesh = bpy.data.collections.new(main_name + "__Meshes"); col_main.children.link(col_mesh)
col_proj = bpy.data.collections.new(main_name + "__Projection"); col_main.children.link(col_proj)
emp = bpy.data.objects.new(f"SBX_FrameAxes_{idx:03d}_{face_code}", None)
emp.empty_display_type = "PLAIN_AXES"
emp.matrix_world = box.matrix_world.copy()
_link_exclusive_to_collection(emp, col_main)
iter_tag = f"S{idx:03d}_{face_code}"
box[PROP_LAST_ITER_BOX] = main_name
box[PROP_LAST_ITER_TAGB] = iter_tag
return col_main, col_cut, col_mesh, col_proj, idx, iter_tag
# -------- Results collections (Plane) --------
def _ensure_results_collection_plane(plane):
name = f"SBP_Results_{plane.name}"
col = bpy.data.collections.get(name)
if not col:
col = bpy.data.collections.new(name)
if plane.users_collection:
plane.users_collection[0].children.link(col)
else:
bpy.context.scene.collection.children.link(col)
return col
def _next_iteration_collections_plane(plane, face_tag):
root = _ensure_results_collection_plane(plane)
base = f"{root.name}__Section_"
idx = 1
while True:
main_name = f"{base}{idx:03d}_{face_tag}"
if bpy.data.collections.get(main_name) is None:
break
idx += 1
col_main = bpy.data.collections.new(main_name); root.children.link(col_main)
col_plane = bpy.data.collections.new(main_name + "__Plane"); col_main.children.link(col_plane)
col_cut = bpy.data.collections.new(main_name + "__Cut"); col_main.children.link(col_cut)
col_mesh = bpy.data.collections.new(main_name + "__Meshes"); col_main.children.link(col_mesh)
col_elev = bpy.data.collections.new(main_name + "__Elevation"); col_main.children.link(col_elev)
plane[PROP_LAST_ITER_PLN] = main_name
plane[PROP_LAST_ITER_TAGP] = f"S{idx:03d}_{face_tag}"
return col_main, col_plane, col_cut, col_mesh, col_elev, idx, plane[PROP_LAST_ITER_TAGP]
# ----------------------- Transforms & frames --------------------------------
def _axis_vectors_world(mw):
xw = (mw.to_3x3() @ Vector((1, 0, 0))).normalized()
yw = (mw.to_3x3() @ Vector((0, 1, 0))).normalized()
zw = (mw.to_3x3() @ Vector((0, 0, 1))).normalized()
return xw, yw, zw
def _apply_dims_with_anchors(box, w, d, h, ax_anchor, ay_anchor, az_anchor):
mw = box.matrix_world
origin = mw @ Vector((0, 0, 0))
xw, yw, zw = _axis_vectors_world(mw)
cur_w = max(box.dimensions.x, 0.001)
cur_d = max(box.dimensions.y, 0.001)
cur_h = max(box.dimensions.z, 0.001)
px_cur = origin + xw * (cur_w * 0.5); nx_cur = origin - xw * (cur_w * 0.5)
py_cur = origin + yw * (cur_d * 0.5); ny_cur = origin - yw * (cur_d * 0.5)
pz_cur = origin + zw * (cur_h * 0.5); nz_cur = origin - zw * (cur_h * 0.5)
w = max(w, 0.001); d = max(d, 0.001); h = max(h, 0.001)
box.dimensions = (w, d, h)
new_origin = origin
if ax_anchor == "NEG":
nx_new = new_origin - xw * (w * 0.5); new_origin += (nx_cur - nx_new)
elif ax_anchor == "POS":
px_new = new_origin + xw * (w * 0.5); new_origin += (px_cur - px_new)
if ay_anchor == "NEG":
ny_new = new_origin - yw * (d * 0.5); new_origin += (ny_cur - ny_new)
elif ay_anchor == "POS":
py_new = new_origin + yw * (d * 0.5); new_origin += (py_cur - py_new)
if az_anchor == "NEG":
nz_new = new_origin - zw * (h * 0.5); new_origin += (nz_cur - nz_new)
elif az_anchor == "POS":
pz_new = new_origin + zw * (h * 0.5); new_origin += (pz_cur - pz_new)
cur_origin = box.matrix_world @ Vector((0, 0, 0))
box.location += (new_origin - cur_origin)
def _on_dim_update(self, context):
try:
if not context or not getattr(self, "live_link", True):
return
box = _get_active_box(context)
if not box:
return
_apply_dims_with_anchors(
box,
self.width, self.depth, self.height,
self.anchor_x, self.anchor_y, self.anchor_z
)
except Exception:
pass
# -------- Live move & rotate (box local axes) --------
def _on_move_update(self, context):
try:
if not context or not getattr(self, "live_link", True):
return
box = _get_active_box(context)
if not box:
return
dx = self.move_x - self.prev_move_x
dy = self.move_y - self.prev_move_y
dz = self.move_z - self.prev_move_z
if abs(dx) + abs(dy) + abs(dz) < 1e-12:
return
xw, yw, zw = _axis_vectors_world(box.matrix_world)
box.location += xw * dx + yw * dy + zw * dz
self.prev_move_x = self.move_x
self.prev_move_y = self.move_y
self.prev_move_z = self.move_z
except Exception:
pass
def _rotate_about_origin_local(box, rx_deg, ry_deg, rz_deg):
if abs(rx_deg) + abs(ry_deg) + abs(rz_deg) < 1e-12:
return
rx = rx_deg * 3.141592653589793 / 180.0
ry = ry_deg * 3.141592653589793 / 180.0
rz = rz_deg * 3.141592653589793 / 180.0
mw = box.matrix_world.copy()
loc = mw.translation.copy()
Rloc = Euler((rx, ry, rz), "XYZ").to_matrix().to_4x4()
box.matrix_world = Matrix.Translation(loc) @ (mw.to_3x3().to_4x4() @ Rloc) @ (mw.to_3x3().to_4x4().inverted()) @ Matrix.Translation(-loc) @ mw
def _on_rot_update(self, context):
try:
if not context or not getattr(self, "live_link", True):
return
box = _get_active_box(context)
if not box:
return
drx = self.rot_x - self.prev_rot_x
dry = self.rot_y - self.prev_rot_y
drz = self.rot_z - self.prev_rot_z
if abs(drx) + abs(dry) + abs(drz) < 1e-12:
return
_rotate_about_origin_local(box, drx, dry, drz)
self.prev_rot_x = self.rot_x
self.prev_rot_y = self.rot_y
self.prev_rot_z = self.rot_z
except Exception:
pass
# -------- Plane frame & live size with anchors --------
def _ensure_right_handed_uv(u: Vector, v: Vector, n: Vector):
"""Ensure (u, v, n) is right-handed: if u×v doesn't align with n, flip v."""
if u.cross(v).dot(n) < 0.0:
v = -v
return u.normalized(), v.normalized()
def _plane_frame_from_object(plane_obj):
mw = plane_obj.matrix_world
u = (mw.to_3x3() @ Vector((1, 0, 0))).normalized()
v = (mw.to_3x3() @ Vector((0, 1, 0))).normalized()
n = (mw.to_3x3() @ Vector((0, 0, 1))).normalized()
u, v = _ensure_right_handed_uv(u, v, n)
center = mw.translation
hu = max(0.001, plane_obj.dimensions.x * 0.5)
hv = max(0.001, plane_obj.dimensions.y * 0.5)
return {"center": center, "normal": n, "u": u, "v": v, "hu": hu, "hv": hv, "dir_in": n}
def _apply_plane_sizes_with_anchors(plane, su, sv, au, av):
mw = plane.matrix_world
origin = mw @ Vector((0, 0, 0))
u = (mw.to_3x3() @ Vector((1, 0, 0))).normalized()
v = (mw.to_3x3() @ Vector((0, 1, 0))).normalized()
cur_su = max(plane.dimensions.x, 0.001)
cur_sv = max(plane.dimensions.y, 0.001)
pu_cur = origin + u * (cur_su * 0.5); nu_cur = origin - u * (cur_su * 0.5)
pv_cur = origin + v * (cur_sv * 0.5); nv_cur = origin - v * (cur_sv * 0.5)
su = max(su, 0.001); sv = max(sv, 0.001)
plane.dimensions = (su, sv, plane.dimensions.z)
new_origin = origin
if au == "NEG":
nu_new = new_origin - u * (su * 0.5); new_origin += (nu_cur - nu_new)
elif au == "POS":
pu_new = new_origin + u * (su * 0.5); new_origin += (pu_cur - pu_new)
if av == "NEG":
nv_new = new_origin - v * (sv * 0.5); new_origin += (nv_cur - nv_new)
elif av == "POS":
pv_new = new_origin + v * (sv * 0.5); new_origin += (pv_cur - pv_new)
cur_origin = plane.matrix_world @ Vector((0, 0, 0))
plane.location += (new_origin - cur_origin)
def _on_plane_size_update(self, context):
try:
if not context or not getattr(self, "plane_live_link", True):
return
pl = _get_active_plane(context)
if not pl:
return
_apply_plane_sizes_with_anchors(pl, self.plane_size_u, self.plane_size_v, self.plane_anchor_u, self.plane_anchor_v)
except Exception:
pass
# ---------------------------- Mesh & projection utils ------------------------
def _project_to_frame(p_world: Vector, frame):
d = p_world - frame["center"]
return d.dot(frame["u"]), d.dot(frame["v"])
def _unproject_from_frame(u: float, v: float, frame):
return frame["center"] + frame["u"] * u + frame["v"] * v
def _project_point_onto_plane(p: Vector, frame):
n = frame["normal"]
return p - n * (p - frame["center"]).dot(n)
def _clip_segment_to_rect(u1, v1, u2, v2, hu, hv):
du, dv = u2 - u1, v2 - v1
t0, t1 = 0.0, 1.0
def clip(p, q, t0, t1):
if p == 0.0:
return (t0, t1) if q >= 0.0 else (None, None)
t = q / p
if p < 0.0:
if t > t1: return (None, None)
if t > t0: t0 = t
else:
if t < t0: return (None, None)
if t < t1: t1 = t
return (t0, t1)
for p, q in [(-du, u1 + hu), (du, hu - u1), (-dv, v1 + hv), (dv, hv - v1)]:
t0, t1 = clip(p, q, t0, t1)
if t0 is None:
return None
return (u1 + du * t0, v1 + dv * t0, u1 + du * t1, v1 + dv * t1)
def _intersect_mesh_with_plane(obj, plane_point_world, plane_normal_world):
"""Return polylines (list[list[Vector]]) where the mesh intersects the plane (evaluated)."""
deps = bpy.context.evaluated_depsgraph_get()
ob_eval = obj.evaluated_get(deps)
me = ob_eval.to_mesh(preserve_all_data_layers=False)
mw = ob_eval.matrix_world
inv = mw.inverted()
plane_co_local = inv @ plane_point_world
plane_no_local = (inv.to_3x3().transposed() @ plane_normal_world).normalized()
bm = bmesh.new()
bm.from_mesh(me)
geom = bm.verts[:] + bm.edges[:] + bm.faces[:]
res = bmesh.ops.bisect_plane(
bm,
geom=geom,
plane_co=plane_co_local,
plane_no=plane_no_local,
use_snap_center=False,
clear_inner=False,
clear_outer=False,
)
cut_edges = [e for e in res.get("geom_cut", []) if isinstance(e, bmesh.types.BMEdge)]
segments = []
for e in cut_edges:
v1 = mw @ e.verts[0].co
v2 = mw @ e.verts[1].co
segments.append((v1, v2))
bm.free()
ob_eval.to_mesh_clear()
return _stitch_segments(segments)
def _all_mesh_edges_world(obj):
deps = bpy.context.evaluated_depsgraph_get()
ob_eval = obj.evaluated_get(deps)
me = ob_eval.to_mesh(preserve_all_data_layers=False)
mw = ob_eval.matrix_world
edges = []
for e in me.edges:
v1 = mw @ me.vertices[e.vertices[0]].co
v2 = mw @ me.vertices[e.vertices[1]].co
edges.append((v1, v2))
ob_eval.to_mesh_clear()
return edges
def _stitch_segments(segments, tol=1e-6):
chains = []
for a, b in segments:
placed = False
for ch in chains:
if (ch[-1] - a).length <= tol:
ch.append(b); placed = True; break
if (ch[-1] - b).length <= tol:
ch.append(a); placed = True; break
if (ch[0] - a).length <= tol:
ch.insert(0, b); placed = True; break
if (ch[0] - b).length <= tol:
ch.insert(0, a); placed = True; break
if not placed:
chains.append([a, b])
return chains
def _make_curve_from_polyline(points, name="SBX_Line"):
cu = bpy.data.curves.new(name, "CURVE")
cu.dimensions = "3D"
spl = cu.splines.new("POLY")
spl.points.add(len(points) - 1)
for i, p in enumerate(points):
spl.points[i].co = (p.x, p.y, p.z, 1)
ob = bpy.data.objects.new(name, cu)
return ob
def _ensure_closed(points, tol=1e-5):
if not points:
return points
if (points[0] - points[-1]).length > tol:
points = points + [points[0].copy()]
return points
def _make_ngon_face(points_world, name="SBX_FillFace"):
if len(points_world) < 3:
return None
bm = bmesh.new()
verts = [bm.verts.new((p.x, p.y, p.z)) for p in points_world]
bm.verts.index_update()
try:
bm.faces.new(verts)
except ValueError:
edges = [bm.edges.new((verts[i], verts[(i+1) % len(verts)])) for i in range(len(verts))]
bmesh.ops.edgenet_fill(bm, edges=edges)
bm.normal_update()
me = bpy.data.meshes.new(name)
bm.to_mesh(me)
bm.free()
ob = bpy.data.objects.new(name, me)
return ob
def _clip_edge_to_slab(a: Vector, b: Vector, face, tmin: float, tmax: float):
d = b - a
dir_in = face["dir_in"]
ta = (a - face["center"]).dot(dir_in)
tb = (b - face["center"]).dot(dir_in)
if (ta < tmin and tb < tmin) or (ta > tmax and tb > tmax):
return None
denom = (tb - ta)
qa, qb = a.copy(), b.copy()
if abs(denom) < 1e-12:
return (a, b) if (tmin <= ta <= tmax) else None
if ta < tmin:
lam = (tmin - ta) / denom; qa = a + d * lam; ta = tmin
elif ta > tmax:
lam = (tmax - ta) / denom; qa = a + d * lam; ta = tmax
if tb < tmin:
lam = (tmin - tb) / denom; qb = b + d * lam; tb = tmin
elif tb > tmax:
lam = (tmax - tb) / denom; qb = b + d * lam; tb = tmax
if (qb - qa).length <= 1e-9:
return None
return (qa, qb)
# -------------------- Freestyle-like outlines helpers ------------------------
def _world_normal_from_face(mw: Matrix, n_local: Vector) -> Vector:
return (mw.to_3x3().inverted().transposed() @ n_local).normalized()
def _build_world_bvhs(objects):
"""Build BVH trees in world space for simple hidden-line tests."""
deps = bpy.context.evaluated_depsgraph_get()
trees = []
for ob in objects:
ob_eval = ob.evaluated_get(deps)
me = ob_eval.to_mesh(preserve_all_data_layers=False)
if not me:
continue
mw = ob_eval.matrix_world
verts = [mw @ v.co for v in me.vertices]
if not verts or not me.polygons:
ob_eval.to_mesh_clear()
continue
verts_tuples = [tuple(v) for v in verts]
polys = [tuple(p.vertices) for p in me.polygons]
try:
tree = BVHTree.FromPolygons(verts_tuples, polys)
trees.append(tree)
except Exception:
pass
ob_eval.to_mesh_clear()
return trees
def _candidate_outline_edges_world(obj, view_dir_world: Vector):
"""
Return world-space segments that are either boundary edges (front-facing)
or silhouette edges (adjacent faces flip front/back) relative to view_dir_world.
"""
deps = bpy.context.evaluated_depsgraph_get()
ob_eval = obj.evaluated_get(deps)
me = ob_eval.to_mesh(preserve_all_data_layers=False)
if not me:
return []
mw = ob_eval.matrix_world
bm = bmesh.new()
bm.from_mesh(me)
bm.verts.ensure_lookup_table()
bm.edges.ensure_lookup_table()
bm.faces.ensure_lookup_table()
segs = []
cam_dir = view_dir_world.normalized()
def is_front(n_world: Vector) -> bool:
return (n_world.dot(cam_dir) < 0.0)
for e in bm.edges:
lf = e.link_faces
if len(lf) == 0:
continue # non-manifold
elif len(lf) == 1:
f = lf[0]
nW = _world_normal_from_face(mw, f.normal)
if is_front(nW):
v1 = mw @ e.verts[0].co
v2 = mw @ e.verts[1].co
segs.append((v1, v2))
elif len(lf) == 2:
f1, f2 = lf
n1 = _world_normal_from_face(mw, f1.normal)
n2 = _world_normal_from_face(mw, f2.normal)
if is_front(n1) != is_front(n2):
v1 = mw @ e.verts[0].co
v2 = mw @ e.verts[1].co
segs.append((v1, v2))
bm.free()
ob_eval.to_mesh_clear()
return segs
def _estimate_max_depth_along_dir(objects, frame, dir_sign: float):
"""If plane_depth <= 0, estimate a safe far depth from bounds."""
dir_vec = frame["normal"] * dir_sign
maxd = 0.0
for ob in objects:
mw = ob.matrix_world
try:
for c in ob.bound_box:
w = mw @ Vector(c)
d = (w - frame["center"]).dot(dir_vec)
if d > maxd:
maxd = d
except Exception:
pass
return max(maxd, frame["hu"] + frame["hv"])
# ---- HLR (split segments by visibility) ----
def _ray_occludes_point(p: Vector, frame, to_plane: Vector, bvh_trees, maxdist: float, eps: float) -> bool:
if not bvh_trees or maxdist <= eps:
return False
origin = p + to_plane * eps
dist = max(maxdist - eps * 0.5, eps)
for tree in bvh_trees:
hit = tree.ray_cast(origin, to_plane, dist)
if hit and hit[0] is not None:
return True
return False
def _split_segment_by_visibility(wp1: Vector, wp2: Vector, frame, camera_dir: Vector,
bvh_trees, samples: int = 13,
eps_scale: float = 1e-4, min_len_scale: float = 1e-5):
to_plane = (-camera_dir).normalized()
span = (frame["hu"] + frame["hv"])
seg_len = (wp2 - wp1).length
if seg_len <= 1e-9:
return []
base = max(5, samples)
extra = int(max(0, (seg_len / max(span, 1e-6)) * 64))
samples_eff = min(101, max(base, extra))
eps = max(1e-6, eps_scale * span)
min_len = max(1e-6, min_len_scale * span)
def dist_to_plane(p: Vector) -> float:
return (frame["center"] - p).dot(to_plane)
ts = [i / (samples_eff - 1) for i in range(samples_eff)]
pts = [wp1.lerp(wp2, t) for t in ts]
vis = []
for p in pts:
d = dist_to_plane(p)
if d <= eps * 2.0:
vis.append(True)
continue
occluded = _ray_occludes_point(p, frame, to_plane, bvh_trees, d, eps)
vis.append(not occluded)
out = []
i = 0
while i < len(ts) - 1:
if vis[i]:
j = i + 1
while j < len(ts) and vis[j]:
j += 1
a_t = ts[i]
b_t = ts[j - 1]
if i > 0 and not vis[i - 1]:
lo, hi = ts[i - 1], ts[i]
for _ in range(6):
mid = (lo + hi) * 0.5
pm = wp1.lerp(wp2, mid)
d = dist_to_plane(pm)
occ = (d > eps * 2.0) and _ray_occludes_point(pm, frame, to_plane, bvh_trees, d, eps)
if occ: lo = mid
else: hi = mid
a_t = hi
if j < len(ts) and not vis[j]:
lo, hi = ts[j - 1], ts[j]
for _ in range(6):
mid = (lo + hi) * 0.5
pm = wp1.lerp(wp2, mid)
d = dist_to_plane(pm)
occ = (d > eps * 2.0) and _ray_occludes_point(pm, frame, to_plane, bvh_trees, d, eps)
if occ: hi = mid
else: lo = mid
b_t = lo
pa = wp1.lerp(wp2, a_t)
pb = wp1.lerp(wp2, b_t)
if (pb - pa).length >= min_len:
out.append((pa, pb))
i = j
else:
i += 1
return out
# ------------- Helpers to map clipped UV back to 3D along a segment ---------
def _t_from_uv(u1, v1, u2, v2, uc, vc):
du = u2 - u1; dv = v2 - v1
if abs(du) >= abs(dv) and abs(du) > 1e-12:
return (uc - u1) / du
elif abs(dv) > 1e-12:
return (vc - v1) / dv
return 0.0
# ---- outline generation (3D-first HLR, then project) -----------------------
def _outline_segments_for_plane(targets, frame, dir_sign: float):
camera_dir = frame["normal"] * dir_sign
eps = max(1e-6, 1e-5 * (frame["hu"] + frame["hv"]))
tmin = eps
s = bpy.context.scene.sbx_settings
base_depth = max(0.0, getattr(s, "plane_depth", 0.0))
if base_depth <= 0.0:
tmax = max(eps, _estimate_max_depth_along_dir(targets, frame, dir_sign))
else:
tmax = max(eps, base_depth)
trees = _build_world_bvhs(targets)
out = []
tested = 0
for t in targets:
cand = _candidate_outline_edges_world(t, camera_dir)
for (a, b) in cand:
clipped = _clip_edge_to_plane_depth(a, b, frame, tmin, tmax, dir_sign=dir_sign)
if not clipped:
continue
qa, qb = clipped
pa = _project_point_onto_plane(qa, frame)
pb = _project_point_onto_plane(qb, frame)
u1, v1 = _project_to_frame(pa, frame)
u2, v2 = _project_to_frame(pb, frame)
c = _clip_segment_to_rect(u1, v1, u2, v2, frame["hu"], frame["hv"])
if not c:
continue
cu1, cv1, cu2, cv2 = c
tA = max(0.0, min(1.0, _t_from_uv(u1, v1, u2, v2, cu1, cv1)))
tB = max(0.0, min(1.0, _t_from_uv(u1, v1, u2, v2, cu2, cv2)))
qA = qa.lerp(qb, tA)
qB = qb.lerp(qb, tB) if False else qa.lerp(qb, tB) # keep style, ensure same lerp origin
tested += 1
visible_3d = _split_segment_by_visibility(
qA, qB, frame, camera_dir, trees,
samples=getattr(s, "hlr_samples", 13),
eps_scale=getattr(s, "hlr_eps", 1e-4),
min_len_scale=1e-5
)
for p3, q3 in visible_3d:
p2 = _project_point_onto_plane(p3, frame)
q2 = _project_point_onto_plane(q3, frame)
out.append((p2, q2))
if not out:
if tested == 0:
elev_segments = []
if tmax > tmin + 1e-9:
for t in targets:
edges = _all_mesh_edges_world(t)
for (a, b) in edges:
clipped = _clip_edge_to_plane_depth(a, b, frame, tmin, tmax, dir_sign=dir_sign)
if not clipped:
continue
qa, qb = clipped
pa = _project_point_onto_plane(qa, frame)
pb = _project_point_onto_plane(qb, frame)
u1, v1 = _project_to_frame(pa, frame)
u2, v2 = _project_to_frame(pb, frame)
c = _clip_segment_to_rect(u1, v1, u2, v2, frame["hu"], frame["hv"])
if not c:
continue
cu1, cv1, cu2, cv2 = c
p2 = _unproject_from_frame(cu1, cv1, frame)
q2 = _unproject_from_frame(cu2, cv2, frame)
elev_segments.append((p2, q2))
return _stitch_segments(elev_segments, tol=1e-6)
else:
return []
return _stitch_segments(out, tol=1e-6)
def _outline_segments_for_box(targets, face):
camera_dir = face["dir_in"]
eps = max(1e-6, 1e-5 * (face["hu"] + face["hv"]))
tmin = eps
tmax = max(eps, face["thickness"] - eps)
trees = _build_world_bvhs(targets)
out = []
tested = 0
for t in targets:
cand = _candidate_outline_edges_world(t, camera_dir)
for (a, b) in cand:
clipped = _clip_edge_to_slab(a, b, face, tmin, tmax)
if not clipped:
continue
qa, qb = clipped
pa = _project_point_onto_plane(qa, face)
pb = _project_point_onto_plane(qb, face)
u1, v1 = _project_to_frame(pa, face)
u2, v2 = _project_to_frame(pb, face)
c = _clip_segment_to_rect(u1, v1, u2, v2, face["hu"], face["hv"])
if not c:
continue
cu1, cv1, cu2, cv2 = c
tA = max(0.0, min(1.0, _t_from_uv(u1, v1, u2, v2, cu1, cv1)))
tB = max(0.0, min(1.0, _t_from_uv(u1, v1, u2, v2, cu2, cv2)))
qA = qa.lerp(qb, tA)
qB = qb.lerp(qb, tB) if False else qa.lerp(qb, tB)
tested += 1
s = bpy.context.scene.sbx_settings
visible_3d = _split_segment_by_visibility(
qA, qB, face, camera_dir, trees,
samples=getattr(s, "hlr_samples", 13),
eps_scale=getattr(s, "hlr_eps", 1e-4),
min_len_scale=1e-5
)
for p3, q3 in visible_3d:
p2 = _project_point_onto_plane(p3, face)
q2 = _project_point_onto_plane(q3, face)
out.append((p2, q2))
if not out:
if tested == 0:
proj_segments = []
for t in targets:
for (a, b) in _all_mesh_edges_world(t):
clipped = _clip_edge_to_slab(a, b, face, tmin, tmax)
if not clipped:
continue
qa, qb = clipped
pa = _project_point_onto_plane(qa, face)
pb = _project_point_onto_plane(qb, face)
u1, v1 = _project_to_frame(pa, face)
u2, v2 = _project_to_frame(pb, face)
c = _clip_segment_to_rect(u1, v1, u2, v2, face["hu"], face["hv"])
if not c:
continue
cu1, cv1, cu2, cv2 = c
p2 = _unproject_from_frame(cu1, cv1, face)
q2 = _unproject_from_frame(cu2, cv2, face)
proj_segments.append((p2, q2))
return _stitch_segments(proj_segments, tol=1e-6)
else:
return []
return _stitch_segments(out, tol=1e-6)
# --------- Frame objects for 2D export (view-aligned) -----------------------
def _create_face_frame_empty(face, iter_tag, col_main, n_view=None):
"""Create an Empty whose local XY matches the section plane in VIEW orientation."""
u = face["u"]; v = face["v"]; n = n_view if n_view is not None else face["normal"]
u, v = _ensure_right_handed_uv(u, v, n)
c = face["center"]
mw = Matrix((
(u.x, v.x, n.x, c.x),
(u.y, v.y, n.y, c.y),
(u.z, v.z, n.z, c.z),
(0.0, 0.0, 0.0, 1.0),
))
emp = bpy.data.objects.new(f"SBX_Frame2D_{iter_tag}", None)
emp.empty_display_type = "ARROWS"
emp.matrix_world = mw
_link_exclusive_to_collection(emp, col_main)
return emp
def _create_plane_frame_empty(frame, iter_tag, col_main, n_view):
"""Plane 2D frame, view-aligned (for planar sections)."""
u = frame["u"]; v = frame["v"]; n = n_view
u, v = _ensure_right_handed_uv(u, v, n)
c = frame["center"]
mw = Matrix((
(u.x, v.x, n.x, c.x),
(u.y, v.y, n.y, c.y),
(u.z, v.z, n.z, c.z),
(0.0, 0.0, 0.0, 1.0),
))
emp = bpy.data.objects.new(f"SBP_Frame2D_{iter_tag}", None)
emp.empty_display_type = "ARROWS"
emp.matrix_world = mw
_link_exclusive_to_collection(emp, col_main)
return emp
# ------------------------------- Properties ---------------------------------
class SBX_Settings(PropertyGroup):
# Box targeting
target_mode: EnumProperty(
name="Targets",
items=[("SELECTION", "Selection", "Use current selection"),
("COLLECTION", "Collection", "Use objects in a collection")],
default="SELECTION")
collection_name: StringProperty(name="Collection", description="Target collection name")
live_link: BoolProperty(name="Live Link (Box)", default=True, description="Live update for box size/move/rotate")
# Box: anchors & dims (live)
anchor_x: EnumProperty(name="X Anchor", items=[("CENTER","Center","Grow both"),("NEG","-X","Grow +X"),("POS","+X","Grow -X")], default="CENTER")
anchor_y: EnumProperty(name="Y Anchor", items=[("CENTER","Center","Grow both"),("NEG","-Y","Grow +Y"),("POS","+Y","Grow -Y")], default="CENTER")
anchor_z: EnumProperty(name="Z Anchor", items=[("CENTER","Center","Grow both"),("NEG","-Z","Grow +Z (bottom fixed)"),("POS","+Z","Grow -Z (top fixed)")], default="NEG")
width: FloatProperty(name="Width", default=1.0, min=0.001, update=_on_dim_update)
depth: FloatProperty(name="Depth", default=1.0, min=0.001, update=_on_dim_update)
height: FloatProperty(name="Height", default=1.0, min=0.001, update=_on_dim_update)
# Box: face for sectioning
face_choice: EnumProperty(name="Face", items=[("PX","+X",""),("NX","-X",""),("PY","+Y",""),("NY","-Y",""),("PZ","+Z",""),("NZ","-Z","")], default="PZ")
# Box: live move
move_x: FloatProperty(name="Move X", default=0.0, update=_on_move_update)
move_y: FloatProperty(name="Move Y", default=0.0, update=_on_move_update)
move_z: FloatProperty(name="Move Z", default=0.0, update=_on_move_update)
prev_move_x: FloatProperty(name="prev_move_x", default=0.0)
prev_move_y: FloatProperty(name="prev_move_y", default=0.0)
prev_move_z: FloatProperty(name="prev_move_z", default=0.0)
# Box: live rotate (degrees, local axes)
rot_x: FloatProperty(name="Rot X°", default=0.0, update=_on_rot_update)
rot_y: FloatProperty(name="Rot Y°", default=0.0, update=_on_rot_update)
rot_z: FloatProperty(name="Rot Z°", default=0.0, update=_on_rot_update)
prev_rot_x: FloatProperty(name="prev_rot_x", default=0.0)
prev_rot_y: FloatProperty(name="prev_rot_y", default=0.0)
prev_rot_z: FloatProperty(name="prev_rot_z", default=0.0)
# Planar: live link & anchors
plane_live_link: BoolProperty(name="Plane Live Link", default=True)
plane_anchor_u: EnumProperty(name="U Anchor", items=[("CENTER","Center","Grow both"),("NEG","-U","Grow +U"),("POS","+U","Grow -U")], default="CENTER")
plane_anchor_v: EnumProperty(name="V Anchor", items=[("CENTER","Center","Grow both"),("NEG","-V","Grow +V"),("POS","+V","Grow -V")], default="CENTER")
plane_orient: EnumProperty(name="Plane", items=[("XY","XY",""),("XZ","XZ",""),("YZ","YZ","")], default="XY")
plane_size_u: FloatProperty(name="Size U", default=5.0, min=0.01, update=_on_plane_size_update)
plane_size_v: FloatProperty(name="Size V", default=5.0, min=0.01, update=_on_plane_size_update)
plane_offset: FloatProperty(name="Offset", default=0.0, description="Move active plane along its normal by this amount")
plane_dir: EnumProperty(name="Direction", items=[("POS","+Normal","toward +N"),("NEG","-Normal","toward -N")], default="POS")
plane_depth: FloatProperty(name="Depth", default=2.0, min=0.0, description="Elevation slab thickness from plane along chosen direction")
# HLR tuning (shared by box & planar)
hlr_samples: IntProperty(
name="Visibility Samples",
description="Samples along each edge for visibility splitting",
default=13, min=5, max=101
)