"""FAIRINO FR3 の3D（glb）を、公式の見た目用の形（DAE・Apache 2.0）から作る。MITRA の3D（mitra_v1.glb）と組み合わせる前提。

元のデータ：FAIR-INNOVATION/frcobot_ros（版 04b24d4a・2024-07-16）の frcobot_description
  形：meshes/fr3v6/visual/*.DAE（見た目用。前回の LOG639 は当たり判定用の形を2割に減らして使っていた）
  関節の位置と向き：urdf/fr3v6.urdf（新しい frcobot_ros2 の fairino3_v6.urdf と同じ値）
  ライセンス：Apache License 2.0（frcobot_description/package.xml）

座標：MITRA の3Dに合わせる。+X 前、+Y 上、+Z 右。単位 m。原点はアームの付け根の底の中心。
  URDF（Z が上）から glTF（Y が上）へは、X 軸まわりに −90° 回す。
  アームの「前」（腕を伸ばす向き）は URDF の −X（関節が −X 側に並ぶ）。腕を MITRA の前へ伸ばすには、J1 を 180° にするか、
  付け根の節（fr3）を Y 軸まわりに 180° 回して置く（MITRA との組み合わせのページで決める）。

節の名前（ページはこの名前で関節を回す）：
  fr3                     いちばん上。ここを動かしてアームを置く
    fr3_base              付け根の形
    fr3_j1_origin         J1 の位置（固定）
      fr3_j1              J1（この節の Z 軸まわりに回す。三.js の rotation.z ＝ 関節の角度）
        fr3_link1         J1 の形
        fr3_j2_origin ... fr3_j6 まで同じ形で続く
          fr3_tool0       先端の取り付け面の中心（形なし。つかむ道具はここに付ける）

色：本体は白、関節のふたの縁はオレンジ、先端の取り付け面は銀。どの部品をどの色にしたかは paint_rules（下）に書く。
  色の分け方は、FAIRINO のカタログ（2026-06-10 版）の製品写真と、描いた絵を見比べて決めた。
使い方: python3 build_fr3.py <frcobot_description のフォルダ> <出力の glb> [--probe]
  --probe：輪の候補の部品を、見分けやすい色で塗った確かめ用の glb を作る
"""
import sys, os, math, json
import numpy as np
import trimesh
import xml.etree.ElementTree as ET
from trimesh.visual.material import PBRMaterial

DESC, OUT = sys.argv[1], sys.argv[2]
PROBE = '--probe' in sys.argv
LINKS = ['base_link', 'j1_Link', 'j2_Link', 'j3_Link', 'j4_Link', 'j5_Link', 'j6_Link']

MATS = {   # 色は glTF の尺度（明るさが直線）。写真の色からの換算は paint_rules.json の _色の出どころ
    'white':     dict(c=[0.86, 0.87, 0.88, 1], metal=0.0, rough=0.25),
    'orange':    dict(c=[0.753, 0.159, 0.105, 1], metal=0.0, rough=0.35),
    'gray':      dict(c=[0.62, 0.62, 0.62, 1], metal=0.0, rough=0.5),
    'lightgray': dict(c=[0.74, 0.75, 0.76, 1], metal=0.0, rough=0.8),
    'silver':    dict(c=[0.62, 0.63, 0.64, 1], metal=0.2, rough=0.35),
}
PROBE_COLS = [[1, 0, 0, 1], [0, 0.7, 0, 1], [0, 0.3, 1, 1], [1, 0.8, 0, 1], [0.8, 0, 0.8, 1], [0, 0.8, 0.8, 1]]

def material(name):
    m = MATS[name]
    return PBRMaterial(name='fr3_' + name, baseColorFactor=m['c'], metallicFactor=m['metal'], roughnessFactor=m['rough'])

def load_link(name):
    s = trimesh.load(os.path.join(DESC, 'meshes/fr3v6/visual', name + '.DAE'), force='scene')
    return trimesh.util.concatenate(s.dump())

def ring_geom(c):
    """部品が軸のまわりの輪なら (軸, 中心, 軸の向きの最小と最大, 内と外の半径) を返す。単位 mm"""
    v = c.vertices * 1000; best = None
    for ax in range(3):
        o = [i for i in range(3) if i != ax]
        ctr = (v[:, o].max(0) + v[:, o].min(0)) / 2
        d = v[:, o] - ctr; r = np.hypot(d[:, 0], d[:, 1])
        cover = len(np.unique(np.floor(np.degrees(np.arctan2(d[:, 1], d[:, 0])) / 10))) / 36
        thick = np.ptp(v[:, ax])
        if cover > 0.95 and r.max() > 30 and r.min() > 0.6 * r.max():
            cand = (ax, ctr, v[:, ax].min(), v[:, ax].max(), r.min(), r.max(), thick)
            if best is None or thick < best[6]: best = cand
    return best

RULES = json.load(open(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'paint_rules.json'))) if not PROBE else None

def classify(link, idx, c):
    if PROBE:
        rg = ring_geom(c)
        return ('probe', idx) if rg is not None else ('white', None)
    for rule in RULES.get(link, []):
        if idx in rule['ids']: return (rule['color'], None)
    return ('white', None)

def paint_faces(link, idx, c):
    """部品 c の面ごとの色を返す（paint_rules.json の上から順に当てはめる）"""
    labels = np.array(['white'] * len(c.faces), dtype=object)
    done = np.zeros(len(c.faces), bool)
    cen = c.triangles_center * 1000
    for rule in RULES.get(link, []):
        if 'comps' in rule:
            hit = np.full(len(c.faces), idx in rule['comps'])
        else:
            z = rule['zone']; ax = z['axis']; o = [i for i in range(3) if i != ax]
            d = cen[:, o] - np.array(z['center']); r = np.hypot(d[:, 0], d[:, 1]); a = cen[:, ax]
            hit = (a >= z['a'][0]) & (a <= z['a'][1]) & (r >= z['r'][0]) & (r <= z['r'][1])
        hit &= ~done; labels[hit] = rule['color']; done |= hit
    return labels

def tf_origin(xyz, rpy):
    T = trimesh.transformations.euler_matrix(*rpy, axes='sxyz'); T[:3, 3] = xyz; return T

root = ET.parse(os.path.join(DESC, 'urdf/fr3v6.urdf')).getroot()
joints = {j.find('child').get('link'): j for j in root.findall('joint') if j.get('type') in ('revolute', 'fixed') and j.find('parent').get('link') != 'world'}

scene = trimesh.Scene()
R_up = trimesh.transformations.rotation_matrix(-math.pi / 2, [1, 0, 0])   # URDF Z 上 → glTF Y 上
scene.graph.update(frame_to='fr3', frame_from='world', matrix=R_up)
stats = {}
parent = 'fr3'
probe_map = []
for i, link in enumerate(LINKS):
    if i > 0:
        j = joints[link]; o = j.find('origin')
        T = tf_origin([float(x) for x in o.get('xyz').split()], [float(x) for x in o.get('rpy').split()])
        scene.graph.update(frame_to=f'fr3_j{i}_origin', frame_from=parent, matrix=T)
        scene.graph.update(frame_to=f'fr3_j{i}', frame_from=f'fr3_j{i}_origin', matrix=np.eye(4))
        parent = f'fr3_j{i}'
    mesh = load_link(link); comps = mesh.split(only_watertight=False)
    groups = {}
    for k, c in enumerate(comps):
        if PROBE:
            col, _ = classify(link, k, c)
            key = col if col != 'probe' else f'probe{len(probe_map) % len(PROBE_COLS)}'
            if col == 'probe': probe_map.append((link, k, key))
            groups.setdefault(key, []).append(c); continue
        labels = paint_faces(link, k, c)
        for col in set(labels):
            sub = c.submesh([np.where(labels == col)[0]], append=True)
            groups.setdefault(col, []).append(sub)
    # 関節のふたの白い円：元の形は角が少ない多角形で、オレンジの縁との境がぎざぎざに見える。
    # オレンジの輪ごとに、細かい円（128 角）の白い板を、ふたの面のすぐ外に重ねて境を丸くする
    if 'orange' in groups and not PROBE:
        allv = np.vstack([p.vertices for ps in groups.values() for p in ps]) * 1000
        for ring in trimesh.util.concatenate(groups['orange']).split(only_watertight=False):
            rg = ring_geom(ring)
            if rg is None or len(ring.faces) < 40: continue
            ax, ctr, amin, amax, rmin, rmax, _ = rg
            o = [k for k in range(3) if k != ax]
            sign = 1.0 if (amin + amax) / 2 > allv[:, ax].mean() else -1.0
            d = allv[:, o] - ctr; r = np.hypot(d[:, 0], d[:, 1])
            near = (r < rmin) & (allv[:, ax] > amin - 8) & (allv[:, ax] < amax + 8)
            if near.sum() < 3: continue
            face = (allv[near, ax] * sign).max() * sign            # ふたの中央の面の位置
            disc = trimesh.creation.cylinder(radius=rmax * 0.78 / 1000, height=0.0003, sections=128)
            T = np.eye(4); pos = np.zeros(3); pos[o[0]], pos[o[1]] = ctr / 1000; pos[ax] = (face + sign * 0.2) / 1000
            if ax == 0: T[:3, :3] = trimesh.transformations.rotation_matrix(math.pi / 2, [0, 1, 0])[:3, :3]
            if ax == 1: T[:3, :3] = trimesh.transformations.rotation_matrix(math.pi / 2, [1, 0, 0])[:3, :3]
            T[:3, 3] = pos; disc.apply_transform(T)
            col = 'lightgray' if link == 'j1_Link' else 'white'
            groups.setdefault(col, []).append(disc)
    node = 'fr3_base' if i == 0 else f'fr3_link{i}'
    for key, parts in groups.items():
        g = trimesh.util.concatenate(parts)
        g.merge_vertices(merge_tex=True, merge_norm=True)
        g = g.smooth_shaded if False else trimesh.graph.smooth_shade(g, angle=math.radians(30)) if hasattr(trimesh.graph, 'smooth_shade') else g.smoothed(angle=math.radians(30))
        if key.startswith('probe'):
            n = int(key[5:]); mat = PBRMaterial(name=key, baseColorFactor=PROBE_COLS[n], metallicFactor=0, roughnessFactor=0.6)
        else:
            mat = material(key)
        g.visual = trimesh.visual.TextureVisuals(material=mat)
        scene.add_geometry(g, node_name=f'{node}_{key}', geom_name=f'{link}_{key}', parent_node_name=parent)
        stats[f'{link}:{key}'] = len(g.faces)
scene.graph.update(frame_to='fr3_tool0', frame_from=parent, matrix=tf_origin([0, 0, 0.1], [0, 0, 0]))

# 吸着グリッパー（OnRobot VGC10 の大きさに合わせた仮の形。データシートの外形 101×100×100mm・重さ 0.814kg）
# 細かい形（腕・吸盤の数と大きさ）は既定の付属品を写真から読んだ目安。ロゴは入れない。
GMATS = {'g_dark': ([0.035, 0.038, 0.042, 1], 0.1, 0.5), 'g_gray': ([0.30, 0.31, 0.33, 1], 0.1, 0.45),
         'g_cup': ([0.55, 0.60, 0.62, 1], 0.0, 0.7), 'silver': None}
def gmat(k):
    if k == 'silver': return material('silver')
    c, m, r = GMATS[k]; return PBRMaterial(name=k, baseColorFactor=c, metallicFactor=m, roughnessFactor=r)
def rbox(w, d, h, rad, z0):   # 角を丸めた箱（mm）：中心の箱＋角の円柱
    parts = [trimesh.creation.box([w - 2 * rad, d, h]), trimesh.creation.box([w, d - 2 * rad, h])]
    for sx in (-1, 1):
        for sy in (-1, 1):
            c = trimesh.creation.cylinder(radius=rad, height=h, sections=32); c.apply_translation([sx * (w / 2 - rad), sy * (d / 2 - rad), 0]); parts.append(c)
    m = trimesh.boolean.union(parts) if False else trimesh.util.concatenate(parts)
    m.apply_translation([0, 0, z0 + h / 2]); return m
def cyl(r, h, z0, xy=(0, 0), sec=64):
    c = trimesh.creation.cylinder(radius=r, height=h, sections=sec); c.apply_translation([xy[0], xy[1], z0 + h / 2]); return c
def cone(r0, r1, h, z0, xy=(0, 0), sec=48):   # 円すい台
    t = np.linspace(0, 2 * np.pi, sec, endpoint=False)
    v = np.vstack([np.c_[r0 * np.cos(t), r0 * np.sin(t), np.zeros(sec)], np.c_[r1 * np.cos(t), r1 * np.sin(t), np.full(sec, h)]])
    f = []
    for k in range(sec):
        a, b = k, (k + 1) % sec; f += [[a, b, sec + b], [a, sec + b, sec + a]]
    m = trimesh.Trimesh(v, f); m.fix_normals(); m.apply_translation([xy[0], xy[1], z0]); return m
G = {'silver': [cyl(31.5, 8, 0)],                                  # 取り付けの板（ISO 50 の面に合わせる・仮）
     'g_gray': [rbox(100, 100, 10, 14, 8)],                        # 本体の上の板
     'g_dark': [rbox(100, 100, 50, 14, 18)],                       # 本体（中に電動のポンプ）
     'g_cup': []}
for sx in (-1, 1):                                                  # 吸盤 4 つ（既定の付属品の並びの目安）
    for sy in (-1, 1):
        xy = (sx * 30, sy * 30)
        G['g_gray'].append(cyl(6, 8, 68, xy, 24))                  # 吸盤の付け根
        G['g_cup'] += [cone(9, 12, 7, 76, xy), cone(12, 9, 5, 83, xy), cone(9, 13, 6, 88, xy), cone(13, 16, 7, 94, xy)]
scene.graph.update(frame_to='gripper_vgc10', frame_from='fr3_tool0', matrix=np.eye(4))
for k, parts in G.items():
    g = trimesh.util.concatenate(parts); g.apply_scale(0.001)
    g.merge_vertices(); g = trimesh.graph.smooth_shade(g, angle=math.radians(30))
    g.visual = trimesh.visual.TextureVisuals(material=gmat(k))
    scene.add_geometry(g, node_name=f'gripper_vgc10_{k}', geom_name=f'vgc10_{k}', parent_node_name='gripper_vgc10')
T = np.eye(4); T[2, 3] = 0.101
scene.graph.update(frame_to='gripper_vgc10_tcp', frame_from='gripper_vgc10', matrix=T)   # 吸盤の先（データシートの高さ 101mm）
scene.export(OUT, include_normals=True)
print('書き出し', OUT, os.path.getsize(OUT) // 1024, 'KB', '面の合計', sum(stats.values()))
for k, v in stats.items(): print('  ', k, v)
if PROBE:
    json.dump(probe_map, open(OUT + '.probe.json', 'w'), ensure_ascii=False)
    print('輪の候補', len(probe_map))
