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,381 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Deterministic bounded analysis-by-synthesis fitting."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import argparse
|
|
7
|
+
from copy import deepcopy
|
|
8
|
+
import json
|
|
9
|
+
import math
|
|
10
|
+
import sys
|
|
11
|
+
from collections.abc import Callable, Mapping, Sequence
|
|
12
|
+
from dataclasses import dataclass
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from typing import Final, Literal
|
|
15
|
+
|
|
16
|
+
if __package__:
|
|
17
|
+
from ._fit_divine_eye import is_approved_divine_eye_result, normalize_history
|
|
18
|
+
else:
|
|
19
|
+
from _fit_divine_eye import is_approved_divine_eye_result, normalize_history
|
|
20
|
+
|
|
21
|
+
MAX_DIMENSIONS: Final = 15
|
|
22
|
+
FitStatus = Literal["max-iterations", "max-evaluations", "plateau", "oscillation"]
|
|
23
|
+
ParameterVector = tuple[float, ...]
|
|
24
|
+
Bounds = tuple[tuple[float, float], ...]
|
|
25
|
+
Objective = Callable[[ParameterVector], float]
|
|
26
|
+
RenderForParameters = Callable[[ParameterVector], str | Path]
|
|
27
|
+
DivineEyeEvaluator = Callable[[Path, Path], Mapping[str, object]]
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@dataclass(frozen=True, slots=True)
|
|
31
|
+
class FitInputError(ValueError):
|
|
32
|
+
field: str
|
|
33
|
+
detail: str
|
|
34
|
+
|
|
35
|
+
def __str__(self) -> str:
|
|
36
|
+
return f"invalid fit input {self.field}: {self.detail}"
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@dataclass(frozen=True, slots=True)
|
|
40
|
+
class NonFiniteScoreError(ValueError):
|
|
41
|
+
value_repr: str
|
|
42
|
+
|
|
43
|
+
def __str__(self) -> str:
|
|
44
|
+
return f"objective returned non-finite score {self.value_repr}"
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
@dataclass(frozen=True, slots=True)
|
|
48
|
+
class FitConfig:
|
|
49
|
+
max_iterations: int = 40
|
|
50
|
+
max_evaluations: int = 500
|
|
51
|
+
min_improvement: float = 1e-9
|
|
52
|
+
plateau_iterations: int = 3
|
|
53
|
+
oscillation_flips: int = 2
|
|
54
|
+
seed: int | None = None
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
@dataclass(frozen=True, slots=True)
|
|
58
|
+
class FitTelemetry:
|
|
59
|
+
iteration: int
|
|
60
|
+
evaluations: int
|
|
61
|
+
best_score: float
|
|
62
|
+
improved: bool
|
|
63
|
+
step_sizes: ParameterVector
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
@dataclass(frozen=True, slots=True)
|
|
67
|
+
class FitResult:
|
|
68
|
+
parameters: ParameterVector
|
|
69
|
+
best_score: float
|
|
70
|
+
status: FitStatus
|
|
71
|
+
iterations: int
|
|
72
|
+
evaluations: int
|
|
73
|
+
seed: int | None
|
|
74
|
+
history: tuple[FitTelemetry, ...]
|
|
75
|
+
|
|
76
|
+
def to_correction_history(self, defect_tags: Sequence[str] = ()) -> list[dict[str, float | bool | list[str]]]:
|
|
77
|
+
tags = list(defect_tags)
|
|
78
|
+
for index, record in enumerate(self.history):
|
|
79
|
+
if not 0.0 <= record.best_score <= 1.0:
|
|
80
|
+
raise FitInputError(f"history[{index}].best_score", "must be within [0, 1] for fidelity")
|
|
81
|
+
return [
|
|
82
|
+
{"fidelity": record.best_score, "defectTags": tags.copy(), "reverted": False}
|
|
83
|
+
for record in self.history
|
|
84
|
+
]
|
|
85
|
+
|
|
86
|
+
def to_json(self) -> dict[str, object]:
|
|
87
|
+
return {
|
|
88
|
+
"parameters": list(self.parameters),
|
|
89
|
+
"bestScore": self.best_score,
|
|
90
|
+
"bestObjectiveScore": self.best_score,
|
|
91
|
+
"status": self.status,
|
|
92
|
+
"iterations": self.iterations,
|
|
93
|
+
"evaluations": self.evaluations,
|
|
94
|
+
"seed": self.seed,
|
|
95
|
+
"history": [
|
|
96
|
+
{
|
|
97
|
+
"iteration": record.iteration,
|
|
98
|
+
"evaluations": record.evaluations,
|
|
99
|
+
"bestScore": record.best_score,
|
|
100
|
+
"bestObjectiveScore": record.best_score,
|
|
101
|
+
"improved": record.improved,
|
|
102
|
+
"stepSizes": list(record.step_sizes),
|
|
103
|
+
}
|
|
104
|
+
for record in self.history
|
|
105
|
+
],
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
@dataclass(frozen=True, slots=True)
|
|
110
|
+
class DivineEyeFitResult:
|
|
111
|
+
fit_result: FitResult
|
|
112
|
+
best_raw_fidelity: float | None
|
|
113
|
+
divine_eye_results: tuple[dict[str, object], ...]
|
|
114
|
+
correction_history: tuple[dict[str, object], ...]
|
|
115
|
+
|
|
116
|
+
def to_json(self) -> dict[str, object]:
|
|
117
|
+
return {
|
|
118
|
+
"fitResult": self.fit_result.to_json(),
|
|
119
|
+
"bestObjectiveScore": self.fit_result.best_score,
|
|
120
|
+
"bestRawFidelity": self.best_raw_fidelity,
|
|
121
|
+
"divineEyeResults": deepcopy(self.divine_eye_results),
|
|
122
|
+
"correctionHistory": deepcopy(self.correction_history),
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def divine_eye_fidelity(result: Mapping[str, object]) -> float:
|
|
127
|
+
if not isinstance(result, Mapping):
|
|
128
|
+
raise FitInputError("Divine Eye result", "must be a mapping")
|
|
129
|
+
score = result.get("fidelity")
|
|
130
|
+
if score is None:
|
|
131
|
+
raise FitInputError("Divine Eye result", "missing fidelity")
|
|
132
|
+
if isinstance(score, bool) or not isinstance(score, int | float) or not math.isfinite(score) or not 0.0 <= score <= 1.0:
|
|
133
|
+
raise FitInputError("Divine Eye result.fidelity", "must be a finite number in [0, 1]")
|
|
134
|
+
return float(score)
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def divine_eye_correction_history(
|
|
138
|
+
results: Sequence[Mapping[str, object]],
|
|
139
|
+
) -> list[dict[str, object]]:
|
|
140
|
+
"""Normalize unmodified Divine Eye results into correction-loop history."""
|
|
141
|
+
return normalize_history(results, divine_eye_fidelity, FitInputError)
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _divine_eye_objective_score(result: Mapping[str, object]) -> float:
|
|
145
|
+
fidelity = divine_eye_fidelity(result)
|
|
146
|
+
return fidelity if is_approved_divine_eye_result(result, FitInputError, "Divine Eye result") else -1.0
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def fit_against_divine_eye(
|
|
150
|
+
initial: Sequence[float],
|
|
151
|
+
bounds: Sequence[Sequence[float]],
|
|
152
|
+
render_for_parameters: RenderForParameters,
|
|
153
|
+
reference_png: str | Path,
|
|
154
|
+
evaluator: DivineEyeEvaluator | None = None,
|
|
155
|
+
config: FitConfig = FitConfig(),
|
|
156
|
+
) -> DivineEyeFitResult:
|
|
157
|
+
if not callable(render_for_parameters):
|
|
158
|
+
raise FitInputError("render_for_parameters", "must be callable")
|
|
159
|
+
evaluator = _default_divine_eye_evaluator if evaluator is None else evaluator
|
|
160
|
+
if not callable(evaluator):
|
|
161
|
+
raise FitInputError("evaluator", "must be callable")
|
|
162
|
+
reference_path = Path(reference_png)
|
|
163
|
+
results: list[Mapping[str, object]] = []
|
|
164
|
+
|
|
165
|
+
def objective(parameters: ParameterVector) -> float:
|
|
166
|
+
render_path = render_for_parameters(parameters)
|
|
167
|
+
evaluated = evaluator(reference_path, Path(render_path))
|
|
168
|
+
if not isinstance(evaluated, Mapping):
|
|
169
|
+
raise FitInputError("Divine Eye result", "must be a mapping")
|
|
170
|
+
result = deepcopy(dict(evaluated))
|
|
171
|
+
result.setdefault("hardGateFailures", [])
|
|
172
|
+
result["fitCandidateParameters"] = list(parameters)
|
|
173
|
+
result["fitReferencePng"] = str(reference_path)
|
|
174
|
+
result["fitRenderPath"] = str(render_path)
|
|
175
|
+
results.append(result)
|
|
176
|
+
return _divine_eye_objective_score(result)
|
|
177
|
+
|
|
178
|
+
fit_result = fit(initial, bounds, objective, config)
|
|
179
|
+
history = divine_eye_correction_history(results)
|
|
180
|
+
best_raw_fidelity = _selected_raw_fidelity(fit_result.parameters, results)
|
|
181
|
+
return DivineEyeFitResult(fit_result, best_raw_fidelity, tuple(deepcopy(dict(result)) for result in results), tuple(history))
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def _selected_raw_fidelity(parameters: ParameterVector, results: Sequence[Mapping[str, object]]) -> float | None:
|
|
185
|
+
candidate = list(parameters)
|
|
186
|
+
scores = [divine_eye_fidelity(result) for result in results if result["fitCandidateParameters"] == candidate and is_approved_divine_eye_result(result, FitInputError, "Divine Eye result")]
|
|
187
|
+
return max(scores, default=None)
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def _default_divine_eye_evaluator(reference_png: Path, render_png: Path) -> Mapping[str, object]:
|
|
191
|
+
if __package__:
|
|
192
|
+
from .divine_eye import evaluate
|
|
193
|
+
else:
|
|
194
|
+
from divine_eye import evaluate
|
|
195
|
+
return evaluate(reference_png, render_png)
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def fit(initial: Sequence[float], bounds: Sequence[Sequence[float]], objective: Objective, config: FitConfig = FitConfig()) -> FitResult:
|
|
199
|
+
if not callable(objective):
|
|
200
|
+
raise FitInputError("objective", "must be callable")
|
|
201
|
+
parameters, normalized_bounds = _normalize_inputs(initial, bounds)
|
|
202
|
+
_validate_config(config)
|
|
203
|
+
current_score = _finite_score(objective(parameters))
|
|
204
|
+
evaluations = 1
|
|
205
|
+
step_sizes = tuple((upper - lower) / 4.0 for lower, upper in normalized_bounds)
|
|
206
|
+
history: list[FitTelemetry] = [FitTelemetry(0, evaluations, current_score, False, step_sizes)]
|
|
207
|
+
plateau_count = 0
|
|
208
|
+
direction_by_coordinate: dict[int, int] = {}
|
|
209
|
+
direction_flips = 0
|
|
210
|
+
for iteration in range(1, config.max_iterations + 1):
|
|
211
|
+
iteration_start = current_score
|
|
212
|
+
improved = False
|
|
213
|
+
iteration_directions: dict[int, int] = {}
|
|
214
|
+
for index, (lower, upper) in enumerate(normalized_bounds):
|
|
215
|
+
coordinate_start = parameters[index]
|
|
216
|
+
candidate_parameters = parameters
|
|
217
|
+
candidate_score = current_score
|
|
218
|
+
candidate_direction = 0
|
|
219
|
+
for direction in (-1, 1):
|
|
220
|
+
value = min(upper, max(lower, coordinate_start + direction * step_sizes[index]))
|
|
221
|
+
if value == coordinate_start:
|
|
222
|
+
continue
|
|
223
|
+
if evaluations >= config.max_evaluations:
|
|
224
|
+
if candidate_direction:
|
|
225
|
+
parameters, current_score = candidate_parameters, candidate_score
|
|
226
|
+
history.append(FitTelemetry(iteration, evaluations, current_score, True, step_sizes))
|
|
227
|
+
return _result(parameters, current_score, "max-evaluations", iteration, evaluations, config, history)
|
|
228
|
+
return _result(parameters, current_score, "max-evaluations", iteration - 1, evaluations, config, history)
|
|
229
|
+
proposal = _replace_coordinate(parameters, index, value)
|
|
230
|
+
proposal_score = _finite_score(objective(proposal))
|
|
231
|
+
evaluations += 1
|
|
232
|
+
if proposal_score > candidate_score:
|
|
233
|
+
candidate_parameters = proposal
|
|
234
|
+
candidate_score = proposal_score
|
|
235
|
+
candidate_direction = direction
|
|
236
|
+
if candidate_direction:
|
|
237
|
+
iteration_directions[index] = candidate_direction
|
|
238
|
+
parameters = candidate_parameters
|
|
239
|
+
current_score = candidate_score
|
|
240
|
+
improved = True
|
|
241
|
+
net_gain = current_score - iteration_start
|
|
242
|
+
if net_gain < config.min_improvement:
|
|
243
|
+
plateau_count += 1
|
|
244
|
+
flips = sum(direction_by_coordinate.get(index) not in (None, direction) for index, direction in iteration_directions.items())
|
|
245
|
+
direction_flips = direction_flips + 1 if flips else 0
|
|
246
|
+
direction_by_coordinate = iteration_directions
|
|
247
|
+
else:
|
|
248
|
+
plateau_count = direction_flips = 0
|
|
249
|
+
direction_by_coordinate = {}
|
|
250
|
+
history.append(FitTelemetry(iteration, evaluations, current_score, improved, step_sizes))
|
|
251
|
+
if direction_flips >= config.oscillation_flips:
|
|
252
|
+
return _result(parameters, current_score, "oscillation", iteration, evaluations, config, history)
|
|
253
|
+
if plateau_count >= config.plateau_iterations:
|
|
254
|
+
return _result(parameters, current_score, "plateau", iteration, evaluations, config, history)
|
|
255
|
+
if not improved:
|
|
256
|
+
step_sizes = tuple(step / 2.0 for step in step_sizes)
|
|
257
|
+
return _result(parameters, current_score, "max-iterations", config.max_iterations, evaluations, config, history)
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def _result(
|
|
261
|
+
parameters: ParameterVector,
|
|
262
|
+
best_score: float,
|
|
263
|
+
status: FitStatus,
|
|
264
|
+
iterations: int,
|
|
265
|
+
evaluations: int,
|
|
266
|
+
config: FitConfig,
|
|
267
|
+
history: list[FitTelemetry],
|
|
268
|
+
) -> FitResult:
|
|
269
|
+
return FitResult(parameters, best_score, status, iterations, evaluations, config.seed, tuple(history))
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
def _normalize_inputs(initial: Sequence[float], bounds: Sequence[Sequence[float]]) -> tuple[ParameterVector, Bounds]:
|
|
273
|
+
if isinstance(initial, str | bytes) or not isinstance(initial, Sequence):
|
|
274
|
+
raise FitInputError("initial", "must be a sequence of parameters")
|
|
275
|
+
if isinstance(bounds, str | bytes) or not isinstance(bounds, Sequence):
|
|
276
|
+
raise FitInputError("bounds", "must be a sequence of bound pairs")
|
|
277
|
+
parameters = tuple(_finite_parameter(value, f"initial[{index}]") for index, value in enumerate(initial))
|
|
278
|
+
if not 1 <= len(parameters) <= MAX_DIMENSIONS:
|
|
279
|
+
raise FitInputError("initial", f"must contain 1..{MAX_DIMENSIONS} parameters")
|
|
280
|
+
if len(bounds) != len(parameters):
|
|
281
|
+
raise FitInputError("bounds", "must have one pair per parameter")
|
|
282
|
+
normalized_bounds: list[tuple[float, float]] = []
|
|
283
|
+
for index, pair in enumerate(bounds):
|
|
284
|
+
if isinstance(pair, str | bytes) or not isinstance(pair, Sequence):
|
|
285
|
+
raise FitInputError(f"bounds[{index}]", "must be a two-value sequence")
|
|
286
|
+
if len(pair) != 2:
|
|
287
|
+
raise FitInputError(f"bounds[{index}]", "must contain [lower, upper]")
|
|
288
|
+
lower = _finite_parameter(pair[0], f"bounds[{index}][0]")
|
|
289
|
+
upper = _finite_parameter(pair[1], f"bounds[{index}][1]")
|
|
290
|
+
if lower >= upper:
|
|
291
|
+
raise FitInputError(f"bounds[{index}]", "lower must be smaller than upper")
|
|
292
|
+
if not lower <= parameters[index] <= upper:
|
|
293
|
+
raise FitInputError(f"initial[{index}]", "must be within its bounds")
|
|
294
|
+
normalized_bounds.append((lower, upper))
|
|
295
|
+
return parameters, tuple(normalized_bounds)
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
def _finite_parameter(value: float, field: str) -> float:
|
|
299
|
+
if isinstance(value, bool) or not isinstance(value, int | float) or not math.isfinite(value):
|
|
300
|
+
raise FitInputError(field, "must be a finite non-boolean number")
|
|
301
|
+
return float(value)
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
def _finite_score(score: float) -> float:
|
|
305
|
+
if isinstance(score, bool) or not isinstance(score, int | float) or not math.isfinite(score):
|
|
306
|
+
raise NonFiniteScoreError(repr(score))
|
|
307
|
+
return float(score)
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
def _replace_coordinate(values: ParameterVector, index: int, value: float) -> ParameterVector:
|
|
311
|
+
return tuple(value if position == index else current for position, current in enumerate(values))
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
def _validate_config(config: FitConfig) -> None:
|
|
315
|
+
if not isinstance(config, FitConfig):
|
|
316
|
+
raise FitInputError("config", "must be a FitConfig")
|
|
317
|
+
if not all(_is_positive_integer(value) for value in (config.max_iterations, config.max_evaluations, config.plateau_iterations, config.oscillation_flips)):
|
|
318
|
+
raise FitInputError("config", "iteration, evaluation, plateau, and oscillation limits must be positive")
|
|
319
|
+
if (
|
|
320
|
+
isinstance(config.min_improvement, bool)
|
|
321
|
+
or not isinstance(config.min_improvement, int | float)
|
|
322
|
+
or config.min_improvement < 0.0
|
|
323
|
+
or not math.isfinite(config.min_improvement)
|
|
324
|
+
):
|
|
325
|
+
raise FitInputError("config.min_improvement", "must be a finite non-negative number")
|
|
326
|
+
if config.seed is not None and (isinstance(config.seed, bool) or not isinstance(config.seed, int)):
|
|
327
|
+
raise FitInputError("config.seed", "must be an integer or null")
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
def _is_positive_integer(value: int) -> bool:
|
|
331
|
+
return isinstance(value, int) and not isinstance(value, bool) and value > 0
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
def _quadratic_objective(target: ParameterVector) -> Objective:
|
|
335
|
+
return lambda values: 1.0 - sum((value - target[index]) ** 2 for index, value in enumerate(values))
|
|
336
|
+
|
|
337
|
+
|
|
338
|
+
def _cli_config(raw: Mapping[str, object]) -> FitConfig:
|
|
339
|
+
names = {"maxIterations": "max_iterations", "maxEvaluations": "max_evaluations", "minImprovement": "min_improvement", "plateauIterations": "plateau_iterations", "oscillationFlips": "oscillation_flips", "seed": "seed"}
|
|
340
|
+
unknown = sorted(set(raw) - set(names))
|
|
341
|
+
if unknown:
|
|
342
|
+
raise FitInputError("config", f"unknown key(s): {', '.join(unknown)}")
|
|
343
|
+
values = {names[key]: value for key, value in raw.items() if key in names}
|
|
344
|
+
return FitConfig(**values)
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
def main(argv: Sequence[str]) -> int:
|
|
348
|
+
parser = argparse.ArgumentParser(description=__doc__)
|
|
349
|
+
parser.add_argument("--input", required=True, type=Path, help="quadratic objective JSON input")
|
|
350
|
+
parser.add_argument("--json", action="store_true", help="emit JSON result")
|
|
351
|
+
args = parser.parse_args(argv)
|
|
352
|
+
try:
|
|
353
|
+
raw = json.loads(args.input.read_text(encoding="utf-8"))
|
|
354
|
+
if not isinstance(raw, dict):
|
|
355
|
+
raise FitInputError("input", "must be a JSON object")
|
|
356
|
+
expected = {"initial", "bounds", "target", "config"}
|
|
357
|
+
if set(raw) != expected:
|
|
358
|
+
raise FitInputError("input", f"must contain exactly {sorted(expected)}; missing={sorted(expected - set(raw))} unknown={sorted(set(raw) - expected)}")
|
|
359
|
+
initial = raw.get("initial")
|
|
360
|
+
bounds = raw.get("bounds")
|
|
361
|
+
target = raw.get("target")
|
|
362
|
+
config_raw = raw.get("config")
|
|
363
|
+
if not isinstance(initial, list) or not isinstance(bounds, list) or not isinstance(target, list):
|
|
364
|
+
raise FitInputError("input", "initial, bounds, and target must be arrays")
|
|
365
|
+
if not isinstance(config_raw, dict):
|
|
366
|
+
raise FitInputError("config", "must be an object")
|
|
367
|
+
target_parameters, _ = _normalize_inputs(target, bounds)
|
|
368
|
+
result = fit(initial, bounds, _quadratic_objective(target_parameters), _cli_config(config_raw))
|
|
369
|
+
except (FitInputError, NonFiniteScoreError, OSError, json.JSONDecodeError) as exc:
|
|
370
|
+
print(f"error: {exc}", file=sys.stderr)
|
|
371
|
+
return 2
|
|
372
|
+
payload = result.to_json()
|
|
373
|
+
if args.json:
|
|
374
|
+
print(json.dumps(payload, sort_keys=True))
|
|
375
|
+
else:
|
|
376
|
+
print(f"{payload['status']} score={payload['bestScore']} evaluations={payload['evaluations']}")
|
|
377
|
+
return 0
|
|
378
|
+
|
|
379
|
+
|
|
380
|
+
if __name__ == "__main__":
|
|
381
|
+
raise SystemExit(main(sys.argv[1:]))
|
|
@@ -0,0 +1,294 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import sys
|
|
4
|
+
from collections import Counter
|
|
5
|
+
from itertools import combinations
|
|
6
|
+
from math import isfinite
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Any, TypeAlias
|
|
9
|
+
|
|
10
|
+
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
|
11
|
+
from self_intersection import analyze_mesh # noqa: E402
|
|
12
|
+
|
|
13
|
+
SEAM_MIN_OVERLAP = 0.02
|
|
14
|
+
SEAM_MAX_OVERLAP = 0.05
|
|
15
|
+
SEAM_SOURCE = "grimoire/build/geometry_patterns.md"
|
|
16
|
+
DEFAULT_TRIANGLE_BUDGET = 50_000
|
|
17
|
+
NORMAL_DOT_THRESHOLD = 0.0
|
|
18
|
+
EdgeKey: TypeAlias = tuple[tuple[float, ...], tuple[float, ...]]
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _vertex_key(vertex: Any, precision: int = 6) -> tuple[float, ...]:
|
|
22
|
+
if not isinstance(vertex, (list, tuple)) or len(vertex) < 3:
|
|
23
|
+
raise ValueError("vertices must contain 3D positions")
|
|
24
|
+
return tuple(round(float(value), precision) for value in vertex[:3])
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def mesh_edge_counts(vertices: list[Any], indices: list[Any], *, precision: int = 6) -> dict[str, int]:
|
|
28
|
+
keys = [_vertex_key(vertex, precision) for vertex in vertices]
|
|
29
|
+
edges: Counter[EdgeKey] = Counter()
|
|
30
|
+
triangles: list[Any] = indices if indices and isinstance(indices[0], (list, tuple)) else [indices[i:i + 3] for i in range(0, len(indices), 3)]
|
|
31
|
+
if any(len(triangle) != 3 for triangle in triangles):
|
|
32
|
+
raise ValueError("triangle indices must contain groups of three")
|
|
33
|
+
for triangle in triangles:
|
|
34
|
+
points = [keys[int(index)] for index in triangle]
|
|
35
|
+
for left, right in ((points[0], points[1]), (points[1], points[2]), (points[2], points[0])):
|
|
36
|
+
edge: EdgeKey = (left, right) if left <= right else (right, left)
|
|
37
|
+
edges[edge] += 1
|
|
38
|
+
return {"boundaryEdges": sum(count == 1 for count in edges.values()),
|
|
39
|
+
"nonManifoldEdges": sum(count > 2 for count in edges.values()), "edgeCount": len(edges)}
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _bounds(mesh: dict[str, Any]) -> list[list[float]] | None:
|
|
43
|
+
bounds = mesh.get("bounds") or mesh.get("boundingBox")
|
|
44
|
+
if isinstance(bounds, dict):
|
|
45
|
+
bounds = [bounds.get("min"), bounds.get("max")]
|
|
46
|
+
if isinstance(bounds, (list, tuple)) and len(bounds) == 2 and all(isinstance(point, (list, tuple)) and len(point) >= 3 for point in bounds):
|
|
47
|
+
points = [point for point in bounds if isinstance(point, (list, tuple))]
|
|
48
|
+
if len(points) == 2:
|
|
49
|
+
return [[float(value) for value in points[index][:3]] for index in range(2)]
|
|
50
|
+
vertices = mesh.get("vertices")
|
|
51
|
+
if not isinstance(vertices, list) or not vertices:
|
|
52
|
+
return None
|
|
53
|
+
points = [_vertex_key(point, 12) for point in vertices]
|
|
54
|
+
return [[min(point[axis] for point in points) for axis in range(3)], [max(point[axis] for point in points) for axis in range(3)]]
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _axis_index(value: Any) -> int:
|
|
58
|
+
if isinstance(value, int) and value in (0, 1, 2):
|
|
59
|
+
return value
|
|
60
|
+
return {"x": 0, "y": 1, "z": 2, "long": 0, "length": 0, "thickness": 2}.get(str(value or "").lower(), 0)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _seam_overlap(first: dict[str, Any], second: dict[str, Any]) -> tuple[float, int] | None:
|
|
64
|
+
raw_attachment = second.get("attachment")
|
|
65
|
+
attachment: dict[str, Any] = raw_attachment if isinstance(raw_attachment, dict) else {}
|
|
66
|
+
axis = attachment.get("seamAxis", second.get("seamAxis", first.get("seamAxis")))
|
|
67
|
+
a, b = _bounds(first), _bounds(second)
|
|
68
|
+
if axis is None or a is None or b is None:
|
|
69
|
+
return None
|
|
70
|
+
index = _axis_index(axis)
|
|
71
|
+
return min(a[1][index], b[1][index]) - max(a[0][index], b[0][index]), index
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _blade_thickness(mesh: dict[str, Any]) -> dict[str, Any]:
|
|
75
|
+
samples = mesh.get("thicknessSamples") or mesh.get("crossSections")
|
|
76
|
+
grind_samples = mesh.get("grindSamples") or samples
|
|
77
|
+
distal_samples = mesh.get("distalThicknessSamples") or samples
|
|
78
|
+
values = []
|
|
79
|
+
def numeric_values(source: Any) -> list[float]:
|
|
80
|
+
result: list[float] = []
|
|
81
|
+
if isinstance(source, list):
|
|
82
|
+
for sample in source:
|
|
83
|
+
value = sample.get("thickness") if isinstance(sample, dict) else sample
|
|
84
|
+
if isinstance(value, (int, float)):
|
|
85
|
+
result.append(float(value))
|
|
86
|
+
return result
|
|
87
|
+
if isinstance(samples, list):
|
|
88
|
+
for sample in samples:
|
|
89
|
+
value = sample.get("thickness") if isinstance(sample, dict) else sample
|
|
90
|
+
if isinstance(value, (int, float)):
|
|
91
|
+
values.append(float(value))
|
|
92
|
+
grind_values = numeric_values(grind_samples)
|
|
93
|
+
distal_values = numeric_values(distal_samples)
|
|
94
|
+
grind_variation = max(grind_values) - min(grind_values) if grind_values else 0.0
|
|
95
|
+
distal_variation = max(distal_values) - min(distal_values) if distal_values else 0.0
|
|
96
|
+
return {"grindVariation": grind_variation, "distalVariation": distal_variation,
|
|
97
|
+
"constantGrind": grind_variation <= 1e-6, "missingDistalTaper": distal_variation <= 1e-6,
|
|
98
|
+
"reported": bool(values)}
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _triangle_count(mesh: dict[str, Any]) -> int | None:
|
|
102
|
+
if isinstance(mesh.get("triangleCount"), (int, float)) and not isinstance(mesh["triangleCount"], bool):
|
|
103
|
+
return max(0, int(mesh["triangleCount"]))
|
|
104
|
+
indices = mesh.get("indices")
|
|
105
|
+
if isinstance(indices, list):
|
|
106
|
+
return len(indices) if indices and isinstance(indices[0], (list, tuple)) else len(indices) // 3
|
|
107
|
+
return None
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _has_reduced_lod_tiers(lod_plan: Any) -> bool:
|
|
111
|
+
if not isinstance(lod_plan, list) or len(lod_plan) < 2:
|
|
112
|
+
return False
|
|
113
|
+
previous_distance: float | None = None
|
|
114
|
+
previous_triangles: int | None = None
|
|
115
|
+
for tier in lod_plan:
|
|
116
|
+
if not isinstance(tier, dict):
|
|
117
|
+
return False
|
|
118
|
+
distance = tier.get("distance")
|
|
119
|
+
triangles = tier.get("triangleCount")
|
|
120
|
+
if (
|
|
121
|
+
not isinstance(distance, (int, float))
|
|
122
|
+
or isinstance(distance, bool)
|
|
123
|
+
or not isfinite(distance)
|
|
124
|
+
or not isinstance(triangles, int)
|
|
125
|
+
or isinstance(triangles, bool)
|
|
126
|
+
or triangles < 1
|
|
127
|
+
):
|
|
128
|
+
return False
|
|
129
|
+
if previous_distance is not None and distance <= previous_distance:
|
|
130
|
+
return False
|
|
131
|
+
if previous_triangles is not None and triangles >= previous_triangles:
|
|
132
|
+
return False
|
|
133
|
+
previous_distance = float(distance)
|
|
134
|
+
previous_triangles = triangles
|
|
135
|
+
return True
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def _normal_consistency(mesh: dict[str, Any]) -> dict[str, Any] | None:
|
|
139
|
+
normals = mesh.get("normals")
|
|
140
|
+
if not isinstance(normals, list) or not isinstance(mesh.get("vertices"), list):
|
|
141
|
+
return None
|
|
142
|
+
if len(normals) != len(mesh["vertices"]):
|
|
143
|
+
return {"checked": False, "consistent": False, "reason": "normal count does not match vertex count"}
|
|
144
|
+
indices = mesh.get("indices")
|
|
145
|
+
triangles = indices if isinstance(indices, list) and indices and isinstance(indices[0], (list, tuple)) else (
|
|
146
|
+
[indices[i:i + 3] for i in range(0, len(indices), 3)] if isinstance(indices, list) else []
|
|
147
|
+
)
|
|
148
|
+
if not triangles:
|
|
149
|
+
return None
|
|
150
|
+
flips = 0
|
|
151
|
+
checked = 0
|
|
152
|
+
invalid_normals = 0
|
|
153
|
+
for triangle in triangles:
|
|
154
|
+
if len(triangle) != 3:
|
|
155
|
+
continue
|
|
156
|
+
try:
|
|
157
|
+
a, b, c = (mesh["vertices"][int(index)] for index in triangle)
|
|
158
|
+
edge_a = [float(b[i]) - float(a[i]) for i in range(3)]
|
|
159
|
+
edge_b = [float(c[i]) - float(a[i]) for i in range(3)]
|
|
160
|
+
face = [
|
|
161
|
+
edge_a[1] * edge_b[2] - edge_a[2] * edge_b[1],
|
|
162
|
+
edge_a[2] * edge_b[0] - edge_a[0] * edge_b[2],
|
|
163
|
+
edge_a[0] * edge_b[1] - edge_a[1] * edge_b[0],
|
|
164
|
+
]
|
|
165
|
+
length = sum(value * value for value in face) ** 0.5
|
|
166
|
+
if length <= 1e-12:
|
|
167
|
+
continue
|
|
168
|
+
face = [value / length for value in face]
|
|
169
|
+
average = [
|
|
170
|
+
sum(float(mesh["normals"][int(index)][axis]) for index in triangle) / 3
|
|
171
|
+
for axis in range(3)
|
|
172
|
+
]
|
|
173
|
+
normal_length = sum(value * value for value in average) ** 0.5
|
|
174
|
+
if normal_length <= 1e-12:
|
|
175
|
+
invalid_normals += 1
|
|
176
|
+
continue
|
|
177
|
+
dot = sum(face[axis] * average[axis] for axis in range(3)) / normal_length
|
|
178
|
+
checked += 1
|
|
179
|
+
flips += dot < NORMAL_DOT_THRESHOLD
|
|
180
|
+
except (IndexError, TypeError, ValueError):
|
|
181
|
+
return {"checked": False, "consistent": False, "reason": "invalid vertex/normal data"}
|
|
182
|
+
return {
|
|
183
|
+
"checked": checked > 0,
|
|
184
|
+
"consistent": flips == 0 and invalid_normals == 0,
|
|
185
|
+
"checkedTriangles": checked,
|
|
186
|
+
"flippedTriangles": flips,
|
|
187
|
+
"invalidNormalTriangles": invalid_normals,
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def measure_geometry_integrity(payload: dict[str, Any]) -> dict[str, Any]:
|
|
192
|
+
meshes = payload.get("meshes") or payload.get("components") or []
|
|
193
|
+
if isinstance(meshes, dict):
|
|
194
|
+
meshes = [dict(value, id=key) if isinstance(value, dict) else {"id": key} for key, value in meshes.items()]
|
|
195
|
+
if not isinstance(meshes, list):
|
|
196
|
+
raise ValueError("built geometry meshes/components must be an array or object")
|
|
197
|
+
reports: list[dict[str, Any]] = []
|
|
198
|
+
failures: list[str] = []
|
|
199
|
+
issues: list[dict[str, Any]] = []
|
|
200
|
+
performance = payload.get("performanceBudget") if isinstance(payload.get("performanceBudget"), dict) else {}
|
|
201
|
+
triangle_budget = performance.get("triangleBudget", payload.get("triangleBudget", DEFAULT_TRIANGLE_BUDGET))
|
|
202
|
+
if not isinstance(triangle_budget, (int, float)) or isinstance(triangle_budget, bool) or triangle_budget <= 0:
|
|
203
|
+
triangle_budget = DEFAULT_TRIANGLE_BUDGET
|
|
204
|
+
lod_plan = payload.get("lodPlan")
|
|
205
|
+
lod_plan_valid = _has_reduced_lod_tiers(lod_plan)
|
|
206
|
+
total_triangles = 0
|
|
207
|
+
for index, mesh in enumerate(meshes):
|
|
208
|
+
if not isinstance(mesh, dict):
|
|
209
|
+
continue
|
|
210
|
+
item: dict[str, Any] = {"id": mesh.get("id") or mesh.get("name") or f"mesh-{index}", "realization": mesh.get("realization", "separate-geometry")}
|
|
211
|
+
if isinstance(mesh.get("vertices"), list) and isinstance(mesh.get("indices"), list):
|
|
212
|
+
item.update(mesh_edge_counts(mesh["vertices"], mesh["indices"]))
|
|
213
|
+
else:
|
|
214
|
+
item.update({"boundaryEdges": None, "nonManifoldEdges": None, "note": "mesh topology not supplied"})
|
|
215
|
+
role = str(mesh.get("role") or "").lower()
|
|
216
|
+
triangles = _triangle_count(mesh)
|
|
217
|
+
item["triangleCount"] = triangles
|
|
218
|
+
if triangles is not None:
|
|
219
|
+
total_triangles += triangles
|
|
220
|
+
normals = _normal_consistency(mesh)
|
|
221
|
+
if normals is not None:
|
|
222
|
+
item["normalConsistency"] = normals
|
|
223
|
+
if normals.get("consistent") is False:
|
|
224
|
+
message = f"{item['id']}: inconsistent face/vertex normals"
|
|
225
|
+
failures.append(message)
|
|
226
|
+
issues.append({"severity": "error", "code": "normal-consistency", "mesh": item["id"], "message": message})
|
|
227
|
+
elif isinstance(mesh.get("vertices"), list) and isinstance(mesh.get("indices"), list):
|
|
228
|
+
message = f"{item['id']}: normals are required for watertight geometry validation"
|
|
229
|
+
failures.append(message)
|
|
230
|
+
item["normalConsistency"] = {"checked": False, "consistent": False, "reason": "normals missing"}
|
|
231
|
+
issues.append({"severity": "error", "code": "normal-missing", "mesh": item["id"], "message": message})
|
|
232
|
+
if role == "blade" or "blade" in str(item["id"]).lower():
|
|
233
|
+
item["thickness"] = _blade_thickness(mesh)
|
|
234
|
+
if item["thickness"]["constantGrind"] or item["thickness"]["missingDistalTaper"]:
|
|
235
|
+
failures.append(f"{item['id']}: blade has constant thickness or missing distal taper")
|
|
236
|
+
if item.get("boundaryEdges", 0) not in (0, None):
|
|
237
|
+
message = f"{item['id']}: openEdges={item['boundaryEdges']} ({item['realization']})"
|
|
238
|
+
failures.append(message)
|
|
239
|
+
issues.append({"severity": "error", "code": "watertight", "mesh": item["id"], "message": message})
|
|
240
|
+
if item.get("nonManifoldEdges", 0):
|
|
241
|
+
message = f"{item['id']}: nonManifoldEdges={item['nonManifoldEdges']}"
|
|
242
|
+
failures.append(message)
|
|
243
|
+
issues.append({"severity": "error", "code": "non-manifold", "mesh": item["id"], "message": message})
|
|
244
|
+
# Both checks above are TOPOLOGICAL, and a surface pushed through its own far side changes no
|
|
245
|
+
# connectivity at all -- it reports 0 open edges, 0 non-manifold edges, and an identical edge
|
|
246
|
+
# count to the clean mesh. That is not a hypothetical: it is how a punched-through skull shipped.
|
|
247
|
+
# The geometric check belongs right here, beside the two it complements, or it is a CLI nobody
|
|
248
|
+
# remembers to run.
|
|
249
|
+
if isinstance(mesh.get("vertices"), list) and isinstance(mesh.get("indices"), list):
|
|
250
|
+
probe = analyze_mesh(mesh)
|
|
251
|
+
item["selfIntersection"] = {
|
|
252
|
+
key: probe[key]
|
|
253
|
+
for key in (
|
|
254
|
+
"selfIntersecting", "insideVertexCount", "undecidedVertexCount",
|
|
255
|
+
"sampledVertexCount", "totalVertexCount", "samplingStride",
|
|
256
|
+
)
|
|
257
|
+
if key in probe
|
|
258
|
+
}
|
|
259
|
+
if probe.get("selfIntersecting"):
|
|
260
|
+
message = (
|
|
261
|
+
f"{item['id']}: selfIntersecting, {probe.get('insideVertexCount')} of "
|
|
262
|
+
f"{probe.get('sampledVertexCount')} sampled vertices lie inside their own surface"
|
|
263
|
+
)
|
|
264
|
+
failures.append(message)
|
|
265
|
+
issues.append({"severity": "error", "code": "self-intersection", "mesh": item["id"], "message": message})
|
|
266
|
+
reports.append(item)
|
|
267
|
+
seams: list[dict[str, Any]] = []
|
|
268
|
+
for first, second in combinations([item for item in meshes if isinstance(item, dict)], 2):
|
|
269
|
+
relation = second.get("adjacentTo") or first.get("adjacentTo")
|
|
270
|
+
attached = isinstance(second.get("attachment"), dict) and second["attachment"].get("parentId") == first.get("id")
|
|
271
|
+
if relation not in (None, first.get("id"), second.get("id")) and not attached:
|
|
272
|
+
continue
|
|
273
|
+
result = _seam_overlap(first, second)
|
|
274
|
+
if result is None:
|
|
275
|
+
continue
|
|
276
|
+
overlap, axis = result
|
|
277
|
+
seam = {"a": first.get("id"), "b": second.get("id"), "axis": axis, "overlap": round(overlap, 6), "minimum": SEAM_MIN_OVERLAP, "source": SEAM_SOURCE}
|
|
278
|
+
seams.append(seam)
|
|
279
|
+
if overlap < SEAM_MIN_OVERLAP:
|
|
280
|
+
failures.append(f"seam {seam['a']}↔{seam['b']}: overlap={overlap:.3f} < {SEAM_MIN_OVERLAP:.2f}")
|
|
281
|
+
if total_triangles > triangle_budget:
|
|
282
|
+
message = f"triangle budget exceeded: {total_triangles} > {int(triangle_budget)}"
|
|
283
|
+
failures.append(message)
|
|
284
|
+
issues.append({"severity": "error", "code": "triangle-budget", "message": message, "triangles": total_triangles, "budget": int(triangle_budget)})
|
|
285
|
+
if not lod_plan_valid:
|
|
286
|
+
lod_message = "triangle budget exceeded without LOD tiers with increasing distance and decreasing triangleCount"
|
|
287
|
+
failures.append(lod_message)
|
|
288
|
+
code = "lod-required" if not isinstance(lod_plan, list) or not lod_plan else "lod-invalid"
|
|
289
|
+
issues.append({"severity": "error", "code": code, "message": lod_message})
|
|
290
|
+
return {"passed": not failures, "source": SEAM_SOURCE, "minimumSeamOverlap": SEAM_MIN_OVERLAP,
|
|
291
|
+
"maximumDocumentedSeamOverlap": SEAM_MAX_OVERLAP, "triangleBudget": int(triangle_budget),
|
|
292
|
+
"triangleCount": total_triangles, "lodPlanPresent": isinstance(lod_plan, list) and bool(lod_plan),
|
|
293
|
+
"lodPlanValid": lod_plan_valid,
|
|
294
|
+
"meshes": reports, "seams": seams, "failures": failures, "issues": issues}
|