"""スマホのカメラから評価板の開口部が見えるか(部品が視野をふさがないか)を幾何的に確かめる.
PLAN_03 の要件「カメラの視野」の確認用.カメラ位置の候補点(既定: 中心と ±dx・±dy の 9 点)から
開口部の矩形上の格子点へ線分を引き,筐体・評価板・スマホ以外のメッシュ(LED 基板カバー・
遮光板など)の軸平行バウンディングボックスと交わるかを調べる.AABB で判定するので保守側
(実際より「ふさぐ」と出やすい)である.斜めに置いた部品は AABB が大きく過大に出るので,
--exact で三角形と線分の交差を調べる(計算は重いので研究室サーバで回す).
SH-02M のメッシュは直方体でカメラの穴が無いため,カメラ位置は引数で与える(既定は箱形の
スマホ側の窓の中心 (0, 4) mm・Z = -144 mm).
実行方法:
uv run python scripts/check_camera_view.py configs/_tmp_candidates/scene_C1.yaml
uv run python scripts/check_camera_view.py configs/_tmp_candidates/scene_B2.yaml \
--camera 0 4 -144 --spread 10
"""
from __future__ import annotations
import argparse
import sys
from pathlib import Path
import numpy as np
import trimesh
import yaml
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
# 評価板の開口(照明ムラ補正ボードの裏面の範囲.SPEC_03)
OPENING_HALF = (49.5, 51.0)
OPENING_Z = -4.5
# 視野の判定から外すメッシュ(壁・評価板・スマホ側)
IGNORED_IDS = ("housing", "evaluation_board", "phone", "holder")
def segment_hits_aabb(
start: np.ndarray, ends: np.ndarray, lo: np.ndarray, hi: np.ndarray
) -> np.ndarray:
"""線分 start→ends[i] が AABB [lo, hi] と交わるかを slab 法で返す(ends: (N, 3))."""
d = ends - start
with np.errstate(divide="ignore", invalid="ignore"):
t1 = (lo - start) / d
t2 = (hi - start) / d
tmin = np.where(d == 0, np.where((start >= lo) & (start <= hi), -np.inf, np.inf),
np.minimum(t1, t2))
tmax = np.where(d == 0, np.where((start >= lo) & (start <= hi), np.inf, -np.inf),
np.maximum(t1, t2))
enter = np.max(tmin, axis=1)
leave = np.min(tmax, axis=1)
return (enter <= leave) & (leave >= 0.0) & (enter <= 1.0)
def segment_hits_triangles(
start: np.ndarray, ends: np.ndarray, triangles: np.ndarray, chunk: int = 64
) -> np.ndarray:
"""線分 start→ends[i] がいずれかの三角形と交わるかを返す(Moller-Trumbore 法)."""
d = ends - start # (N, 3).交点は t ∈ (0, 1)
hit = np.zeros(len(ends), dtype=bool)
for k in range(0, len(triangles), chunk):
tri = triangles[k:k + chunk]
a = tri[:, 0]
e1, e2 = tri[:, 1] - a, tri[:, 2] - a # (M, 3)
p = np.cross(d[:, None, :], e2[None, :, :]) # (N, M, 3)
det = np.einsum("nmk,mk->nm", p, e1)
ok = np.abs(det) > 1e-12
inv = np.where(ok, 1.0 / np.where(ok, det, 1.0), 0.0)
s = start - a # (M, 3)
u = np.einsum("nmk,mk->nm", p, s) * inv
q = np.cross(s, e1) # (M, 3)
v = np.einsum("nk,mk->nm", d, q) * inv
t = np.einsum("mk,mk->m", q, e2)[None, :] * inv
hit |= np.any(ok & (u >= 0) & (v >= 0) & (u + v <= 1) & (t > 0) & (t < 1), axis=1)
return hit
def check_scene(
scene: Path, camera: np.ndarray, spread: float, grid: int, exact: bool = False
) -> list[str]:
"""シーン 1 つを調べ,視野をふさぐメッシュ id とふさぐ割合を文字列で返す."""
config = yaml.safe_load(scene.read_text(encoding="utf-8"))
xs = np.linspace(-OPENING_HALF[0], OPENING_HALF[0], grid)
ys = np.linspace(-OPENING_HALF[1], OPENING_HALF[1], grid)
targets = np.array([[x, y, OPENING_Z] for x in xs for y in ys])
cams = [camera + np.array([dx, dy, 0.0])
for dx in (-spread, 0.0, spread) for dy in (-spread, 0.0, spread)]
found = []
for mesh in config["geometry"]["meshes"]:
if any(key in mesh["id"] for key in IGNORED_IDS):
continue
part = trimesh.load(scene.parent / mesh["path"], force="mesh")
if exact:
worst = max(segment_hits_triangles(c, targets, part.triangles).mean() for c in cams)
else:
worst = max(segment_hits_aabb(c, targets, part.bounds[0], part.bounds[1]).mean()
for c in cams)
if worst > 0:
found.append(f"{mesh['id']}: 開口部の {worst * 100:.1f}% をふさぐ(最悪のカメラ位置)")
return found
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("scenes", nargs="+", type=Path)
parser.add_argument("--camera", nargs=3, type=float, default=[0.0, 4.0, -144.0],
metavar=("X", "Y", "Z"), help="カメラ位置 [mm]")
parser.add_argument("--spread", type=float, default=10.0,
help="カメラ位置の不確かさ(±mm.9 点で調べる)")
parser.add_argument("--grid", type=int, default=41, help="開口部の格子の 1 辺の点数")
parser.add_argument("--exact", action="store_true",
help="AABB ではなく三角形との交差で調べる(斜めの部品向け.重い)")
args = parser.parse_args(argv)
camera = np.array(args.camera)
for scene in args.scenes:
found = check_scene(scene, camera, args.spread, args.grid, args.exact)
status = "OK(ふさぐ部品なし)" if not found else "要確認"
print(f"{scene.name}: {status}")
for line in found:
print(f" {line}")
return 0
if __name__ == "__main__":
raise SystemExit(main())