Newer
Older
SmTIAS-LightSim / scripts / fusion / build_smtias_v4_led_modules.py
"""SmTIASv4 の LED モジュール(基板・カバー・台座・ねじ)を Fusion に作り直す.

Fusion の中で実行するスクリプト(MCP の fusion_mcp_execute で,このファイルを `exec` で読み込んで
`run` を呼ぶ.日本語の名前を化けさせないため中身を貼らずにファイルから読む.TECH_12).

基板は `scripts/generate_led_module_boards.py`(Fusion Electronics の SmTIASv4_LED_side_v2 /
SmTIASv4_LED_bottom_v2)と同じ外形・部品の位置にする.基板の座標 u(長さ方向)・v(幅方向.
KiCad の Y − 55.+12V の線が v < 0,GND の線が v > 0)を装置の座標へ写す:

- 左右用(LED 6 個): y = u + SIDE_DY,右は x = 74 + v,左は x = −74 + v(左は右を平行移動した
  もの.同じ基板)
- 下用(LED 6 個.1 枚): x = u・y = BOTTOM_LED_Y − v

LED の高さと位置は,鼻の穴を閉じた筐体で基板の付け方を探した結果(TEST_21 結果 13.2026-11-09):
横は LED の面 Z −28・下の組の LED が Y 1〜9(SIDE_DY −5),下は Z −18・Y −83(顔の近くの丸い壁に
当たらないよう壁から 7 mm).その前は全部 Z −38・横 SIDE_DY 0・下 Y −84(結果 12).

カバーは SmTIASv3 の「LED 基板カバー」と同じ作り: 基板の部品の面(下)に重ねる厚さ 1 mm の白い板
(LED・定電流 IC・電源パッドの窓と M3 の穴)と,基板の内側の長い縁を隠す縁.カバーは 3D プリント
なので左右で鏡像にしてよい.ねじ(M3×8)はカバーの下から基板を通し,前側の台座の下穴に締める.台座は基板の上(顔の側)に
あり,横の壁・下の壁から張り出す棚にする.

実行すると次を作り直す(同じ名前のものは消してから作る):
- コンポーネント「LEDモジュール」(基板・LED・定電流 IC・カバー)
- 筐体の前側の LED 台座(「LED台座」「LED台座_結合」「LED台座_下穴」.名前の無い古い版は
  「基準フィーチャ*」とその直後の「結合*」2 つ.消してから足す)
- ねじ類の「M3x8 なべ小ねじ」の配置
"""

import adsk.core
import adsk.fusion

# 電源パッドはケーブル 1 本分(+12V と GND を幅の向きに並べた 2.0 × 3.0 mm)が長さの向きに 2 列
SIDE = {
    "u": (-18.3, 44.0), "chamfer": (38.0, 3.5), "holes": (-8.0, 40.0),
    "leds": (6.0, 10.0, 14.0, 26.0, 30.0, 34.0), "ccrs": (-2.0, 2.0, 18.0, 22.0),
    "pad_u": (-16.1, -12.6), "z_led": -28.0,
}
BOTTOM = {
    "u": (-41.3, 41.3), "chamfer": None, "holes": (-31.0, 31.0),
    "leds": (-25.0, -21.0, -17.0, 17.0, 21.0, 25.0), "ccrs": (-13.0, -9.0, 9.0, 13.0),
    "pad_u": (-39.1, -35.6, 35.6, 39.1), "z_led": -18.0,
}
SIDE_DY = -5.0        # 左右用の基板を Y へずらす量(u = 10 の LED が Y 5 に来る)
BOTTOM_LED_Y = -83.0  # 下の LED 列の Y(下の壁の内面 −90 から 7 mm)
# 下の台座の壁側の端.顔の近くで下の壁が丸くなり,Y −91 まで伸ばすと壁の外へ出るので,
# 台座の高さ(Z −15.7〜−9.7)で壁の外の面(Z −9.7 で Y −88.7)より内側にする
BOTTOM_BOSS_Y0 = -88.6
# 台座の顔の側の 45° の支え(前側は顔の面を下にして刷るので,台座の顔の側の面が浮かないように
# 壁から 45° で立ち上げる).GUSSET_LEN だけ伸ばした三角柱から前側の壁を引き,箱の中に残った
# ひとかたまりだけを使う(支えが壁の内側の面でちょうど止まり,壁の外へ出ない)
GUSSET_LEN = 15.0
HALF_W = 5.0          # 基板の幅の半分(v = −5〜+5)
BOARD_T = 1.6
LED_H = 0.7           # LED の高さ(発光面 z_led から基板の下面まで)
COVER_T = 1.0         # カバーの板の厚さ(LED の発光面より 0.3 mm 下まで)
LIP_T = 1.0           # カバーの縁の厚さ
HOLE_D = 3.4          # カバー・基板のねじの通し穴
# 台座の下穴(M3 の小ねじを PLA に直接ねじ込む.2.6 では固くて奥まで入らなかった.
# 2026-11-09 ユーザー.刷ると 0.1〜0.2 mm 小さく仕上がる)
PILOT_D = 2.9
PILOT_DEPTH = 6.0     # 下穴の深さ(M3×8 がカバーと基板の 2.6 mm を抜けて 5.4 mm かかる)
BOSS = 7.0            # 台座の一辺
tbm = adsk.fusion.TemporaryBRepManager.get()


def _box(lo, hi):
    c = adsk.core.Point3D.create(*((a + b) / 20 for a, b in zip(lo, hi, strict=True)))
    ob = adsk.core.OrientedBoundingBox3D.create(
        c, adsk.core.Vector3D.create(1, 0, 0), adsk.core.Vector3D.create(0, 1, 0),
        *((b - a) / 10 for a, b in zip(lo, hi, strict=True)))
    return tbm.createBox(ob)


def _cyl(x, y, z0, z1, d):
    return tbm.createCylinderOrCone(adsk.core.Point3D.create(x / 10, y / 10, z0 / 10), d / 20,
                                    adsk.core.Point3D.create(x / 10, y / 10, z1 / 10), d / 20)


def _sub(body, tool):
    tbm.booleanOperation(body, tool, adsk.fusion.BooleanTypes.DifferenceBooleanType)


def _union(body, tool):
    tbm.booleanOperation(body, tool, adsk.fusion.BooleanTypes.UnionBooleanType)


def _layouts():
    """(名前, 基板の定義, (u, v) → (x, y) の写し方, 内側の縁の v の向き) を返す."""
    return [
        ("右", SIDE, lambda u, v: (74.0 + v, u + SIDE_DY), -1),
        ("左", SIDE, lambda u, v: (-74.0 + v, u + SIDE_DY), +1),
        ("下", BOTTOM, lambda u, v: (u, BOTTOM_LED_Y - v), -1),
    ]


def _rect_uv(f, u0, u1, v0, v1):
    xs, ys = zip(*(f(u, v) for u in (u0, u1) for v in (v0, v1)), strict=True)
    return (min(xs), min(ys)), (max(xs), max(ys))


def _plate(spec, f, z0, z1):
    """基板の外形(左右用は上の端の両角を斜めに落とす)の板を z0〜z1 に作る."""
    u0, u1 = spec["u"]
    lo, hi = _rect_uv(f, u0, u1, -HALF_W, HALF_W)
    plate = _box((lo[0], lo[1], z0), (hi[0], hi[1], z1))
    if spec["chamfer"] is None:
        return plate
    uc, vc = spec["chamfer"]
    ox, oy = f(0.0, 0.0)

    def vec(du, dv):
        x, y = f(du, dv)
        return x - ox, y - oy

    for s in (1.0, -1.0):
        # 角を落とす線 (uc, s·5) → (u1, s·(5 − vc)) の外側を大きな箱で引く
        du, dv = u1 - uc, -s * vc
        n = (du * du + dv * dv) ** 0.5
        du, dv = du / n, dv / n
        nu, nv = vc / n * 1.0, s * (u1 - uc) / n  # 外向きの法線(長さ 1)
        mu, mv = (uc + u1) / 2 + nu * 10.0, s * (HALF_W + HALF_W - vc) / 2 + nv * 10.0
        cx, cy = f(mu, mv)
        lx, ly = vec(du, dv)
        wx, wy = vec(nu, nv)
        ob = adsk.core.OrientedBoundingBox3D.create(
            adsk.core.Point3D.create(cx / 10, cy / 10, (z0 + z1) / 20),
            adsk.core.Vector3D.create(lx, ly, 0), adsk.core.Vector3D.create(wx, wy, 0),
            4.0, 2.0, (z1 - z0 + 2.0) / 10)
        _sub(plate, tbm.createBox(ob))
    return plate


def _module(comp, base, name, spec, f, inward):
    z = spec["z_led"]
    zb0, zb1 = z + LED_H, z + LED_H + BOARD_T          # 基板の下面・上面
    zc0 = z - (COVER_T - LED_H)                         # カバーの下面
    board = _plate(spec, f, zb0, zb1)
    cover = _plate(spec, f, zc0, zb0)
    holes = []
    for hu in spec["holes"]:
        x, y = f(hu, 0.0)
        _sub(board, _cyl(x, y, zb0 - 1, zb1 + 1, 3.2))
        _sub(cover, _cyl(x, y, zc0 - 1, zb0 + 1, HOLE_D))
        holes.append((x, y))
    parts = []
    for lu in spec["leds"]:
        lo, hi = _rect_uv(f, lu - 1.4, lu + 1.4, -1.75, 1.75)
        parts.append(("LED", _box((lo[0], lo[1], z), (hi[0], hi[1], zb0))))
        lo, hi = _rect_uv(f, lu - 1.7, lu + 1.7, -2.05, 2.05)
        _sub(cover, _box((lo[0], lo[1], zc0 - 1), (hi[0], hi[1], zb0 + 0.1)))
    for cu in spec["ccrs"]:
        lo, hi = _rect_uv(f, cu - 0.8, cu + 0.8, -1.35, 1.35)
        parts.append(("定電流IC", _box((lo[0], lo[1], zb0 - 1.1), (hi[0], hi[1], zb0))))
        lo, hi = _rect_uv(f, cu - 1.1, cu + 1.1, -2.4, 2.4)
        _sub(cover, _box((lo[0], lo[1], zc0 - 1), (hi[0], hi[1], zb0 + 0.1)))
    for pu in spec["pad_u"]:
        lo, hi = _rect_uv(f, pu - 1.3, pu + 1.3, -4.0, 4.0)
        _sub(cover, _box((lo[0], lo[1], zc0 - 1), (hi[0], hi[1], zb0 + 0.1)))
    # 内側の長い縁を隠す縁(面取りの手前まで)
    u0, u1 = spec["u"]
    u_end = spec["chamfer"][0] if spec["chamfer"] else u1
    v_edge = inward * HALF_W
    lo, hi = _rect_uv(f, u0, u_end, v_edge, v_edge + inward * LIP_T)
    _union(cover, _box((lo[0], lo[1], zc0), (hi[0], hi[1], zb1 + 0.4)))
    comp.bRepBodies.add(board, base).name = f"基板_{name}"
    comp.bRepBodies.add(cover, base).name = f"カバー_{name}"
    for k, (kind, body) in enumerate(parts):
        comp.bRepBodies.add(body, base).name = f"{kind}_{name}_{k + 1}"
    return [(x, y, zc0, zb1) for x, y in holes]


def _delete_old_bosses(des, hcomp):
    """前回の LED 台座(基準フィーチャ 1 つと結合 2 つ)を消す."""
    tl = des.timeline
    items = []
    for i in range(tl.count):
        it = tl.item(i)
        try:
            pc = it.entity.parentComponent
        except Exception:  # タイムラインの一部の項目は親を持たない
            pc = None
        if pc == hcomp:
            items.append(it)
    found = []
    for k, it in enumerate(items[:-2]):
        nxt = [items[k + 1].name, items[k + 2].name]
        if it.name == "LED台座" or (
            it.name.startswith("基準フィーチャ") and all(n.startswith("結合") for n in nxt)
        ):
            found.append(items[k:k + 3])
    if len(found) != 1:
        names = [[i.name for i in f] for f in found]
        raise RuntimeError(f"LED 台座のフィーチャが 1 組に決まらない: {names}")
    for it in reversed(found[0]):
        it.entity.deleteMe()


def _gusset(p0, toward, end, width_axis, center_w, wall):
    """台座の顔の側の 45° の支え(三角柱から壁を引いた,箱の中の部分).

    p0 は台座の顔の側の面の内側の縁(mm).toward は壁へ向かう向き(単位ベクトル.XY 平面),
    end は三角形の底辺の長さ.三角形 p0 → 壁側の端 → そこから +Z へ end の点で,
    width_axis の向きに center_w ± BOSS/2 の幅を持つ.wall は前側の写し(一時ボディ).
    """
    tx, ty = toward
    lo = [min(p0[0], p0[0] + tx * end), min(p0[1], p0[1] + ty * end), p0[2]]
    hi = [max(p0[0], p0[0] + tx * end), max(p0[1], p0[1] + ty * end), p0[2] + end]
    k = 0 if width_axis == "x" else 1
    lo[k], hi[k] = center_w - BOSS / 2, center_w + BOSS / 2
    body = _box(tuple(lo), tuple(hi))
    # p0 を通り,壁から離れて +Z へ上がる側(z − z0 > 壁へ向かう距離)を大きな箱で削る
    r2 = 2 ** 0.5
    m = adsk.core.Vector3D.create(-tx / r2, -ty / r2, 1 / r2)
    u = adsk.core.Vector3D.create(tx / r2, ty / r2, 1 / r2)
    w = adsk.core.Vector3D.create(-ty, tx, 0)
    big = 10.0  # cm
    c = adsk.core.Point3D.create(p0[0] / 10 + m.x * big / 2, p0[1] / 10 + m.y * big / 2,
                                 p0[2] / 10 + m.z * big / 2)
    _sub(body, tbm.createBox(adsk.core.OrientedBoundingBox3D.create(c, u, w, big, big, big)))
    _sub(body, tbm.copy(wall))
    probe = adsk.core.Point3D.create((p0[0] + tx * 0.5) / 10, (p0[1] + ty * 0.5) / 10,
                                     (p0[2] + 0.2) / 10)
    inside = adsk.fusion.PointContainment.PointInsidePointContainment
    for k in range(body.lumps.count):
        piece = tbm.copy(body.lumps.item(k))
        if piece.pointContainment(probe) == inside:
            return piece
    raise RuntimeError(f"台座の支えの箱の中の部分が見つからない: {p0}")


def _bosses(hcomp, front, holes):
    # 編集中は前側を読めないので先に写す(台座を消したあとは前のボディの参照が切れるので取り直す)
    front = [b for b in hcomp.bRepBodies if b.name == "前側"][0]
    walls = tbm.copy(front)
    if walls is None:
        raise RuntimeError("前側を一時ボディに写せない")
    hb = hcomp.features.baseFeatures.add()
    hb.startEdit()
    for i, (x, y, _zc0, zb1, kind) in enumerate(holes):
        top = zb1 + 6.0
        if kind == "side":
            s = 1 if x > 0 else -1
            wall = (81.0 if y < 20 else 79.0) * s
            x0, x1 = sorted([x - BOSS / 2 * s, wall])
            box = _box((x0, y - BOSS / 2, zb1), (x1, y + BOSS / 2, top))
            x_in = x - BOSS / 2 * s
            _union(box, _gusset((x_in, y, top), (s, 0.0), GUSSET_LEN, "y", y, walls))
        else:  # 下の壁(内面 Y −90)から張り出す棚
            box = _box((x - BOSS / 2, BOTTOM_BOSS_Y0, zb1), (x + BOSS / 2, y + BOSS / 2, top))
            y_in = y + BOSS / 2
            _union(box, _gusset((x, y_in, top), (0.0, -1.0), GUSSET_LEN, "x", x, walls))
        hcomp.bRepBodies.add(box, hb).name = f"LED台座_{i}"
        pilot = _cyl(x, y, zb1 - 0.1, zb1 + PILOT_DEPTH, PILOT_D)
        hcomp.bRepBodies.add(pilot, hb).name = f"LED下穴_{i}"
    hb.finishEdit()
    hb.name = "LED台座"
    join = adsk.core.ObjectCollection.create()
    cut = adsk.core.ObjectCollection.create()
    # 和を取った一時ボディは名前が付かないことがあるので,このベースフィーチャのボディを
    # 下穴かどうかで分ける
    for k in range(hb.bodies.count):
        body = hb.bodies.item(k)
        (cut if body.name.startswith("LED下穴") else join).add(body)
    if join.count != len(holes) or cut.count != len(holes):
        raise RuntimeError(f"台座 {join.count}・下穴 {cut.count}({len(holes)} のはず)")
    for tools, op, name in ((join, adsk.fusion.FeatureOperations.JoinFeatureOperation, "_結合"),
                            (cut, adsk.fusion.FeatureOperations.CutFeatureOperation, "_下穴")):
        ci = hcomp.features.combineFeatures.createInput(front, tools)
        ci.operation = op
        hcomp.features.combineFeatures.add(ci).name = "LED台座" + name


def _screws(root, holes):
    grp = [o.component for o in root.occurrences if o.component.name == "ねじ類"][0]
    for o in [o for o in grp.occurrences if o.component.name.startswith("M3x8")]:
        o.deleteMe()

    def mat(x, y, z):
        m = adsk.core.Matrix3D.create()
        m.translation = adsk.core.Vector3D.create(x / 10, y / 10, z / 10)
        return m

    x, y, zc0, _zb1, _k = holes[0]
    first = grp.occurrences.addNewComponent(mat(x, y, zc0))
    comp = first.component
    comp.name = "M3x8 なべ小ねじ"
    base = comp.features.baseFeatures.add()
    base.startEdit()
    head = _cyl(0, 0, -2.0, 0, 5.5)
    _union(head, _cyl(0, 0, 0, 8.0, 3.0))
    comp.bRepBodies.add(head, base).name = "M3x8"
    base.finishEdit()
    for x, y, zc0, _zb1, _k in holes[1:]:
        grp.occurrences.addExistingComponent(comp, mat(x, y, zc0))


def run(_context: str):
    app = adsk.core.Application.get()
    des = adsk.fusion.Design.cast(app.activeProduct)
    if app.activeDocument.name != "SmTIASv4":
        raise RuntimeError("SmTIASv4 をアクティブにしてから実行する")
    root = des.rootComponent
    hcomp = [o.component for o in root.occurrences if o.component.name == "筐体"][0]
    front = [b for b in hcomp.bRepBodies if b.name == "前側"][0]
    for o in list(root.occurrences):
        if o.component.name == "LEDモジュール":
            o.deleteMe()
    _delete_old_bosses(des, hcomp)
    occ = root.occurrences.addNewComponent(adsk.core.Matrix3D.create())
    comp = occ.component
    comp.name = "LEDモジュール"
    base = comp.features.baseFeatures.add()
    base.startEdit()
    holes = []
    for name, spec, f, inward in _layouts():
        kind = "side" if spec is SIDE else "bottom"
        holes += [(*h, kind) for h in _module(comp, base, name, spec, f, inward)]
    base.finishEdit()
    _bosses(hcomp, front, holes)
    _screws(root, holes)
    des.computeAll()
    bad = [b.name for b in comp.bRepBodies
           if any(front.pointContainment(v.geometry) == 0 for v in b.vertices)]
    tl = des.timeline
    unhealthy = []
    for i in range(tl.count):
        try:
            state = tl.item(i).healthState
        except RuntimeError:  # 一部の項目(スナップショット等)は読むと例外になる
            continue
        if state != adsk.fusion.FeatureHealthStates.HealthyFeatureHealthState:
            unhealthy.append(tl.item(i).name)
    print("bodies", comp.bRepBodies.count, "holes", len(holes))
    print("module parts inside front wall:", bad)
    print("unhealthy timeline items:", unhealthy)