using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;

namespace ServiceSim.Closeups.EditorTools
{
    /// <summary>
    /// 依頼270：要所の場面 ⑩「ストレッチャーに道を空ける」。場面 stretcher_alcove（⑩-1 くぼみに入って待つ）・stretcher_back（⑩-2 くぼみに間に合わず下がる）。
    /// 台本は closeup270_script.json（make_script270.py）。Closeup237.cs の作り（廊下・看護師の焼いた形・口・寺島さんの 2 つめの CloseupDirector・画面の帯・真上の型・撮り方）を土台にした。
    /// 237 から変えたこと：
    ///   ・車いす・茂さんの代わりに、空のストレッチャー（Models_stretcher/stretcher.fbx。Closeup270Stretcher が読む）。根の位置は台本の c270.stretcher（毎コマ・向き 180°）。
    ///     4 つの車輪は 237 の前の車輪と同じ「支柱に引っぱられて後ろへ付いていく」形で向きを決め、進んだ長さ ÷ 0.1 m だけ回す。柵は上げたまま（動かさない）
    ///   ・大城さんは頭の側の押す手（横の棒）を両手で押す。寺島さんは足の側の横（−x の側）を一緒に歩き、左手を柵（Rail_R）の上の棒に添える
    ///   ・ハコブくんの位置・向きは台本の c270.robot（make_script270.py が 229 の決まりで出した値）をそのまま置く。Unity では確かめる（見つけた時の前の端どうしのあいだも頂点で測る）
    ///   ・確かめ：当たり（ハコブくんと物・物と壁・看護師とストレッチャー・手が棒/柵の中）・手が棒/柵から離れない・車輪の横すべり・1 コマの骨の動き・肘が肩より上にならない・
    ///     足のすべり（2 人）・くぼみの中で止まっている間に廊下の側（x −0.84 より +x）へ出ている分
    ///   ・真上の型 frames/<場面>_top_obj は赤＝ハコブくん・緑＝ストレッチャーと大城さんと寺島さん（2 人とも手をのせたままなので 1 つのもの）
    /// コマンド  Unity -batchmode -quit -projectPath … -executeMethod ServiceSim.Closeups.EditorTools.Closeup270.Run \
    ///                 -c270Out <出力フォルダ> -c270Shot <場面> [-c270Script closeup270_script.json] [-c270Frames on|off] [-c270Stills on|off] [-c270Views main,top] [-c270From 秒] [-c270To 秒] [-c270Until 秒]
    /// 出すもの：frames/<場面>/f_*.png・frames/<場面>_top(_mask/_obj)/f_*.png・stills/・stills_check/・frames270.csv・top270.csv・bones270.csv・feet270.csv・wc270.csv・check270.txt・events270.txt
    /// </summary>
    public static class Closeup270
    {
        const string Root = CloseupShoot.Root;
        const string TexDir = CloseupShoot.TexDir;
        static readonly CultureInfo IC = CultureInfo.InvariantCulture;
        static string F(float v, string f = "0.0000") { return v.ToString(f, IC); }
        const int LayerSt = 30, LayerNurse = 31, LayerTera = 28;
        const int LayerMask232 = 29;

        class RobotShape
        {
            public float band = 0.02f, top, minX, maxX, minZ, maxZ;
            public List<Vector2[]> hulls = new List<Vector2[]>();
            public Vector2[] all;
            public Vector3[] verts;
        }

        static Vector2[] Hull(List<Vector2> p)
        {
            if (p.Count < 3) return null;
            p.Sort((a, b) => a.x != b.x ? a.x.CompareTo(b.x) : a.y.CompareTo(b.y));
            var h = new Vector2[p.Count * 2]; int k = 0;
            Func<Vector2, Vector2, Vector2, float> cr = (o, a, b) => (a.x - o.x) * (b.y - o.y) - (a.y - o.y) * (b.x - o.x);
            for (int i = 0; i < p.Count; i++) { while (k >= 2 && cr(h[k - 2], h[k - 1], p[i]) <= 0) k--; h[k++] = p[i]; }
            for (int i = p.Count - 2, t = k + 1; i >= 0; i--) { while (k >= t && cr(h[k - 2], h[k - 1], p[i]) <= 0) k--; h[k++] = p[i]; }
            var r = new Vector2[k - 1]; Array.Copy(h, r, k - 1); return r;
        }

        static float PolyDist(Vector2[] poly, Vector2 q)
        {
            bool inside = true; float best = float.MaxValue;
            for (int i = 0; i < poly.Length; i++)
            {
                Vector2 a = poly[i], b = poly[(i + 1) % poly.Length];
                Vector2 e = b - a;
                if (e.x * (q.y - a.y) - e.y * (q.x - a.x) < 0) inside = false;
                float u = Mathf.Clamp01(Vector2.Dot(q - a, e) / Mathf.Max(1e-12f, e.sqrMagnitude));
                best = Mathf.Min(best, (a + e * u - q).sqrMagnitude);
            }
            return inside ? 0f : Mathf.Sqrt(best);
        }

        static RobotShape MeasureRobot(CloseupDirector dir)
        {
            var rs = new RobotShape();
            var pts = new List<Vector3>();
            foreach (var mf in dir.robot.GetComponentsInChildren<MeshFilter>(true))
            {
                if (dir.screenOverlay != null && mf.gameObject == dir.screenOverlay.gameObject) continue;
                if (!mf.gameObject.activeInHierarchy || mf.sharedMesh == null) continue;
                foreach (var v in mf.sharedMesh.vertices) pts.Add(dir.robot.InverseTransformPoint(mf.transform.TransformPoint(v)));
            }
            rs.verts = pts.ToArray();
            rs.top = float.MinValue; rs.minX = rs.minZ = float.MaxValue; rs.maxX = rs.maxZ = float.MinValue;
            foreach (var p in pts) { rs.top = Mathf.Max(rs.top, p.y); rs.minX = Mathf.Min(rs.minX, p.x); rs.maxX = Mathf.Max(rs.maxX, p.x); rs.minZ = Mathf.Min(rs.minZ, p.z); rs.maxZ = Mathf.Max(rs.maxZ, p.z); }
            int nb = Mathf.CeilToInt(rs.top / rs.band) + 1;
            var bl = new List<Vector2>[nb]; for (int i = 0; i < nb; i++) bl[i] = new List<Vector2>();
            var al = new List<Vector2>();
            foreach (var p in pts)
            {
                int b = Mathf.Clamp(Mathf.FloorToInt(p.y / rs.band), 0, nb - 1);
                bl[b].Add(new Vector2(p.x, p.z)); al.Add(new Vector2(p.x, p.z));
                int b2 = Mathf.Clamp(Mathf.FloorToInt((p.y + 0.005f) / rs.band), 0, nb - 1); if (b2 != b) bl[b2].Add(new Vector2(p.x, p.z));
                b2 = Mathf.Clamp(Mathf.FloorToInt((p.y - 0.005f) / rs.band), 0, nb - 1); if (b2 != b) bl[b2].Add(new Vector2(p.x, p.z));
            }
            for (int i = 0; i < nb; i++) rs.hulls.Add(Hull(bl[i]));
            for (int i = 0; i < nb; i++)
                if (rs.hulls[i] == null)
                {
                    var m = new List<Vector2>();
                    for (int j = i - 1; j >= 0; j--) if (rs.hulls[j] != null) { m.AddRange(rs.hulls[j]); break; }
                    for (int j = i + 1; j < nb; j++) if (bl[j].Count >= 3) { m.AddRange(Hull(new List<Vector2>(bl[j]))); break; }
                    rs.hulls[i] = Hull(m);
                }
            rs.all = Hull(al);
            return rs;
        }

        static float RobotDist(RobotShape rs, Vector3 p, float cut)
        {
            Vector2 q = new Vector2(p.x, p.z);
            float dAll = PolyDist(rs.all, q);
            float dyTop = Mathf.Max(0f, p.y - rs.top), dyBot = Mathf.Max(0f, -p.y);
            if (Mathf.Sqrt(dAll * dAll + Mathf.Max(dyTop, dyBot) * Mathf.Max(dyTop, dyBot)) > cut) return float.MaxValue;
            float best = float.MaxValue;
            int b0 = Mathf.FloorToInt((p.y - cut) / rs.band), b1 = Mathf.FloorToInt((p.y + cut) / rs.band);
            for (int b = Mathf.Max(0, b0); b <= Mathf.Min(rs.hulls.Count - 1, b1); b++)
            {
                if (rs.hulls[b] == null) continue;
                float y0 = b * rs.band, y1 = y0 + rs.band;
                float dy = p.y < y0 ? y0 - p.y : p.y > y1 ? p.y - y1 : 0f;
                if (dy >= best) continue;
                float dh = PolyDist(rs.hulls[b], q);
                best = Mathf.Min(best, Mathf.Sqrt(dh * dh + dy * dy));
            }
            return best;
        }

        class SolidBox { public string name; public Vector3 min, max; public bool rail; }
        static float PointBoxDist(Vector3 p, Vector3 mn, Vector3 mx)
        {
            Vector3 q = new Vector3(Mathf.Clamp(p.x, mn.x, mx.x), Mathf.Clamp(p.y, mn.y, mx.y), Mathf.Clamp(p.z, mn.z, mx.z));
            return Vector3.Distance(p, q);
        }
        static bool InBox(Vector3 p, Vector3 mn, Vector3 mx) { return p.x > mn.x && p.x < mx.x && p.y > mn.y && p.y < mx.y && p.z > mn.z && p.z < mx.z; }

        /// <summary>看護師ひとり分（焼いた形・手の頂点の分け方・骨・靴）</summary>
        class NurseRig
        {
            public string name; public CloseupNurse n; public Animator an;
            public List<SkinnedMeshRenderer> parts = new List<SkinnedMeshRenderer>();
            public List<string[]> partCat = new List<string[]>();
            public List<HumanBodyBones> bones = new List<HumanBodyBones>();
            public Vector3[] prevBones; public Vector3 prevRoot; public bool havePrev;
            public float jumpR, jumpRT, jumpW, jumpWT; public string jumpRB = "", jumpWB = "";
            public float elbowOver = -9f, elbowOverT = -1f; public string elbowOverSide = "";
            public SkinnedMeshRenderer shoe; public Mesh shoeMesh = new Mesh();
            public Vector3[] shoePrev; public bool[] shoeOn; public bool prevInWalk;
            public float slideMax, slideMaxT, sinkMax, sinkMaxT, floatMax, floatMaxT; public int walkFrames;
        }
        static NurseRig MakeRig(string name, CloseupNurse n)
        {
            var g = new NurseRig { name = name, n = n, an = n.Anim };
            foreach (var smr in n.GetComponentsInChildren<SkinnedMeshRenderer>(true))
                foreach (var nm in new[] { "Nurse_Skin", "Nurse_Top", "Nurse_Sleeves", "Nurse_Pants", "Nurse_Shoes", "Nurse_Hair" })
                    if (smr.name == nm) g.parts.Add(smr);
            var boneMap = new Dictionary<Transform, HumanBodyBones>();
            for (int i = 0; i < (int)HumanBodyBones.LastBone; i++) { var tb = g.an.GetBoneTransform((HumanBodyBones)i); if (tb != null) { boneMap[tb] = (HumanBodyBones)i; g.bones.Add((HumanBodyBones)i); } }
            foreach (var smr in g.parts)
            {
                var bw = smr.sharedMesh.boneWeights;
                var cat = new string[smr.sharedMesh.vertexCount];
                for (int i = 0; i < cat.Length; i++) cat[i] = bw.Length > i ? HandCat(smr.bones[bw[i].boneIndex0], boneMap) : "";
                g.partCat.Add(cat);
                if (smr.name == "Nurse_Shoes") g.shoe = smr;
            }
            g.prevBones = new Vector3[g.bones.Count];
            return g;
        }

        public static void Run()
        {
            string outDir = CloseupArgs.Get("-c270Out", "");
            if (outDir == "") throw new Exception("-c270Out がない");
            string scriptName = CloseupArgs.Get("-c270Script", "closeup270_script.json");
            string shotName = CloseupArgs.Get("-c270Shot", "stretcher_alcove");
            bool frames = CloseupArgs.Get("-c270Frames", "off") == "on";
            bool stillsOn = CloseupArgs.Get("-c270Stills", "off") == "on";
            var views = new HashSet<string>(CloseupArgs.Get("-c270Views", "main,top").Split(','));
            float fromT = float.Parse(CloseupArgs.Get("-c270From", "-1"), IC), toT = float.Parse(CloseupArgs.Get("-c270To", "1e9"), IC);
            Directory.CreateDirectory(outDir);
            var log = new StringBuilder();
            var tab = new StringBuilder();
            try
            {
                Closeup270Stretcher.CheckImport(log);
                EditorSceneManager.OpenScene(CloseupShoot.ScenePath, OpenSceneMode.Single);
                var dir = UnityEngine.Object.FindObjectOfType<CloseupDirector>();
                string scriptText = File.ReadAllText(Path.IsPathRooted(scriptName) ? scriptName : Root + "/" + scriptName);
                dir.LoadScript(scriptText);
                var js = dir.script;
                string topErr; var topAll = JsonValue.Parse(File.ReadAllText(Root + "/closeup270_top.json"), out topErr); if (topAll == null) throw new Exception("closeup270_top.json: " + topErr);
                var topJs = topAll[shotName];
                dir.nurse.Init();
                dir.Measure();
                dir.BuildOverlay();
                dir.MeasurePocket();

                // ---- 廊下（237 と同じ。台本の rooms の「廊下…」。くぼみの箱も入っている）
                var solids = new List<SolidBox>();
                var corr = new GameObject("Corridor270").transform;
                var mats = new Dictionary<string, Material>();
                foreach (var k in js["colors"].Keys)
                {
                    var m = new Material(Shader.Find("Standard")) { name = "C270_" + k };
                    Color c; ColorUtility.TryParseHtmlString(js["colors"][k].S(), out c); m.color = c; m.SetFloat("_Glossiness", 0.15f);
                    mats[k] = m;
                }
                var rooms = js["rooms"];
                int nCorr = 0;
                for (int i = 0; i < rooms.Count; i++)
                {
                    var r = rooms[i];
                    if (!r["name"].S("").StartsWith("廊下")) continue;
                    Vector3 a = CloseupDirector.V3(r["min"]), b = CloseupDirector.V3(r["max"]);
                    var go = GameObject.CreatePrimitive(PrimitiveType.Cube);
                    UnityEngine.Object.DestroyImmediate(go.GetComponent<Collider>());
                    go.name = r["name"].S(); go.transform.SetParent(corr, false);
                    go.transform.position = (a + b) * 0.5f; go.transform.localScale = b - a;
                    var rr = go.GetComponent<Renderer>(); rr.sharedMaterial = mats[r["mat"].S()];
                    if (!r["shadow"].B(false)) rr.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
                    if (r["solid"].B(false)) solids.Add(new SolidBox { name = r["name"].S(), min = a, max = b, rail = r["rail"].B(false) });
                    nCorr++;
                }
                log.AppendLine("廊下の箱 " + nCorr + " 個（当たりを数える箱 " + solids.Count + " 個）");

                // ---- 焼いた形（描くのは焼いた形。237 と同じ）
                var proxies = new List<KeyValuePair<SkinnedMeshRenderer, MeshFilter>>();
                var proxyRoot = new GameObject("Baked270").transform;
                var proxyRootT = new GameObject("Baked270Tera").transform;
                Action<SkinnedMeshRenderer, Transform> addProxy = (smr, pr) =>
                {
                    var g = new GameObject(smr.name + "_Baked"); g.transform.SetParent(pr, false);
                    var mf = g.AddComponent<MeshFilter>(); mf.sharedMesh = new Mesh();
                    var mr = g.AddComponent<MeshRenderer>(); mr.sharedMaterials = smr.sharedMaterials;
                    smr.enabled = false;
                    proxies.Add(new KeyValuePair<SkinnedMeshRenderer, MeshFilter>(smr, mf));
                };
                foreach (var smr in dir.nurse.GetComponentsInChildren<SkinnedMeshRenderer>(true)) addProxy(smr, proxyRoot);
                Action syncProxies = () =>
                {
                    foreach (var kv in proxies)
                    {
                        bool on = kv.Key.gameObject.activeInHierarchy;
                        kv.Value.gameObject.SetActive(on);
                        if (!on) continue;
                        kv.Key.BakeMesh(kv.Value.sharedMesh, true);
                        kv.Value.sharedMesh.RecalculateBounds();
                        kv.Value.transform.SetPositionAndRotation(kv.Key.transform.position, kv.Key.transform.rotation);
                    }
                };
                var O_ = MakeRig("大城さん", dir.nurse);
                var an = O_.an;

                // ---- 寺島さん（235 と同じ：2 つめの CloseupDirector。部品の名前 Terashima_ → Nurse_）
                var teraGo = (GameObject)PrefabUtility.InstantiatePrefab(AssetDatabase.LoadAssetAtPath<GameObject>(Closeup231Terashima.Prefab));
                teraGo.name = "Terashima270";
                foreach (var tr in teraGo.GetComponentsInChildren<Transform>(true)) if (tr.name.StartsWith("Terashima_")) tr.name = "Nurse_" + tr.name.Substring("Terashima_".Length);
                var teraN = teraGo.GetComponent<CloseupNurse>(); if (teraN == null) teraN = teraGo.AddComponent<CloseupNurse>();
                // 寺島さんのプレハブの Animator には動かし方（controller）が入っていない（235〜238 は入れずに動かしていた）。大城さんと同じ Closeup_Nurse.controller をこの場面の中だけで入れる（プレハブは変えない）
                var anTg = teraGo.GetComponent<Animator>();
                if (anTg.runtimeAnimatorController == null) { anTg.runtimeAnimatorController = AssetDatabase.LoadAssetAtPath<RuntimeAnimatorController>(Root + "/Closeup_Nurse.controller"); log.AppendLine("寺島さん：Animator に Closeup_Nurse.controller を入れた（場面の中だけ）"); }
                anTg.cullingMode = AnimatorCullingMode.AlwaysAnimate;
                teraN.Init();
                var dir2 = new GameObject("Director270Tera").AddComponent<CloseupDirector>();
                dir2.nurse = teraN; dir2.robot = dir.robot; dir2.drawer = dir.drawer; dir2.body = dir.body; dir2.face = dir.face; dir2.ring = dir.ring;
                dir2.trays = dir.trays; dir2.box = dir.box; dir2.bag = dir.bag; dir2.card = dir.card; dir2.pocket = dir.pocket; dir2.cam = dir.cam;
                dir2.screenOverlay = dir.screenOverlay; dir2.screenTex = dir.screenTex; dir2.screenTexNames = dir.screenTexNames;
                dir2.LoadScript(scriptText);
                int nProxyO = proxies.Count;
                foreach (var smr in teraN.GetComponentsInChildren<SkinnedMeshRenderer>(true)) addProxy(smr, proxyRootT);
                var T_ = MakeRig("寺島さん", teraN);
                var anT = T_.an;
                log.AppendLine("寺島さん：部品 " + T_.parts.Count + "（体）・写し " + (proxies.Count - nProxyO));

                // 口（217・218 と同じ：talk を上の端を止めて縦に倍）
                Func<int, CloseupNurse, Func<float>, Action> mouthScaler = (from, nn, sc) =>
                {
                    MeshFilter tp = null;
                    for (int i = from; i < proxies.Count; i++) if (proxies[i].Key.name == "Nurse_Mouth_talk" && proxies[i].Key.transform.IsChildOf(nn.transform)) tp = proxies[i].Value;
                    if (tp == null) throw new Exception("口の部品 Nurse_Mouth_talk が無い: " + nn.name);
                    return () =>
                    {
                        float s = sc();
                        if (!tp.gameObject.activeSelf || Mathf.Abs(s - 1f) < 1e-4f) return;
                        var mesh = tp.sharedMesh; var vs = mesh.vertices;
                        Vector3 fw = nn.HeadForward().normalized;
                        Vector3 upW = Vector3.ProjectOnPlane(Vector3.up, fw).normalized;
                        Vector3 u = Quaternion.Inverse(tp.transform.rotation) * upW;
                        float top = float.MinValue; foreach (var v in vs) top = Mathf.Max(top, Vector3.Dot(v, u));
                        for (int i = 0; i < vs.Length; i++) { float h = Vector3.Dot(vs[i], u) - top; vs[i] -= u * (h * (1f - s)); }
                        mesh.vertices = vs; mesh.RecalculateBounds();
                    };
                };
                float curMouthScale = 1f, curMouthScaleT = 1f;
                var scaleMouth = mouthScaler(0, dir.nurse, () => curMouthScale);
                var scaleMouthT = mouthScaler(nProxyO, teraN, () => curMouthScaleT);

                // ---- ストレッチャー
                var st = Closeup270Stretcher.Spawn("Stretcher270").transform;
                Func<string, Transform> SF = n => { var t0 = CloseupNurse.Find(st, n); if (t0 == null) throw new Exception("ストレッチャーの部品が無い: " + n); return t0; };
                string[] casN = { "FL", "FR", "BL", "BR" };
                var cas = new Transform[4]; var cw = new Transform[4];
                for (int i = 0; i < 4; i++) { cas[i] = SF("Caster_" + casN[i]); cw[i] = SF("CasterWheel_" + casN[i]); }
                st.SetPositionAndRotation(Vector3.zero, Quaternion.identity);
                var casRest = new Quaternion[4]; var cwRest = new Quaternion[4]; var axC = new Vector3[4]; var axW = new Vector3[4]; var stem0 = new Vector3[4]; var hub0 = new Vector3[4];
                for (int i = 0; i < 4; i++)
                {
                    casRest[i] = cas[i].localRotation; cwRest[i] = cw[i].localRotation;
                    axC[i] = cas[i].parent.InverseTransformDirection(Vector3.up); axW[i] = cw[i].parent.InverseTransformDirection(Vector3.right);
                    stem0[i] = cas[i].position; hub0[i] = cw[i].position;
                }
                var stMF = new List<MeshFilter>(st.GetComponentsInChildren<MeshFilter>(true));
                var stCol = new Dictionary<Collider, string>();
                foreach (var mf in stMF) { var mc = mf.gameObject.AddComponent<MeshCollider>(); mc.sharedMesh = mf.sharedMesh; mf.gameObject.layer = LayerSt; stCol[mc] = mf.name; }
                var stVerts = new List<Vector3>(); var stPart = new List<string>();
                foreach (var mf in stMF) foreach (var v in mf.sharedMesh.vertices) { stVerts.Add(mf.transform.TransformPoint(v)); stPart.Add(mf.name); }
                var stMin = Vector3.one * 9f; var stMax = -Vector3.one * 9f;
                foreach (var p in stVerts) { stMin = Vector3.Min(stMin, p); stMax = Vector3.Max(stMax, p); }
                log.AppendLine(string.Format(IC, "ストレッチャー：頂点 {0}・範囲 {1}〜{2}", stVerts.Count, stMin.ToString("0.000"), stMax.ToString("0.000")));

                // 看護師の体の当たり（焼いた形の MeshCollider）：大城さん LayerNurse・寺島さん LayerTera
                Func<NurseRig, int, List<KeyValuePair<SkinnedMeshRenderer, MeshCollider>>> mkCols = (g, layer) =>
                {
                    var root = new GameObject("Col_" + g.name); root.layer = layer;
                    var l = new List<KeyValuePair<SkinnedMeshRenderer, MeshCollider>>();
                    foreach (var smr in g.parts)
                    {
                        var go = new GameObject(smr.name + "_Col"); go.layer = layer; go.transform.SetParent(root.transform, false);
                        var mc = go.AddComponent<MeshCollider>(); mc.sharedMesh = new Mesh();
                        l.Add(new KeyValuePair<SkinnedMeshRenderer, MeshCollider>(smr, mc));
                    }
                    return l;
                };
                var colsO = mkCols(O_, LayerNurse); var colsT = mkCols(T_, LayerTera);

                // ---- 画面の絵
                var faceR = dir.face.GetComponent<Renderer>();
                var faceAlb = new Dictionary<string, Texture2D>(); var faceEmi = new Dictionary<string, Texture2D>();
                foreach (var fk in new[] { "closed", "small", "large", "happy" })
                {
                    faceAlb[fk] = PrepTex(TexDir + "/face218_" + fk + "_albedo.png"); faceEmi[fk] = PrepTex(TexDir + "/face218_" + fk + "_emission.png");
                }
                faceAlb["happy_closed"] = faceAlb["happy"]; faceEmi["happy_closed"] = faceEmi["happy"];
                foreach (var mk in new[] { "small", "mid", "large" }) { faceAlb["happy_" + mk] = PrepTex(TexDir + "/face224_happy_" + mk + "_albedo.png"); faceEmi["happy_" + mk] = PrepTex(TexDir + "/face224_happy_" + mk + "_emission.png"); }
                var scrTex = new Dictionary<string, Texture2D> { { "wait", ScreenTex(TexDir + "/c235_wait_band.png") }, { "back", ScreenTex(TexDir + "/c270_back_band.png") } };

                int fps = js["fps"].I(30), W = js["width"].I(1920), H = js["height"].I(1080), SS = js["supersample"].I(2);
                int iters = js["nurse"]["ik_iters"].I(3);
                float dt = 1f / fps;

                dir2.BeginShot(shotName + "__tera");
                anT.Rebind();
                dir.BeginShot(shotName);
                an.Rebind();
                var shot = dir.shot;
                var C = shot["c270"];
                Vector3 O = CloseupDirector.V3(shot["origin"]);
                var robotKeys = C["robot"]; var stKeys = C["stretcher"]; var stV = C["stretcher_v"];
                var scrKeys = C["screen"];
                var robotMouth = C["robot_mouth"]; var nurseMouth = C["nurse_mouth"]; var teraMouth = C["tera_mouth"]; var nmScale = C["nurse_mouth_scale"];
                var bar = C["bar"]; float barY = bar["y"].F(), barZ = -bar["z_behind_root"].F(), barR = bar["r"].F(), barHalf = bar["x_half"].F();
                var railJ = C["rail"]; float railX = railJ["x"].F(), railY = railJ["y"].F(), railR = railJ["r"].F();
                var alc = C["alcove"]; float alcZ0 = alc["z0"].F(), alcZ1 = alc["z1"].F();
                var evJ = C["events"];
                float detT = evJ["detect"].F(), inStopT = evJ["in_stop"].F(), exitT = evJ["exit"].F();
                int vFrom0 = Mathf.RoundToInt(C["video_from"].F(0f) * 30f);

                dir.Apply(0f, dt);
                var rs = MeasureRobot(dir);
                log.AppendLine(string.Format(IC, "ハコブくんの外形（根から）: 幅 x {0:0.000}〜{1:0.000}・奥行 z {2:0.000}〜{3:0.000}・高さ {4:0.000} m", rs.minX, rs.maxX, rs.minZ, rs.maxZ, rs.top));

                // 確かめ
                var cats = new[] { "ストレッチャー", "大城さん", "寺島さん" };
                var gapMin = new Dictionary<string, float>(); var gapMinT = new Dictionary<string, float>(); var gapMinWhere = new Dictionary<string, string>();
                foreach (var c in cats) { gapMin[c] = float.MaxValue; gapMinT[c] = -1f; gapMinWhere[c] = ""; }
                int hitRG = 0, hitRS = 0, hitSS = 0, hitOS = 0, hitTS = 0, hitOSt = 0, hitTSt = 0, hitOT = 0, hitBar = 0, hitRail = 0;
                string hitRSW = "", hitSSW = "", hitOSW = "", hitTSW = "", hitOStW = "", hitTStW = "", hitOTW = "", hitBarW = "", hitRailW = "";
                float robotRailMin = float.MaxValue, stSolidMin = float.MaxValue, oSolidMin = float.MaxValue, tSolidMin = float.MaxValue;
                float palmBarMin = float.MaxValue, palmBarMax = float.MinValue, palmRailMin = float.MaxValue, palmRailMax = float.MinValue, palmErrO = 0f, palmErrT = 0f;
                float handBarMin = float.MaxValue, handRailMin = float.MaxValue;
                float wheelSlip = 0f, casYawMax = 0f, tireYMin = float.MaxValue, tireYMax = float.MinValue, rollErr = 0f;
                var cwAng = new float[4]; var casYaw = new float[4]; var cAx = new Vector3[4]; bool haveSt = false;
                float protrudeMax = -9f, protrudeT = -1f; int alcoveFrames = 0; float robotXMaxInAlc = -9f;
                float detGapUnity = float.NaN, detGapUnityT = -1f; bool seenU = false;
                float stVmin = float.MaxValue, stVmax = 0f;
                string prevScr = ""; var scrChanges = new List<string>();
                var csv = new StringBuilder("frame,t,cam,robot_x,robot_z,robot_yaw,robot_v,mode,screen,st_z,st_v,gap_m,gap_st,gap_o,gap_t,front_gap_m,rail_gap_m,robot_maxx,palm_bar_l,palm_bar_r,palm_rail_t,o_head_yaw,t_head_yaw,nurse_mouth,tera_mouth,o_z,t_z\n");
                var topCsv = new StringBuilder("frame,t,st_x,st_z,st_px,st_py,robot_x,robot_z,robot_px,robot_py,st_in,robot_in\n");
                var bonesCsv = new StringBuilder("frame,t"); foreach (var hb in O_.bones) bonesCsv.Append(",o_" + hb + "_x,o_" + hb + "_y,o_" + hb + "_z"); bonesCsv.AppendLine();
                var feetCsv = new StringBuilder("frame,t,who,step,lshoe_min_y,rshoe_min_y,shoe_slide\n");
                var wcCsv = new StringBuilder("frame,t,st_z,dist,caster_yaw_fl,caster_yaw_fr,caster_yaw_bl,caster_yaw_br,wheel_deg_fl,wheel_deg_fr,wheel_deg_bl,wheel_deg_br,tire_min_y,slip_m\n");
                var baked = new Mesh();
                var stills = shot["stills"];

                int nFrames = Mathf.RoundToInt(Mathf.Min(dir.duration, float.Parse(CloseupArgs.Get("-c270Until", "1e9"), IC)) * fps);
                nFrames = Mathf.Min(nFrames, robotKeys.Count);
                string fdirM = Path.Combine(outDir, "frames", shotName), fdirT = Path.Combine(outDir, "frames", shotName + "_top");
                bool vMain = frames && views.Contains("main"), vTop = frames && views.Contains("top");
                if (vMain) Directory.CreateDirectory(fdirM);
                if (vTop) { Directory.CreateDirectory(fdirT); Directory.CreateDirectory(fdirT + "_mask"); Directory.CreateDirectory(fdirT + "_obj"); }

                for (int f = 0; f < nFrames; f++)
                {
                    float t = f * dt;
                    if (f > 0 && f % 150 == 0) GC.Collect();
                    // ---------- ハコブくん（台本の値）
                    var rk = robotKeys[f];
                    float rx = rk[0].F(), rz = rk[1].F(), ryaw = rk[2].F(), rv = rk[3].F(); string mode = rk[4].S();
                    // ---------- 看護師（寺島さんを先に。大城さんの Apply がハコブくん・画面を決め直す）
                    dir2.Apply(t, dt);
                    int tml = f < teraMouth.Count ? teraMouth[f].I() : 0;
                    if (tml > 0) teraN.mouth = "talk";
                    curMouthScaleT = tml > 0 ? nmScale[tml].F() : 1f;
                    teraN.Step(f == 0 ? 0f : dt, iters);
                    dir.Apply(t, dt);
                    dir.robot.position = O + new Vector3(rx, 0f, rz);
                    dir.robot.rotation = Quaternion.Euler(0f, ryaw, 0f);
                    int nml = f < nurseMouth.Count ? nurseMouth[f].I() : 0;
                    if (nml > 0) dir.nurse.mouth = "talk";
                    curMouthScale = nml > 0 ? nmScale[nml].F() : 1f;
                    dir.nurse.Step(f == 0 ? 0f : dt, iters);
                    Transform nr = dir.nurse.transform;

                    // ---------- ストレッチャー：台本の根（向き 180°）・車輪
                    var sk = stKeys[Mathf.Min(f, stKeys.Count - 1)];
                    st.SetPositionAndRotation(O + new Vector3(sk[0].F(), 0f, sk[1].F()), Quaternion.Euler(0f, 180f, 0f));
                    float svNow = stV[Mathf.Min(f, stV.Count - 1)].F(); if (f > 0) { stVmin = Mathf.Min(stVmin, svNow); stVmax = Mathf.Max(stVmax, svNow); }
                    {
                        float slipNow = 0f, tmn = float.MaxValue;
                        for (int i = 0; i < 4; i++)
                        {
                            Vector3 s0 = st.TransformPoint(stem0[i]); s0.y = 0f;
                            float trail = new Vector2(hub0[i].x - stem0[i].x, hub0[i].z - stem0[i].z).magnitude;
                            if (!haveSt) { cAx[i] = st.TransformPoint(new Vector3(hub0[i].x, 0f, hub0[i].z)); cAx[i].y = 0f; }
                            Vector3 d = cAx[i] - s0; d.y = 0f;
                            Vector3 axN = s0 + (d.sqrMagnitude > 1e-12f ? d.normalized : -st.forward) * trail;
                            Vector3 move = axN - cAx[i]; move.y = 0f;
                            Vector3 fwdW = -(axN - s0).normalized;
                            float roll = Vector3.Dot(move, fwdW);
                            float slip = Vector3.Dot(move, Vector3.Cross(Vector3.up, fwdW));
                            slipNow = Mathf.Max(slipNow, Mathf.Abs(slip));
                            casYaw[i] = Mathf.DeltaAngle(st.eulerAngles.y, Mathf.Atan2(fwdW.x, fwdW.z) * Mathf.Rad2Deg);
                            casYawMax = Mathf.Max(casYawMax, Mathf.Abs(casYaw[i]));
                            cAx[i] = axN;
                            cwAng[i] += roll / 0.1f * Mathf.Rad2Deg;
                            cas[i].localRotation = Quaternion.AngleAxis(casYaw[i], axC[i]) * casRest[i];
                            cw[i].localRotation = Quaternion.AngleAxis(cwAng[i], axW[i]) * cwRest[i];
                        }
                        for (int i = 0; i < 4; i++) foreach (var v in cw[i].GetComponent<MeshFilter>().sharedMesh.vertices) tmn = Mathf.Min(tmn, cw[i].TransformPoint(v).y);
                        tireYMin = Mathf.Min(tireYMin, tmn); tireYMax = Mathf.Max(tireYMax, tmn); wheelSlip = Mathf.Max(wheelSlip, slipNow);
                        float dist = (stKeys[0][1].F() - sk[1].F());
                        rollErr = Mathf.Max(rollErr, Mathf.Abs(cwAng[0] * Mathf.Deg2Rad * 0.1f - dist));
                        wcCsv.AppendLine(f + "," + F(t, "0.000") + "," + F(sk[1].F()) + "," + F(dist) + "," + F(casYaw[0], "0.00") + "," + F(casYaw[1], "0.00") + "," + F(casYaw[2], "0.00") + "," + F(casYaw[3], "0.00") + "," +
                                         F(cwAng[0], "0.00") + "," + F(cwAng[1], "0.00") + "," + F(cwAng[2], "0.00") + "," + F(cwAng[3], "0.00") + "," + F(tmn, "0.00000") + "," + F(slipNow, "0.00000"));
                        haveSt = true;
                    }

                    // ---------- 画面
                    string rmo = f < robotMouth.Count ? robotMouth[f].S() : "mid";
                    string skey = "face"; for (int k = 0; k < scrKeys.Count; k++) if (scrKeys[k][0].F() <= t + 1e-4f) skey = scrKeys[k][1].S();
                    bool bandNow = scrTex.ContainsKey(skey), happyNow = skey == "happy";
                    dir.screenOverlay.gameObject.SetActive(bandNow);
                    if (bandNow) { var mpo = new MaterialPropertyBlock(); mpo.SetTexture("_MainTex", scrTex[skey]); dir.screenOverlay.SetPropertyBlock(mpo); }
                    string fk = happyNow ? "happy_" + rmo : rmo != "mid" ? rmo : "";
                    { var mpf = new MaterialPropertyBlock(); if (fk != "") { mpf.SetTexture("_MainTex", faceAlb[fk]); mpf.SetTexture("_EmissionMap", faceEmi[fk]); } faceR.SetPropertyBlock(mpf); }
                    string scrNow = (bandNow ? "帯" + skey : "") + (happyNow ? "目まで笑う顔" : "基本");
                    if (scrNow != prevScr) scrChanges.Add(F(t, "0.000") + "\t" + (prevScr == "" ? "-" : prevScr) + " → " + scrNow);
                    prevScr = scrNow;

                    // 区切って撮る時（-c270From）：範囲より前のコマは動き（看護師・ストレッチャー・車輪）だけ進め、確かめは飛ばす（確かめの値は区切らずに回した回のものを使う）
                    if (frames && t < fromT - 1e-4f) continue;
                    // ---------- 当たりの形を焼く
                    foreach (var l in new[] { colsO, colsT })
                        foreach (var kv in l)
                        {
                            var cm = kv.Value.sharedMesh; kv.Key.BakeMesh(cm, true);
                            kv.Value.sharedMesh = null; kv.Value.sharedMesh = cm;
                            kv.Value.transform.SetPositionAndRotation(kv.Key.transform.position, kv.Key.transform.rotation);
                        }
                    Physics.SyncTransforms();
                    Matrix4x4 toR = dir.robot.worldToLocalMatrix, toS = st.worldToLocalMatrix;
                    var gapNow = new Dictionary<string, float>(); foreach (var c in cats) gapNow[c] = float.MaxValue;
                    string gapWhereNow = ""; float nearZ = float.MaxValue;
                    Action<Vector3, string, string> seeVert = (w, cat, what) =>
                    {
                        nearZ = Mathf.Min(nearZ, w.z - O.z);
                        Vector3 lr = toR.MultiplyPoint3x4(w);
                        if (lr.x < rs.minX - 1.6f || lr.x > rs.maxX + 1.6f || lr.z < rs.minZ - 1.6f || lr.z > rs.maxZ + 1.6f) return;
                        float d = RobotDist(rs, lr, Mathf.Min(gapNow[cat], 1.5f));
                        if (d < gapNow[cat]) { gapNow[cat] = d; if (d < gapMin[cat]) { gapMin[cat] = d; gapMinT[cat] = t; gapMinWhere[cat] = what; } }
                    };
                    // ストレッチャーの頂点：見る・壁
                    bool ssHit = false;
                    {
                        Matrix4x4 sw = st.localToWorldMatrix;
                        for (int k = 0; k < stVerts.Count; k++)
                        {
                            Vector3 w = sw.MultiplyPoint3x4(stVerts[k]);
                            seeVert(w, "ストレッチャー", stPart[k]);
                            foreach (var s in solids)
                            {
                                if (w.x < s.min.x - 0.3f || w.x > s.max.x + 0.3f || w.z < s.min.z - 0.3f || w.z > s.max.z + 0.3f) continue;
                                if (InBox(w, s.min, s.max)) { ssHit = true; if (hitSSW == "") hitSSW = F(t, "0.000") + " 秒 " + stPart[k] + "→" + s.name; }
                                stSolidMin = Mathf.Min(stSolidMin, PointBoxDist(w, s.min, s.max));
                            }
                        }
                    }
                    // 看護師の頂点：見る・壁・ストレッチャー（手は押す手の棒／柵のほかに当たらない）・大城さんと寺島さん
                    bool osHit = false, tsHit = false, ostHit = false, tstHit = false, otHit = false, barHit = false, railHit = false;
                    foreach (var g in new[] { O_, T_ })
                    {
                        bool isO = g == O_;
                        for (int pi = 0; pi < g.parts.Count; pi++)
                        {
                            var smr = g.parts[pi];
                            smr.BakeMesh(baked, true);
                            Matrix4x4 m = Matrix4x4.TRS(smr.transform.position, smr.transform.rotation, Vector3.one);
                            var vs = baked.vertices; var cat = g.partCat[pi];
                            for (int i = 0; i < vs.Length; i += isO ? 1 : 1)
                            {
                                Vector3 w = m.MultiplyPoint3x4(vs[i]);
                                seeVert(w, g.name, smr.name);
                                foreach (var s in solids)
                                {
                                    if (w.x < s.min.x - 0.3f || w.x > s.max.x + 0.3f || w.z < s.min.z - 0.3f || w.z > s.max.z + 0.3f) continue;
                                    float dd = PointBoxDist(w, s.min, s.max);
                                    if (isO) oSolidMin = Mathf.Min(oSolidMin, dd); else tSolidMin = Mathf.Min(tSolidMin, dd);
                                    if (InBox(w, s.min, s.max)) { if (isO) { osHit = true; if (hitOSW == "") hitOSW = F(t, "0.000") + " 秒 " + smr.name + "→" + s.name; } else { tsHit = true; if (hitTSW == "") hitTSW = F(t, "0.000") + " 秒 " + smr.name + "→" + s.name; } }
                                }
                                if (!isO && Physics.CheckSphere(w, 0.003f, 1 << LayerNurse)) { otHit = true; if (hitOTW == "") hitOTW = F(t, "0.000") + " 秒 寺島さん " + smr.name + "→大城さん"; }
                                Vector3 lc = toS.MultiplyPoint3x4(w);
                                if (lc.x < stMin.x - 0.05f || lc.x > stMax.x + 0.05f || lc.z < stMin.z - 0.05f || lc.z > stMax.z + 0.05f || lc.y > stMax.y + 0.05f) continue;
                                bool hand = cat[i] != "";
                                if (hand && isO)
                                {
                                    // 押す手の棒（根から x ±barHalf・y barY・z barZ）：筒の中に入らない
                                    if (Mathf.Abs(lc.x) <= barHalf + 0.02f) { float dg = new Vector2(lc.y - barY, lc.z - barZ).magnitude - barR; handBarMin = Mathf.Min(handBarMin, dg); if (dg < -0.001f) { barHit = true; if (hitBarW == "") hitBarW = F(t, "0.000") + " 秒 " + cat[i] + " 棒の中 " + F(dg); } }
                                    foreach (var col in Physics.OverlapSphere(w, 0.001f, 1 << LayerSt))
                                        if (!(stCol[col] == "ST_Frame" && lc.y > 0.9f && lc.z < -0.95f)) { ostHit = true; if (hitOStW == "") hitOStW = F(t, "0.000") + " 秒 " + cat[i] + "→" + stCol[col]; }
                                }
                                else if (hand && !isO)
                                {
                                    // 柵（Rail_R：根から x +railX・y railY・z −0.63〜0.63 の上の棒）
                                    if (Mathf.Abs(lc.z) <= 0.63f) { float dg = new Vector2(lc.x - railX, lc.y - railY).magnitude - railR; handRailMin = Mathf.Min(handRailMin, dg); if (dg < -0.001f) { railHit = true; if (hitRailW == "") hitRailW = F(t, "0.000") + " 秒 " + cat[i] + " 柵の中 " + F(dg); } }
                                    foreach (var col in Physics.OverlapSphere(w, 0.001f, 1 << LayerSt))
                                        if (stCol[col] != "Rail_R") { tstHit = true; if (hitTStW == "") hitTStW = F(t, "0.000") + " 秒 " + cat[i] + "→" + stCol[col]; }
                                }
                                else
                                {
                                    var cols = Physics.OverlapSphere(w, 0.003f, 1 << LayerSt);
                                    if (cols.Length > 0) { if (isO) { ostHit = true; if (hitOStW == "") hitOStW = F(t, "0.000") + " 秒 " + smr.name + "→" + stCol[cols[0]] + " " + lc.ToString("0.000"); } else { tstHit = true; if (hitTStW == "") hitTStW = F(t, "0.000") + " 秒 " + smr.name + "→" + stCol[cols[0]] + " " + lc.ToString("0.000"); } }
                                }
                            }
                        }
                    }
                    // ストレッチャーの頂点が看護師の体の中（押す手の棒・柵の上の棒は手でさわる所なので除く）
                    {
                        Matrix4x4 sw = st.localToWorldMatrix;
                        for (int k = 0; k < stVerts.Count; k++)
                        {
                            Vector3 lp = stVerts[k];
                            Vector3 w = sw.MultiplyPoint3x4(lp);
                            bool barV = stPart[k] == "ST_Frame" && lp.y > 0.9f && lp.z < -0.95f;
                            bool railV = stPart[k] == "Rail_R" && lp.y > 0.95f;
                            if (!barV && Physics.CheckSphere(w, 0.002f, 1 << LayerNurse)) { ostHit = true; if (hitOStW == "") hitOStW = F(t, "0.000") + " 秒 ストレッチャー " + stPart[k] + " が大城さんの体に"; }
                            if (!railV && Physics.CheckSphere(w, 0.002f, 1 << LayerTera)) { tstHit = true; if (hitTStW == "") hitTStW = F(t, "0.000") + " 秒 ストレッチャー " + stPart[k] + " が寺島さんの体に"; }
                        }
                    }
                    float gapAll = Mathf.Min(gapNow["ストレッチャー"], Mathf.Min(gapNow["大城さん"], gapNow["寺島さん"]));
                    if (gapAll <= 0f) hitRG++;
                    if (ssHit) hitSS++; if (osHit) hitOS++; if (tsHit) hitTS++; if (ostHit) hitOSt++; if (tstHit) hitTSt++; if (otHit) hitOT++; if (barHit) hitBar++; if (railHit) hitRail++;
                    float frontGap = nearZ - (rz + rs.maxZ);
                    if (!seenU && f > 0 && frontGap < 6.0f) { seenU = true; detGapUnity = frontGap; detGapUnityT = t; }

                    // ハコブくんと箱（壁・手すり・扉）・くぼみの中で廊下の側へ出ている分
                    bool rsHit = false; float railGapNow = float.MaxValue, rMaxX = float.MinValue;
                    Matrix4x4 toW = dir.robot.localToWorldMatrix;
                    foreach (var v in rs.verts)
                    {
                        Vector3 w = toW.MultiplyPoint3x4(v);
                        rMaxX = Mathf.Max(rMaxX, w.x - O.x);
                        foreach (var s in solids)
                        {
                            if (w.x < s.min.x - 0.3f || w.x > s.max.x + 0.3f || w.z < s.min.z - 0.3f || w.z > s.max.z + 0.3f) continue;
                            if (InBox(w, s.min, s.max)) { rsHit = true; if (hitRSW == "") hitRSW = F(t, "0.000") + " 秒 →" + s.name; }
                            railGapNow = Mathf.Min(railGapNow, PointBoxDist(w, s.min, s.max));
                        }
                    }
                    if (rsHit) hitRS++;
                    robotRailMin = Mathf.Min(robotRailMin, railGapNow);
                    if (mode == "wait") { alcoveFrames++; float pr = rMaxX - (-0.84f); if (pr > protrudeMax) { protrudeMax = pr; protrudeT = t; } robotXMaxInAlc = Mathf.Max(robotXMaxInAlc, rMaxX); }

                    // 手と棒・柵
                    float pbL = float.NaN, pbR = float.NaN, prT = float.NaN;
                    for (int s = 0; s < 2; s++)
                    {
                        Vector3 pc = toS.MultiplyPoint3x4(dir.nurse.PalmCenter(s));
                        float d = new Vector2(pc.y - barY, pc.z - barZ).magnitude - barR;
                        if (s == 0) pbL = d; else pbR = d;
                        palmBarMin = Mathf.Min(palmBarMin, d); palmBarMax = Mathf.Max(palmBarMax, d);
                        palmErrO = Mathf.Max(palmErrO, Vector3.Distance(dir.nurse.PalmCenter(s), dir.nurse.hands[s].palmTarget));
                    }
                    {
                        Vector3 pc = toS.MultiplyPoint3x4(teraN.PalmCenter(0));
                        prT = new Vector2(pc.x - railX, pc.y - railY).magnitude - railR;
                        palmRailMin = Mathf.Min(palmRailMin, prT); palmRailMax = Mathf.Max(palmRailMax, prT);
                        palmErrT = Mathf.Max(palmErrT, Vector3.Distance(teraN.PalmCenter(0), teraN.hands[0].palmTarget));
                    }

                    // 骨：1 コマの動き（根の動きを除く）・肘が肩より上にならない・足
                    bonesCsv.Append(f + "," + F(t, "0.000"));
                    foreach (var g in new[] { O_, T_ })
                    {
                        Vector3 rootNow = g.n.transform.position;
                        for (int b = 0; b < g.bones.Count; b++)
                        {
                            Vector3 p = g.an.GetBoneTransform(g.bones[b]).position;
                            if (g == O_) bonesCsv.Append("," + F(p.x, "0.00000") + "," + F(p.y, "0.00000") + "," + F(p.z, "0.00000"));
                            if (g.havePrev && f > vFrom0)     // 動画の始め（video_from）より前の、はじめの形が落ち着くコマは数えない
                            {
                                float dw = Vector3.Distance(p, g.prevBones[b]);
                                float drl = ((p - g.prevBones[b]) - (rootNow - g.prevRoot)).magnitude;
                                if (dw > g.jumpW) { g.jumpW = dw; g.jumpWT = t; g.jumpWB = g.bones[b].ToString(); }
                                if (drl > g.jumpR) { g.jumpR = drl; g.jumpRT = t; g.jumpRB = g.bones[b].ToString(); }
                            }
                            g.prevBones[b] = p;
                        }
                        g.prevRoot = rootNow; g.havePrev = true;
                        foreach (var sd in new[] { new[] { HumanBodyBones.LeftUpperArm, HumanBodyBones.LeftLowerArm }, new[] { HumanBodyBones.RightUpperArm, HumanBodyBones.RightLowerArm } })
                        {
                            float over = g.an.GetBoneTransform(sd[1]).position.y - g.an.GetBoneTransform(sd[0]).position.y;
                            if (over > g.elbowOver) { g.elbowOver = over; g.elbowOverT = t; g.elbowOverSide = sd[1].ToString(); }
                        }
                        // 足（237 と同じ数え方）
                        var dd2 = g == O_ ? dir : dir2;
                        bool inWalk = dd2.InStep(t);
                        float lMin = float.MaxValue, rMin = float.MaxValue;
                        g.shoe.BakeMesh(g.shoeMesh, true);
                        Matrix4x4 sm = Matrix4x4.TRS(g.shoe.transform.position, g.shoe.transform.rotation, Vector3.one);
                        Vector3 lfp = g.an.GetBoneTransform(HumanBodyBones.LeftFoot).position, rfp = g.an.GetBoneTransform(HumanBodyBones.RightFoot).position;
                        var sv = g.shoeMesh.vertices;
                        if (g.shoePrev == null || g.shoePrev.Length != sv.Length) { g.shoePrev = new Vector3[sv.Length]; g.shoeOn = new bool[sv.Length]; }
                        bool winChange = inWalk != g.prevInWalk; g.prevInWalk = inWalk;
                        float slideNow = 0f;
                        for (int i = 0; i < sv.Length; i++)
                        {
                            Vector3 w = sm.MultiplyPoint3x4(sv[i]);
                            if ((w - lfp).sqrMagnitude < (w - rfp).sqrMagnitude) lMin = Mathf.Min(lMin, w.y); else rMin = Mathf.Min(rMin, w.y);
                            bool on = w.y <= 0.01f;
                            if (on && (!g.shoeOn[i] || winChange)) g.shoePrev[i] = w;
                            float acc = on ? new Vector2(w.x - g.shoePrev[i].x, w.z - g.shoePrev[i].z).magnitude : 0f;
                            g.shoeOn[i] = on;
                            slideNow = Mathf.Max(slideNow, acc);
                        }
                        if (inWalk)
                        {
                            g.walkFrames++;
                            if (slideNow > g.slideMax) { g.slideMax = slideNow; g.slideMaxT = t; }
                            float low = Mathf.Min(lMin, rMin);
                            if (-low > g.sinkMax) { g.sinkMax = -low; g.sinkMaxT = t; }
                            if (low > g.floatMax) { g.floatMax = low; g.floatMaxT = t; }
                        }
                        feetCsv.AppendLine(f + "," + F(t, "0.000") + "," + (g == O_ ? "o" : "t") + "," + (inWalk ? 1 : 0) + "," + F(lMin) + "," + F(rMin) + "," + F(slideNow));
                    }
                    bonesCsv.AppendLine();

                    string camName = CutAt(shot, t);
                    csv.AppendLine(f + "," + F(t, "0.000") + "," + camName + "," + F(rx) + "," + F(rz) + "," + F(ryaw, "0.000") + "," + F(rv) + "," + mode + "," + scrNow + "," +
                                   F(sk[1].F()) + "," + F(svNow) + "," + F(gapAll) + "," + F(gapNow["ストレッチャー"]) + "," + F(gapNow["大城さん"]) + "," + F(gapNow["寺島さん"]) + "," + F(frontGap) + "," + F(railGapNow) + "," + F(rMaxX) + "," +
                                   F(pbL) + "," + F(pbR) + "," + F(prT) + "," + F(dir.nurse.headYawDeg, "0.00") + "," + F(teraN.headYawDeg, "0.00") + "," + nml + "," + tml + "," + F(nr.position.z - O.z) + "," + F(teraN.transform.position.z - O.z));

                    // ---------- 真上の画面の位置（ストレッチャーの根・ハコブくんの根）
                    {
                        SetTop(dir.cam, topJs, O);
                        Func<Vector3, Vector2> px = w => { Vector3 vp = dir.cam.WorldToViewportPoint(w); return new Vector2(vp.x * W, (1f - vp.y) * H); };
                        Func<Vector3, bool> inV = w => { Vector3 vp = dir.cam.WorldToViewportPoint(w); return vp.x >= 0f && vp.x <= 1f && vp.y >= 0f && vp.y <= 1f; };
                        Vector3 sp = st.position; sp.y = 0f; Vector3 rRoot = dir.robot.position; rRoot.y = 0f;
                        Vector2 pa = px(sp), pr = px(rRoot);
                        int sIn = 0; foreach (var c4 in new[] { new Vector3(-0.37f, 0f, -1.06f), new Vector3(0.37f, 0f, -1.06f), new Vector3(-0.37f, 0f, 1.0f), new Vector3(0.37f, 0f, 1.0f) }) if (inV(st.TransformPoint(c4))) sIn++;
                        int rIn = 0; foreach (var c4 in new[] { new Vector3(rs.minX, 0f, rs.minZ), new Vector3(rs.maxX, 0f, rs.minZ), new Vector3(rs.minX, 0f, rs.maxZ), new Vector3(rs.maxX, 0f, rs.maxZ) }) if (inV(dir.robot.TransformPoint(c4))) rIn++;
                        topCsv.AppendLine(f + "," + F(t, "0.000") + "," + F(sp.x - O.x, "0.00000") + "," + F(sp.z - O.z, "0.00000") + "," + F(pa.x, "0.000") + "," + F(pa.y, "0.000") + "," +
                                          F(rRoot.x - O.x, "0.00000") + "," + F(rRoot.z - O.z, "0.00000") + "," + F(pr.x, "0.000") + "," + F(pr.y, "0.000") + "," + (sIn == 4 ? 2 : sIn > 0 ? 1 : 0) + "," + (rIn == 4 ? 2 : rIn > 0 ? 1 : 0));
                        if (f == 0)
                        {
                            var cj = new StringBuilder("{\n");
                            cj.AppendLine(string.Format(IC, "  \"center_x\": {0}, \"center_z\": {1}, \"height\": {2}, \"ortho_size\": {3}, \"aspect\": {4:0.000000}, \"orthographic\": {5},",
                                topJs["center_x"].F(), topJs["center_z"].F(), topJs["height"].F(), topJs["ortho_size"].F(), dir.cam.aspect, dir.cam.orthographic ? "true" : "false"));
                            var p00 = px(O); var p10 = px(O + Vector3.right); var p01 = px(O + Vector3.forward);
                            cj.AppendLine(string.Format(IC, "  \"px_origin\": [{0:0.0000}, {1:0.0000}], \"px_per_x\": [{2:0.0000}, {3:0.0000}], \"px_per_z\": [{4:0.0000}, {5:0.0000}]",
                                p00.x, p00.y, p10.x - p00.x, p10.y - p00.y, p01.x - p00.x, p01.y - p00.y));
                            cj.AppendLine("}");
                            File.WriteAllText(Path.Combine(outDir, "top270_cam.json"), cj.ToString(), new UTF8Encoding(false));
                        }
                    }

                    // ---------- 撮る
                    bool inRange = t >= fromT - 1e-4f && t <= toT + 1e-4f;
                    if ((vMain || vTop) && inRange)
                    {
                        syncProxies(); scaleMouth(); scaleMouthT();
                        if (vMain) { SetCam(dir.cam, shot["cameras"][camName], O, dir); SavePng(Shoot(dir.cam, W, H, SS), Path.Combine(fdirM, string.Format("f_{0:00000}.png", f))); }
                        if (vTop)
                        {
                            SetTop(dir.cam, topJs, O); SavePng(Shoot(dir.cam, W, H, SS), Path.Combine(fdirT, string.Format("f_{0:00000}.png", f)));
                            var body = BodyRenderers(new[] { dir.robot, st, proxyRoot, dir.nurse.transform, proxyRootT, teraN.transform });
                            if (!log.ToString().Contains("体の型に入れた部品")) LogRenderers(body, log);
                            SavePng(ShootMask(dir.cam, body, W, H, SS), Path.Combine(fdirT + "_mask", string.Format("f_{0:00000}.png", f)));
                            // もの別の型：赤＝ハコブくん・緑＝ストレッチャーと大城さんと寺島さん（2 人とも手をストレッチャーにのせたままなので 1 つのものとして埋める。make270.py）
                            var grp = new List<Renderer>[2]; for (int g = 0; g < 2; g++) grp[g] = new List<Renderer>();
                            foreach (var rd in body) grp[rd.transform.IsChildOf(dir.robot) ? 0 : 1].Add(rd);
                            var obj = new Texture2D(W, H, TextureFormat.RGBA32, false);
                            var pxs = new Color32[W * H];
                            for (int i = 0; i < pxs.Length; i++) pxs[i].a = 255;
                            for (int g = 0; g < 2; g++)
                            {
                                var m = ShootMask(dir.cam, grp[g], W, H, SS); var mp = m.GetPixels32();
                                for (int i = 0; i < pxs.Length; i++) { if (g == 0) pxs[i].r = mp[i].r; else pxs[i].g = mp[i].r; }
                                UnityEngine.Object.DestroyImmediate(m);
                            }
                            obj.SetPixels32(pxs); obj.Apply();
                            SavePng(obj, Path.Combine(fdirT + "_obj", string.Format("f_{0:00000}.png", f)));
                        }
                    }
                    for (int s = 0; stillsOn && s < (stills != null ? stills.Count : 0); s++)
                    {
                        if (Mathf.RoundToInt(stills[s][0].F() * fps) != f) continue;
                        syncProxies(); scaleMouth(); scaleMouthT();
                        if (stills[s][1].S() == "top") SetTop(dir.cam, topJs, O); else SetCam(dir.cam, shot["cameras"][stills[s][1].S()], O, dir);
                        string sn = stills[s][2].S();
                        string sd = Path.Combine(outDir, sn.StartsWith("chk_") ? "stills_check" : "stills"); Directory.CreateDirectory(sd);
                        SavePng(Shoot(dir.cam, W, H, SS), Path.Combine(sd, shotName + "_" + sn + ".png"));
                    }
                }
                File.WriteAllText(Path.Combine(outDir, "frames270.csv"), csv.ToString(), new UTF8Encoding(false));
                File.WriteAllText(Path.Combine(outDir, "top270.csv"), topCsv.ToString(), new UTF8Encoding(false));
                File.WriteAllText(Path.Combine(outDir, "bones270.csv"), bonesCsv.ToString(), new UTF8Encoding(false));
                File.WriteAllText(Path.Combine(outDir, "feet270.csv"), feetCsv.ToString(), new UTF8Encoding(false));
                File.WriteAllText(Path.Combine(outDir, "wc270.csv"), wcCsv.ToString(), new UTF8Encoding(false));

                tab.AppendLine("■ " + shotName + "（" + nFrames + " コマ）");
                tab.AppendLine(string.Format(IC, "見つけた（Unity の頂点で測った前の端どうし）\t{0:0.000} 秒・{1:0.000} m（台本の見つけた時刻 {2:0.000}）", detGapUnityT, detGapUnity, detT));
                tab.AppendLine(string.Format(IC, "当たったコマ\tハコブくんと物 {0}・ハコブくんと壁/手すり/扉 {1}（{2}）・ストレッチャーと壁 {3}（{4}）・大城さんと壁 {5}（{6}）・寺島さんと壁 {7}（{8}）",
                                              hitRG, hitRS, hitRSW, hitSS, hitSSW, hitOS, hitOSW, hitTS, hitTSW));
                tab.AppendLine(string.Format(IC, "当たったコマ（看護師）\t大城さんとストレッチャー {0}（{1}）・寺島さんとストレッチャー {2}（{3}）・寺島さんと大城さん {4}（{5}）・手が押す手の棒の中 {6}（{7}）・手が柵の中 {8}（{9}）",
                                              hitOSt, hitOStW, hitTSt, hitTStW, hitOT, hitOTW, hitBar, hitBarW, hitRail, hitRailW));
                foreach (var c in cats) tab.AppendLine(string.Format(IC, "ハコブくんと{0}の一番近い距離\t{1:0.000} m（{2:0.000} 秒・{3}）", c, gapMin[c], gapMinT[c], gapMinWhere[c]));
                tab.AppendLine(string.Format(IC, "壁・手すりとのすき間\tハコブくん {0:0.000} m・ストレッチャー {1:0.000} m・大城さん {2:0.000} m・寺島さん {3:0.000} m", robotRailMin, stSolidMin, oSolidMin, tSolidMin));
                tab.AppendLine(string.Format(IC, "くぼみの中で止まっている間（{0} コマ）\tハコブくんの一番 +x の所 x {1:0.0000}（手すりの内の面 −0.84 から廊下の側へ出ている分 {2:0.0000} m・負は出ていない・{3:0.000} 秒）", alcoveFrames, robotXMaxInAlc, protrudeMax, protrudeT));
                tab.AppendLine(string.Format(IC, "大城さんの手と押す手の棒\t手のひらの中心と棒の面 {0:0.0000}〜{1:0.0000} m・的とのずれの最大 {2:0.0000} m・手の頂点と棒の面の一番近い {3:0.0000} m", palmBarMin, palmBarMax, palmErrO, handBarMin));
                tab.AppendLine(string.Format(IC, "寺島さんの手と柵\t手のひらの中心と柵の面 {0:0.0000}〜{1:0.0000} m・的とのずれの最大 {2:0.0000} m・手の頂点と柵の面の一番近い {3:0.0000} m", palmRailMin, palmRailMax, palmErrT, handRailMin));
                tab.AppendLine(string.Format(IC, "ストレッチャー\t車輪の横すべりの最大 {0:0.00000} m/コマ・車輪の向きの最大 {1:0.00}°・車輪の下 {2:0.00000}〜{3:0.00000} m・回った角度と進んだ長さのずれ {4:0.00000} m・速さ {5:0.000}〜{6:0.000} m/秒",
                                              wheelSlip, casYawMax, tireYMin, tireYMax, rollErr, stVmin, stVmax));
                foreach (var g in new[] { O_, T_ })
                {
                    tab.AppendLine(string.Format(IC, "{0}\t1 コマの骨の動き（根の動きを除く）{1:0.00} cm（{2}・{3:0.000} 秒）・世界（参考）{4:0.00} cm（{5}・{6:0.000}）・肘と肩の高さの差の最大 {7:0.000} m（{8}・{9:0.000} 秒。正は肘が上）",
                                                  g.name, g.jumpR * 100f, g.jumpRB, g.jumpRT, g.jumpW * 100f, g.jumpWB, g.jumpWT, g.elbowOver, g.elbowOverSide, g.elbowOverT));
                    tab.AppendLine(string.Format(IC, "{0}の足\t歩く所 {1} コマ・すべり最大 {2:0.00} cm（{3:0.000} 秒）・沈み {4:0.00} cm・両足とも浮いた {5:0.00} cm", g.name, g.walkFrames, g.slideMax * 100f, g.slideMaxT, g.sinkMax * 100f, g.floatMax * 100f));
                }
                tab.AppendLine("画面の変わり目\t" + string.Join("／", scrChanges.ToArray()));
                tab.AppendLine("大城さんのまばたき\t" + string.Join("・", dir.Blinks.ConvertAll(x => x.ToString("0.000", IC)).ToArray()));
                foreach (var e in dir.events) log.AppendLine("  " + e);
            }
            catch (Exception e)
            {
                Debug.LogError(e);
                log.AppendLine("エラー: " + e);
            }
            File.WriteAllText(Path.Combine(outDir, "check270.txt"), tab.ToString(), new UTF8Encoding(false));
            File.WriteAllText(Path.Combine(outDir, "events270.txt"), log.ToString(), new UTF8Encoding(false));
            Debug.Log("[C270] done\n" + log + "\n" + tab);
        }

        static string HandCat(Transform b, Dictionary<Transform, HumanBodyBones> map)
        {
            for (var t = b; t != null; t = t.parent)
            {
                HumanBodyBones hb;
                if (!map.TryGetValue(t, out hb)) continue;
                string s = hb.ToString();
                if (hb == HumanBodyBones.LeftHand || (s.StartsWith("Left") && (s.Contains("Thumb") || s.Contains("Index") || s.Contains("Middle") || s.Contains("Ring") || s.Contains("Little")))) return "左手";
                if (hb == HumanBodyBones.RightHand || (s.StartsWith("Right") && (s.Contains("Thumb") || s.Contains("Index") || s.Contains("Middle") || s.Contains("Ring") || s.Contains("Little")))) return "右手";
                return "";
            }
            return "";
        }

        static Texture2D ScreenTex(string path)
        {
            var ti = (TextureImporter)AssetImporter.GetAtPath(path);
            if (ti == null) throw new Exception("絵が無い: " + path);
            if (ti.textureCompression != TextureImporterCompression.Uncompressed || ti.maxTextureSize < 2048 || ti.npotScale != TextureImporterNPOTScale.None || !ti.alphaIsTransparency || !ti.mipmapEnabled || ti.wrapMode != TextureWrapMode.Clamp || !ti.sRGBTexture)
            {
                ti.textureCompression = TextureImporterCompression.Uncompressed; ti.maxTextureSize = 2048; ti.npotScale = TextureImporterNPOTScale.None;
                ti.alphaIsTransparency = true; ti.mipmapEnabled = true; ti.wrapMode = TextureWrapMode.Clamp; ti.sRGBTexture = true; ti.filterMode = FilterMode.Trilinear; ti.anisoLevel = 4;
                ti.SaveAndReimport();
            }
            var tx = AssetDatabase.LoadAssetAtPath<Texture2D>(path);
            if (tx == null) throw new Exception("絵が読めない: " + path);
            return tx;
        }

        static Texture2D PrepTex(string path)
        {
            var tx = AssetDatabase.LoadAssetAtPath<Texture2D>(path);
            if (tx == null) throw new Exception("絵が無い: " + path);
            return tx;
        }

        static string CutAt(JsonValue shot, float t)
        {
            var c = shot["cuts"];
            string name = c[0][1].S();
            for (int i = 0; i < c.Count; i++) if (c[i][0].F() <= t + 1e-4f) name = c[i][1].S();
            return name;
        }

        /// <summary>カメラ：pos・look は廊下の原点から。follow "robot"・"nurse" は z を足す（237 と同じ）。"robot_pose" はハコブくんの根の位置と向きから</summary>
        static void SetCam(Camera cam, JsonValue C, Vector3 O, CloseupDirector dir)
        {
            if (C == null || C.IsNull) throw new Exception("台本にカメラが無い");
            cam.orthographic = false; cam.ResetAspect();
            string fo = C["follow"].S("");
            if (fo == "robot_pose")
            {
                Transform r = dir.robot;
                cam.transform.position = r.TransformPoint(CloseupDirector.V3(C["pos"]));
                cam.transform.rotation = Quaternion.LookRotation(r.TransformPoint(CloseupDirector.V3(C["look"])) - cam.transform.position, Vector3.up);
                cam.fieldOfView = C["fov"].F(40f);
                return;
            }
            Vector3 add = Vector3.zero;
            if (fo == "robot") add = new Vector3(0f, 0f, dir.robot.position.z - O.z);
            else if (fo == "nurse") add = new Vector3(0f, 0f, dir.nurse.transform.position.z - O.z);
            cam.transform.position = O + add + CloseupDirector.V3(C["pos"]);
            cam.transform.rotation = Quaternion.LookRotation((O + add + CloseupDirector.V3(C["look"])) - cam.transform.position, Vector3.up);
            cam.fieldOfView = C["fov"].F(40f);
        }

        /// <summary>動かない真上のカメラ（230 と同じ正射影）。画面の上が −x・右が +z</summary>
        static void SetTop(Camera cam, JsonValue T, Vector3 O)
        {
            cam.orthographic = true;
            cam.orthographicSize = T["ortho_size"].F();
            cam.transform.position = O + new Vector3(T["center_x"].F(), T["height"].F(), T["center_z"].F());
            cam.transform.rotation = Quaternion.LookRotation(Vector3.down, Vector3.left);
            cam.nearClipPlane = 0.3f; cam.farClipPlane = T["height"].F() + 5f;
            cam.aspect = T["width_px"].F(1920f) / T["height_px"].F(1080f);
        }

        static Camera maskCam; static Material whiteMat;

        static List<Renderer> BodyRenderers(Transform[] roots)
        {
            var list = new List<Renderer>();
            foreach (var r in roots)
                foreach (var rd in r.GetComponentsInChildren<Renderer>(false))
                    if (rd.enabled && rd.gameObject.activeInHierarchy && !list.Contains(rd)) list.Add(rd);
            return list;
        }

        static void LogRenderers(List<Renderer> body, StringBuilder log)
        {
            log.AppendLine("体の型に入れた部品 " + body.Count + "：");
            foreach (var r in body) log.AppendLine(string.Format(IC, "  体 {0}（層 {1}）", r.name, r.gameObject.layer));
            foreach (var r in UnityEngine.Object.FindObjectsOfType<Renderer>())
                if (r.enabled && r.gameObject.activeInHierarchy && !body.Contains(r) && r.gameObject.layer == LayerMask232) throw new Exception("層 " + LayerMask232 + " を使っている部品がある：" + r.name);
        }

        static Texture2D ShootMask(Camera cam, List<Renderer> body, int W, int H, int SS)
        {
            if (maskCam == null)
            {
                var g = new GameObject("MaskCam270"); maskCam = g.AddComponent<Camera>(); maskCam.enabled = false;
                whiteMat = new Material(Shader.Find("Unlit/Color")) { name = "Mask270" }; whiteMat.color = Color.white;
            }
            maskCam.CopyFrom(cam);
            maskCam.cullingMask = 1 << LayerMask232;
            maskCam.clearFlags = CameraClearFlags.SolidColor; maskCam.backgroundColor = Color.black;
            maskCam.allowHDR = false; maskCam.allowMSAA = false;
            var layers = new int[body.Count]; var mats = new Material[body.Count][]; var mpbs = new MaterialPropertyBlock[body.Count]; var hadMpb = new bool[body.Count];
            for (int i = 0; i < body.Count; i++)
            {
                layers[i] = body[i].gameObject.layer; mats[i] = body[i].sharedMaterials;
                hadMpb[i] = body[i].HasPropertyBlock(); if (hadMpb[i]) { mpbs[i] = new MaterialPropertyBlock(); body[i].GetPropertyBlock(mpbs[i]); body[i].SetPropertyBlock(null); }
                body[i].gameObject.layer = LayerMask232;
                var w = new Material[Mathf.Max(1, mats[i].Length)]; for (int k = 0; k < w.Length; k++) w[k] = whiteMat;
                body[i].sharedMaterials = w;
            }
            try { return Shoot(maskCam, W, H, SS); }
            finally
            {
                for (int i = 0; i < body.Count; i++) { body[i].gameObject.layer = layers[i]; body[i].sharedMaterials = mats[i]; if (hadMpb[i]) body[i].SetPropertyBlock(mpbs[i]); }
            }
        }

        static Texture2D Shoot(Camera cam, int W, int H, int SS)
        {
            var big = RenderTexture.GetTemporary(W * SS, H * SS, 24, RenderTextureFormat.ARGB32, RenderTextureReadWrite.Default);
            var small = RenderTexture.GetTemporary(W, H, 0, RenderTextureFormat.ARGB32, RenderTextureReadWrite.Default);
            big.filterMode = FilterMode.Bilinear;
            cam.targetTexture = big;
            cam.Render();
            cam.targetTexture = null;
            Graphics.Blit(big, small);
            var prev = RenderTexture.active;
            RenderTexture.active = small;
            var tex = new Texture2D(W, H, TextureFormat.RGB24, false);
            tex.ReadPixels(new Rect(0, 0, W, H), 0, 0);
            tex.Apply();
            RenderTexture.active = prev;
            RenderTexture.ReleaseTemporary(big);
            RenderTexture.ReleaseTemporary(small);
            return tex;
        }

        static void SavePng(Texture2D tex, string path)
        {
            File.WriteAllBytes(path, tex.EncodeToPNG());
            UnityEngine.Object.DestroyImmediate(tex);
        }
    }
}
