vibedgames 0.10.0 → 0.10.2
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.
- package/assets/rebuild-object/.cache/spec-search/core_3d.json +1 -0
- package/assets/rebuild-object/.cache/spec-search/cs2.json +1 -0
- package/assets/rebuild-object/LICENSE +201 -0
- package/assets/rebuild-object/NOTICE +7 -0
- package/assets/rebuild-object/docs/materials/material-reference.json +2324 -0
- package/assets/rebuild-object/docs/specs/render-profile.v2.example.json +63 -0
- package/assets/rebuild-object/docs/specs/render-profile.v2.schema.json +56 -0
- package/assets/rebuild-object/docs/specs/vocabulary/README.md +86 -0
- package/assets/rebuild-object/docs/specs/vocabulary/core_3d.jsonl +12 -0
- package/assets/rebuild-object/docs/specs/vocabulary/core_3d_reconstruction.jsonl +37 -0
- package/assets/rebuild-object/docs/specs/vocabulary/cs2.jsonl +8 -0
- package/assets/rebuild-object/docs/specs/vocabulary/cs2_reconstruction.jsonl +62 -0
- package/assets/rebuild-object/forge/_shared/artifact_cache.py +54 -0
- package/assets/rebuild-object/forge/_shared/chirality.py +272 -0
- package/assets/rebuild-object/forge/_shared/color_metrics.py +107 -0
- package/assets/rebuild-object/forge/_shared/feature_acceptance_policy.py +113 -0
- package/assets/rebuild-object/forge/_shared/image_hash.py +113 -0
- package/assets/rebuild-object/forge/_shared/jpeg.py +448 -0
- package/assets/rebuild-object/forge/_shared/material_physics.py +253 -0
- package/assets/rebuild-object/forge/_shared/pipeline_routing.py +177 -0
- package/assets/rebuild-object/forge/_shared/scalp_field.py +302 -0
- package/assets/rebuild-object/forge/_shared/sdf_primitives.py +172 -0
- package/assets/rebuild-object/forge/_shared/spec_search.py +1792 -0
- package/assets/rebuild-object/forge/_shared/spec_search_profiles.json +58 -0
- package/assets/rebuild-object/forge/_shared/status_banner.py +35 -0
- package/assets/rebuild-object/forge/_shared/subdivision.py +232 -0
- package/assets/rebuild-object/forge/_shared/vertex_paint.py +236 -0
- package/assets/rebuild-object/forge/_shared/workflow_state.py +406 -0
- package/assets/rebuild-object/forge/materials/__init__.py +17 -0
- package/assets/rebuild-object/forge/materials/compatibility.py +106 -0
- package/assets/rebuild-object/forge/materials/reference.py +240 -0
- package/assets/rebuild-object/forge/next.py +116 -0
- package/assets/rebuild-object/forge/report.py +38 -0
- package/assets/rebuild-object/forge/requirements.txt +6 -0
- package/assets/rebuild-object/forge/stage1_intake/analyze_texture.py +255 -0
- package/assets/rebuild-object/forge/stage1_intake/bind_detail_properties.py +99 -0
- package/assets/rebuild-object/forge/stage1_intake/build_detail_inventory.py +349 -0
- package/assets/rebuild-object/forge/stage1_intake/camera_fitting_math.py +133 -0
- package/assets/rebuild-object/forge/stage1_intake/camera_fitting_solver.py +197 -0
- package/assets/rebuild-object/forge/stage1_intake/camera_fitting_types.py +291 -0
- package/assets/rebuild-object/forge/stage1_intake/camera_image_helpers.py +133 -0
- package/assets/rebuild-object/forge/stage1_intake/check_intake_correctness.py +116 -0
- package/assets/rebuild-object/forge/stage1_intake/check_reference_admission.py +203 -0
- package/assets/rebuild-object/forge/stage1_intake/cs2_foundation.py +139 -0
- package/assets/rebuild-object/forge/stage1_intake/cs2_manifest.py +230 -0
- package/assets/rebuild-object/forge/stage1_intake/cs2_review_contract.py +42 -0
- package/assets/rebuild-object/forge/stage1_intake/delight_albedo.py +352 -0
- package/assets/rebuild-object/forge/stage1_intake/detect_cs2.py +276 -0
- package/assets/rebuild-object/forge/stage1_intake/detect_reference_effects.py +275 -0
- package/assets/rebuild-object/forge/stage1_intake/extract_cs2_textures.py +126 -0
- package/assets/rebuild-object/forge/stage1_intake/extract_gradient_stops.py +149 -0
- package/assets/rebuild-object/forge/stage1_intake/extract_hair_evidence.py +385 -0
- package/assets/rebuild-object/forge/stage1_intake/extract_landmarks.py +456 -0
- package/assets/rebuild-object/forge/stage1_intake/extract_part_color_recipe.py +496 -0
- package/assets/rebuild-object/forge/stage1_intake/extract_pbr_evidence.py +843 -0
- package/assets/rebuild-object/forge/stage1_intake/fetch_cs2_metadata.py +147 -0
- package/assets/rebuild-object/forge/stage1_intake/label_glb_nodes.py +318 -0
- package/assets/rebuild-object/forge/stage1_intake/locate_cs2_vpk.py +73 -0
- package/assets/rebuild-object/forge/stage1_intake/material_region_analysis.py +227 -0
- package/assets/rebuild-object/forge/stage1_intake/probe_glb.py +357 -0
- package/assets/rebuild-object/forge/stage1_intake/probe_image.py +168 -0
- package/assets/rebuild-object/forge/stage1_intake/run_vision_adapter.py +45 -0
- package/assets/rebuild-object/forge/stage1_intake/search_specs.py +258 -0
- package/assets/rebuild-object/forge/stage1_intake/semantic_decomposition.py +119 -0
- package/assets/rebuild-object/forge/stage1_intake/solve_camera_pose.py +254 -0
- package/assets/rebuild-object/forge/stage2_spec/apply_material_analysis.py +192 -0
- package/assets/rebuild-object/forge/stage2_spec/cs2_adapters.py +62 -0
- package/assets/rebuild-object/forge/stage2_spec/derive_geometry.py +118 -0
- package/assets/rebuild-object/forge/stage2_spec/hair_profile.py +306 -0
- package/assets/rebuild-object/forge/stage2_spec/humanoid_proportions.py +214 -0
- package/assets/rebuild-object/forge/stage2_spec/new_pre_spec_assessment.py +343 -0
- package/assets/rebuild-object/forge/stage2_spec/new_sculpt_spec.py +2396 -0
- package/assets/rebuild-object/forge/stage2_spec/validate_sculpt_spec.py +2871 -0
- package/assets/rebuild-object/forge/stage3_build/bake_projected_texture.py +181 -0
- package/assets/rebuild-object/forge/stage3_build/decimate.py +272 -0
- package/assets/rebuild-object/forge/stage3_build/generate_threejs_factory.py +4099 -0
- package/assets/rebuild-object/forge/stage3_build/module_cache.py +155 -0
- package/assets/rebuild-object/forge/stage3_build/morph_targets.py +178 -0
- package/assets/rebuild-object/forge/stage3_build/orchestrate_passes.py +653 -0
- package/assets/rebuild-object/forge/stage3_build/uv_unwrap.py +622 -0
- package/assets/rebuild-object/forge/stage3_build/visual_hull.py +357 -0
- package/assets/rebuild-object/forge/stage4_review/_fit_divine_eye.py +64 -0
- package/assets/rebuild-object/forge/stage4_review/append_review.py +453 -0
- package/assets/rebuild-object/forge/stage4_review/attachment_anchor.py +349 -0
- package/assets/rebuild-object/forge/stage4_review/calibrate_eye.py +131 -0
- package/assets/rebuild-object/forge/stage4_review/check_part_coverage.py +298 -0
- package/assets/rebuild-object/forge/stage4_review/compare_region_passes.py +169 -0
- package/assets/rebuild-object/forge/stage4_review/correction_loop.py +258 -0
- package/assets/rebuild-object/forge/stage4_review/cs2_review.py +224 -0
- package/assets/rebuild-object/forge/stage4_review/diagnose_render.py +356 -0
- package/assets/rebuild-object/forge/stage4_review/diagnose_render_multi_angle.py +143 -0
- package/assets/rebuild-object/forge/stage4_review/divine_eye.py +461 -0
- package/assets/rebuild-object/forge/stage4_review/fit_params.py +381 -0
- package/assets/rebuild-object/forge/stage4_review/geometry_integrity.py +294 -0
- package/assets/rebuild-object/forge/stage4_review/hair_gate.py +216 -0
- package/assets/rebuild-object/forge/stage4_review/interior_difference.py +188 -0
- package/assets/rebuild-object/forge/stage4_review/joint_loops.py +209 -0
- package/assets/rebuild-object/forge/stage4_review/make_comparison_sheet.py +292 -0
- package/assets/rebuild-object/forge/stage4_review/material_comparator.py +181 -0
- package/assets/rebuild-object/forge/stage4_review/material_feedback.py +143 -0
- package/assets/rebuild-object/forge/stage4_review/material_gate.py +126 -0
- package/assets/rebuild-object/forge/stage4_review/material_views.py +184 -0
- package/assets/rebuild-object/forge/stage4_review/mesh_reference_compare.py +362 -0
- package/assets/rebuild-object/forge/stage4_review/multi_pass.py +102 -0
- package/assets/rebuild-object/forge/stage4_review/objectness.py +143 -0
- package/assets/rebuild-object/forge/stage4_review/pairwise_penetration.py +376 -0
- package/assets/rebuild-object/forge/stage4_review/per_feature.py +215 -0
- package/assets/rebuild-object/forge/stage4_review/render_bridge.py +556 -0
- package/assets/rebuild-object/forge/stage4_review/scalp_exposure.py +257 -0
- package/assets/rebuild-object/forge/stage4_review/self_intersection.py +592 -0
- package/assets/rebuild-object/forge/stage4_review/swept_arc_gate.py +336 -0
- package/assets/rebuild-object/forge/stage4_review/turntable_gate.py +415 -0
- package/assets/rebuild-object/forge/stage4_review/validate_render_profile.py +182 -0
- package/assets/rebuild-object/forge/stage4_review/vertex_region_gate.py +456 -0
- package/assets/rebuild-object/forge/stage4_review/vlm_gate.py +196 -0
- package/assets/rebuild-object/forge/stage5_rig/NOTES.md +149 -0
- package/assets/rebuild-object/forge/stage5_rig/__init__.py +6 -0
- package/assets/rebuild-object/forge/stage5_rig/emit_rig.py +420 -0
- package/assets/rebuild-object/forge/stage5_rig/geodesic_skinning.py +508 -0
- package/assets/rebuild-object/forge/stage5_rig/rig_spec.py +174 -0
- package/assets/rebuild-object/forge/stage5_rig/validate_rig_payload.py +195 -0
- package/assets/rebuild-object/forge/state.py +98 -0
- package/assets/rebuild-object/steps.json +381 -0
- package/dist/{chunk-FXXVXDTW.js → chunk-24TITAFS.js} +1 -1
- package/dist/{chunk-OGX4DKIS.js → chunk-2C5PG2QO.js} +1 -1
- package/dist/{chunk-HYOXGNWS.js → chunk-2DEVOKI7.js} +1 -1
- package/dist/{chunk-RRI23NK2.js → chunk-2GHPYT2P.js} +1 -1
- package/dist/{chunk-S7HYWITX.js → chunk-2HXGMXGC.js} +1 -1
- package/dist/{chunk-N2UHAQXC.js → chunk-36FORP7T.js} +0 -1
- package/dist/{chunk-VB4WLJR2.js → chunk-3IXRQTRF.js} +1 -1
- package/dist/{chunk-2KVQJKIZ.js → chunk-4ENHS32B.js} +23 -36
- package/dist/{chunk-SXYQL4GK.js → chunk-4YHA32OE.js} +1 -1
- package/dist/{chunk-4FJXCS3K.js → chunk-4ZGQKPK5.js} +1 -1
- package/dist/{chunk-SBXCK2I2.js → chunk-6CLUPFQA.js} +2 -2
- package/dist/{chunk-TXOE5UY5.js → chunk-7WTF2BA4.js} +1 -1
- package/dist/{chunk-R2WVORGD.js → chunk-AAXZNK4Z.js} +1 -1
- package/dist/{chunk-DOOQUFPG.js → chunk-ALLBT4FB.js} +1 -1
- package/dist/{chunk-HRKVAXNN.js → chunk-BAZDPPIG.js} +5 -5
- package/dist/{chunk-RPJR3S5S.js → chunk-CYDENLZ4.js} +5 -8
- package/dist/{chunk-I5LELJSK.js → chunk-DKSUD44G.js} +1 -1
- package/dist/{chunk-43P4U7CB.js → chunk-DWWSJKTE.js} +1 -1
- package/dist/{chunk-SUSX3QIA.js → chunk-E72TFJZP.js} +1 -1
- package/dist/{chunk-E3FJUPLT.js → chunk-EUAAQMUA.js} +2 -0
- package/dist/{chunk-U6DTE5IX.js → chunk-F7LYJSZE.js} +1 -1
- package/dist/{chunk-MEAO33XW.js → chunk-FMON3C74.js} +8 -8
- package/dist/{chunk-GLEW7VJQ.js → chunk-FPILHRLZ.js} +1 -1
- package/dist/{chunk-OPUCUUID.js → chunk-G63MXDX2.js} +4 -0
- package/dist/{chunk-4UU622RK.js → chunk-GGO6ZYYI.js} +1 -3
- package/dist/{chunk-2ZKS7V72.js → chunk-GZCRYYS6.js} +5 -5
- package/dist/{chunk-E7NDOZ27.js → chunk-LE4GVTYI.js} +8 -8
- package/dist/{chunk-RKS7SI5L.js → chunk-NO6KPV64.js} +1 -1
- package/dist/{chunk-KJK5CB6E.js → chunk-NXW3Z4Y4.js} +1 -1
- package/dist/{chunk-7RPLQWR2.js → chunk-OHOAZGO4.js} +1 -1
- package/dist/chunk-PYJNI5WD.js +83 -0
- package/dist/{chunk-NCX6LYNJ.js → chunk-Q4XAGTFX.js} +1 -1
- package/dist/{chunk-3UGGMFJJ.js → chunk-QMZBSVKF.js} +1 -1
- package/dist/{chunk-ABTUEIRC.js → chunk-QO66UBOS.js} +2 -2
- package/dist/{chunk-LONQWRTR.js → chunk-S4KVGQQO.js} +8 -8
- package/dist/{chunk-HX5Q63UA.js → chunk-T777EXAO.js} +1 -1
- package/dist/{chunk-UQ7VO6B3.js → chunk-TZZNRA3S.js} +1 -1
- package/dist/{chunk-CTY2WZQK.js → chunk-UC3QLWMQ.js} +1 -1
- package/dist/{chunk-MR5KIFI7.js → chunk-UDJH2RED.js} +3 -3
- package/dist/{chunk-ZHLPE6LI.js → chunk-UIKYK7KI.js} +1 -1
- package/dist/{chunk-KAGVI3CE.js → chunk-UJRSQO2B.js} +1 -1
- package/dist/{chunk-Q2QC6KAZ.js → chunk-V7LEYVXB.js} +29 -25
- package/dist/{chunk-DB7WVFS7.js → chunk-WRMQEXUC.js} +1 -1
- package/dist/{chunk-HSMG6U7J.js → chunk-WXSBNC67.js} +3 -9
- package/dist/{chunk-QLCVLCPM.js → chunk-X4QIOXNQ.js} +1 -1
- package/dist/{chunk-5YPLKGY3.js → chunk-Y6WHUK2O.js} +1 -1
- package/dist/{chunk-VZEJ2ZHE.js → chunk-Z3E7ORGQ.js} +5 -5
- package/dist/index.js +20 -20
- package/package.json +32 -22
- package/dist/{chunk-Q3XQPNF6.js → chunk-BN7TR6OR.js} +3 -3
- package/dist/{chunk-LORGE2NB.js → chunk-U2NCN5RO.js} +3 -3
- package/dist/{chunk-UPHB5HWO.js → chunk-VQTTSPA3.js} +3 -3
|
@@ -0,0 +1,622 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""UV unwrapping: chart segmentation, least-squares conformal mapping, and packing.
|
|
3
|
+
|
|
4
|
+
Nothing in this repository produced UVs. That is not a cosmetic gap -- it is the missing link that
|
|
5
|
+
makes the whole material track unreachable. Without a UV layout there is nowhere to bake a projected
|
|
6
|
+
photograph, so `bake_projected_texture.py` can only ever emit a descriptor; and there is nowhere to
|
|
7
|
+
bake a normal or an ambient-occlusion map either. The pipeline's own guidance calls
|
|
8
|
+
projection-first texturing the single biggest fidelity lever, and it has been resting on a step that
|
|
9
|
+
did not exist.
|
|
10
|
+
|
|
11
|
+
Three analytic stages, no machine learning anywhere:
|
|
12
|
+
|
|
13
|
+
1. CHART SEGMENTATION by normal similarity. A single chart over a closed surface is impossible
|
|
14
|
+
without a cut, and a conformal map of a highly curved region has unbounded area distortion, so the
|
|
15
|
+
surface is grown into near-planar regions first.
|
|
16
|
+
|
|
17
|
+
2. LSCM (Lévy et al. 2002). Each triangle is flattened into its own plane, and the conformal
|
|
18
|
+
condition -- that the map is locally a rotation and scale, never a shear -- becomes two linear
|
|
19
|
+
equations per triangle. Two pinned vertices fix the remaining translation/rotation/scale freedom.
|
|
20
|
+
The overdetermined system is solved in the least-squares sense by conjugate gradient on the normal
|
|
21
|
+
equations, which needs only sparse mat-vec products and therefore no third-party linear algebra.
|
|
22
|
+
|
|
23
|
+
LSCM preserves ANGLES, not AREAS. A conformal map of a region with real Gaussian curvature must
|
|
24
|
+
distort area somewhere; that is a theorem, not an implementation shortcoming. `areaDistortion` is
|
|
25
|
+
reported per chart so the caller can see how much, and segmentation is what keeps it bounded.
|
|
26
|
+
|
|
27
|
+
3. PACKING into the unit square by a skyline heuristic. This is a heuristic, and it is reported as
|
|
28
|
+
`packingEfficiency` rather than claimed as optimal -- rectangle packing is NP-hard.
|
|
29
|
+
|
|
30
|
+
LSCM requires each chart to be a topological disk. Normal-based growing does not guarantee that, so
|
|
31
|
+
each chart's Euler characteristic is checked and non-disk charts are REPORTED rather than silently
|
|
32
|
+
flattened into a tangle. A fold-over would otherwise look like a valid layout right up until the bake.
|
|
33
|
+
|
|
34
|
+
Pure Python 3.10+ stdlib. No pip installs, no numpy.
|
|
35
|
+
"""
|
|
36
|
+
|
|
37
|
+
from __future__ import annotations
|
|
38
|
+
|
|
39
|
+
import argparse
|
|
40
|
+
import json
|
|
41
|
+
import math
|
|
42
|
+
import sys
|
|
43
|
+
from pathlib import Path
|
|
44
|
+
from typing import Any
|
|
45
|
+
|
|
46
|
+
# Measured on a real 4162-vertex organic skull, sweeping the threshold and counting inverted
|
|
47
|
+
# triangles: 50 deg -> 40 flips, 35 -> 2, 25 -> 0, 18 -> 2, 12 -> 13. 25 is the widest setting that
|
|
48
|
+
# folded nothing, and wider charts mean fewer seams, so it is the default. Hard-surface subjects
|
|
49
|
+
# tolerate more; the flag exists for that.
|
|
50
|
+
DEFAULT_CHART_ANGLE_DEGREES = 25.0
|
|
51
|
+
DEFAULT_CG_ITERATIONS = 400
|
|
52
|
+
DEFAULT_CG_TOLERANCE = 1e-8
|
|
53
|
+
DEFAULT_CHART_PADDING = 0.004
|
|
54
|
+
MIN_TRIANGLE_AREA = 1e-12
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
# ---------------------------------------------------------------------------
|
|
58
|
+
# Mesh helpers
|
|
59
|
+
# ---------------------------------------------------------------------------
|
|
60
|
+
|
|
61
|
+
def _triangles(indices: list[Any]) -> list[tuple[int, int, int]]:
|
|
62
|
+
if indices and isinstance(indices[0], (list, tuple)):
|
|
63
|
+
return [(int(t[0]), int(t[1]), int(t[2])) for t in indices]
|
|
64
|
+
return [
|
|
65
|
+
(int(indices[i]), int(indices[i + 1]), int(indices[i + 2]))
|
|
66
|
+
for i in range(0, len(indices) - 2, 3)
|
|
67
|
+
]
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _sub(a: list[float], b: list[float]) -> list[float]:
|
|
71
|
+
return [a[0] - b[0], a[1] - b[1], a[2] - b[2]]
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _cross(a: list[float], b: list[float]) -> list[float]:
|
|
75
|
+
return [
|
|
76
|
+
a[1] * b[2] - a[2] * b[1],
|
|
77
|
+
a[2] * b[0] - a[0] * b[2],
|
|
78
|
+
a[0] * b[1] - a[1] * b[0],
|
|
79
|
+
]
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _dot(a: list[float], b: list[float]) -> float:
|
|
83
|
+
return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _norm(a: list[float]) -> float:
|
|
87
|
+
return math.sqrt(_dot(a, a))
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _face_normal(vertices: list[list[float]], face: tuple[int, int, int]) -> tuple[list[float], float]:
|
|
91
|
+
p0, p1, p2 = (vertices[i] for i in face)
|
|
92
|
+
n = _cross(_sub(p1, p0), _sub(p2, p0))
|
|
93
|
+
length = _norm(n)
|
|
94
|
+
if length <= MIN_TRIANGLE_AREA:
|
|
95
|
+
return [0.0, 0.0, 0.0], 0.0
|
|
96
|
+
return [n[0] / length, n[1] / length, n[2] / length], length / 2.0
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
# ---------------------------------------------------------------------------
|
|
100
|
+
# 1. Chart segmentation
|
|
101
|
+
# ---------------------------------------------------------------------------
|
|
102
|
+
|
|
103
|
+
def segment_charts(
|
|
104
|
+
vertices: list[list[float]],
|
|
105
|
+
faces: list[tuple[int, int, int]],
|
|
106
|
+
angle_threshold_degrees: float = DEFAULT_CHART_ANGLE_DEGREES,
|
|
107
|
+
) -> list[list[int]]:
|
|
108
|
+
"""Grow near-planar regions across shared edges.
|
|
109
|
+
|
|
110
|
+
Growth is compared against the SEED's normal rather than the neighbour's. Comparing against the
|
|
111
|
+
neighbour lets a chart creep around a cylinder one tolerable step at a time until its two ends
|
|
112
|
+
face opposite directions, which is exactly the runaway a threshold is supposed to prevent.
|
|
113
|
+
"""
|
|
114
|
+
cos_limit = math.cos(math.radians(angle_threshold_degrees))
|
|
115
|
+
normals = [_face_normal(vertices, face)[0] for face in faces]
|
|
116
|
+
|
|
117
|
+
edge_faces: dict[tuple[int, int], list[int]] = {}
|
|
118
|
+
for index, (a, b, c) in enumerate(faces):
|
|
119
|
+
for u, v in ((a, b), (b, c), (c, a)):
|
|
120
|
+
key = (u, v) if u < v else (v, u)
|
|
121
|
+
edge_faces.setdefault(key, []).append(index)
|
|
122
|
+
|
|
123
|
+
neighbours: list[list[int]] = [[] for _ in faces]
|
|
124
|
+
for shared in edge_faces.values():
|
|
125
|
+
if len(shared) != 2:
|
|
126
|
+
continue
|
|
127
|
+
first, second = shared
|
|
128
|
+
neighbours[first].append(second)
|
|
129
|
+
neighbours[second].append(first)
|
|
130
|
+
|
|
131
|
+
unassigned = set(range(len(faces)))
|
|
132
|
+
charts: list[list[int]] = []
|
|
133
|
+
while unassigned:
|
|
134
|
+
seed = min(unassigned)
|
|
135
|
+
seed_normal = normals[seed]
|
|
136
|
+
chart = [seed]
|
|
137
|
+
unassigned.discard(seed)
|
|
138
|
+
queue = [seed]
|
|
139
|
+
while queue:
|
|
140
|
+
current = queue.pop()
|
|
141
|
+
for neighbour in neighbours[current]:
|
|
142
|
+
if neighbour not in unassigned:
|
|
143
|
+
continue
|
|
144
|
+
if _dot(seed_normal, normals[neighbour]) < cos_limit:
|
|
145
|
+
continue
|
|
146
|
+
unassigned.discard(neighbour)
|
|
147
|
+
chart.append(neighbour)
|
|
148
|
+
queue.append(neighbour)
|
|
149
|
+
charts.append(sorted(chart))
|
|
150
|
+
return charts
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def _chart_adjacency(faces: list[tuple[int, int, int]], chart: list[int]) -> dict[int, list[int]]:
|
|
154
|
+
"""Face adjacency restricted to one chart."""
|
|
155
|
+
edge_faces: dict[tuple[int, int], list[int]] = {}
|
|
156
|
+
for index in chart:
|
|
157
|
+
a, b, c = faces[index]
|
|
158
|
+
for u, v in ((a, b), (b, c), (c, a)):
|
|
159
|
+
edge_faces.setdefault((u, v) if u < v else (v, u), []).append(index)
|
|
160
|
+
adjacency: dict[int, list[int]] = {index: [] for index in chart}
|
|
161
|
+
for shared in edge_faces.values():
|
|
162
|
+
if len(shared) != 2:
|
|
163
|
+
continue
|
|
164
|
+
first, second = shared
|
|
165
|
+
adjacency[first].append(second)
|
|
166
|
+
adjacency[second].append(first)
|
|
167
|
+
return adjacency
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _split_chart(faces: list[tuple[int, int, int]], chart: list[int]) -> tuple[list[int], list[int]]:
|
|
171
|
+
"""Break a chart into a connected half and the remainder, by breadth-first growth.
|
|
172
|
+
|
|
173
|
+
Breadth-first rather than by a cutting plane: a plane can slice a chart into pieces that are not
|
|
174
|
+
connected, and a disconnected piece is not a disk either, so the recursion would not terminate on
|
|
175
|
+
the thing it was called to fix.
|
|
176
|
+
"""
|
|
177
|
+
adjacency = _chart_adjacency(faces, chart)
|
|
178
|
+
target = max(1, len(chart) // 2)
|
|
179
|
+
start = chart[0]
|
|
180
|
+
taken = [start]
|
|
181
|
+
seen = {start}
|
|
182
|
+
queue = [start]
|
|
183
|
+
while queue and len(taken) < target:
|
|
184
|
+
current = queue.pop(0)
|
|
185
|
+
for neighbour in adjacency[current]:
|
|
186
|
+
if neighbour in seen:
|
|
187
|
+
continue
|
|
188
|
+
seen.add(neighbour)
|
|
189
|
+
taken.append(neighbour)
|
|
190
|
+
queue.append(neighbour)
|
|
191
|
+
if len(taken) >= target:
|
|
192
|
+
break
|
|
193
|
+
remainder = [index for index in chart if index not in seen]
|
|
194
|
+
return sorted(taken), sorted(remainder)
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def enforce_disk_charts(
|
|
198
|
+
faces: list[tuple[int, int, int]],
|
|
199
|
+
charts: list[list[int]],
|
|
200
|
+
max_charts: int = 4096,
|
|
201
|
+
) -> tuple[list[list[int]], int]:
|
|
202
|
+
"""Subdivide until every chart is a topological disk.
|
|
203
|
+
|
|
204
|
+
Reporting a non-disk chart is not enough. LSCM returns UVs for one regardless, and they fold over
|
|
205
|
+
-- measured on a real 4162-vertex skull, seven non-disk charts drove worst-case area distortion to
|
|
206
|
+
171300 and produced twelve inverted triangles. A single triangle is always a disk, so this
|
|
207
|
+
terminates; `max_charts` only bounds pathological input.
|
|
208
|
+
"""
|
|
209
|
+
resolved: list[list[int]] = []
|
|
210
|
+
pending = [list(chart) for chart in charts]
|
|
211
|
+
splits = 0
|
|
212
|
+
while pending:
|
|
213
|
+
chart = pending.pop()
|
|
214
|
+
if len(resolved) + len(pending) >= max_charts:
|
|
215
|
+
resolved.append(chart)
|
|
216
|
+
continue
|
|
217
|
+
if len(chart) <= 1 or chart_is_disk(faces, chart):
|
|
218
|
+
resolved.append(chart)
|
|
219
|
+
continue
|
|
220
|
+
first, second = _split_chart(faces, chart)
|
|
221
|
+
# A split that fails to shrink the chart would loop forever; keep it and let it be reported.
|
|
222
|
+
if not first or not second:
|
|
223
|
+
resolved.append(chart)
|
|
224
|
+
continue
|
|
225
|
+
splits += 1
|
|
226
|
+
pending.extend((first, second))
|
|
227
|
+
return sorted(resolved), splits
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def chart_is_disk(faces: list[tuple[int, int, int]], chart: list[int]) -> bool:
|
|
231
|
+
"""Euler characteristic V - E + F == 1 identifies a disk.
|
|
232
|
+
|
|
233
|
+
A chart that closes into a tube or a sphere has no valid flattening at all, and LSCM will happily
|
|
234
|
+
return one anyway -- overlapping, folded, and indistinguishable from a good layout in the numbers.
|
|
235
|
+
"""
|
|
236
|
+
verts: set[int] = set()
|
|
237
|
+
edges: set[tuple[int, int]] = set()
|
|
238
|
+
for index in chart:
|
|
239
|
+
a, b, c = faces[index]
|
|
240
|
+
verts.update((a, b, c))
|
|
241
|
+
for u, v in ((a, b), (b, c), (c, a)):
|
|
242
|
+
edges.add((u, v) if u < v else (v, u))
|
|
243
|
+
return len(verts) - len(edges) + len(chart) == 1
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
# ---------------------------------------------------------------------------
|
|
247
|
+
# 2. LSCM
|
|
248
|
+
# ---------------------------------------------------------------------------
|
|
249
|
+
|
|
250
|
+
def _local_coordinates(
|
|
251
|
+
vertices: list[list[float]], face: tuple[int, int, int]
|
|
252
|
+
) -> tuple[tuple[float, float], tuple[float, float], tuple[float, float]] | None:
|
|
253
|
+
"""Isometrically flatten one triangle into its own plane."""
|
|
254
|
+
p0, p1, p2 = (vertices[i] for i in face)
|
|
255
|
+
e1 = _sub(p1, p0)
|
|
256
|
+
length = _norm(e1)
|
|
257
|
+
if length <= MIN_TRIANGLE_AREA:
|
|
258
|
+
return None
|
|
259
|
+
axis_x = [component / length for component in e1]
|
|
260
|
+
e2 = _sub(p2, p0)
|
|
261
|
+
x2 = _dot(e2, axis_x)
|
|
262
|
+
perpendicular = [e2[i] - x2 * axis_x[i] for i in range(3)]
|
|
263
|
+
y2 = _norm(perpendicular)
|
|
264
|
+
if y2 <= MIN_TRIANGLE_AREA:
|
|
265
|
+
return None
|
|
266
|
+
return (0.0, 0.0), (length, 0.0), (x2, y2)
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
def _conjugate_gradient(
|
|
270
|
+
rows: list[list[tuple[int, float]]],
|
|
271
|
+
rhs: list[float],
|
|
272
|
+
unknowns: int,
|
|
273
|
+
iterations: int,
|
|
274
|
+
tolerance: float,
|
|
275
|
+
) -> list[float]:
|
|
276
|
+
"""Least squares by CG on the normal equations, with only sparse mat-vecs.
|
|
277
|
+
|
|
278
|
+
Never forms M^T M. That matrix is dense enough to be the memory wall this whole approach exists to
|
|
279
|
+
avoid, and CG only ever needs its product with a vector.
|
|
280
|
+
"""
|
|
281
|
+
|
|
282
|
+
def multiply(x: list[float]) -> list[float]:
|
|
283
|
+
return [sum(value * x[column] for column, value in row) for row in rows]
|
|
284
|
+
|
|
285
|
+
def multiply_transpose(y: list[float]) -> list[float]:
|
|
286
|
+
out = [0.0] * unknowns
|
|
287
|
+
for row, weight in zip(rows, y):
|
|
288
|
+
for column, value in row:
|
|
289
|
+
out[column] += value * weight
|
|
290
|
+
return out
|
|
291
|
+
|
|
292
|
+
x = [0.0] * unknowns
|
|
293
|
+
residual = multiply_transpose(rhs)
|
|
294
|
+
direction = list(residual)
|
|
295
|
+
residual_norm = sum(value * value for value in residual)
|
|
296
|
+
if residual_norm <= tolerance:
|
|
297
|
+
return x
|
|
298
|
+
for _ in range(iterations):
|
|
299
|
+
md = multiply(direction)
|
|
300
|
+
denominator = sum(value * value for value in md)
|
|
301
|
+
if denominator <= 1e-30:
|
|
302
|
+
break
|
|
303
|
+
step = residual_norm / denominator
|
|
304
|
+
for i in range(unknowns):
|
|
305
|
+
x[i] += step * direction[i]
|
|
306
|
+
residual = [a - step * b for a, b in zip(residual, multiply_transpose(md))]
|
|
307
|
+
new_norm = sum(value * value for value in residual)
|
|
308
|
+
if new_norm <= tolerance:
|
|
309
|
+
break
|
|
310
|
+
beta = new_norm / residual_norm
|
|
311
|
+
residual_norm = new_norm
|
|
312
|
+
direction = [r + beta * d for r, d in zip(residual, direction)]
|
|
313
|
+
return x
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
def lscm(
|
|
317
|
+
vertices: list[list[float]],
|
|
318
|
+
faces: list[tuple[int, int, int]],
|
|
319
|
+
chart: list[int],
|
|
320
|
+
iterations: int = DEFAULT_CG_ITERATIONS,
|
|
321
|
+
tolerance: float = DEFAULT_CG_TOLERANCE,
|
|
322
|
+
) -> dict[int, tuple[float, float]]:
|
|
323
|
+
"""Flatten one chart, returning UV per original vertex index."""
|
|
324
|
+
chart_vertices = sorted({v for index in chart for v in faces[index]})
|
|
325
|
+
position = {v: i for i, v in enumerate(chart_vertices)}
|
|
326
|
+
if len(chart_vertices) < 3:
|
|
327
|
+
return {v: (0.0, 0.0) for v in chart_vertices}
|
|
328
|
+
|
|
329
|
+
# Pin the two most distant vertices. Pinning adjacent ones leaves the solve nearly free to rotate
|
|
330
|
+
# and scale, and CG then wanders instead of converging.
|
|
331
|
+
pin_a, pin_b, best = chart_vertices[0], chart_vertices[1], -1.0
|
|
332
|
+
for i, vi in enumerate(chart_vertices):
|
|
333
|
+
for vj in chart_vertices[i + 1:]:
|
|
334
|
+
distance = _norm(_sub(vertices[vi], vertices[vj]))
|
|
335
|
+
if distance > best:
|
|
336
|
+
best, pin_a, pin_b = distance, vi, vj
|
|
337
|
+
if best <= MIN_TRIANGLE_AREA:
|
|
338
|
+
return {v: (0.0, 0.0) for v in chart_vertices}
|
|
339
|
+
|
|
340
|
+
pinned = {pin_a: (0.0, 0.0), pin_b: (best, 0.0)}
|
|
341
|
+
free = [v for v in chart_vertices if v not in pinned]
|
|
342
|
+
column_of = {v: i for i, v in enumerate(free)}
|
|
343
|
+
unknowns = 2 * len(free)
|
|
344
|
+
if unknowns == 0:
|
|
345
|
+
return dict(pinned)
|
|
346
|
+
|
|
347
|
+
rows: list[list[tuple[int, float]]] = []
|
|
348
|
+
rhs: list[float] = []
|
|
349
|
+
for index in chart:
|
|
350
|
+
face = faces[index]
|
|
351
|
+
local = _local_coordinates(vertices, face)
|
|
352
|
+
if local is None:
|
|
353
|
+
continue
|
|
354
|
+
(x1, y1), (x2, y2), (x3, y3) = local
|
|
355
|
+
area = abs((x2 - x1) * (y3 - y1) - (x3 - x1) * (y2 - y1)) / 2.0
|
|
356
|
+
if area <= MIN_TRIANGLE_AREA:
|
|
357
|
+
continue
|
|
358
|
+
scale = 1.0 / math.sqrt(2.0 * area)
|
|
359
|
+
w = [
|
|
360
|
+
((x3 - x2) * scale, (y3 - y2) * scale),
|
|
361
|
+
((x1 - x3) * scale, (y1 - y3) * scale),
|
|
362
|
+
((x2 - x1) * scale, (y2 - y1) * scale),
|
|
363
|
+
]
|
|
364
|
+
# Sum_j W_j * U_j = 0 over the complex plane, split into its real and imaginary parts.
|
|
365
|
+
real_row: list[tuple[int, float]] = []
|
|
366
|
+
imaginary_row: list[tuple[int, float]] = []
|
|
367
|
+
real_rhs = 0.0
|
|
368
|
+
imaginary_rhs = 0.0
|
|
369
|
+
for corner, vertex in enumerate(face):
|
|
370
|
+
wr, wi = w[corner]
|
|
371
|
+
if vertex in pinned:
|
|
372
|
+
pu, pv = pinned[vertex]
|
|
373
|
+
real_rhs -= wr * pu - wi * pv
|
|
374
|
+
imaginary_rhs -= wi * pu + wr * pv
|
|
375
|
+
else:
|
|
376
|
+
column = column_of[vertex]
|
|
377
|
+
real_row.append((column, wr))
|
|
378
|
+
real_row.append((len(free) + column, -wi))
|
|
379
|
+
imaginary_row.append((column, wi))
|
|
380
|
+
imaginary_row.append((len(free) + column, wr))
|
|
381
|
+
rows.append(real_row)
|
|
382
|
+
rhs.append(real_rhs)
|
|
383
|
+
rows.append(imaginary_row)
|
|
384
|
+
rhs.append(imaginary_rhs)
|
|
385
|
+
|
|
386
|
+
solution = _conjugate_gradient(rows, rhs, unknowns, iterations, tolerance)
|
|
387
|
+
uv = dict(pinned)
|
|
388
|
+
for vertex in free:
|
|
389
|
+
column = column_of[vertex]
|
|
390
|
+
uv[vertex] = (solution[column], solution[len(free) + column])
|
|
391
|
+
return uv
|
|
392
|
+
|
|
393
|
+
|
|
394
|
+
# ---------------------------------------------------------------------------
|
|
395
|
+
# Distortion
|
|
396
|
+
# ---------------------------------------------------------------------------
|
|
397
|
+
|
|
398
|
+
def chart_distortion(
|
|
399
|
+
vertices: list[list[float]],
|
|
400
|
+
faces: list[tuple[int, int, int]],
|
|
401
|
+
chart: list[int],
|
|
402
|
+
uv: dict[int, tuple[float, float]],
|
|
403
|
+
) -> dict[str, float]:
|
|
404
|
+
"""Worst per-triangle area scaling, normalised so a perfect map scores 1.0.
|
|
405
|
+
|
|
406
|
+
Reported as a ratio of the WORST triangle to the chart's median, not as an absolute UV area: an
|
|
407
|
+
absolute number changes with the arbitrary global scale of the layout and would make two identical
|
|
408
|
+
unwraps at different scales look different.
|
|
409
|
+
"""
|
|
410
|
+
ratios: list[float] = []
|
|
411
|
+
flipped = 0
|
|
412
|
+
for index in chart:
|
|
413
|
+
face = faces[index]
|
|
414
|
+
_, area3d = _face_normal(vertices, face)
|
|
415
|
+
if area3d <= MIN_TRIANGLE_AREA:
|
|
416
|
+
continue
|
|
417
|
+
(u1, v1), (u2, v2), (u3, v3) = (uv[v] for v in face)
|
|
418
|
+
signed = ((u2 - u1) * (v3 - v1) - (u3 - u1) * (v2 - v1)) / 2.0
|
|
419
|
+
if signed <= 0:
|
|
420
|
+
flipped += 1
|
|
421
|
+
area2d = abs(signed)
|
|
422
|
+
if area2d <= MIN_TRIANGLE_AREA:
|
|
423
|
+
continue
|
|
424
|
+
ratios.append(area2d / area3d)
|
|
425
|
+
if not ratios:
|
|
426
|
+
return {"areaDistortion": float("inf"), "flippedTriangles": flipped}
|
|
427
|
+
ratios.sort()
|
|
428
|
+
median = ratios[len(ratios) // 2]
|
|
429
|
+
if median <= 0:
|
|
430
|
+
return {"areaDistortion": float("inf"), "flippedTriangles": flipped}
|
|
431
|
+
worst = max(max(ratios) / median, median / max(min(ratios), 1e-30))
|
|
432
|
+
return {"areaDistortion": round(worst, 6), "flippedTriangles": flipped}
|
|
433
|
+
|
|
434
|
+
|
|
435
|
+
# ---------------------------------------------------------------------------
|
|
436
|
+
# 3. Packing
|
|
437
|
+
# ---------------------------------------------------------------------------
|
|
438
|
+
|
|
439
|
+
def pack_charts(
|
|
440
|
+
chart_uvs: list[dict[int, tuple[float, float]]],
|
|
441
|
+
padding: float = DEFAULT_CHART_PADDING,
|
|
442
|
+
) -> tuple[list[dict[int, tuple[float, float]]], float]:
|
|
443
|
+
"""Skyline packing of chart bounding boxes into the unit square.
|
|
444
|
+
|
|
445
|
+
A heuristic, and reported as one. Charts are normalised to preserve their relative scale so a
|
|
446
|
+
small chart does not get blown up to the same texel density as a large one -- uniform texel
|
|
447
|
+
density is the property a bake actually needs.
|
|
448
|
+
"""
|
|
449
|
+
boxes = []
|
|
450
|
+
for uv in chart_uvs:
|
|
451
|
+
if not uv:
|
|
452
|
+
boxes.append((0.0, 0.0, 0.0, 0.0))
|
|
453
|
+
continue
|
|
454
|
+
us = [p[0] for p in uv.values()]
|
|
455
|
+
vs = [p[1] for p in uv.values()]
|
|
456
|
+
boxes.append((min(us), min(vs), max(us) - min(us), max(vs) - min(vs)))
|
|
457
|
+
|
|
458
|
+
largest = max((max(w, h) for _, _, w, h in boxes), default=0.0)
|
|
459
|
+
if largest <= 0:
|
|
460
|
+
return [dict(uv) for uv in chart_uvs], 0.0
|
|
461
|
+
|
|
462
|
+
order = sorted(range(len(boxes)), key=lambda i: -boxes[i][3])
|
|
463
|
+
placed: list[dict[int, tuple[float, float]]] = [dict() for _ in chart_uvs]
|
|
464
|
+
cursor_x = 0.0
|
|
465
|
+
cursor_y = 0.0
|
|
466
|
+
shelf_height = 0.0
|
|
467
|
+
used_area = 0.0
|
|
468
|
+
|
|
469
|
+
for index in order:
|
|
470
|
+
min_u, min_v, width, height = boxes[index]
|
|
471
|
+
scale = 1.0 / (largest * (len(boxes) ** 0.5 + 1))
|
|
472
|
+
w = width * scale
|
|
473
|
+
h = height * scale
|
|
474
|
+
if cursor_x + w + padding > 1.0:
|
|
475
|
+
cursor_x = 0.0
|
|
476
|
+
cursor_y += shelf_height + padding
|
|
477
|
+
shelf_height = 0.0
|
|
478
|
+
shelf_height = max(shelf_height, h)
|
|
479
|
+
for vertex, (u, v) in chart_uvs[index].items():
|
|
480
|
+
placed[index][vertex] = (
|
|
481
|
+
cursor_x + (u - min_u) * scale,
|
|
482
|
+
cursor_y + (v - min_v) * scale,
|
|
483
|
+
)
|
|
484
|
+
cursor_x += w + padding
|
|
485
|
+
used_area += w * h
|
|
486
|
+
|
|
487
|
+
total_height = cursor_y + shelf_height
|
|
488
|
+
efficiency = used_area / max(total_height, 1e-9) if total_height > 0 else 0.0
|
|
489
|
+
return placed, round(min(efficiency, 1.0), 6)
|
|
490
|
+
|
|
491
|
+
|
|
492
|
+
# ---------------------------------------------------------------------------
|
|
493
|
+
# Public entry point
|
|
494
|
+
# ---------------------------------------------------------------------------
|
|
495
|
+
|
|
496
|
+
def unwrap(mesh: dict[str, Any], angle_threshold_degrees: float = DEFAULT_CHART_ANGLE_DEGREES) -> dict[str, Any]:
|
|
497
|
+
vertices = mesh.get("vertices")
|
|
498
|
+
indices = mesh.get("indices")
|
|
499
|
+
if not isinstance(vertices, list) or not vertices:
|
|
500
|
+
raise ValueError("mesh.vertices must be a non-empty array")
|
|
501
|
+
if not isinstance(indices, list) or len(indices) < 3:
|
|
502
|
+
raise ValueError("mesh.indices must describe at least one triangle")
|
|
503
|
+
|
|
504
|
+
faces = _triangles(indices)
|
|
505
|
+
charts = segment_charts(vertices, faces, angle_threshold_degrees)
|
|
506
|
+
charts, topology_splits = enforce_disk_charts(faces, charts)
|
|
507
|
+
|
|
508
|
+
uv_all: list[tuple[float, float]] = [(0.0, 0.0)] * len(vertices)
|
|
509
|
+
chart_uvs: list[dict[int, tuple[float, float]]] = []
|
|
510
|
+
reports: list[dict[str, Any]] = []
|
|
511
|
+
non_disk: list[int] = []
|
|
512
|
+
|
|
513
|
+
for number, chart in enumerate(charts):
|
|
514
|
+
is_disk = chart_is_disk(faces, chart)
|
|
515
|
+
if not is_disk:
|
|
516
|
+
non_disk.append(number)
|
|
517
|
+
uv = lscm(vertices, faces, chart)
|
|
518
|
+
chart_uvs.append(uv)
|
|
519
|
+
distortion = chart_distortion(vertices, faces, chart, uv)
|
|
520
|
+
reports.append({
|
|
521
|
+
"chart": number,
|
|
522
|
+
"faceCount": len(chart),
|
|
523
|
+
"vertexCount": len(uv),
|
|
524
|
+
"isDisk": is_disk,
|
|
525
|
+
**distortion,
|
|
526
|
+
})
|
|
527
|
+
|
|
528
|
+
packed, efficiency = pack_charts(chart_uvs)
|
|
529
|
+
# A vertex on a chart seam belongs to more than one chart. Writing whichever chart lands last is
|
|
530
|
+
# what produces a visible seam artefact, so the split is reported instead of hidden: the caller
|
|
531
|
+
# must duplicate those vertices before baking.
|
|
532
|
+
seam_vertices: set[int] = set()
|
|
533
|
+
seen: dict[int, int] = {}
|
|
534
|
+
for number, uv in enumerate(packed):
|
|
535
|
+
for vertex, coordinate in uv.items():
|
|
536
|
+
if vertex in seen and seen[vertex] != number:
|
|
537
|
+
seam_vertices.add(vertex)
|
|
538
|
+
seen[vertex] = number
|
|
539
|
+
uv_all[vertex] = coordinate
|
|
540
|
+
|
|
541
|
+
# Weighted by face count, and reported as a distribution rather than a single worst case. The max
|
|
542
|
+
# alone is not a usable quality signal here: sweeping the segmentation threshold on a real skull
|
|
543
|
+
# produced 2299 -> 93609 -> 6595 -> 378 -> 15.85, which is not a trend, it is one sliver chart
|
|
544
|
+
# dominating a max while the other two hundred charts stayed fine. A layout is good or bad by how
|
|
545
|
+
# much of its SURFACE maps well.
|
|
546
|
+
weighted: list[float] = []
|
|
547
|
+
for report in reports:
|
|
548
|
+
if math.isfinite(report["areaDistortion"]):
|
|
549
|
+
weighted.extend([report["areaDistortion"]] * report["faceCount"])
|
|
550
|
+
weighted.sort()
|
|
551
|
+
|
|
552
|
+
def percentile(fraction: float) -> float | None:
|
|
553
|
+
if not weighted:
|
|
554
|
+
return None
|
|
555
|
+
return round(weighted[min(len(weighted) - 1, int(fraction * len(weighted)))], 6)
|
|
556
|
+
|
|
557
|
+
finite = [report["areaDistortion"] for report in reports if math.isfinite(report["areaDistortion"])]
|
|
558
|
+
return {
|
|
559
|
+
"areaDistortionMedian": percentile(0.5),
|
|
560
|
+
"areaDistortionP95": percentile(0.95),
|
|
561
|
+
"uv": [[round(u, 6), round(v, 6)] for u, v in uv_all],
|
|
562
|
+
"chartCount": len(charts),
|
|
563
|
+
"charts": reports,
|
|
564
|
+
"nonDiskCharts": non_disk,
|
|
565
|
+
"topologySplits": topology_splits,
|
|
566
|
+
"packingEfficiency": efficiency,
|
|
567
|
+
"worstAreaDistortion": round(max(finite), 6) if finite else None,
|
|
568
|
+
"totalFlippedTriangles": sum(report["flippedTriangles"] for report in reports),
|
|
569
|
+
"seamVertexCount": len(seam_vertices),
|
|
570
|
+
"seamVertices": sorted(seam_vertices)[:64],
|
|
571
|
+
"notes": [
|
|
572
|
+
"LSCM preserves angles, not areas; area distortion over a curved chart is unavoidable "
|
|
573
|
+
"and is bounded by segmentation, not by the solver",
|
|
574
|
+
"packing is a skyline heuristic, not an optimal packing",
|
|
575
|
+
"vertices listed in seamVertices carry more than one UV and must be duplicated before a bake",
|
|
576
|
+
],
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
|
|
580
|
+
def _format_summary(result: dict[str, Any]) -> str:
|
|
581
|
+
lines = [
|
|
582
|
+
f"charts: {result['chartCount']}",
|
|
583
|
+
f"packing efficiency: {result['packingEfficiency']}",
|
|
584
|
+
f"area distortion: median {result['areaDistortionMedian']}, "
|
|
585
|
+
f"p95 {result['areaDistortionP95']}, worst {result['worstAreaDistortion']} "
|
|
586
|
+
"(read the median and p95; the max is one sliver chart away from meaningless)",
|
|
587
|
+
f"flipped triangles: {result['totalFlippedTriangles']}",
|
|
588
|
+
f"seam vertices: {result['seamVertexCount']}",
|
|
589
|
+
]
|
|
590
|
+
if result["nonDiskCharts"]:
|
|
591
|
+
lines.append(
|
|
592
|
+
f"NON-DISK charts {result['nonDiskCharts']}: these have no valid flattening and their "
|
|
593
|
+
"UVs will fold over; cut them before baking"
|
|
594
|
+
)
|
|
595
|
+
return "\n".join(lines)
|
|
596
|
+
|
|
597
|
+
|
|
598
|
+
def main(argv: list[str]) -> int:
|
|
599
|
+
parser = argparse.ArgumentParser(description="Unwrap a mesh into a UV layout.")
|
|
600
|
+
parser.add_argument("mesh", type=Path, help="JSON file with vertices and indices")
|
|
601
|
+
parser.add_argument("--angle", type=float, default=DEFAULT_CHART_ANGLE_DEGREES)
|
|
602
|
+
parser.add_argument("--out", type=Path)
|
|
603
|
+
parser.add_argument("--json", action="store_true")
|
|
604
|
+
args = parser.parse_args(argv)
|
|
605
|
+
try:
|
|
606
|
+
mesh = json.loads(args.mesh.read_text())
|
|
607
|
+
if isinstance(mesh, dict) and isinstance(mesh.get("meshes"), list) and mesh["meshes"]:
|
|
608
|
+
mesh = mesh["meshes"][0]
|
|
609
|
+
result = unwrap(mesh, args.angle)
|
|
610
|
+
except Exception as exc:
|
|
611
|
+
print(f"error: {exc}", file=sys.stderr)
|
|
612
|
+
return 2
|
|
613
|
+
if args.out:
|
|
614
|
+
args.out.write_text(json.dumps(result))
|
|
615
|
+
print(json.dumps(result, indent=2) if args.json else _format_summary(result))
|
|
616
|
+
# Fold-overs and non-disk charts are the two states where the layout is unusable rather than
|
|
617
|
+
# merely imperfect, so they are the only ones that fail the run.
|
|
618
|
+
return 1 if result["totalFlippedTriangles"] or result["nonDiskCharts"] else 0
|
|
619
|
+
|
|
620
|
+
|
|
621
|
+
if __name__ == "__main__":
|
|
622
|
+
raise SystemExit(main(sys.argv[1:]))
|