"""scripts/fusion_to_scene.py(Fusion エクスポート → シーン YAML の CLI)の回帰・統合テスト.
仕様出典(Fusion 取り込みの確定事項.docs/04_SPEC には Phase 4 で追記予定):
- manifest.json の各ボディの STL はローカル座標.transform(16 要素・行優先・平行移動 mm)を
STL 読込直後に適用してワールド座標にし,aabb_mm(ワールド mm)と照合する.
桁違い(2 倍以上 / 半分以下)は ValueError,許容差超は警告
- 回転+平行移動の transform を適用した後でも LED 判定・基板ラベルが正しいこと
(回転したユニットが bottom に潰れない)
- ワールド座標 STL を mesh-dir(既定 `<out の親>/meshes/<design>/`)に書き出し,YAML は相対パスで
参照する.生成 YAML は scene.schema のローダで読める
- 光源はベース YAML の lights[0] をテンプレートに差し替え.メッシュは対応表順,exclude と LED は
含めない
- 実データ検証: SmTIASv3 の LED 18 個は scene_baseline.yaml と(Fusion 側の設計値 1 個を除き)一致
テスト方針:
- configs/scene_baseline.yaml の LED 18 個から 2835 の箱を作り,下ユニットは平行移動のみ,
右・左ユニットはローカル座標の STL + Z 軸まわり ±90° 回転の transform で表した
「SmTIASv3 相当」の合成エクスポートを tmp_path に作る
(実データ output/fusion_export は参照しない)
- CLI の main(argv) を呼び,生成 YAML の lights / meshes を baseline と突き合わせる
"""
from __future__ import annotations
import importlib.util
import json
import logging
import sys
from pathlib import Path
from types import ModuleType
import numpy as np
import pytest
import trimesh
import yaml
from sm_tias_lightsim.scene.schema import load_scene_yaml
_ROOT = Path(__file__).resolve().parents[2]
_SCRIPT = _ROOT / "scripts" / "fusion_to_scene.py"
_BASELINE = _ROOT / "configs" / "scene_baseline.yaml"
_MAPPING = _ROOT / "configs" / "fusion" / "smtias_v3_mapping.yaml"
_LED_LOCAL_EXTENTS = (2.8, 3.5, 1.05) # 下基板の向き(局所 X 2.8 × Y 3.5 × 厚み)
_COVER_LOCAL_EXTENTS = (60.0, 8.0, 2.0)
_COVER_Z_OFFSET = 2.0 # カバーは LED より +Z 側(LED は -Z へ光る)
_UNITS = {
# board: (オカレンス名, 回転角 [deg](Z 軸まわり), 平行移動 [mm])
"bottom": ("LEDユニット:1", 0.0, (3.8, -71.0, -66.0)),
"right": ("LEDユニット:2", 90.0, (137.0, -11.0, -10.0)),
"left": ("LEDユニット:3", -90.0, (-137.0, -18.8, 5.0)),
}
_ROOT_BODIES = [
# (名前, extents, center).ルート直下(ワールド座標 = ローカル座標)
("前側", (150.0, 160.0, 40.0), (0.0, 0.0, -100.0)),
("後側", (150.0, 160.0, 20.0), (0.0, 0.0, -30.0)),
("スマホホルダ", (90.0, 170.0, 10.0), (0.0, 0.0, 10.0)),
("SH-02M", (70.0, 140.0, 8.0), (0.0, 0.0, 20.0)),
("照明ムラ補正ボード", (120.0, 120.0, 2.0), (0.0, 0.0, -160.0)),
("スイッチカバー下", (20.0, 10.0, 5.0), (0.0, -90.0, -50.0)),
]
def _load_script() -> ModuleType:
cached = sys.modules.get("fusion_to_scene")
if cached is not None and Path(getattr(cached, "__file__", "")).resolve() == _SCRIPT:
return cached
spec = importlib.util.spec_from_file_location("fusion_to_scene", _SCRIPT)
assert spec is not None and spec.loader is not None
module = importlib.util.module_from_spec(spec)
sys.modules["fusion_to_scene"] = module
spec.loader.exec_module(module)
return module
def _baseline() -> dict:
return yaml.safe_load(_BASELINE.read_text(encoding="utf-8"))
def _rz(deg: float) -> np.ndarray:
t = np.radians(deg)
c, s = np.cos(t), np.sin(t)
m = np.eye(4)
m[:2, :2] = [[c, -s], [s, c]]
# ±90° の cos の丸め残差(6e-17)を掃除しておく(Fusion も整数回転は厳密値を返す)
m[np.abs(m) < 1e-15] = 0.0
return m
def _unit_transform(deg: float, t: tuple[float, float, float]) -> np.ndarray:
m = _rz(deg)
m[:3, 3] = t
return m
def _box(extents, center) -> trimesh.Trimesh:
tf = np.eye(4)
tf[:3, 3] = center
return trimesh.creation.box(extents=extents, transform=tf)
def _write_export(export_dir: Path, *, with_transform: bool = True, stl_scale: float = 1.0,
aabb_shift: float = 0.0, drop_transform_of: str | None = None) -> dict:
"""baseline の LED から SmTIASv3 相当の合成エクスポートを書き出す.
Args:
export_dir: 出力先.
with_transform: False なら STL をワールド座標で書き,manifest から transform を省く
(古いマニフェスト形式).
stl_scale: STL の頂点に掛ける倍率(0.1 で「cm で書き出した」状態を再現).
aabb_shift: manifest の aabb_mm を全ボディでずらす量 [mm].
drop_transform_of: このオカレンス名のボディだけ transform を書かない(取り違えの再現).
Returns:
manifest dict.
"""
base = _baseline()
stl_dir = export_dir / "stl"
stl_dir.mkdir(parents=True, exist_ok=True)
bodies: list[dict] = []
def _add(name: str, occ: str, local: trimesh.Trimesh, tf: np.ndarray) -> None:
world = local.copy()
world.apply_transform(tf)
out = local.copy() if with_transform else world.copy()
out.apply_scale(stl_scale)
rel = f"stl/{len(bodies):03d}.stl"
out.export(str(export_dir / rel), file_type="stl")
lo, hi = world.bounds
entry = {
"name": name,
"occurrence_path": occ,
"top_occurrence": occ,
"stl": rel,
"aabb_mm": [(lo + aabb_shift).tolist(), (hi + aabb_shift).tolist()],
}
if with_transform and occ != drop_transform_of:
entry["transform"] = tf.flatten().tolist()
bodies.append(entry)
for name, ext, center in _ROOT_BODIES:
_add(name, "", _box(ext, center), np.eye(4))
for board, (occ, deg, t) in _UNITS.items():
tf = _unit_transform(deg, t)
inv = np.linalg.inv(tf)
leds = [lt for lt in base["lights"] if lt["id"].startswith(f"led_{board}_")]
# manifest 上は ID と逆順に並べる(ID が座標順に振られることを確かめるため)
world_centers = [np.asarray(lt["center"], dtype=float) for lt in reversed(leds)]
cover_world = np.mean(world_centers, axis=0) + [0.0, 0.0, _COVER_Z_OFFSET]
cover_local = (inv @ [*cover_world, 1.0])[:3]
_add("LED基板カバー", occ, _box(_COVER_LOCAL_EXTENTS, cover_local), tf)
for c in world_centers:
local = (inv @ [*c, 1.0])[:3]
_add("LED", occ, _box(_LED_LOCAL_EXTENTS, local), tf)
manifest = {"design": "SmTIASv3", "version": 12, "units": "mm", "bodies": bodies}
(export_dir / "manifest.json").write_text(json.dumps(manifest, ensure_ascii=False, indent=1),
encoding="utf-8")
return manifest
def _run(tmp_path: Path, export_dir: Path, *extra: str) -> Path:
out = tmp_path / "out" / "scene_smtias_v3.yaml"
rc = _load_script().main([
"--export-dir", str(export_dir),
"--base", str(_BASELINE),
"--mapping", str(_MAPPING),
"--out", str(out),
*extra,
])
assert rc == 0
return out
@pytest.fixture(autouse=True)
def _same_drive(tmp_path):
if tmp_path.resolve().drive.upper() != _ROOT.drive.upper():
pytest.skip("tmp_path とリポジトリが別ドライブの環境")
# ---------------------------------------------------------------------------
# 回帰: SmTIASv3 相当の合成エクスポート → baseline の LED 18 個と一致
# ---------------------------------------------------------------------------
def _assert_lights_match_baseline(scene: dict) -> None:
base = _baseline()
base_lights = base["lights"]
gen = scene["lights"]
assert [lt["id"] for lt in gen] == [lt["id"] for lt in base_lights]
assert len(gen) == 18
template = base_lights[0]
for g, b in zip(gen, base_lights, strict=True):
np.testing.assert_allclose(g["center"], b["center"], atol=1.01e-4, err_msg=g["id"])
np.testing.assert_allclose(g["size"], b["size"], atol=1.01e-4, err_msg=g["id"])
np.testing.assert_allclose(g["direction"], b["direction"], atol=1e-6, err_msg=g["id"])
# 放射パラメータはベースの lights[0] をそのまま流用する
for key in template:
if key not in ("id", "center", "size", "direction"):
assert g[key] == template[key], (g["id"], key)
def test_regression_rotated_units_reproduce_baseline_leds(tmp_path):
export = tmp_path / "export"
_write_export(export)
out = _run(tmp_path, export)
scene = yaml.safe_load(out.read_text(encoding="utf-8"))
_assert_lights_match_baseline(scene)
def test_regression_mesh_ids_and_materials_match_baseline(tmp_path):
export = tmp_path / "export"
_write_export(export)
scene = yaml.safe_load(_run(tmp_path, export).read_text(encoding="utf-8"))
base = _baseline()
gen_meshes = scene["geometry"]["meshes"]
# 対応表の記載順 → 基板順(bottom/right/left).exclude(スイッチカバー下)と LED は含まない
assert [m["id"] for m in gen_meshes] == [m["id"] for m in base["geometry"]["meshes"]]
base_mat = {m["id"]: m["material"] for m in base["geometry"]["meshes"]}
assert {m["id"]: m["material"] for m in gen_meshes} == base_mat
assert all(m["unit"] == "mm" for m in gen_meshes)
# materials・sensor・render はベースのまま
for key in ("materials", "sensor", "render"):
assert scene[key] == base[key]
def test_generated_yaml_loads_with_scene_schema(tmp_path):
export = tmp_path / "export"
_write_export(export)
cfg = load_scene_yaml(_run(tmp_path, export))
assert len(cfg.lights) == 18
assert len(cfg.geometry.meshes) == 8
def test_mesh_paths_are_relative_and_point_to_world_space_stl(tmp_path):
export = tmp_path / "export"
manifest = _write_export(export)
out = _run(tmp_path, export)
scene = yaml.safe_load(out.read_text(encoding="utf-8"))
default_dir = (out.parent / "meshes" / "SmTIASv3").resolve()
aabb_by_occ_cover = {
b["top_occurrence"]: b["aabb_mm"] for b in manifest["bodies"]
if b["name"] == "LED基板カバー"
}
board_to_occ = {board: occ for board, (occ, _, _) in _UNITS.items()}
for m in scene["geometry"]["meshes"]:
path = m["path"]
assert not Path(path).is_absolute()
assert "\\" not in path
resolved = (out.parent / path).resolve()
assert resolved.is_file(), path
assert resolved.parent == default_dir
if m["id"].startswith("led_cover_"):
# 書き出した STL はワールド座標(manifest の aabb_mm と一致)
lo, hi = trimesh.load_mesh(str(resolved)).bounds
ref = aabb_by_occ_cover[board_to_occ[m["id"].removeprefix("led_cover_")]]
np.testing.assert_allclose(lo, ref[0], atol=1e-3)
np.testing.assert_allclose(hi, ref[1], atol=1e-3)
def test_only_scene_meshes_are_written(tmp_path):
"""LED・除外ボディのワールド STL は書き出さない(シーンが参照するものだけ)."""
export = tmp_path / "export"
_write_export(export)
out = _run(tmp_path, export)
written = sorted((out.parent / "meshes" / "SmTIASv3").glob("*.stl"))
assert len(written) == 8
def test_mesh_dir_option(tmp_path):
export = tmp_path / "export"
_write_export(export)
mesh_dir = tmp_path / "custom_meshes"
out = _run(tmp_path, export, "--mesh-dir", str(mesh_dir))
scene = yaml.safe_load(out.read_text(encoding="utf-8"))
for m in scene["geometry"]["meshes"]:
assert (out.parent / m["path"]).resolve().parent == mesh_dir.resolve()
assert not Path(m["path"]).is_absolute()
def test_name_option(tmp_path):
export = tmp_path / "export"
_write_export(export)
scene = yaml.safe_load(_run(tmp_path, export, "--name", "fusion_v3").read_text(
encoding="utf-8"))
assert scene["name"] == "fusion_v3"
def test_legacy_manifest_without_transform(tmp_path):
"""transform を持たない(ワールド座標 STL の)古いマニフェストでも同じ結果になる."""
export = tmp_path / "export"
manifest = _write_export(export, with_transform=False)
assert all("transform" not in b for b in manifest["bodies"])
scene = yaml.safe_load(_run(tmp_path, export).read_text(encoding="utf-8"))
_assert_lights_match_baseline(scene)
def test_reference_option_prints_zero_difference(tmp_path, capsys):
export = tmp_path / "export"
_write_export(export)
_run(tmp_path, export, "--reference", str(_BASELINE))
out = capsys.readouterr().out
assert "led_left_5" in out
assert "位置差 max 0.0000 mm" in out
# ---------------------------------------------------------------------------
# AABB 照合
# ---------------------------------------------------------------------------
def test_stl_in_wrong_units_raises(tmp_path):
export = tmp_path / "export"
_write_export(export, stl_scale=0.1)
with pytest.raises(ValueError):
_run(tmp_path, export)
def test_aabb_mismatch_beyond_tolerance_warns(tmp_path, caplog):
export = tmp_path / "export"
_write_export(export, aabb_shift=1.0)
with caplog.at_level(logging.WARNING):
_run(tmp_path, export)
assert any(r.levelno == logging.WARNING and "AABB" in r.getMessage()
for r in caplog.records)
def test_aabb_mismatch_within_tolerance_does_not_warn(tmp_path, caplog):
export = tmp_path / "export"
_write_export(export, aabb_shift=0.2)
with caplog.at_level(logging.WARNING):
_run(tmp_path, export)
assert not any("AABB" in r.getMessage() for r in caplog.records
if r.levelno >= logging.WARNING)
def test_aabb_tolerance_option(tmp_path, caplog):
export = tmp_path / "export"
_write_export(export, aabb_shift=1.0)
with caplog.at_level(logging.WARNING):
_run(tmp_path, export, "--aabb-tolerance", "2.0")
assert not any("AABB" in r.getMessage() for r in caplog.records
if r.levelno >= logging.WARNING)
def test_missing_transform_of_rotated_unit_is_detected(tmp_path, caplog):
"""回転ユニットの transform が抜けると,ワールド AABB との差として検出される."""
export = tmp_path / "export"
_write_export(export, drop_transform_of="LEDユニット:2")
with caplog.at_level(logging.WARNING):
try:
_run(tmp_path, export)
except ValueError:
return # 基板ラベルの重複等で止まるのも可
assert any(r.levelno == logging.WARNING and "AABB" in r.getMessage()
for r in caplog.records)
def test_missing_stl_raises(tmp_path):
export = tmp_path / "export"
_write_export(export)
(export / "stl" / "000.stl").unlink()
with pytest.raises(FileNotFoundError):
_run(tmp_path, export)