stack3js 0.2.0 → 0.6.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/COMMAND.md +145 -0
  2. package/README.md +167 -4
  3. package/bin/stack3.mjs +1386 -186
  4. package/blender/import_stack.py +89 -0
  5. package/meshing/blocks.py +82 -0
  6. package/meshing/branches.py +62 -0
  7. package/meshing/dexel.py +67 -0
  8. package/meshing/field_data.py +19 -0
  9. package/meshing/finish_blender.py +203 -0
  10. package/meshing/finishing.py +155 -0
  11. package/meshing/geometry.py +71 -0
  12. package/meshing/guided.py +150 -0
  13. package/meshing/implicit.py +178 -0
  14. package/meshing/intersection.py +33 -0
  15. package/meshing/material.py +115 -0
  16. package/meshing/mesh.py +103 -0
  17. package/meshing/network.py +136 -0
  18. package/meshing/regularization.py +213 -0
  19. package/meshing/sections.py +165 -0
  20. package/meshing/signed_distance.py +93 -0
  21. package/package.json +9 -2
  22. package/references/hard-surface/README.md +40 -0
  23. package/references/hard-surface/atlas/concrete-barrier-4view.png +0 -0
  24. package/references/hard-surface/atlas/preview.pipeline.yaml +14 -0
  25. package/references/hard-surface/case-studies/benchmark/README.md +22 -0
  26. package/references/hard-surface/case-studies/benchmark/lod-bevel.pipeline.yaml +258 -0
  27. package/references/hard-surface/finishing/exports.yaml +10 -0
  28. package/references/hard-surface/finishing/finish-lod.pipeline.yaml +33 -0
  29. package/references/hard-surface/finishing/inputs/stack/stack.json +1 -0
  30. package/references/hard-surface/finishing/inputs/stack/stack.png +0 -0
  31. package/references/hard-surface/finishing/regularize.pipeline.yaml +46 -0
  32. package/references/hard-surface/measured-depth/sdf/compare.pipeline.yaml +12 -0
  33. package/references/hard-surface/measured-depth/sdf/inputs/field.npy +0 -0
  34. package/references/hard-surface/measured-depth/sdf/inputs/stack/stack.json +1 -0
  35. package/references/hard-surface/measured-depth/sdf/inputs/stack/stack.png +0 -0
  36. package/references/hard-surface/measured-depth/sdf/inputs/truth.json +1 -0
  37. package/references/hard-surface/measured-depth/sdf/sdf.guide.json +3 -0
  38. package/references/hard-surface/measured-depth/triple-dexel/compare.pipeline.yaml +12 -0
  39. package/references/hard-surface/measured-depth/triple-dexel/dexel.guide.json +3 -0
  40. package/references/hard-surface/measured-depth/triple-dexel/inputs/fixture.json +22 -0
  41. package/references/hard-surface/measured-depth/triple-dexel/inputs/stack/stack.json +22 -0
  42. package/references/hard-surface/measured-depth/triple-dexel/inputs/stack/stack.png +0 -0
  43. package/references/hard-surface/measured-depth/triple-dexel/inputs/triple-dexel.npz +0 -0
  44. package/references/hard-surface/schema/pipeline-fragment.schema.json +5 -0
  45. package/references/hard-surface/schema/pipeline.schema.json +181 -0
  46. package/schema/pipeline-fragment.schema.json +5 -0
  47. package/schema/pipeline.schema.json +181 -0
  48. package/verification/assembly.py +96 -0
  49. package/verification/landmarks.py +53 -0
  50. package/verification/panels.py +137 -0
  51. package/verification/projections.py +135 -0
  52. package/verification/verify.py +108 -0
  53. package/viewer/dist/assets/{GLTFExporter--hziUXc8.js → GLTFExporter-xdVCArY-.js} +1 -1
  54. package/viewer/dist/assets/compare-Du4RoRQO.js +6 -0
  55. package/viewer/dist/assets/compare.worker-CgJq-znx.js +21 -0
  56. package/viewer/dist/assets/presets-jXE0t1fU.js +1 -0
  57. package/viewer/dist/assets/preview-cache-BKV0EZl9.js +1 -0
  58. package/viewer/dist/assets/project-DtHHhfo-.js +17 -0
  59. package/viewer/dist/assets/reconstruct.worker-ONc9GyFO.js +21 -0
  60. package/viewer/dist/assets/{script-engine-CLj7QMLe.js → script-engine-Bs3azDYZ.js} +1 -1
  61. package/viewer/dist/assets/style-D6eZHs3D.js +4004 -0
  62. package/viewer/dist/assets/viewer-DIjS0No7.js +2 -0
  63. package/viewer/dist/compare.html +4 -4
  64. package/viewer/dist/index.html +9 -8
  65. package/viewer/dist/project.html +3 -3
  66. package/viewer/dist/assets/compare-DJ8rV3Rn.js +0 -6
  67. package/viewer/dist/assets/compare.worker-DK2lJl0n.js +0 -21
  68. package/viewer/dist/assets/presets-DwdZVYhs.js +0 -1
  69. package/viewer/dist/assets/preview-cache-DRF_H5pq.js +0 -58
  70. package/viewer/dist/assets/project-D8tR6U-_.js +0 -17
  71. package/viewer/dist/assets/reconstruct.worker-Cf8iZwT3.js +0 -21
  72. package/viewer/dist/assets/style-CWGgpweN.js +0 -3947
  73. package/viewer/dist/assets/viewer-CyGodHLY.js +0 -2
@@ -0,0 +1,89 @@
1
+ """Build a portable Blender scene from a stack3 bundle validated by the calling CLI."""
2
+ import json
3
+ import math
4
+ import sys
5
+ from pathlib import Path
6
+
7
+ import bpy
8
+ from mathutils import Vector
9
+
10
+ folder, output = map(Path, sys.argv[sys.argv.index('--') + 1:])
11
+ meta = json.loads((folder / 'stack.json').read_text())
12
+ bpy.ops.wm.read_factory_settings(use_empty=True)
13
+ scene = bpy.context.scene
14
+ atlas = bpy.data.images.load(str(folder / 'stack.png'))
15
+ atlas.pack()
16
+ width, depth = meta['width'], meta['depth']
17
+ sx, sy, _ = meta['size']
18
+ px, py, pz = meta['pivot']
19
+ spacing = meta['spacing']
20
+ aw, ah = atlas.size
21
+ verts, faces, uvs = [], [], []
22
+ for layer in range(meta['layers']):
23
+ left = (layer % meta['columns']) * width
24
+ top = (layer // meta['columns']) * depth
25
+ z = (layer + .5) * spacing - pz
26
+ start = len(verts)
27
+ faces.append((start, start + 1, start + 2, start + 3))
28
+ for x, y in ((0, 0), (1, 0), (1, 1), (0, 1)):
29
+ verts.append(((x - .5) * sx - px, (y - .5) * sy - py, z))
30
+ uvs.extend(((left + .5 + x * (width - 1)) / aw,
31
+ 1 - (top + .5 + y * (depth - 1)) / ah))
32
+
33
+ mesh = bpy.data.meshes.new('Sprite slices')
34
+ mesh.from_pydata(verts, [], faces)
35
+ mesh.update()
36
+ mesh.uv_layers.new(name='Stack atlas').uv.foreach_set('vector', uvs)
37
+ stack = bpy.data.objects.new(folder.name, mesh)
38
+ scene.collection.objects.link(stack)
39
+ mat = bpy.data.materials.new('Sprite color and coverage')
40
+ mat.use_nodes = True
41
+ nodes, links = mat.node_tree.nodes, mat.node_tree.links
42
+ nodes.clear()
43
+ tex = nodes.new('ShaderNodeTexImage')
44
+ tex.image = atlas
45
+ tex.extension = 'CLIP'
46
+ color = nodes.new('ShaderNodeEmission')
47
+ links.new(tex.outputs['Color'], color.inputs['Color'])
48
+ cutoff = nodes.new('ShaderNodeMath')
49
+ cutoff.operation = 'GREATER_THAN'
50
+ cutoff.inputs[1].default_value = .5
51
+ links.new(tex.outputs['Alpha'], cutoff.inputs[0])
52
+ mix = nodes.new('ShaderNodeMixShader')
53
+ links.new(cutoff.outputs[0], mix.inputs[0])
54
+ links.new(nodes.new('ShaderNodeBsdfTransparent').outputs[0], mix.inputs[1])
55
+ links.new(color.outputs[0], mix.inputs[2])
56
+ links.new(mix.outputs[0], nodes.new('ShaderNodeOutputMaterial').inputs['Surface'])
57
+ mesh.materials.append(mat)
58
+
59
+ scene.render.engine = 'BLENDER_EEVEE'
60
+ scene.render.film_transparent = True
61
+ scene.view_settings.view_transform = 'Standard'
62
+ scene.render.resolution_x = scene.render.resolution_y = 720
63
+ scene.render.resolution_percentage = 100
64
+ extent = meta['layers'] * spacing
65
+ center = Vector((-px, -py, extent / 2 - pz))
66
+ radius = math.hypot(sx, sy, extent) / 2
67
+ cam = bpy.data.objects.new('Preview camera', bpy.data.cameras.new('Orthographic'))
68
+ scene.collection.objects.link(cam)
69
+ scene.camera = cam
70
+ cam.data.type = 'ORTHO'
71
+ cam.data.ortho_scale = 2.15 * radius
72
+ direction = Vector((1, 1.4, .85)).normalized()
73
+ cam.location = center + direction * (3 * radius)
74
+ cam.rotation_euler = (-direction).to_track_quat('-Z', 'Y').to_euler()
75
+ cam.data.clip_start = radius * .01
76
+ cam.data.clip_end = radius * 6
77
+ for screen in bpy.data.screens:
78
+ for area in screen.areas:
79
+ if area.type == 'VIEW_3D':
80
+ view = area.spaces.active
81
+ view.region_3d.view_rotation = cam.rotation_euler.to_quaternion()
82
+ view.region_3d.view_perspective = 'ORTHO'
83
+ view.region_3d.view_distance = 3 * radius
84
+ view.region_3d.view_location = center
85
+ view.shading.type = 'MATERIAL'
86
+ view.overlay.show_overlays = False
87
+ bpy.context.view_layer.objects.active = stack
88
+ stack.select_set(True)
89
+ bpy.ops.wm.save_as_mainfile(filepath=str(output), compress=True)
@@ -0,0 +1,82 @@
1
+ """Partition directed exposed-face masks, then conform seams across all three plane families."""
2
+
3
+ from collections import defaultdict
4
+
5
+ import numpy as np
6
+ import shapely as sh
7
+ from geometry import cyclic, indexed, planar_triangles, runs, xyz
8
+ from shapely.geometry import Polygon
9
+
10
+
11
+ def rectangles(mask):
12
+ mask = mask.copy()
13
+ for y, row in enumerate(mask.T):
14
+ for x in np.flatnonzero(row):
15
+ if not mask[x, y]:
16
+ continue
17
+ hi = x + 1
18
+ while hi < len(row) and mask[hi, y]:
19
+ hi += 1
20
+ end = y + 1
21
+ while end < mask.shape[1] and mask[x:hi, end].all():
22
+ end += 1
23
+ mask[x:hi, y:end] = False
24
+ yield sh.box(x, y, hi, end)
25
+
26
+
27
+ def monotone_regions(mask):
28
+ # A chain of one-to-one overlapping scan runs is y-monotone. Close chains
29
+ # at splits and joins; no polygon crosses a hole or bridges two islands.
30
+ active = {}
31
+ for y, row in enumerate(np.vstack((mask.T, np.zeros(mask.shape[0], bool)))):
32
+ current = runs(row)
33
+ links = {r: [p for p in active if max(r[0], p[0]) < min(r[1], p[1])] for r in current}
34
+ degree = defaultdict(int)
35
+ for prev in links.values():
36
+ for p in prev:
37
+ degree[p] += 1
38
+ next_active = {}
39
+ for r, prev in links.items():
40
+ pieces = active.pop(prev[0]) if len(prev) == 1 and degree[prev[0]] == 1 else []
41
+ pieces.append(sh.box(r[0], y, r[1], y + 1))
42
+ next_active[r] = pieces
43
+ for pieces in active.values():
44
+ yield sh.union_all(pieces).simplify(0)
45
+ active = next_active
46
+
47
+
48
+ def block_mesh(mask, monotone):
49
+ panels = []
50
+ lines = defaultdict(set)
51
+ for axis in range(3):
52
+ slices = mask.transpose(cyclic(axis))
53
+ for sign in (-1, 1):
54
+ neighbor = np.roll(slices, -sign, axis=2)
55
+ neighbor[:, :, -1 if sign > 0 else 0] = False
56
+ exposed = slices & ~neighbor
57
+ for k in np.flatnonzero(exposed.any(axis=(0, 1))):
58
+ partition = monotone_regions if monotone else rectangles
59
+ for poly in partition(exposed[:, :, k]):
60
+ ring = np.asarray(sh.orient_polygons(poly).exterior.coords[:-1], dtype=int)
61
+ points = xyz(np.column_stack((ring, np.full(len(ring), k + (sign > 0)))), axis)
62
+ for p in points:
63
+ for a, (u, v, _) in enumerate(map(cyclic, range(3))):
64
+ lines[a, p[u], p[v]].add(p[a])
65
+ panels.append((axis, sign, points))
66
+ triangles = []
67
+ for axis, sign, points in panels:
68
+ boundary = []
69
+ for p, q in zip(points, np.roll(points, -1, axis=0)):
70
+ a = np.flatnonzero(p != q).item()
71
+ u, v, _ = cyclic(a)
72
+ stops = sorted(t for t in lines[a, p[u], p[v]] if min(p[a], q[a]) < t < max(p[a], q[a]))
73
+ boundary.append(p)
74
+ for t in stops if p[a] < q[a] else reversed(stops):
75
+ point = p.copy()
76
+ point[a] = t
77
+ boundary.append(point)
78
+ u, v, _ = cyclic(axis)
79
+ for tri in planar_triangles(Polygon(np.asarray(boundary)[:, [u, v]])):
80
+ face = xyz(np.column_stack((tri, np.full(3, points[0, axis]))), axis)
81
+ triangles.append(face if sign > 0 else face[::-1])
82
+ return indexed(triangles)
@@ -0,0 +1,62 @@
1
+ """Match connected cross-section regions per slab; interpolate each overlap group separately."""
2
+
3
+ from collections import Counter
4
+
5
+ import numpy as np
6
+ from geometry import cyclic, indexed, xyz
7
+ from implicit import iso
8
+ from scipy.ndimage import distance_transform_edt, label
9
+ from scipy.sparse import coo_matrix
10
+ from scipy.sparse.csgraph import connected_components
11
+
12
+
13
+ def section_field(mask, pitch):
14
+ if not mask.any():
15
+ return None
16
+ padded = np.pad(mask, 1)
17
+ return distance_transform_edt(padded, sampling=pitch) - distance_transform_edt(~padded, sampling=pitch)
18
+
19
+
20
+ def branch_loft(mask, step, axis):
21
+ u, v, _ = cyclic(axis)
22
+ slices = mask.transpose(cyclic(axis))
23
+ previous = np.zeros(slices.shape[:2], dtype=int)
24
+ triangles, events = [], Counter()
25
+ for k in range(slices.shape[2] + 1):
26
+ current, nc = label(slices[:, :, k]) if k < slices.shape[2] else (np.zeros_like(previous), 0)
27
+ nparts = int(previous.max())
28
+ if nparts + nc == 0:
29
+ continue
30
+ # Vertices of this bipartite graph are filled regions including their holes.
31
+ both = (previous != 0) & (current != 0)
32
+ rows, cols = previous[both] - 1, nparts + current[both] - 1
33
+ graph = coo_matrix((np.ones(len(rows)), (rows, cols)), shape=(nparts + nc, nparts + nc))
34
+ count, groups = connected_components(graph, directed=False)
35
+ for group in range(count):
36
+ aa, bb = (
37
+ np.flatnonzero(groups[:nparts] == group) + 1,
38
+ np.flatnonzero(groups[nparts:] == group) + 1,
39
+ )
40
+ if len(aa) != 1 or len(bb) != 1:
41
+ events[f"{len(aa)}->{len(bb)}"] += 1
42
+ a, b = np.isin(previous, aa), np.isin(current, bb)
43
+ ij = np.argwhere(a | b)
44
+ lo, hi = ij.min(axis=0), ij.max(axis=0) + 1
45
+
46
+ crop = np.s_[lo[0] : hi[0], lo[1] : hi[1]]
47
+ d0, d1 = (section_field(layer[crop], step[[u, v]]) for layer in (a, b))
48
+ if d0 is None:
49
+ fields = [-abs(d1), d1]
50
+ elif d1 is None:
51
+ fields = [d0, -abs(d0)]
52
+ else:
53
+ # Sample the intermediate signed-distance contour at splits and joins.
54
+ middle = (d0 + d1) * 0.5
55
+ middle[middle == 0] = -0.001 * min(step[u], step[v])
56
+ fields = [d0, middle, d1]
57
+ p, f = iso(np.stack(fields, axis=2), 0)
58
+ p = p.astype(float) * [1, 1, 1 / (len(fields) - 1)] + [*(lo - 0.5), k - 0.5]
59
+ triangles.extend(p[f])
60
+ previous = current
61
+ print("branch overlap events:", dict(events))
62
+ return indexed(xyz(triangles, axis))
@@ -0,0 +1,67 @@
1
+ """Read registered triple-dexel intersections for Hermite Dual Contouring."""
2
+
3
+ from pathlib import Path
4
+
5
+ import numpy as np
6
+
7
+
8
+ def load_dexel(mask, step, origin, name, directory):
9
+ if not isinstance(name, str) or not name or not directory:
10
+ raise ValueError("dexel must be a .npz path relative to the guide")
11
+ path = Path(directory) / name
12
+ if path.suffix.lower() != ".npz":
13
+ raise ValueError("dexel must be a .npz path")
14
+ crossings = {}
15
+ ignored = 0
16
+ with np.load(path, allow_pickle=False) as data:
17
+ if (data["version"].ndim != 0 or data["version"].item() != 1 or
18
+ not np.array_equal(data["grid"], mask.shape) or
19
+ data["origin"].shape != (3,) or data["step"].shape != (3,) or
20
+ not np.allclose(data["origin"], origin, rtol=0, atol=1e-8) or
21
+ not np.allclose(data["step"], step, rtol=0, atol=1e-8)):
22
+ raise ValueError("dexel registration must match the saved stack grid, origin and spacing")
23
+ for axis, axis_name in enumerate("xyz"):
24
+ transverse = tuple(i for i in range(3) if i != axis)
25
+ shape = tuple(mask.shape[i] for i in transverse)
26
+ count = int(np.prod(shape))
27
+ offsets, depth, normals = [data[axis_name + "_" + key] for key in ("offsets", "depth", "normals")]
28
+ if (offsets.ndim != 1 or offsets.shape != (count + 1,) or offsets.dtype.kind not in "ui" or
29
+ offsets[0] != 0 or offsets[-1] != len(depth) or np.any(offsets[:-1] > offsets[1:])):
30
+ raise ValueError(f"dexel {axis_name}: invalid ray offsets")
31
+ if (depth.ndim != 1 or normals.shape != (len(depth), 3) or depth.dtype.kind != "f" or
32
+ normals.dtype.kind != "f" or not np.isfinite(depth).all() or not np.isfinite(normals).all() or
33
+ np.any(depth < 0) or np.any(depth > mask.shape[axis] * step[axis] + 1e-8)):
34
+ raise ValueError(f"dexel {axis_name}: invalid depth or normal samples")
35
+ lengths = np.linalg.norm(normals, axis=1)
36
+ if np.any(abs(lengths - 1) > 1e-3):
37
+ raise ValueError(f"dexel {axis_name}: normals must be unit vectors")
38
+ centers = (np.arange(mask.shape[axis]) + 0.5) * step[axis]
39
+ columns = np.moveaxis(mask, axis, -1).reshape(count, -1)
40
+ for ray, (start, end) in enumerate(zip(offsets[:-1], offsets[1:])):
41
+ t = depth[start:end]
42
+ n = normals[start:end]
43
+ if (len(t) % 2 or np.any(t[:-1] >= t[1:]) or
44
+ np.any(n[::2, axis] >= 0) or np.any(n[1::2, axis] <= 0)):
45
+ raise ValueError(f"dexel {axis_name} ray {ray}: expected ordered, outward-facing enter/exit pairs")
46
+ if not np.array_equal(np.searchsorted(t, centers, side="right") % 2, columns[ray]):
47
+ raise ValueError(f"dexel {axis_name} ray {ray}: occupancy differs from the saved stack")
48
+ if not len(t):
49
+ continue
50
+ # Padded sample i sits at (i - 0.5) * step. A DC edge spans i..i+1.
51
+ pad = np.pad(columns[ray], 1)
52
+ changes = np.flatnonzero(pad[:-1] != pad[1:])
53
+ indexed = np.searchsorted(centers, t, side="left")
54
+ u, v = np.unravel_index(ray, shape)
55
+ for i in changes:
56
+ events = np.flatnonzero(indexed == i)
57
+ if len(events) != 1:
58
+ raise ValueError(f"dexel {axis_name} ray {ray}: multiple crossings on a sign-changing grid edge; use a finer grid")
59
+ event = events[0]
60
+ p = [0, 0, 0]
61
+ p[axis], p[transverse[0]], p[transverse[1]] = i, u + 1, v + 1
62
+ position = np.array(p, dtype=float)
63
+ position[axis] = t[event] / step[axis] + 0.5
64
+ crossings[(*p, axis)] = (position, n[event])
65
+ ignored += len(t) - len(changes)
66
+ print(f"triple-dexel: used {len(crossings)} measured crossings; {ignored} crossings on edges without a sampled sign change")
67
+ return crossings
@@ -0,0 +1,19 @@
1
+ """Read an authored signed distance field aligned to the saved occupancy."""
2
+
3
+ from pathlib import Path
4
+
5
+ import numpy as np
6
+
7
+
8
+ def load_field(occupied, name, directory):
9
+ if not isinstance(name, str) or not name or not directory:
10
+ raise ValueError("field must be a .npy path relative to the guide")
11
+ path = Path(directory) / name
12
+ if path.suffix.lower() != ".npy":
13
+ raise ValueError("field must be a .npy path")
14
+ field = np.load(path, allow_pickle=False)
15
+ if not isinstance(field, np.ndarray) or field.shape != occupied.shape or field.dtype.kind != "f" or not np.isfinite(field).all():
16
+ raise ValueError(f"field must be a finite XYZ float array of padded shape {occupied.shape}")
17
+ if not np.array_equal(field < 0, occupied) or np.any(field == 0):
18
+ raise ValueError("field signs must match the saved stack at all padded cell centers")
19
+ return field.astype(np.float64, copy=False)
@@ -0,0 +1,203 @@
1
+ """Run topology-changing operations in a disposable headless Blender process."""
2
+
3
+ import json
4
+ import math
5
+ import sys
6
+ from pathlib import Path
7
+
8
+ import bmesh
9
+ import bpy
10
+ import numpy as np
11
+ from mathutils import Vector
12
+ from mathutils.bvhtree import BVHTree
13
+
14
+
15
+ def dissolve(bm, angle):
16
+ bmesh.ops.dissolve_limit(bm, angle_limit=math.radians(angle), verts=list(bm.verts), edges=list(bm.edges))
17
+ bm.normal_update()
18
+
19
+
20
+ def bevel(bm, options):
21
+ dissolve(bm, 0.001)
22
+ edges = [edge for edge in bm.edges if edge.is_manifold and edge.calc_face_angle(0) > math.radians(40)]
23
+ if edges:
24
+ bevel_edges(bm, edges, options)
25
+ print(f"bevel: {len(edges)} candidate creases")
26
+
27
+
28
+ def bevel_edges(bm, edges, options):
29
+ return bmesh.ops.bevel(bm, geom=edges, offset=options["bevelWidth"], segments=options.get("bevelSegments", 2),
30
+ affect="EDGES", profile=0.5, clamp_overlap=True, loop_slide=True)
31
+
32
+
33
+ def mesh_arrays(mesh):
34
+ mesh.calc_loop_triangles()
35
+ vertices = np.empty(len(mesh.vertices) * 3, dtype=np.float32)
36
+ faces = np.empty(len(mesh.loop_triangles) * 3, dtype=np.int32)
37
+ mesh.vertices.foreach_get("co", vertices)
38
+ mesh.loop_triangles.foreach_get("vertices", faces)
39
+ return vertices.reshape(-1, 3), faces.reshape(-1, 3)
40
+
41
+
42
+ def topology(mesh):
43
+ vertices, faces = mesh_arrays(mesh)
44
+ if not len(faces) or not np.isfinite(vertices).all():
45
+ return None
46
+ # Blender's triangle area can round a valid, thin triangle to zero.
47
+ a, b, c = vertices[faces].astype(np.float64).transpose(1, 0, 2)
48
+ if np.any(np.all(np.cross(b - a, c - a) == 0, axis=1)):
49
+ return None
50
+ bm = bmesh.new()
51
+ try:
52
+ bm.from_mesh(mesh)
53
+ if any(not edge.is_manifold or not edge.is_contiguous for edge in bm.edges):
54
+ return None
55
+ pending = {vert for vert in bm.verts if vert.link_faces}
56
+ euler = len(pending) - len(bm.edges) + len(bm.faces)
57
+ components = 0
58
+ while pending:
59
+ components += 1
60
+ frontier = [pending.pop()]
61
+ while frontier:
62
+ vert = frontier.pop()
63
+ for edge in vert.link_edges:
64
+ neighbor = edge.other_vert(vert)
65
+ if neighbor in pending:
66
+ pending.remove(neighbor)
67
+ frontier.append(neighbor)
68
+ return components, euler
69
+ finally:
70
+ bm.free()
71
+
72
+
73
+ def edit_mesh(mesh, operation):
74
+ candidate = bpy.data.meshes.new("stack3-edited")
75
+ bm = bmesh.new()
76
+ try:
77
+ bm.from_mesh(mesh)
78
+ bm.normal_update()
79
+ operation(bm)
80
+ bm.to_mesh(candidate)
81
+ finally:
82
+ bm.free()
83
+ candidate.update()
84
+ return candidate
85
+
86
+
87
+ def keep_closed(previous, candidate, signature, name):
88
+ if candidate is previous or topology(candidate) == signature:
89
+ return candidate
90
+ print(f"{name}: retained previous geometry because the result changed the closed topology")
91
+ return previous
92
+
93
+
94
+ def simplify(mesh, budget):
95
+ mesh.calc_loop_triangles()
96
+ if len(mesh.loop_triangles) <= budget:
97
+ return mesh
98
+ obj = bpy.data.objects.new("stack3-surface", mesh)
99
+ bpy.context.scene.collection.objects.link(obj)
100
+ modifier = obj.modifiers.new("Quadric simplification", "DECIMATE")
101
+ modifier.ratio = budget / len(mesh.loop_triangles)
102
+ modifier.use_collapse_triangulate = True
103
+ evaluated = obj.evaluated_get(bpy.context.evaluated_depsgraph_get())
104
+ return bpy.data.meshes.new_from_object(evaluated)
105
+
106
+
107
+ def bevel_rim(mesh, rim, options, signature):
108
+ axis = "xyz".index(rim["axis"])
109
+ u, v = (i for i in range(3) if i != axis)
110
+ center = rim["center"]
111
+
112
+ def near_rim(vertex):
113
+ point = vertex.co
114
+ distance = math.hypot(point[u] - center[u], point[v] - center[v])
115
+ return (abs(distance - rim["radius"]) < rim["radialTolerance"]
116
+ and abs(point[axis] - center[axis]) < rim["axialTolerance"])
117
+
118
+ def operation(bm):
119
+ edges = [edge for edge in bm.edges
120
+ if edge.is_manifold and edge.calc_face_angle(0) > math.radians(26)
121
+ and all(near_rim(vertex) for vertex in edge.verts)]
122
+ if not edges:
123
+ raise ValueError(f'LOD bevel rim {rim["id"]}: no matching crease edges')
124
+ faces = bevel_edges(bm, edges, options)["faces"]
125
+ if not faces:
126
+ raise ValueError(f'LOD bevel rim {rim["id"]}: bevel created no faces')
127
+ print(f'LOD bevel rim {rim["id"]}: {len(edges)} edges, {len(faces)} bevel faces', flush=True)
128
+
129
+ candidate = edit_mesh(mesh, operation)
130
+ if topology(candidate) != signature:
131
+ raise ValueError(f'LOD bevel rim {rim["id"]}: bevel changed the closed topology')
132
+ return candidate
133
+
134
+
135
+ def lod_bevel(mesh, options, signature):
136
+ if "dissolveAngle" in options:
137
+ mesh = keep_closed(mesh, edit_mesh(mesh, lambda bm: dissolve(bm, options["dissolveAngle"])), signature, "planar dissolve")
138
+ plan = options["lodBevel"]
139
+ mesh = simplify(mesh, plan["preTriangleBudget"])
140
+ if topology(mesh) != signature or len(mesh.loop_triangles) > plan["preTriangleBudget"]:
141
+ raise ValueError("LOD bevel: pre-bevel QEM did not meet its triangle budget with closed topology")
142
+ print(f"LOD bevel: pre-QEM {len(mesh.loop_triangles)} triangles", flush=True)
143
+ for rim in plan["rims"]:
144
+ mesh = bevel_rim(mesh, rim, options, signature)
145
+ triangles, budget = len(mesh.loop_triangles), options["triangleBudget"]
146
+ if triangles > budget:
147
+ raise ValueError(f"LOD bevel: {triangles} triangles exceed finish.triangleBudget {budget}; lower preTriangleBudget to leave room for bevels")
148
+ return mesh
149
+
150
+
151
+ def ambient_occlusion(mesh, vertices, triangles, radius):
152
+ bvh = BVHTree.FromPolygons(vertices.tolist(), triangles.tolist(), all_triangles=True)
153
+ epsilon = max(float(np.ptp(vertices, axis=0).max()) * 1e-6, 1e-8)
154
+ count = 16
155
+ offsets = []
156
+ for i in range(count):
157
+ z = math.sqrt((i + 0.5) / count)
158
+ phi = i * math.pi * (3 - math.sqrt(5))
159
+ radial = math.sqrt(1 - z * z)
160
+ offsets.append((math.cos(phi) * radial, math.sin(phi) * radial, z))
161
+ values = np.empty(len(vertices), dtype=np.float32)
162
+ for vertex in mesh.vertices:
163
+ n = vertex.normal
164
+ if n.length < 0.5:
165
+ values[vertex.index] = 1
166
+ continue
167
+ tangent = n.cross(Vector((1, 0, 0)) if abs(n.x) < 0.9 else Vector((0, 1, 0))).normalized()
168
+ bitangent = n.cross(tangent)
169
+ launch = vertex.co + n * epsilon
170
+ occluded = sum(bvh.ray_cast(launch, x * tangent + y * bitangent + z * n, radius)[0] is not None for x, y, z in offsets)
171
+ values[vertex.index] = 1 - occluded / count
172
+ return values
173
+
174
+
175
+ def main(folder):
176
+ options = json.loads((folder / "input.json").read_text())["finish"]
177
+ file = folder / "geometry.npz"
178
+ with np.load(file, allow_pickle=False) as data:
179
+ vertices, triangles = data["vertices"], data["faces"]
180
+ mesh = bpy.data.meshes.new("stack3-surface")
181
+ mesh.from_pydata(vertices.tolist(), [], triangles.tolist())
182
+ mesh.update()
183
+ signature = topology(mesh)
184
+ if signature is None:
185
+ raise ValueError("input is not a closed, nondegenerate Blender surface")
186
+ if "lodBevel" in options:
187
+ mesh = lod_bevel(mesh, options, signature)
188
+ else:
189
+ if "bevelWidth" in options:
190
+ mesh = keep_closed(mesh, edit_mesh(mesh, lambda bm: bevel(bm, options)), signature, "bevel")
191
+ if "dissolveAngle" in options:
192
+ mesh = keep_closed(mesh, edit_mesh(mesh, lambda bm: dissolve(bm, options["dissolveAngle"])), signature, "planar dissolve")
193
+ if "triangleBudget" in options:
194
+ mesh = keep_closed(mesh, simplify(mesh, options["triangleBudget"]), signature, "QEM")
195
+ vertices, faces = mesh_arrays(mesh)
196
+ output = {"vertices": vertices, "faces": faces}
197
+ if "aoRadius" in options:
198
+ output["occlusion"] = ambient_occlusion(mesh, vertices, faces, options["aoRadius"])
199
+ print(f"finished surface: {len(faces)} triangles")
200
+ np.savez(file, **output)
201
+
202
+
203
+ main(Path(sys.argv[sys.argv.index("--") + 1]))
@@ -0,0 +1,155 @@
1
+ """Fit surfaces on a shared topology, then apply optional offline mesh operations."""
2
+
3
+ import json
4
+ import subprocess
5
+ from pathlib import Path
6
+
7
+ import numpy as np
8
+ from scipy.sparse import coo_matrix
9
+ from scipy.sparse.csgraph import connected_components
10
+
11
+ from geometry import unit
12
+
13
+
14
+ def face_normals(vertices, faces):
15
+ a, b, c = vertices[faces].transpose(1, 0, 2)
16
+ return np.cross(b - a, c - a)
17
+
18
+
19
+ def edge_pairs(faces):
20
+ edges = faces[:, [[0, 1], [1, 2], [2, 0]]].reshape(-1, 2)
21
+ ordered = np.sort(edges, axis=1)
22
+ order = np.lexsort((ordered[:, 1], ordered[:, 0]))
23
+ return edges[order], ordered[order], order // 3
24
+
25
+
26
+ def topology(vertices, faces):
27
+ vertices = np.asarray(vertices, dtype=np.float64)
28
+ if not len(faces) or not np.isfinite(vertices).all() or np.any(np.all(face_normals(vertices, faces) == 0, axis=1)):
29
+ raise ValueError("finishing needs finite, nondegenerate geometry")
30
+ directed, edges, _ = edge_pairs(faces)
31
+ if len(edges) % 2 or not np.array_equal(edges[::2], edges[1::2]) or np.any(np.all(edges[2::2] == edges[:-2:2], axis=1)):
32
+ raise ValueError("finishing needs a closed surface with two faces per edge")
33
+ if not np.array_equal(directed[::2], directed[1::2, ::-1]):
34
+ raise ValueError("surface winding is inconsistent")
35
+ count, _, inverse = np.unique(faces, return_index=True, return_inverse=True)
36
+ remapped = inverse.reshape(faces.shape)
37
+ links = remapped[:, :2].ravel(), remapped[:, 1:].ravel()
38
+ graph = coo_matrix((np.ones(len(links[0])), links), shape=(len(count), len(count)))
39
+ components = connected_components(graph, directed=False, return_labels=False)
40
+ return components, len(count) - len(edges) // 2 + len(faces)
41
+
42
+
43
+ def fit_round(points, normals, tolerance):
44
+ """Try a sphere and a cylinder in physical coordinates, with normal support."""
45
+ center = points.mean(axis=0)
46
+ p = points - center
47
+ _, support, axes = np.linalg.svd(normals, full_matrices=False)
48
+ bases = []
49
+ if support[2] >= 0.25 * support[0]:
50
+ bases.append((np.eye(3), "sphere"))
51
+ if support[1] >= 0.35 * support[0] and support[2] <= 0.30 * support[0]:
52
+ bases.append((axes[:2].T, "cylinder"))
53
+ candidates = []
54
+ for basis, kind in bases:
55
+ coordinates = p @ basis
56
+ system = np.column_stack((2 * coordinates, np.ones(len(p))))
57
+ result, _, rank, _ = np.linalg.lstsq(system, np.sum(coordinates**2, axis=1), rcond=None)
58
+ if rank < system.shape[1]:
59
+ continue
60
+ r2 = result[-1] + np.dot(result[:-1], result[:-1])
61
+ if r2 <= tolerance**2:
62
+ continue
63
+ radius = np.sqrt(r2)
64
+ radial = (coordinates - result[:-1]) @ basis.T
65
+ directions = unit(radial)
66
+ error = radius - np.linalg.norm(radial, axis=1)
67
+ rms = np.sqrt(np.mean(error**2))
68
+ if rms <= tolerance and np.max(np.abs(error)) <= 2 * tolerance and np.mean(np.abs(np.sum(directions * normals, axis=1))) >= 0.88:
69
+ candidates.append((rms, directions, error, kind))
70
+ return min(candidates, key=lambda item: item[0], default=None)
71
+
72
+
73
+ def fit_features(vertices, faces, tolerance, primitives):
74
+ raw_normals = face_normals(vertices, faces)
75
+ normals = unit(raw_normals)
76
+ _, edges, owners = edge_pairs(faces)
77
+ angle = 35 if primitives else 15
78
+ near = np.all(edges[:-1] == edges[1:], axis=1) & (np.sum(normals[owners[:-1]] * normals[owners[1:]], axis=1) > np.cos(np.deg2rad(angle)))
79
+ rows, cols = owners[:-1][near], owners[1:][near]
80
+ graph = coo_matrix((np.ones(len(rows)), (rows, cols)), shape=(len(faces), len(faces)))
81
+ _, labels = connected_components(graph, directed=False)
82
+ groups = np.split(np.argsort(labels, kind="stable"), np.flatnonzero(np.diff(np.sort(labels))) + 1)
83
+ constraints = {}
84
+ counts = {"plane": 0, "sphere": 0, "cylinder": 0}
85
+ for group in groups:
86
+ indices = np.unique(faces[group])
87
+ if len(group) < 4 or len(indices) < 6:
88
+ continue
89
+ p = vertices[indices]
90
+ center = p.mean(axis=0)
91
+ normal = np.linalg.svd(p - center, full_matrices=False)[2][-1]
92
+ error = (center - p) @ normal
93
+ if np.max(abs(error)) <= tolerance and np.mean(abs(normals[group] @ normal)) >= 0.97:
94
+ directions = np.broadcast_to(normal, p.shape)
95
+ kind = "plane"
96
+ elif primitives and len(group) >= 24:
97
+ vertex_normals = np.zeros((len(indices), 3))
98
+ np.add.at(vertex_normals, np.searchsorted(indices, faces[group]).ravel(), np.repeat(raw_normals[group], 3, axis=0))
99
+ result = fit_round(p, unit(vertex_normals), tolerance)
100
+ if result is None:
101
+ continue
102
+ _, directions, error, kind = result
103
+ else:
104
+ continue
105
+ counts[kind] += 1
106
+ for i, n, offset in zip(indices, directions, error):
107
+ constraints.setdefault(i, []).append((n, offset))
108
+ displacement = np.zeros_like(vertices)
109
+ for i, entries in constraints.items():
110
+ if len(entries) == 1:
111
+ n, offset = entries[0]
112
+ delta = n * offset
113
+ else:
114
+ directions, offsets = zip(*entries)
115
+ delta = np.linalg.lstsq(directions, offsets, rcond=0.15)[0]
116
+ if np.linalg.norm(delta) <= 2 * tolerance:
117
+ displacement[i] = delta
118
+ # Boundary vertices are shared by every patch. Limit motion before a face folds.
119
+ for strength in [1.0, 0.5, 0.25, 0.125]:
120
+ candidate = vertices + strength * displacement
121
+ if np.all(np.sum(face_normals(candidate, faces) * raw_normals, axis=1) > 0.1 * np.sum(raw_normals**2, axis=1)):
122
+ print(f"feature fitting: {counts}; displacement factor {strength:g}")
123
+ return candidate
124
+ print("feature fitting: original vertices retained to prevent folded faces")
125
+ return vertices
126
+
127
+
128
+ def finish_surface(mesh, step, origin, options, folder, blender):
129
+ vertices, faces = mesh
130
+ world = vertices * step + origin
131
+ original = topology(world, faces)
132
+ if "fitTolerance" in options:
133
+ world = fit_features(world, faces, options["fitTolerance"], options.get("primitives", False))
134
+ if "regularization" in options:
135
+ from regularization import regularize
136
+
137
+ world = regularize(world, faces, options["regularization"])
138
+ occlusion = None
139
+ if any(name in options for name in ("bevelWidth", "dissolveAngle", "triangleBudget", "aoRadius")):
140
+ data = folder / "geometry.npz"
141
+ np.savez(data, vertices=world, faces=faces)
142
+ script = Path(__file__).with_name("finish_blender.py")
143
+ try:
144
+ subprocess.run([blender, "-b", "--factory-startup", "--python-exit-code", "1", "-P", str(script), "--", str(folder)], check=True)
145
+ except FileNotFoundError:
146
+ raise ValueError("Blender was not found. Set BLENDER_BIN to use bevel, dissolve, QEM or AO.") from None
147
+ except subprocess.CalledProcessError:
148
+ raise ValueError("Blender could not finish the surface") from None
149
+ with np.load(data, allow_pickle=False) as result:
150
+ world, faces = result["vertices"], result["faces"]
151
+ if "occlusion" in result:
152
+ occlusion = result["occlusion"]
153
+ if topology(world, faces) != original:
154
+ raise ValueError("finishing changed the component count or Euler characteristic")
155
+ return ((world - origin) / step, faces), occlusion